router.post('/search/:key/topic', function(req, res, next) { let topicModel = null; let s = Search.forge({id: hashids.decode(req.params.key)[0]}); Topics .upsert([req.body.topic]) .then(function(models) { topicModel = models.at(0); return s.topics().attach(models.map((topic) => { return topic.id; })); }) .then(function() { queue.addJob('topic', { title: topicModel.get('name'), topic: topicModel }, req.sessionID); res.json(s.toJSON()); }) .catch(function(err) { res.status(500).json({ message: err.toString(), status: 400 }); }); });
deleteCourseVideo: function (req, res) { var token = req.params.videoToken; var ids = courseHashids.decode(token); var tutorId = ids[0]; var courseId = ids[1]; var sectionId = ids[2]; var videoId = ids[3]; Video.findOne({id: videoId}, function (err, video) { var videoPath = "";// path.join(root, video.path); var uploader = createUploader2(req, videoPath); uploader.delete(req, res, function (obj) { // delete data in database // delete the duration time from section and course tables CourseSection.findOne({id: sectionId}, function (err, section) { if(!!section) { section.duration -= video.duration; section.save(); Course.findOne({id: courseId}, function (err, course) { course.duration -= video.duration; course.save(); }); } }); res.send(JSON.stringify(obj)); }); }); },
router.get('/:hashedId', function(req,res) { var id = parseInt(hashids.decode(req.params.hashedId)); db.link.find({ where: {id: id} }).then(function(data) { // var shortUrl = req.headers.host + '/' + req.params.hashedId; console.log("Rhh: " + req.headers.host + ' Rphid: ' + req.params.hashedId); res.render("link/index", {url: data.get().url, hashurl: req.headers.host + '/' + req.params.hashedId}); }) })
app.get('/:hash',function(req,res){ db.url.find({where:{id:parseInt(hashid.decode(req.params.hash))}}).then(function(url){ url.count = url.count + 1; url.save(); res.redirect(url.link); }).catch(function(error){ console.log(error); res.render('error',{error:"Your url does not exist!"}); }); });
routes.get('/thumb/:id.:ext', function* thumbGenerator(){ const images = this.db.collection('images'); const thumbs = this.db.collection('thumbs'); const id = hashids.decode(this.params.id); const image = images.get(id[0]); if (image) { const src = `public/images/${image.name}`; const path = `public/images/thumbs/${image.name}`; let thumb = thumbs.where({ id: image.name }).items; if (thumb.length === 0) { if (image.mime === 'image/svg+xml') { // just copy file fs.createReadStream(src) .pipe(fs.createWriteStream(path)); } else if (image.mime === 'image/gif') { yield easyimg.resize({ src, dst: path, height: 100, width: 100, gravity: 'center', quality: 80 }); } else { yield easyimg.thumbnail({ src, dst: path, height: 100, width: 100, gravity: 'center', quality: 80 }); } thumbs.insert({ src, path, id: image.name }); } yield send(this, path, { maxage: 31536000 }); } else { this.status = 404; this.body = 'image not found'; } });
routes.get('/:id', function* imageView() { const images = this.db.collection('images'); const id = hashids.decode(this.params.id); const image = images.get(id[0]); images.update(id[0], { views: (image.views || 0) + 1 }); yield this.render('image', { title: `Image: ${image.id}`, image }); });
router.post('/force-layout/:key', function(req, res, next) { req.body.ignore = req.body.ignore || []; let ignore = []; req.body.ignore.forEach((ignoreKey) => { if(ignorables.hasOwnProperty(ignoreKey)) { ignore = ignore.concat(ignorables[ignoreKey]); } }); knex('searchTopics') .innerJoin('topics', 'searchTopics.topicId', 'topics.id') .innerJoin('contentTopics', 'searchTopics.topicId', 'contentTopics.topicId') .innerJoin('properNouns', 'contentTopics.contentId', 'properNouns.contentId') .where('searchTopics.searchId', hashids.decode(req.params.key)[0]) .whereNotIn('properNouns.text', ignore) .groupBy('topics.id', 'properNouns.text') .select('topics.name', 'properNouns.text') .count('*') .havingRaw('COUNT(*) > ?', [1]) .orderByRaw('COUNT(*)') .limit(5000) .then(function(results) { let nodes = []; let nodeMap = {}; let links = []; results.forEach((link) => { if(!nodeMap.hasOwnProperty(link.name)) { nodeMap[link.name] = nodes.push({ name: link.name, type: 'topic' })-1; } if(!nodeMap.hasOwnProperty(link.text)) { nodeMap[link.text] = nodes.push({ name: link.text, type: 'proper_noun' })-1; } links.push({ source: nodeMap[link.name], target: nodeMap[link.text], value: parseInt(link.count)/10 }); }); res.json({ nodes: nodes, links: links }); }); });
app.get('/:hash', function(req, res){ var hash = req.params.hash; var id = hashids.decode(hash); db.link.find({where: {id: id}}) .then(function(link){ var newCount = link.count + 1; link.updateAttributes({ count: newCount }) res.redirect(link.url); }) });
app.get('/:hash', function(req, res) { var linkId = hashids.decode(req.params.hash); db.link.find({ where: { id: linkId } }) .then(function(link) { res.redirect(link.url); }) .catch(function(error) { res.send('Errors err\'where!'); }); });
app.get('/:hash', function(req, res) { // res.send(req.body.params) to test if stuff is working var linkId = hashids.decode(req.params.hash); db.link.find({ where: { id: linkId } }).then(function(link) { link.clickCount++; link.save().then(function() { res.redirect(link.url); }); }); });
app.get('/:id', function(req, res){ var id = hash.decode(req.params.id); if(!id || !id.length) return res.status(400).end(); var result = db.retrieve(id); if(!result) return res.status(404).end(); db.increment(id); res.redirect(result.url); });
app.get("/:hash", function(req, res) { var linkId = hashids.decode(req.params.hash); db.link.find({ where: { id: linkId } }).then(function(link) { // res.send(link); link.count++; link.save().then(function(count){ res.redirect(link.url); }); }).catch(function(error) { res.send("error"); }); }); // end get(":hash")
app.get('/:hash', function(req,res){ console.log(req.params.hash); var decodeUrl = parseInt(hashids.decode(req.params.hash)); console.log(parseInt(decodeUrl)); db.link.find(decodeUrl).then(function(decoded){ if (decoded) { console.log(decoded) res.redirect(decoded.url); } else { res.redirect('/') } }) })
router.get('/:id',function(req,res) { var myId = parseInt(hashid.decode(req.params.id)); if (typeof myId === 'number') { db.url.find({where:{id:myId}}).then(function(myl){ res.render('preview',{url:myl.link,hash:req.headers.host + '/' +req.params.id,count:myl.count}); }).catch(function(error){ // console.log("Database error:",error); res.render('error',{error:"Your url does not exist!"}); }); } else { // console.log("hash error"); res.render('error',{error:"Your url does not exist!"}); } });
app.get('/:hash', function(req, res) { // decrypt var linkId = hashids.decode(req.params.hash); // find db.link.find({ where: { id: linkId } }).then(function(event) { // redirect var url = event.url event.clicks += 1; event.save().then(function() { res.redirect(url); }); }); });
const decodeID = (id) => { // console.log("[1] decodeID() >> " + id); // 123456, 123+534653+0, Px4xO423c, 123+123456+0+Px4xO423c, Px4xO423c+Px4xO423c if (id === undefined) { id = "0"; } if (Number.isInteger(id)) { id = "" + id; } if (Array.isArray(id)) { // Looks like it is already decoded. assert(Number.isInteger(id[0]) && Number.isInteger(id[1])); return id; } assert(typeof id === "string", "Invalid id " + id); id = id.replace(/\+/g, " "); let parts = id.split(" "); let ids = []; // Concatenate the first two integer ids and the last hash id. Everything // else gets erased. for (let i = 0; i < parts.length; i++) { let n; if (ids.length > 2) { // Found the head, now skip to the last part to get the tail. ids = ids.slice(0, 2); i = parts.length - 1; } if (Number.isInteger(n = +parts[i])) { ids.push(n); } else { ids = ids.concat(hashids.decode(parts[i])); } } // Fix short ids. if (ids.length === 1) { ids = [0, ids[0], 0]; } else if (ids.length === 2) { ids = [0, ids[0], 113, ids[1], 0]; } else if (ids.length === 3 && ids[2] !== 0) { ids = [ids[0], ids[1], 113, ids[2], 0]; } // console.log("[2] decodeID() << " + JSON.stringify(ids)); return ids; };
routes.get('/:id.:ext', function* imageStatic() { const images = this.db.collection('images'); const id = hashids.decode(this.params.id); const image = images.get(id[0]); if (image) { const path = `public/images/${image.name}`; if (this.params.ext === 'json') { this.body = Object.assign({}, image, yield easyimg.info(path)); } else { images.update(id[0], { views: (image.views || 0) + 1 }); yield send(this, path, { maxage: 31536000 }); } } else { this.status = 404; this.body = 'image not found'; } });
app.get('/api/v1/status', function(req, res){ if(!req.query.code) return res.status(400).end(); var id = url.check.test(req.query.code) ? u.parse(req.query.code).path.replace(/\//ig, '') : req.query.code; id = hash.decode(id); if(!id || !id.length) return res.status(400).end(); var result = db.retrieve(id); if(!result) return res.status(404).end(); result.id = hash.encode(result.id); res.json(result); });
router.get('/search/:key', function(req, res, next) { let s = null; Search.forge({ id: hashids.decode(req.params.key)[0] }) .fetch() .then(function(search) { if(!search) { return res.status(404).json({ message: 'Search not found ('+req.params.key+').', status: 404 }); } s = search; return search.topics().fetch(); }) .then(function(topics) { let result = s.toJSON({omitPivot: true}); result.topics = topics.toJSON({omitPivot: true}); res.json(result); }); });
this.decode = params => ( params.response_id? +hashids.decode(params.response_id) : null )
module.exports = function createOrder(req, res) { var database = require('../../database/database'); var queryValues = []; var payment = { "intent" : "sale", "payer" : { "payment_method" : "paypal" }, "redirect_urls" : { "return_url" : app.locals.baseurl + "/success", "cancel_url" : app.locals.baseurl + "/cancel" }, "transactions": [{ "amount" : { "total" : parseInt(req.body.orderInfo.amount), "currency" : req.body.orderInfo.currency }, "description": req.body.orderInfo.description }] }; // req.param is used for get methods req.body.userInfo.user_id = hashids.decode(req.body.userInfo.user_id); queryValues.push(req.body.userInfo); queryValues.push(req.body.orderInfo.amount); queryValues.push(req.body.orderInfo.description); console.log(queryValues); var createOrderQuery = { sql: "INSERT INTO gnomApp.order SET ?;", values: queryValues }; // http://stackoverflow.com/questions/27595796/paypal-integration-with-single-page-app paypal.payment.create(payment, function(error, payment) { if (error) { console.log(error); } else { if(payment.payer.payment_method === 'paypal') { req.paymentId = payment.id; var redirectUrl; console.log("createOrder: Order has been successfully submitted to paypal: " + JSON.stringify(payment)); for(var i = 0; i < payment.links.length; i++) { var link = payment.links[i]; if (link.method === 'REDIRECT') { redirectUrl = link.href; } } console.log("createOrder: Order has been successfully submitted to paypal: " + JSON.stringify(payment)); database.query(createOrderQuery, function(results) { console.log("createOrder: Order has been saved to database: " + JSON.stringify(results)); res.status(200).json(results); }); res.redirect(redirectUrl); } } }); };
id(hash) { if (arguments.length < 1) return false let id = $hash.decode(hash) return (id && id[0]) || false }
app.get('/:hash', function(req, res){ var urlDecoded = hashids.decode(req.params.hash); db.link.findById(urlDecoded[0]).then(function(newUrl){ res.redirect(newUrl.url); }); });
var payload = jwt.verify(token, config.secret, function (err, decoded) { if (err) { res.send({ message: err }); } queryValues = []; queryValues.push(hashids.decode(decoded.id)); var getUserQuery = { sql: "SELECT user_id, user_email, user_password, user_role FROM gnomApp.user WHERE user_id=?;", values: queryValues }; database.query(getUserQuery, function (localUser) { console.log("Instagram Login: Queried database to check for local user with token info."); var checkLocalUser = localUser.length > 0; if (!checkLocalUser) { return res.status(400).send({message: 'Please clear your cache. User not found.'}); } console.log("Instagram Login: User's token has a valid local user account. localUser Result: " + JSON.stringify(localUser)); if (existingInstagramUser && existingInstagramUser.length > 0) { queryValues = []; queryValues.push(body.user.id); queryValues.push(localUser[0].user_email); queryValues.push(localUser[0].user_password); var updateUserQuery = { sql: "UPDATE gnomApp.user SET user_email=?, user_password=? WHERE instagram_id=?;", values: queryValues }; database.query(updateUserQuery, function (updatedLocalUser) { console.log("Instagram Login: User's account has been updated. updatedLocalUser Result: " + JSON.stringify(updatedLocalUser)); queryValues = []; queryValues.push(updatedLocalUser.insertId); var deleteUserQuery = { sql: "DELETE FROM gnomApp.user WHERE user_id=?;", values: queryValues }; database.query(deleteUserQuery, function (deletedUser) { tokenGenerator.generateToken(localUser[0].user_id, localUser[0].user_role, res); }); }); } else { queryValues = []; queryValues.push(body.user.id); queryValues.push(localUser[0].user_id); var saveUserQuery = { sql: "UPDATE gnomApp.user SET instagram_id=? WHERE user_id=?;", values: queryValues }; database.query(saveUserQuery, function (savedLocalUser) { console.log("Instagram Login: Updating user info to add Instagram Login. Result:\n" + JSON.stringify(localUser)); tokenGenerator.generateToken(savedLocalUser.insertId, localUser[0].user_role, res); }); } }); });
app.get("/:hash", function(req,res) { db.links.find(parseInt(hashids.decode(req.params.hash))).then(function(data) { res.redirect(data.url) }) })
this.decode = function (params) { return params.id? +hashids.decode(params.id) : null; }
/* require hashids */ var Hashids = require("hashids"); /* creating class object */ var hashids = new Hashids("this is my salt"); /* encoding several numbers into one id */ var id = hashids.encode(1337, 5, 77, 12345678); /* decoding that id */ var numbers = hashids.decode(id); /* numbers is always an array */ console.log(id, numbers);
app.get("/:hash",function(req,res){ var id = parseInt(hashids.decode(req.params.hash)) db.link.find(id).then(function(link) {res.redirect('http://'+link.url)}) })
decodeBoardHash : function(hash) { return hashId.decode(hash); },