<commit_before>'use strict';

/**
 * Provide the Charm Small widget.
 *
 * @module widgets
 * @submodule juju.widgets.browser.charm-small
 */
YUI.add('browser-charm-slider', function(Y) {

  var ns = Y.namespace('juju.widgets.browser');
  //ns.CharmSmall = Y.Base.create('CharmSmall', Y.Widget, [], {
  //}, {
    //ATTRS: { }
  //});

}, '0.1.0', {
  requires: [
    //'base',
    //'handlebars',
    //'juju-templates',
    //'widget'
  ]
});
<commit_msg>Initialization works.<commit_after>'use strict';

/**
 * Provide the Charm Small widget.
 *
 * @module widgets
 * @submodule juju.widgets.browser.charm-small
 */
YUI.add('browser-charm-slider', function(Y) {

  var ns = Y.namespace('juju.widgets.browser');
  ns.CharmSlider = Y.Base.create('CharmSlider', Y.Widget, [], {
  }, {
    ATTRS: {}
  });

}, '0.1.0', {
  requires: [
    'base',
    //'handlebars',
    //'juju-templates',
    'widget'
  ]
});
<|endoftext|>


<commit_before>'use strict'

module.exports = function (mongoose, config, db) {
    const utils = require('../lib/utils')();

    function articleResponse(article, owner) {
        const user = article.user;
        return {
            id: article.id,
            created_at: article.created_at,
            title: article.title,
            user_id: article.user.id,
            user: {
                id: user.id,
                name: user.name,
                email: user.email
            },
            keywords: article.keywords,
            content: article.content,
            draft: article.draft,
            permission: owner ? article.permission : undefined
        }
    }

    function commentResponse(comment, owner) {
        const user = comment.user;
        return {
            id: comment.id,
            user: {
                id: user.id,
                name: user.name,
                email: user.email
            },
            created_at: comment.created_at,
            content: comment.content,
            ref_id: comment.ref_id,
            hide: comment.hide
        }
    }

    return {
        _checkBlogPermission(permission) {
            return (req, res, next) => {
                if (req.user.isSuperUser()) return next();
                if (req.user.group.blog[permission]) return next();
                utils.error(res, 403);
            }
        },

        _getArticleAndCheckPermission(permission) {
            return (req, res, next) => {
                db.Article.findOne({ id: req.params.articleId })
                    .populate('user')
                    .populate('comments.user').exec((err, article) => {
                        if (err) return utils.error(res, 422, err);
                        if (!article) return utils.error(res, 404);
                        req.article = article;
                        if (req.user.isSuperUser()) return next();
                        if (article.user.id != req.user.id) return next();
                        let target = article.permission.id(req.user.group) || article.permission[0];
                        if (target[permission]) return next();
                        utils.error(res, 403);
                    });
            }
        },

        _getArticleAndCheckPermissionOr(permissions) {
            return (req, res, next) => {
                db.Article.findOne({ id: req.params.articleId })
                    .populate('user')
                    .populate('comments.user').exec((err, article) => {
                        if (err) return utils.error(res, 422, err);
                        if (!article) return utils.error(res, 404);
                        req.article = article;
                        if (article.user.id != req.user.id) return next();
                        let target = article.permission.id(req.user.group) || article.permission[0];
                        if (permissions.filter(permission => target[permission]).count != 0) return next();
                        utils.error(res, 403);
                    });
            }
        },

        _getArticle(req, res, next) {
            db.Article.findOne({ id: req.params.articleId })
                .populate('user')
                .populate('comments.user').exec((err, article) => {
                    if (err) return utils.error(res, 422, err);
                    if (!article) return utils.error(res, 404);
                    req.article = article;
                    next();
                });
        },

        create(req, res) {
            db.Sequence.getNextSequence("articles", (err, nextArticleId) => {
                if (err) return utils.error(res, 422, err);
                const keyword = req.body.keyword || req.body.title;
                const article = db.Article({
                    id: nextArticleId,
                    title: req.body.title,
                    user: req.user,
                    content: req.body.content,
                    keywords: keyword.split(','),
                    permission: req.user.blog.permission,
                    draft: req.body.draft ? req.body.draft : false
                });
                article.save(err => err ?
                    db.Sequence.SequenceRollback("articles", utils.error(res, 422, err.message)) :
                    utils.success(res, "update success!"));
            })
        },
        delete(req, res) {
            if (!req.user.isSuperUser() && req.article.user.id != req.user.id) return utils.error(res, 403);
            req.article.remove(err => err ? utils.error(res, 422)
                : utils.success(res, "delete successful"));
        },
        update(req, res) {
            if (!req.user.isSuperUser() && req.article.user.id != req.user.id) return utils.error(res, 403);

            if (req.body.title) req.article.title = req.body.title;
            if (req.body.content) req.article.price = req.body.content;
            if (req.body.keywords) req.article.keywords = req.body.keywords.split(',');
            if (req.body.permission) {
                try {
                    req.article.permission = JSON.parse(req.body.permission);
                } catch (err) {
                    return utils.error(res, 422, err.message);
                }
            }
            if (req.body.draft) req.article.draft = req.body.draft;

            req.article.save((err, article) => err ? utils.error(res, 422, err.message)
                : utils.success(res, articleResponse(article)));
        },
        get(req, res) {
            const id = req.params.articleId;
            db.Article.findOne({ id }).populate("user").exec((err, article) => {
                if (err) return utils.error(res, 422, err.message);
                if (!article) return utils.error(res, 404);
                if (article.draft && !(req.user && (req.user.isSuperUser() || req.user.id == article.user.id)))
                    return utils.error(res, 422, err.message);
                utils.responseData(res, article.id, article);
            })
        },
        find(req, res) {
            let query = {};
            let sortBy = null;

            sortBy = {};
            sortBy["order_by"] = "created_at";
            sortBy["order_type"] = "desc";
            if (req.query.title) query["title"] = req.query.title;
            if (req.query.user_id) query["user.id"] = req.query.user_id;
            if (req.query.keywords) query["keywords"] = { $in: req.query.keywords.split(',') }
            if (req.query.order_type === "asc") sortBy["order_type"] = req.query.order_type;
            if (req.query.draft) query["draft"] = req.query.draft;

            const queryRequest = db.Article.find(query);
            if (sortBy) {
                var sort = {};
                sort[sortBy["order_by"]] = sortBy["order_type"] === "asc" ? "ascending" : "descending";
                queryRequest.sort(sort);
            }

            queryRequest.populate("user").exec((err, dbResponse) => {
                if (err) return utils.error(res, 422, err.message);
                if (!dbResponse) return utils.error(res, 404);
                let ret = dbResponse
                    .filter(article => !article.draft || (req.user && (req.user.isSuperUser() || req.user.id == article.user.id)))
                    .map(article =>
                        articleResponse(article, req.user && (req.user.isSuperUser() || req.user.id == article.user.id)));
                utils.responseData(res, ret.count, ret);
            })
        },
        Comment: {
            _getComment(req, res, next) {
                let comment = req.article.comments.id(req.params.commentId);
                if (!comment) return utils.error(res, 404);
                req.comment = comment;
                next();
            },

            getAll(req, res) {
                // Only bloggers and commentators can see the hidden comments
                let ret = req.user && (req.user.isSuperUser() || req.article.user.id == req.user.id) ? req.article.comments
                    : req.article.comments.filter(comment => !comment.hide || (req.user && comment.user.id == req.user.id))
                utils.responseData(res, ret.count, ret.map(comment => commentResponse(comment)));
            },

            getSingle(req, res) {
                if (!req.user.isSuperUser()
                    && req.comment.hide
                    && (!req.user || req.article.user.id != req.user.id) // Logged, but not blogger
                    && req.comment.user.id != req.user.id) // Nor is commentator
                    return utils.error(res, 404); // Pretend it does not exist
                utils.responseData(res, "", commentResponse(req.comment));
            },

            create(req, res) {
                if (!req.article.comments) req.article.comments = [];
                if (req.params.commentId
                    && !req.user.isSuperUser()
                    && req.comment.hide
                    && (!req.user || req.article.user.id != req.user.id)
                    && req.comment.user.id != req.user.id)
                    return utils.error(res, 404);
                req.article.comments.push({ user: req.user, content: req.body.content, ref_id: req.comment.id });
                req.article.save(err => err ? utils.error(res, 422, err.message)
                    : utils.responseData(res, "post successful"));
            },

            changeHideState(req, res) {
                if (!req.user.isSuperUser() && (!req.user || req.article.user.id != req.user.id))
                    return utils.error(res, 404); // Pretend it does not exist
                req.comment.hide = !!req.params.hide;
                req.comment.save();
            },

            delete(req, res) {
                req.comment.remove();
                req.article.save(err => err ? utils.error(res, 422, err.message)
                    : utils.responseData(res, "delete successful"));
            }
        }
    }
}<commit_msg>fix id of null<commit_after>'use strict'

module.exports = function (mongoose, config, db) {
    const utils = require('../lib/utils')();

    function articleResponse(article, owner) {
        const user = article.user;
        return {
            id: article.id,
            created_at: article.created_at,
            title: article.title,
            user_id: article.user.id,
            user: {
                id: user.id,
                name: user.name,
                email: user.email
            },
            keywords: article.keywords,
            content: article.content,
            draft: article.draft,
            permission: owner ? article.permission : undefined
        }
    }

    function commentResponse(comment, owner) {
        const user = comment.user;
        return {
            id: comment.id,
            user: {
                id: user.id,
                name: user.name,
                email: user.email
            },
            created_at: comment.created_at,
            content: comment.content,
            ref_id: comment.ref_id,
            hide: comment.hide
        }
    }

    return {
        _checkBlogPermission(permission) {
            return (req, res, next) => {
                if (req.user.isSuperUser()) return next();
                if (req.user.group.blog[permission]) return next();
                utils.error(res, 403);
            }
        },

        _getArticleAndCheckPermission(permission) {
            return (req, res, next) => {
                db.Article.findOne({ id: req.params.articleId })
                    .populate('user')
                    .populate('comments.user').exec((err, article) => {
                        if (err) return utils.error(res, 422, err);
                        if (!article) return utils.error(res, 404);
                        req.article = article;
                        if (req.user.isSuperUser()) return next();
                        if (article.user.id != req.user.id) return next();
                        let target = article.permission.id(req.user.group) || article.permission[0];
                        if (target[permission]) return next();
                        utils.error(res, 403);
                    });
            }
        },

        _getArticleAndCheckPermissionOr(permissions) {
            return (req, res, next) => {
                db.Article.findOne({ id: req.params.articleId })
                    .populate('user')
                    .populate('comments.user').exec((err, article) => {
                        if (err) return utils.error(res, 422, err);
                        if (!article) return utils.error(res, 404);
                        req.article = article;
                        if (article.user.id != req.user.id) return next();
                        let target = article.permission.id(req.user.group) || article.permission[0];
                        if (permissions.filter(permission => target[permission]).count != 0) return next();
                        utils.error(res, 403);
                    });
            }
        },

        _getArticle(req, res, next) {
            db.Article.findOne({ id: req.params.articleId })
                .populate('user')
                .populate('comments.user').exec((err, article) => {
                    if (err) return utils.error(res, 422, err);
                    if (!article) return utils.error(res, 404);
                    req.article = article;
                    next();
                });
        },

        create(req, res) {
            db.Sequence.getNextSequence("articles", (err, nextArticleId) => {
                if (err) return utils.error(res, 422, err);
                const keyword = req.body.keyword || req.body.title;
                const article = db.Article({
                    id: nextArticleId,
                    title: req.body.title,
                    user: req.user,
                    content: req.body.content,
                    keywords: keyword.split(','),
                    permission: req.user.blog.permission,
                    draft: req.body.draft ? req.body.draft : false
                });
                article.save(err => err ?
                    db.Sequence.SequenceRollback("articles", utils.error(res, 422, err.message)) :
                    utils.success(res, "update success!"));
            })
        },
        delete(req, res) {
            if (!req.user.isSuperUser() && req.article.user.id != req.user.id) return utils.error(res, 403);
            req.article.remove(err => err ? utils.error(res, 422)
                : utils.success(res, "delete successful"));
        },
        update(req, res) {
            if (!req.user.isSuperUser() && req.article.user.id != req.user.id) return utils.error(res, 403);

            if (req.body.title) req.article.title = req.body.title;
            if (req.body.content) req.article.price = req.body.content;
            if (req.body.keywords) req.article.keywords = req.body.keywords.split(',');
            if (req.body.permission) {
                try {
                    req.article.permission = JSON.parse(req.body.permission);
                } catch (err) {
                    return utils.error(res, 422, err.message);
                }
            }
            if (req.body.draft) req.article.draft = req.body.draft;

            req.article.save((err, article) => err ? utils.error(res, 422, err.message)
                : utils.success(res, articleResponse(article)));
        },
        get(req, res) {
            const id = req.params.articleId;
            db.Article.findOne({ id }).populate("user").exec((err, article) => {
                if (err) return utils.error(res, 422, err.message);
                if (!article) return utils.error(res, 404);
                if (article.draft && !(req.user && (req.user.isSuperUser() || req.user.id == article.user.id)))
                    return utils.error(res, 422, err.message);
                utils.responseData(res, article.id, article);
            })
        },
        find(req, res) {
            let query = {};
            let sortBy = null;

            sortBy = {};
            sortBy["order_by"] = "created_at";
            sortBy["order_type"] = "desc";
            if (req.query.title) query["title"] = req.query.title;
            if (req.query.user_id) query["user.id"] = req.query.user_id;
            if (req.query.keywords) query["keywords"] = { $in: req.query.keywords.split(',') }
            if (req.query.order_type === "asc") sortBy["order_type"] = req.query.order_type;
            if (req.query.draft) query["draft"] = req.query.draft;

            const queryRequest = db.Article.find(query);
            if (sortBy) {
                var sort = {};
                sort[sortBy["order_by"]] = sortBy["order_type"] === "asc" ? "ascending" : "descending";
                queryRequest.sort(sort);
            }

            queryRequest.populate("user").exec((err, dbResponse) => {
                if (err) return utils.error(res, 422, err.message);
                if (!dbResponse) return utils.error(res, 404);
                let ret = dbResponse
                    .filter(article => !article.draft || (req.user && (req.user.isSuperUser() || req.user.id == article.user.id)))
                    .map(article =>
                        articleResponse(article, req.user && (req.user.isSuperUser() || req.user.id == article.user.id)));
                utils.responseData(res, ret.count, ret);
            })
        },
        Comment: {
            _getComment(req, res, next) {
                let comment = req.article.comments.id(req.params.commentId);
                if (!comment) return utils.error(res, 404);
                req.comment = comment;
                next();
            },

            getAll(req, res) {
                // Only bloggers and commentators can see the hidden comments
                let ret = req.user && (req.user.isSuperUser() || req.article.user.id == req.user.id) ? req.article.comments
                    : req.article.comments.filter(comment => !comment.hide || (req.user && comment.user.id == req.user.id))
                utils.responseData(res, ret.count, ret.map(comment => commentResponse(comment)));
            },

            getSingle(req, res) {
                if (!req.user.isSuperUser()
                    && req.comment.hide
                    && (!req.user || req.article.user.id != req.user.id) // Logged, but not blogger
                    && req.comment.user.id != req.user.id) // Nor is commentator
                    return utils.error(res, 404); // Pretend it does not exist
                utils.responseData(res, "", commentResponse(req.comment));
            },

            create(req, res) {
                if (!req.article.comments) req.article.comments = [];
                if (req.params.commentId
                    && !req.user.isSuperUser()
                    && req.comment.hide
                    && (!req.user || req.article.user.id != req.user.id)
                    && req.comment.user.id != req.user.id)
                    return utils.error(res, 404);
                req.article.comments.push({
                    user: req.user,
                    content: req.body.content,
                    ref_id: req.comment ? req.comment.id : undefined
                });
                req.article.save(err => err ? utils.error(res, 422, err.message)
                    : utils.responseData(res, "post successful"));
            },

            changeHideState(req, res) {
                if (!req.user.isSuperUser() && (!req.user || req.article.user.id != req.user.id))
                    return utils.error(res, 404); // Pretend it does not exist
                req.comment.hide = !!req.params.hide;
                req.comment.save();
            },

            delete(req, res) {
                req.comment.remove();
                req.article.save(err => err ? utils.error(res, 422, err.message)
                    : utils.responseData(res, "delete successful"));
            }
        }
    }
}<|endoftext|>


<commit_before>const express = require('express');
const router = express.Router();

const authHelper = require('../helpers/authentication');
const permissionsHelper = require('../helpers/permissions');
const api = require('../api');

// secure routes
router.use(authHelper.authChecker);

router.get('/', function (req, res, next) {

    const query = req.query.q;
    const action = 'addToLesson';

    const itemsPerPage = (req.query.limit || 9);
    const currentPage = parseInt(req.query.p) || 1;

    // Featured Content
    if (!query) {
        return Promise.all([
            api(req)({
                uri: '/content/resources/',
                qs: {
                    featuredUntil: {
                        $gte: new Date()
                    }
                },
                json: true
            }),
            api(req)({
                uri: '/content/resources/',
                qs: {
                    $sort: {
                        clickCount: -1
                    },
                    $limit: 3
                },
                json: true
            })
        ]).then(([featured, trending]) => {
            return res.render('content/store', {
                title: 'Materialien',
                featuredContent: featured.data,
                trendingContent: trending.data,
                totalCount: trending.total,
                isCourseGroupTopic: req.query.isCourseGroupTopic,
                inline: req.query.inline,
                action
            });
        });
    // Search Results
    } else {
        return api(req)({
            uri: '/content/search/',
            qs: {
                _all: { $match: query },
                $limit: itemsPerPage,
                $skip: itemsPerPage * (currentPage - 1),
            },
            json: true
        }).then(searchResults => {
            const pagination = {
                currentPage,
                numPages: Math.ceil(searchResults.total / itemsPerPage),
                baseUrl: req.baseUrl + '/?' + 'q=' + query + '&p={{page}}'
            };

            return res.render('content/search-results', {
                title: 'Materialien',
                query: query,
                searchResults: searchResults,
                pagination,
                isCourseGroupTopic: req.query.isCourseGroupTopic,
                action
            });
        });
    }
});

router.get('/:id', function (req, res, next) {
    Promise.all([
        api(req).get('/courses/', {
            qs: {
                teacherIds: res.locals.currentUser._id
            }
        }),
        api(req).get('/content/resources/' + req.params.id, {
            json: true
        })
    ]).then(([courses, content]) => {
        // Fix "client" <==> "providerName"
        content.client = content.providerName;
        // Set URL for Redirect
        content.url = '/content/redirect/' + content._id;
        res.json({
            courses: courses,
            content: content
        });
    }).catch(err => {
        next(err);
    });
});

router.get('/redirect/:id', function (req, res, next) {
    return api(req)({
        uri: '/content/redirect/' + req.params.id,
        followRedirect: false,
        resolveWithFullResponse: true,
        simple: false
    }).then(response => {
        if(response.statusCode === 302) {
            res.redirect(response.headers.location);
        } else { // handle non 5xx, e.g. 404
            next();
        }
    }).catch(err => {
        next(err);
    });
});

router.post('/addToLesson', function (req, res, next) {
    api(req).post('/materials/', {
        json: req.body
    }).then(material => {
        api(req).patch('/lessons/' + req.body.lessonId, {
            json: {
                $push: {
                    materialIds: material._id
                }
            }
        }).then(result => {
            res.redirect('/content/?q=' + req.body.query);
        });
    });
});

module.exports = router;
<commit_msg>add courseId to request<commit_after>const express = require('express');
const router = express.Router();

const authHelper = require('../helpers/authentication');
const permissionsHelper = require('../helpers/permissions');
const api = require('../api');

// secure routes
router.use(authHelper.authChecker);

router.get('/', function (req, res, next) {

    const query = req.query.q;
    const action = 'addToLesson';

    const itemsPerPage = (req.query.limit || 9);
    const currentPage = parseInt(req.query.p) || 1;

    // Featured Content
    if (!query) {
        return Promise.all([
            api(req)({
                uri: '/content/resources/',
                qs: {
                    featuredUntil: {
                        $gte: new Date()
                    }
                },
                json: true
            }),
            api(req)({
                uri: '/content/resources/',
                qs: {
                    $sort: {
                        clickCount: -1
                    },
                    $limit: 3
                },
                json: true
            })
        ]).then(([featured, trending]) => {
            return res.render('content/store', {
                title: 'Materialien',
                featuredContent: featured.data,
                trendingContent: trending.data,
                totalCount: trending.total,
                isCourseGroupTopic: req.query.isCourseGroupTopic,
                inline: req.query.inline,
                action
            });
        });
    // Search Results
    } else {
        return api(req)({
            uri: '/content/search/',
            qs: {
                _all: { $match: query },
                $limit: itemsPerPage,
                $skip: itemsPerPage * (currentPage - 1),
            },
            json: true
        }).then(searchResults => {
            const pagination = {
                currentPage,
                numPages: Math.ceil(searchResults.total / itemsPerPage),
                baseUrl: req.baseUrl + '/?' + 'q=' + query + '&p={{page}}'
            };

            return res.render('content/search-results', {
                title: 'Materialien',
                query: query,
                searchResults: searchResults,
                pagination,
                isCourseGroupTopic: req.query.isCourseGroupTopic,
                action
            });
        });
    }
});

router.get('/:id', function (req, res, next) {
    Promise.all([
        api(req).get('/courses/', {
            qs: {
                teacherIds: res.locals.currentUser._id
            }
        }),
        api(req).get('/content/resources/' + req.params.id, {
            json: true
        })
    ]).then(([courses, content]) => {
        // Fix "client" <==> "providerName"
        content.client = content.providerName;
        // Set URL for Redirect
        content.url = '/content/redirect/' + content._id;
        res.json({
            courses: courses,
            content: content
        });
    }).catch(err => {
        next(err);
    });
});

router.get('/redirect/:id', function (req, res, next) {
    return api(req)({
        uri: '/content/redirect/' + req.params.id,
        followRedirect: false,
        resolveWithFullResponse: true,
        simple: false
    }).then(response => {
        if(response.statusCode === 302) {
            res.redirect(response.headers.location);
        } else { // handle non 5xx, e.g. 404
            next();
        }
    }).catch(err => {
        next(err);
    });
});

router.post('/addToLesson', function (req, res, next) {
    api(req).post('/materials/', {
        json: req.body
    }).then(material => {
        api(req).patch('/lessons/' + req.body.lessonId, {
            json: {
                courseId: req.body.courseId,
                $push: {
                    materialIds: material._id
                }
            }
        }).then(result => {
            res.redirect('/content/?q=' + req.body.query);
        });
    });
});

module.exports = router;
<|endoftext|>


<commit_before>"use strict";
var util = require("util");
var fs = require("fs");
var goose = require("../models/mongoose").instance;
var hostnameSchema = require("../models/schema-hostname.js");
var Member = goose.model("Member", hostnameSchema);

module.exports = {
	create: update,
	read: read,
	update: update,
	delete: deleteFn
};

/**
 * @description get an entry from the database
 * @param {object} request
 * @param {object} request.params
 * @param {string} request.params.NAME
 * @param {string} request.params.ADDRESS
 * @return {response} response
 */
function read (req, res) {

	var NAME = req.params.NAME;
	var ADDRESS = getAddress(req);

	if (!req.params.NAME && !req.params.ADDRESS) {
		Member.find({}, respondWithMembers);
	} else {
		fs.readFile(getFilename(NAME, ADDRESS), respondWithFile);
	}

	function respondWithMembers (err, docs) {
		if (err) {
			return res.send(err);
		}

		res.status(200).send(docs);
	}

	function respondWithFile (err, readfileResponse) {

		var fileNotFound = err && err.code === "ENOENT";
		if (fileNotFound) {
			return res.status(404).send({
				errno: err.errno,
				code: err.code
			});
		}

		res.status(200).send(readfileResponse);

	}

}

/**
 * @description Update an entry's IP address or name
 * @param {object} request
 * @param {object} request.params
 * @param {string} request.params.NAME
 * @param {string} request.params.MESSAGE
 * @param {Document} request.body
 * @return {response} response
 */
function update (req, res) {
	var IP = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
	var NAME = req.params.NAME
	var MESSAGE = req.params.MESSAGE;
	var rawData;

	var findMemberCriteria = {
		name: NAME,
		address: IP
	};

	var updateMemberFields = {
		name: NAME,
		address: IP,
		message: MESSAGE
	};

	for (var key in findMemberCriteria) {
		if (findMemberCriteria[key] === null || findMemberCriteria[key] === undefined) {
			delete findMemberCriteria[key];
		}
	}

	req.on("data", save);

	console.log("writing data");

	console.log("the whole request", request);
	console.log("request body? ", request.body);

	Member.findOneAndUpdate(findMemberCriteria,
				updateMemberFields,
				{ new: true, upsert: true },
				respond);

	function save (chunk) {
		console.log("chunkit", chunk);
		rawData = chunk;
	}

	function respond (err, newDoc) {
		console.log("respond: ", err, newDoc);
		newDoc = newDoc || {};

		if (!!rawData) {
			MESSAGE = rawData + "\r";
		}

		console.log("writing file", getFilename(NAME, IP));
		var stream = fs.createWriteStream(getFilename(NAME, IP));
		try {
			stream.write(MESSAGE);
			stream.end();
		} catch (err) {
			console.log("caught err trying to write stream: ", err);
		}

		if (err) {
			console.log("yes ,err. ", err);
			return res.send(err);
		}

		console.log("no err", newDoc);

		return res.status(200).send(newDoc);

	}

}

/**
 * @description delete a row
 * @param {object} request
 * @param {object} request.params
 * @param {string} request.params.NAME
 * @param {string} request.params.ADDRESS
 * @param {object} response
 * @return {response} response
 */
function deleteFn (req, res) {
	var NAME = getName(req);
	var ADDRESS = getAddress(req);

	Member.remove({ name: NAME, address: ADDRESS }, respond);

	function respond (err, docs) {
		if (err) {
			return res.end();
		}

		if (!docs) {
			return res.status(404).send("Not found");
		}

		res.status(200).send(docs.result);
	}

}

function getFilename (entryName, entryAddress) {
	console.log("entryAddress? ", entryAddress);

	entryAddress = entryAddress.replace(/:/g, "-");

	var filename = __dirname.concat("/../").concat("public/hostname/").concat([entryName, entryAddress].join("_")).concat(".html");
	console.log("filename? ", filename);
	return filename;
}

function getName (req) {
	return req.params.NAME || req.body.name || "anonymous";
}

function getAddress (req) {
	return req.params.ADDRESS || req.headers["x-forwarded-for"] || req.connection.remoteAddress;
}

function updateIpAddress (req, res) {
	return res.status(200).send();
}

function updateName (req, res) {
	return res.status(200).send();
}

<commit_msg>fix debugs<commit_after>"use strict";
var util = require("util");
var fs = require("fs");
var goose = require("../models/mongoose").instance;
var hostnameSchema = require("../models/schema-hostname.js");
var Member = goose.model("Member", hostnameSchema);

module.exports = {
	create: update,
	read: read,
	update: update,
	delete: deleteFn
};

/**
 * @description get an entry from the database
 * @param {object} request
 * @param {object} request.params
 * @param {string} request.params.NAME
 * @param {string} request.params.ADDRESS
 * @return {response} response
 */
function read (req, res) {

	var NAME = req.params.NAME;
	var ADDRESS = getAddress(req);

	if (!req.params.NAME && !req.params.ADDRESS) {
		Member.find({}, respondWithMembers);
	} else {
		fs.readFile(getFilename(NAME, ADDRESS), respondWithFile);
	}

	function respondWithMembers (err, docs) {
		if (err) {
			return res.send(err);
		}

		res.status(200).send(docs);
	}

	function respondWithFile (err, readfileResponse) {

		var fileNotFound = err && err.code === "ENOENT";
		if (fileNotFound) {
			return res.status(404).send({
				errno: err.errno,
				code: err.code
			});
		}

		res.status(200).send(readfileResponse);

	}

}

/**
 * @description Update an entry's IP address or name
 * @param {object} request
 * @param {object} request.params
 * @param {string} request.params.NAME
 * @param {string} request.params.MESSAGE
 * @param {Document} request.body
 * @return {response} response
 */
function update (req, res) {
	var IP = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
	var NAME = req.params.NAME
	var MESSAGE = req.params.MESSAGE;
	var rawData;

	var findMemberCriteria = {
		name: NAME,
		address: IP
	};

	var updateMemberFields = {
		name: NAME,
		address: IP,
		message: MESSAGE
	};

	for (var key in findMemberCriteria) {
		if (findMemberCriteria[key] === null || findMemberCriteria[key] === undefined) {
			delete findMemberCriteria[key];
		}
	}

	req.on("data", save);

	console.log("writing data");

	console.log("the whole request", req);
	console.log("request body? ", req.body);

	Member.findOneAndUpdate(findMemberCriteria,
				updateMemberFields,
				{ new: true, upsert: true },
				respond);

	function save (chunk) {
		console.log("chunkit", chunk);
		rawData = chunk;
	}

	function respond (err, newDoc) {
		console.log("respond: ", err, newDoc);
		newDoc = newDoc || {};

		if (!!rawData) {
			MESSAGE = rawData + "\r";
		}

		console.log("writing file", getFilename(NAME, IP));
		var stream = fs.createWriteStream(getFilename(NAME, IP));
		try {
			stream.write(MESSAGE);
			stream.end();
		} catch (err) {
			console.log("caught err trying to write stream: ", err);
		}

		if (err) {
			console.log("yes ,err. ", err);
			return res.send(err);
		}

		console.log("no err", newDoc);

		return res.status(200).send(newDoc);

	}

}

/**
 * @description delete a row
 * @param {object} request
 * @param {object} request.params
 * @param {string} request.params.NAME
 * @param {string} request.params.ADDRESS
 * @param {object} response
 * @return {response} response
 */
function deleteFn (req, res) {
	var NAME = getName(req);
	var ADDRESS = getAddress(req);

	Member.remove({ name: NAME, address: ADDRESS }, respond);

	function respond (err, docs) {
		if (err) {
			return res.end();
		}

		if (!docs) {
			return res.status(404).send("Not found");
		}

		res.status(200).send(docs.result);
	}

}

function getFilename (entryName, entryAddress) {
	console.log("entryAddress? ", entryAddress);

	entryAddress = entryAddress.replace(/:/g, "-");

	var filename = __dirname.concat("/../").concat("public/hostname/").concat([entryName, entryAddress].join("_")).concat(".html");
	console.log("filename? ", filename);
	return filename;
}

function getName (req) {
	return req.params.NAME || req.body.name || "anonymous";
}

function getAddress (req) {
	return req.params.ADDRESS || req.headers["x-forwarded-for"] || req.connection.remoteAddress;
}

function updateIpAddress (req, res) {
	return res.status(200).send();
}

function updateName (req, res) {
	return res.status(200).send();
}

<|endoftext|>


<commit_before>'use strict'

module.exports = function (mongoose, config, db) {
    const utils = require('../lib/utils')();

    function articleResponse(article) {
        const user = article.user;
        return {
            id: article.id,
            created_at: article.created_at,
            title: article.title,
            user_id: article.user.id,
            user: {
                id: user.id,
                name: user.name,
                email: user.email
            },
            keywords: article.keywords,
            content: article.content
        }
    }

    function commentResponse(comment) {
        return {
            id: comment.id,
            user: comment.user,
            content: comment.content,
            ref_id: comment.ref_id,
            hide: hide
        }
    }

    return {
        create(req, res) {
            db.Sequence.getNextSequence("articles", (err, nextArticleId) => {
                if (err) return utils.error(res, 422, err);
                const keyword = req.body.keyword || req.body.title;
                const article = db.Article({
                    id: nextArticleId,
                    title: req.body.title,
                    user: req.user,
                    content: req.body.content,
                    keywords: keyword.split(',')
                });
                article.save(err => err ?
                    utils.error(res, 422, err.message) :
                    utils.success(res, "update success!")
                    );
            })
        },
        delete(req, res) {
            db.Article.findOne({ id: req.params.articleId }).populate('user').exec((err, article) => {
                if (err) return utils.error(res, 422, err);
                if (article.user.id != req.user.id) return utils.error(res, 403, "Forbidden");
                if (!article) return utils.error(res, 404);
                article.remove(err => err ? utils.error(res, 422)
                    : utils.success(res, "delete successful"));
            })
        },
        update(req, res) {
            db.Article.findOne({ id: req.params.articleId }).populate('user').exec((err, article) => {
                if (err) return utils.error(res, 422, err);
                if (!article) return utils.error(res, 404);
                if (article.user.id != req.user.id) return utils.error(res, 403, "Forbidden");

                if (req.body.title) article.title = req.body.title;
                if (req.body.content) article.price = req.body.content;
                if (req.body.keyword) article.keyword = req.body.keyword.split(',');

                article.save((err, article) => utils.success(res, articleResponse(article)));
            });
        },
        get(req, res) {
            const id = req.params.articleId;
            let query = {};
            let sortBy = null;

            if (id) {
                query = { id };
            } else {
                sortBy = {};
                sortBy["order_by"] = "created_at";
                sortBy["order_type"] = "desc";
                if (req.query.title) query["title"] = req.query.title;
                if (req.query.user_id) query["user.id"] = req.query.user_id;
                if (req.query.keyword) query["keyword"] = { $in: req.query.keyword.split(',') }
                if (req.query.order_type === "asc") sortBy["order_type"] = req.query.order_type;
            }

            const queryRequest = db.Article.find(query);
            if (sortBy) {
                var sort = {};
                sort[sortBy["order_by"]] = sortBy["order_type"] === "asc" ? "ascending" : "descending";
                queryRequest.sort(sort);
            }

            queryRequest.populate("user").exec((err, dbResponse) => {
                if (err) return utils.error(res, 422, err.message);
                if (!dbResponse) return utils.error(res, 404);
                utils.responseData(res, dbResponse.count, dbResponse.map(article => articleResponse(article)));
            })
        },
        Comment: {
            preComment(req, res, next) {
                const id = req.params.articleId;
                db.Article.findOne({ id }).populate("user").populate('comments.user').exec((err, article) => {
                    if (err) return utils.error(res, 422, err.message);
                    if (!article) return utils.error(res, 404);
                    req.article = article;
                    next();
                })
            },

            getAll(req, res) {
                // Only bloggers and commentators can see the hidden comments
                let ret = req.user && req.article.user.id == req.user.id ? req.article.comments
                    : req.article.comments.filter(comment => !comment.hide && req.user && comment.user.id != req.user.id)
                utils.responseData(res, ret.count, ret);
            },

            getSingle(req, res) {
                let comment = req.article.comments.id(req.params.commentId);
                if (!comment) return utils.error(res, 404);
                if (comment.hide && !req.user || req.article.user.id != req.user.id && comment.user.id != req.user.id)
                    return utils.error(res, 403, "Forbidden");
                utils.responseData(res, "", comment);
            },

            post(req, res) {
                if (!req.article.comments) req.article.comments = [];
                req.article.comments.push({ user: req.user, content: req.body.content, ref_id: req.params.commentId });
                req.article.save(err => err ? utils.error(res, 422, err.message)
                    : utils.responseData(res, "post successful"));
            },

            delete(req, res) {
                let comment = req.article.comments.id(req.params.commentId);
                if (!comment) return utils.error(res, 404);
                comment.remove();
                req.article.save(err => err ? utils.error(res, 422, err.message)
                    : utils.responseData(res, "post successful"));
            }
        }
    }
}<commit_msg>debug<commit_after>'use strict'

module.exports = function (mongoose, config, db) {
    const utils = require('../lib/utils')();

    function articleResponse(article) {
        const user = article.user;
        return {
            id: article.id,
            created_at: article.created_at,
            title: article.title,
            user_id: article.user.id,
            user: {
                id: user.id,
                name: user.name,
                email: user.email
            },
            keywords: article.keywords,
            content: article.content
        }
    }

    function commentResponse(comment) {
        return {
            id: comment.id,
            user: comment.user,
            content: comment.content,
            ref_id: comment.ref_id,
            hide: hide
        }
    }

    return {
        create(req, res) {
            db.Sequence.getNextSequence("articles", (err, nextArticleId) => {
                if (err) return utils.error(res, 422, err);
                const keyword = req.body.keyword || req.body.title;
                const article = db.Article({
                    id: nextArticleId,
                    title: req.body.title,
                    user: req.user,
                    content: req.body.content,
                    keywords: keyword.split(',')
                });
                article.save(err => err ?
                    utils.error(res, 422, err.message) :
                    utils.success(res, "update success!")
                    );
            })
        },
        delete(req, res) {
            db.Article.findOne({ id: req.params.articleId }).populate('user').exec((err, article) => {
                if (err) return utils.error(res, 422, err);
                if (article.user.id != req.user.id) return utils.error(res, 403, "Forbidden");
                if (!article) return utils.error(res, 404);
                article.remove(err => err ? utils.error(res, 422)
                    : utils.success(res, "delete successful"));
            })
        },
        update(req, res) {
            db.Article.findOne({ id: req.params.articleId }).populate('user').exec((err, article) => {
                if (err) return utils.error(res, 422, err);
                if (!article) return utils.error(res, 404);
                if (article.user.id != req.user.id) return utils.error(res, 403, "Forbidden");

                if (req.body.title) article.title = req.body.title;
                if (req.body.content) article.price = req.body.content;
                if (req.body.keyword) article.keyword = req.body.keyword.split(',');

                article.save((err, article) => utils.success(res, articleResponse(article)));
            });
        },
        get(req, res) {
            const id = req.params.articleId;
            let query = {};
            let sortBy = null;

            if (id) {
                query = { id };
            } else {
                sortBy = {};
                sortBy["order_by"] = "created_at";
                sortBy["order_type"] = "desc";
                if (req.query.title) query["title"] = req.query.title;
                if (req.query.user_id) query["user.id"] = req.query.user_id;
                if (req.query.keyword) query["keyword"] = { $in: req.query.keyword.split(',') }
                if (req.query.order_type === "asc") sortBy["order_type"] = req.query.order_type;
            }

            const queryRequest = db.Article.find(query);
            if (sortBy) {
                var sort = {};
                sort[sortBy["order_by"]] = sortBy["order_type"] === "asc" ? "ascending" : "descending";
                queryRequest.sort(sort);
            }

            queryRequest.populate("user").exec((err, dbResponse) => {
                if (err) return utils.error(res, 422, err.message);
                if (!dbResponse) return utils.error(res, 404);
                utils.responseData(res, dbResponse.count, dbResponse.map(article => articleResponse(article)));
            })
        },
        Comment: {
            preComment(req, res, next) {
                const id = req.params.articleId;
                db.Article.findOne({ id }).populate("user").populate('comments.user').exec((err, article) => {
                    if (err) return utils.error(res, 422, err.message);
                    if (!article) return utils.error(res, 404);
                    req.article = article;
                    next();
                })
            },

            getAll(req, res) {
                // Only bloggers and commentators can see the hidden comments
                console.log(req.article.user.id, req.user.id);
                let ret = req.user && req.article.user.id == req.user.id ? req.article.comments
                    : req.article.comments.filter(comment => !comment.hide && req.user && comment.user.id != req.user.id)
                utils.responseData(res, ret.count, ret);
            },

            getSingle(req, res) {
                let comment = req.article.comments.id(req.params.commentId);
                if (!comment) return utils.error(res, 404);
                if (comment.hide && !req.user || req.article.user.id != req.user.id && comment.user.id != req.user.id)
                    return utils.error(res, 403, "Forbidden");
                utils.responseData(res, "", comment);
            },

            post(req, res) {
                if (!req.article.comments) req.article.comments = [];
                req.article.comments.push({ user: req.user, content: req.body.content, ref_id: req.params.commentId });
                req.article.save(err => err ? utils.error(res, 422, err.message)
                    : utils.responseData(res, "post successful"));
            },

            delete(req, res) {
                let comment = req.article.comments.id(req.params.commentId);
                if (!comment) return utils.error(res, 404);
                comment.remove();
                req.article.save(err => err ? utils.error(res, 422, err.message)
                    : utils.responseData(res, "post successful"));
            }
        }
    }
}<|endoftext|>


<commit_before>(function(window, undefined) {

var Adblocked = function() {

that = this

this.scriptFile = "//pagead2.googlesyndication.com/pagead/show_ads.js";
this.adScript = document.createElement("script")

this.isAdblocked = function() {
  if (typeof(window.google_ad_block) === "undefined") {
    return true;
  }
  else {
    return false;
  }
}
this.done = function() {
  if (that.isAdblocked())  {
    window.adblocked.result = true
  }
  else {
    window.adblocked.result = false
  }
  var error = null;
  window.adblocked.userCallback(error, window.adblocked.result)
}

this.insert = function() {
  var body = document.getElementsByTagName('body')[0]
  var ad = document.createElement("div")
  ad.style.display = "none";
  this.adScript.setAttribute("type","text/javascript")
  this.adScript.setAttribute("src",this.scriptFile)
  body.appendChild(ad).appendChild(this.adScript)
  this.adScript.onload = this.done;
  this.adScript.onerror = this.done;

  return this
};

return this;

}

var checkAds = function(userCallback) {
  window.adblocked.userCallback = userCallback
  var a = new Adblocked()
  // double check, in case google ads are not the ads currently used
  if (that.isAdblocked()) {
    a.insert()
  }
  else {
    a.done()
  }
}

window.adblocked = {
  check : checkAds,
  userCallback : function() {},
  result : "unknown"
}

})(window)
<commit_msg>check if callback was provided<commit_after>(function(window, undefined) {

var Adblocked = function() {

that = this

this.scriptFile = "//pagead2.googlesyndication.com/pagead/show_ads.js";
this.adScript = document.createElement("script")

this.isAdblocked = function() {
  if (typeof(window.google_ad_block) === "undefined") {
    return true;
  }
  else {
    return false;
  }
}
this.done = function() {
  if (that.isAdblocked())  {
    window.adblocked.result = true
  }
  else {
    window.adblocked.result = false
  }
  var error = null;
  window.adblocked.userCallback(error, window.adblocked.result)
}

this.insert = function() {
  var body = document.getElementsByTagName('body')[0]
  var ad = document.createElement("div")
  ad.style.display = "none";
  this.adScript.setAttribute("type","text/javascript")
  this.adScript.setAttribute("src",this.scriptFile)
  body.appendChild(ad).appendChild(this.adScript)
  this.adScript.onload = this.done;
  this.adScript.onerror = this.done;

  return this
};

return this;

}

var checkAds = function(userCallback) {
  if (typeof(userCallback) !== "undefined") {
    window.adblocked.userCallback = userCallback
  }
  var a = new Adblocked()
  // double check, in case google ads are not the ads currently used
  if (that.isAdblocked()) {
    a.insert()
  }
  else {
    a.done()
  }
}

window.adblocked = {
  check : checkAds,
  userCallback : function() {},
  result : "unknown"
}

})(window)
<|endoftext|>


<commit_before>/*Initialise firebase connection*/
var Firebase = require('firebase');
var source = new Firebase('https://publicdata-cryptocurrency.firebaseio.com/');

//maintains latest exchange rate in memory
var rates = {bitcoin: {}, litecoin: {}, dogecoin: {}};
source.on('child_changed', function(snapshot){
    var data = snapshot.val(),
    name = snapshot.name();

    if(!rates[name].live){
        rates[name].live = true;
        console.log('Currency: ' + name + ' now live.');
    }

    rates[name].ask = snapshot.val().ask;
    rates[name].bid = snapshot.val().bid;
    rates[name].last = snapshot.val().last;
});

/*initialise sql connections*/
var sql = require('mssql');
var config = require('../config_dev.json').mssql_users;
var connection = new sql.Connection(config, function(err){
    if(err){
        console.log('Users database connection error:');
        console.log(err);
        process.exit();
    }else{
        console.log('Users database connection established.');
    }
});

/*sign in*/
var signIn = function(identifier, profile, done){
    var id = identifier.slice(identifier.indexOf('=')+1),
    name = profile.name.givenName,
    email = profile.emails[0].value,
    //check if user exists and create if not
    q = "if not exists (select * from traders where identifier = '"+ id +"') begin insert into traders (identifier, name, bitcoin, dogecoin, litecoin, usd, email) values ('"+ id +"', '"+ name +"', 1.0, 1.0, 1.0, 1000.0, '"+ email +"') end";

    var request = connection.request();
    request.query(q, function(err){
        done(err, id);
    });
};

//IMPORTANT! All requests below must be authed by some mechanism before execution!!

/*buy currency*/
var buy = function(currency, quantity, id){
    //check sufficient account balance
    var cost = rates[currency].ask * quantity;
    var q = "declare @var int select @var = id from traders where identifier = '"+ id +"' if (select usd from traders where identifier = '"+ id +"') > "+ cost +" begin update traders set usd = usd - "+ cost +", "+ currency +" = "+ currency +" + "+ quantity +" where identifier = '"+ id +"' insert into transactions (currency, quantity, cost, transactor) values ('"+ currency +"', '"+ quantity +"', '"+ cost +"', @var) return end select usd from traders where identifier = '"+ id +"'";
    var request = connection.request();
    request.query(q, function(err, data){
        if(!err){
            if(!data){
                console.log('Transaction complete.'); //req/response should go here or in else statement following
            }else{
                console.log('Insufficient funds: $', data[0].usd);
            }
        }else{
            console.log('err: ', err);
        }
    });
};

/*sell currency*/
var sell = function(currency, quantity, id){
    var price = rates[currency].bid * quantity;
    var q = "declare @var int select @var = id from traders where identifier = '"+ id +"' if (select "+ currency +" from traders where identifier = '"+ id +"') > "+ quantity +" begin update traders set usd = usd + "+ price +", "+ currency +" = "+ currency +" - "+ quantity +" where identifier = '"+ id +"' insert into transactions (currency, quantity, cost, transactor) values ('"+ currency +"', '"+ quantity +"', '"+ -price +"', @var) return end select "+ currency +" from traders where identifier = '"+ id +"'";
    var request = connection.request();
    request.query(q, function(err, data){
        if(!err){
            if(!data){
                console.log('Transaction complete.'); //req/response should go here or in else statement following
            }else{
                console.log('Insufficient currency: $', data[0][currency]);
            }
        }else{
            console.log('err: ', err);
        }
    });
};

/*delete user permanently*/
var deleteUser = function(id){
    var q = "declare @var int select @var = id from traders where identifier = '"+ id +"'  delete from traders where identifier = '"+ id +"' delete from transactions where id = @var";
    var request = connection.request();
    request.query(q, function(err, data){
        if(!err){
            console.log('User '+ id +' deleted');
        }else{
            console.log('err: ', err);
        }
    });
};

var getAccount = function(id, cb){
    var q = "select * from traders where id = '"+ id +"'";
    var request = connection.request();
    request.query(q, cb); //callback gets passed err, data
};

/*declare exports*/
module.exports.signIn = signIn;
module.exports.buy = buy;
module.exports.sell = sell;
module.exports.deleteUser = deleteUser;
module.exports.getAccount = getAccount;<commit_msg>fixes typo in query<commit_after>/*Initialise firebase connection*/
var Firebase = require('firebase');
var source = new Firebase('https://publicdata-cryptocurrency.firebaseio.com/');

//maintains latest exchange rate in memory
var rates = {bitcoin: {}, litecoin: {}, dogecoin: {}};
source.on('child_changed', function(snapshot){
    var data = snapshot.val(),
    name = snapshot.name();

    if(!rates[name].live){
        rates[name].live = true;
        console.log('Currency: ' + name + ' now live.');
    }

    rates[name].ask = snapshot.val().ask;
    rates[name].bid = snapshot.val().bid;
    rates[name].last = snapshot.val().last;
});

/*initialise sql connections*/
var sql = require('mssql');
var config = require('../config_dev.json').mssql_users;
var connection = new sql.Connection(config, function(err){
    if(err){
        console.log('Users database connection error:');
        console.log(err);
        process.exit();
    }else{
        console.log('Users database connection established.');
    }
});

/*sign in*/
var signIn = function(identifier, profile, done){
    var id = identifier.slice(identifier.indexOf('=')+1),
    name = profile.name.givenName,
    email = profile.emails[0].value,
    //check if user exists and create if not
    q = "if not exists (select * from traders where identifier = '"+ id +"') begin insert into traders (identifier, name, bitcoin, dogecoin, litecoin, usd, email) values ('"+ id +"', '"+ name +"', 1.0, 1.0, 1.0, 1000.0, '"+ email +"') end";

    var request = connection.request();
    request.query(q, function(err){
        done(err, id);
    });
};

//IMPORTANT! All requests below must be authed by some mechanism before execution!!

/*buy currency*/
var buy = function(currency, quantity, id){
    //check sufficient account balance
    var cost = rates[currency].ask * quantity;
    var q = "declare @var int select @var = id from traders where identifier = '"+ id +"' if (select usd from traders where identifier = '"+ id +"') > "+ cost +" begin update traders set usd = usd - "+ cost +", "+ currency +" = "+ currency +" + "+ quantity +" where identifier = '"+ id +"' insert into transactions (currency, quantity, cost, transactor) values ('"+ currency +"', '"+ quantity +"', '"+ cost +"', @var) return end select usd from traders where identifier = '"+ id +"'";
    var request = connection.request();
    request.query(q, function(err, data){
        if(!err){
            if(!data){
                console.log('Transaction complete.'); //req/response should go here or in else statement following
            }else{
                console.log('Insufficient funds: $', data[0].usd);
            }
        }else{
            console.log('err: ', err);
        }
    });
};

/*sell currency*/
var sell = function(currency, quantity, id){
    var price = rates[currency].bid * quantity;
    var q = "declare @var int select @var = id from traders where identifier = '"+ id +"' if (select "+ currency +" from traders where identifier = '"+ id +"') > "+ quantity +" begin update traders set usd = usd + "+ price +", "+ currency +" = "+ currency +" - "+ quantity +" where identifier = '"+ id +"' insert into transactions (currency, quantity, cost, transactor) values ('"+ currency +"', '"+ quantity +"', '"+ -price +"', @var) return end select "+ currency +" from traders where identifier = '"+ id +"'";
    var request = connection.request();
    request.query(q, function(err, data){
        if(!err){
            if(!data){
                console.log('Transaction complete.'); //req/response should go here or in else statement following
            }else{
                console.log('Insufficient currency: $', data[0][currency]);
            }
        }else{
            console.log('err: ', err);
        }
    });
};

/*delete user permanently*/
var deleteUser = function(id){
    var q = "declare @var int select @var = id from traders where identifier = '"+ id +"'  delete from traders where identifier = '"+ id +"' delete from transactions where id = @var";
    var request = connection.request();
    request.query(q, function(err, data){
        if(!err){
            console.log('User '+ id +' deleted');
        }else{
            console.log('err: ', err);
        }
    });
};

var getAccount = function(id, cb){
    var q = "select * from traders where identifier = '"+ id +"'";
    var request = connection.request();
    request.query(q, cb); //callback gets passed err, data
};

/*declare exports*/
module.exports.signIn = signIn;
module.exports.buy = buy;
module.exports.sell = sell;
module.exports.deleteUser = deleteUser;
module.exports.getAccount = getAccount;<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function () {

  'use strict';

  /**
   * @ngdoc controller
   * @name stock-adjustment-creation.controller:StockAdjustmentCreationController
   *
   * @description
   * Controller for managing stock adjustment creation.
   */
  angular
    .module('stock-adjustment-creation')
    .controller('StockAdjustmentCreationController', controller);

  controller.$inject =
    ['$scope', '$state', '$stateParams', '$filter', 'confirmDiscardService', 'program', 'facility',
     'approvedProducts', 'reasons', 'confirmService', 'messageService', 'paginationService',
     'stockAdjustmentCreationService'];

  function controller($scope, $state, $stateParams, $filter, confirmDiscardService, program,
                      facility, approvedProducts, reasons, confirmService, messageService,
                      paginationService, stockAdjustmentCreationService) {
    var vm = this;

    /**
     * @ngdoc property
     * @propertyOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name program
     * @type {Object}
     *
     * @description
     * Holds current program info.
     */
    vm.program = program;

    /**
     * @ngdoc property
     * @propertyOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name facility
     * @type {Object}
     *
     * @description
     * Holds home facility info.
     */
    vm.facility = facility;

    /**
     * @ngdoc property
     * @propertyOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name reasons
     * @type {Array}
     *
     * @description
     * Holds all reasons filtered by adjustment category.
     */
    vm.reasons = reasons.filter(function (reason) {
      return reason.reasonCategory === 'ADJUSTMENT';
    });

    /**
     * @ngdoc method
     * @methodOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name search
     *
     * @description
     * It searches from the total line items with given keyword. If keyword is empty then all line
     * items will be shown.
     */
    vm.search = function () {
      var searchResult = stockAdjustmentCreationService.search(vm.keyword, vm.lineItems);
      vm.displayItems = $filter('orderBy')(searchResult, 'occurredDate');
      paginate(0);
    };

    /**
     * @ngdoc method
     * @methodOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name addProduct
     *
     * @description
     * Add a product for stock adjustment.
     */
    vm.addProduct = function () {
      var occurredDate = new Date();
      occurredDate.setFullYear(vm.occurredDate.getFullYear());
      occurredDate.setMonth(vm.occurredDate.getMonth());
      occurredDate.setDate(vm.occurredDate.getDate());

      vm.lineItems.unshift(Object.assign({
        occurredDate: occurredDate,
        reason: vm.reason,
        reasonFreeText: null
      }, vm.product));
      vm.displayItems = vm.lineItems;
      paginate(0);
    };

    /**
     * @ngdoc method
     * @methodOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name remove
     *
     * @description
     * Remove a line item from added products.
     *
     * @param {Integer} index of line item to be removed.
     */
    vm.remove = function (index) {
      vm.lineItems.splice(index, 1);
      vm.displayItems = vm.lineItems;
      paginate($stateParams.page);
    };

    /**
     * @ngdoc method
     * @methodOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name removeAll
     *
     * @description
     * Remove all added line items.
     */
    vm.removeAll = function () {
      confirmService.confirmDestroy('stockAdjustmentCreation.clearAll', 'stockAdjustmentCreation.clear')
        .then(function () {
          vm.lineItems = [];
        });
      vm.displayItems = vm.lineItems;
      paginate(0);
    };

    /**
     * @ngdoc method
     * @methodOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name validate
     *
     * @description
     * Validate line item quantity.
     *
     * @param {Object} lineItem line item to be validated.
     *
     */
    vm.validate = function (lineItem) {
      if (lineItem.quantity >= 1) {
        lineItem.quantityInvalid = '';
      } else {
        lineItem.quantityInvalid = messageService.get('stockAdjustmentCreation.positiveInteger');
      }
    };

    function paginate(page) {
      paginationService.registerList(null, $stateParams, function () {
        return vm.displayItems;
      }).then(function () {
        $stateParams.page = page;
        $state.go($state.current.name, $stateParams, {reload: false, notify: false});
      });
    }

    function onInit() {
      $stateParams.size = "@@STOCKMANAGEMENT_PAGE_SIZE";

      vm.maxDate = new Date();
      vm.occurredDate = vm.maxDate;
      vm.lineItems = [];
      vm.displayItems = [];

      vm.approvedProducts = approvedProducts.map(function (approvedProduct) {
        return Object.assign({stockOnHand: approvedProduct.stockOnHand}, approvedProduct.orderable);
      });

      confirmDiscardService.register($scope, 'stockmanagement.stockCardSummaries');
    }

    onInit();
  }
})();
<commit_msg>OLMIS-2094 descend order search result<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

(function () {

  'use strict';

  /**
   * @ngdoc controller
   * @name stock-adjustment-creation.controller:StockAdjustmentCreationController
   *
   * @description
   * Controller for managing stock adjustment creation.
   */
  angular
    .module('stock-adjustment-creation')
    .controller('StockAdjustmentCreationController', controller);

  controller.$inject =
    ['$scope', '$state', '$stateParams', '$filter', 'confirmDiscardService', 'program', 'facility',
     'approvedProducts', 'reasons', 'confirmService', 'messageService', 'paginationService',
     'stockAdjustmentCreationService'];

  function controller($scope, $state, $stateParams, $filter, confirmDiscardService, program,
                      facility, approvedProducts, reasons, confirmService, messageService,
                      paginationService, stockAdjustmentCreationService) {
    var vm = this;

    /**
     * @ngdoc property
     * @propertyOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name program
     * @type {Object}
     *
     * @description
     * Holds current program info.
     */
    vm.program = program;

    /**
     * @ngdoc property
     * @propertyOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name facility
     * @type {Object}
     *
     * @description
     * Holds home facility info.
     */
    vm.facility = facility;

    /**
     * @ngdoc property
     * @propertyOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name reasons
     * @type {Array}
     *
     * @description
     * Holds all reasons filtered by adjustment category.
     */
    vm.reasons = reasons.filter(function (reason) {
      return reason.reasonCategory === 'ADJUSTMENT';
    });

    /**
     * @ngdoc method
     * @methodOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name search
     *
     * @description
     * It searches from the total line items with given keyword. If keyword is empty then all line
     * items will be shown.
     */
    vm.search = function () {
      var searchResult = stockAdjustmentCreationService.search(vm.keyword, vm.lineItems);
      vm.displayItems = $filter('orderBy')(searchResult, '-occurredDate');
      paginate(0);
    };

    /**
     * @ngdoc method
     * @methodOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name addProduct
     *
     * @description
     * Add a product for stock adjustment.
     */
    vm.addProduct = function () {
      var occurredDate = new Date();
      occurredDate.setFullYear(vm.occurredDate.getFullYear());
      occurredDate.setMonth(vm.occurredDate.getMonth());
      occurredDate.setDate(vm.occurredDate.getDate());

      vm.lineItems.unshift(Object.assign({
        occurredDate: occurredDate,
        reason: vm.reason,
        reasonFreeText: null
      }, vm.product));
      vm.displayItems = vm.lineItems;
      paginate(0);
    };

    /**
     * @ngdoc method
     * @methodOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name remove
     *
     * @description
     * Remove a line item from added products.
     *
     * @param {Integer} index of line item to be removed.
     */
    vm.remove = function (index) {
      vm.lineItems.splice(index, 1);
      vm.displayItems = vm.lineItems;
      paginate($stateParams.page);
    };

    /**
     * @ngdoc method
     * @methodOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name removeAll
     *
     * @description
     * Remove all added line items.
     */
    vm.removeAll = function () {
      confirmService.confirmDestroy('stockAdjustmentCreation.clearAll', 'stockAdjustmentCreation.clear')
        .then(function () {
          vm.lineItems = [];
        });
      vm.displayItems = vm.lineItems;
      paginate(0);
    };

    /**
     * @ngdoc method
     * @methodOf stock-adjustment-creation.controller:StockAdjustmentCreationController
     * @name validate
     *
     * @description
     * Validate line item quantity.
     *
     * @param {Object} lineItem line item to be validated.
     *
     */
    vm.validate = function (lineItem) {
      if (lineItem.quantity >= 1) {
        lineItem.quantityInvalid = '';
      } else {
        lineItem.quantityInvalid = messageService.get('stockAdjustmentCreation.positiveInteger');
      }
    };

    function paginate(page) {
      paginationService.registerList(null, $stateParams, function () {
        return vm.displayItems;
      }).then(function () {
        $stateParams.page = page;
        $state.go($state.current.name, $stateParams, {reload: false, notify: false});
      });
    }

    function onInit() {
      $stateParams.size = "@@STOCKMANAGEMENT_PAGE_SIZE";

      vm.maxDate = new Date();
      vm.occurredDate = vm.maxDate;
      vm.lineItems = [];
      vm.displayItems = [];

      vm.approvedProducts = approvedProducts.map(function (approvedProduct) {
        return Object.assign({stockOnHand: approvedProduct.stockOnHand}, approvedProduct.orderable);
      });

      confirmDiscardService.register($scope, 'openlmis.stockmanagement.stockCardSummaries');
    }

    onInit();
  }
})();
<|endoftext|>


<commit_before>/**
 * @author David Yzaguirre <dvdyzag@gmail.com>
 *
 * @copyright Copyright (c) 2016, David Yzaguirre, Aníbal Rodríguez
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
var db = require('../models');
exports.listar = function(request, reply){
  if (request.params.idAtleta){
    db.Atleta.findOne({_id: request.params.idAtleta}, function(err, atleta){
      if (err){
        reply({statusCode: 600, error: "Database", message:"Atleta no encontrado"});
      } else if (atleta){
        reply({statusCode:200,atleta:atleta});
      } else {
        reply({statusCode: 600, error: "Database", message:"Atleta no encontrado"});
      }
    });
  } else {
    var querySelector = {};
    if (request.query.edadmax){
      var today = new Date();
      var edadmax = new Date(today);
      var edadmin = new Date(today);
      edadmax.setFullYear(edadmax.getFullYear() - request.query.edadmax);
      edadmin.setFullYear(edadmin.getFullYear() - request.query.edadmin);
      querySelector["$and"] = [
        {nacimiento:{"$gte": edadmax.getTime()}},
        {nacimiento:{"$lte": edadmin.getTime()}}
      ];
    }
    db.Atleta.find(querySelector, function(err, atletas){
      if (err){
        reply({statusCode: 600, error: "Database", message:"Atleta no encontrado"});
      } else if (atletas){
        reply({statusCode:200,atletas:atletas});
      } else {
        reply({statusCode: 600, error: "Database", message:"Atleta no encontrado"});
      }
    });
  }
};
exports.create = function(request, reply){
  new db.Atleta(request.payload).save(function(err, atleta){
    if (err){
      console.log("ATLETAS_CREATE err="+JSON.stringify(err));
      return reply({statusCode:600});
    }
    return reply({statusCode:200, _id: atleta._id});
  });
}
exports.save = function(request, reply){
  var atleta = request.payload;
  atleta.modified = Date.now();
  db.Atleta.update({_id:request.params.idAtleta}, {$set: atleta}, function(err, raw){
    if (err) {
      console.log("ATLETAS_SAVE err="+JSON.stringify(err));
      return reply({statusCode:600});
    }
    return reply({statusCode: 200});
  });
}
exports.delete = function(request, reply){
  db.Atleta.remove({_id:request.params.idAtleta}, function(err){
    if (err) {
      console.log("ATLETAS_DELETE err="+JSON.stringify(err));
      return reply({statusCode:600});
    }
    return reply({statusCode: 200});
  });
}
<commit_msg>Ajuste en rango inferior de edad<commit_after>/**
 * @author David Yzaguirre <dvdyzag@gmail.com>
 *
 * @copyright Copyright (c) 2016, David Yzaguirre, Aníbal Rodríguez
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
var db = require('../models');
exports.listar = function(request, reply){
  if (request.params.idAtleta){
    db.Atleta.findOne({_id: request.params.idAtleta}, function(err, atleta){
      if (err){
        reply({statusCode: 600, error: "Database", message:"Atleta no encontrado"});
      } else if (atleta){
        reply({statusCode:200,atleta:atleta});
      } else {
        reply({statusCode: 600, error: "Database", message:"Atleta no encontrado"});
      }
    });
  } else {
    var querySelector = {};
    if (request.query.edadmax){
      var today = new Date();
      var edadmax = new Date(today);
      var edadmin = new Date(today);
      edadmax.setFullYear(edadmax.getFullYear() - request.query.edadmax - 1);
      edadmin.setFullYear(edadmin.getFullYear() - request.query.edadmin);
      querySelector["$and"] = [
        {nacimiento:{"$gte": edadmax.getTime()}},
        {nacimiento:{"$lte": edadmin.getTime()}}
      ];
    }
    db.Atleta.find(querySelector, function(err, atletas){
      if (err){
        reply({statusCode: 600, error: "Database", message:"Atleta no encontrado"});
      } else if (atletas){
        reply({statusCode:200,atletas:atletas});
      } else {
        reply({statusCode: 600, error: "Database", message:"Atleta no encontrado"});
      }
    });
  }
};
exports.create = function(request, reply){
  new db.Atleta(request.payload).save(function(err, atleta){
    if (err){
      console.log("ATLETAS_CREATE err="+JSON.stringify(err));
      return reply({statusCode:600});
    }
    return reply({statusCode:200, _id: atleta._id});
  });
}
exports.save = function(request, reply){
  var atleta = request.payload;
  atleta.modified = Date.now();
  db.Atleta.update({_id:request.params.idAtleta}, {$set: atleta}, function(err, raw){
    if (err) {
      console.log("ATLETAS_SAVE err="+JSON.stringify(err));
      return reply({statusCode:600});
    }
    return reply({statusCode: 200});
  });
}
exports.delete = function(request, reply){
  db.Atleta.remove({_id:request.params.idAtleta}, function(err){
    if (err) {
      console.log("ATLETAS_DELETE err="+JSON.stringify(err));
      return reply({statusCode:600});
    }
    return reply({statusCode: 200});
  });
}
<|endoftext|>


<commit_before>"use strict";

var request = require('request');
var async = require('async')
var Blog = require('../models/blog').Blog;
var BlogController = require('./blog');
var Blogger = require('../models/blogger').Blogger;

// Callback of form done(profile, error);
exports.getUserProfile = function(passportUser, req, done) {
	if (passportUser.userProvider && passportUser.userId) {
		// This user is registered (so their profile is actually already in req.user, but we need to attach some blogs)
        getBlogs({userId: passportUser.userId, userProvider: passportUser.userProvider}, req, function(page, error) {
            if (error) {
                console.log("[ERROR] %j", error);
                done(null, null, error);
            }
            else {
                done(passportUser, page, null);
            }
        });
	}
	else {
		// Not a registered user
		done(null, null, null);
	}
};

exports.getProfileByVanityUrl = function(vanityUrl, req, done) {
	Blogger.findOne({vanityUrl: vanityUrl}, {emailAddress: 0, __v: 0}, function(error, profile) {
		if (error) {
			console.log("[ERROR] %j", error);
			done(null, null, error);
		}
		else if (profile) {
            // Attach blogs to user to create full profile
            getBlogs({userId: profile.userId, userProvider: profile.userProvider}, req, function(page, error) {
                if (error) {
                    console.log("[ERROR] %j", error);
                    done(null, null, error);
                }
                else {
                    done(profile, page, null);
                }
            });
		}
        else {
            // Not a registered user
            done(null, null, null);
        }
	});
};

exports.getAllProfiles = function(validatedOnly, done) {
	var options = {};
	if (validatedOnly) {
		options.validated = true;
	}

    Blogger.find(options, {emailAddress: 0, __v: 0}, function(error, allBloggers) {
		done(allBloggers, error);
	});
};

function isVanityUrlTaken(vanityUrl, done) {
    Blogger.findOne({vanityUrl: vanityUrl}, function(error, profile) {
        if (error) {
            console.log("[ERROR] %j", error);
            done(true, error);
        }
        else if (profile) {
            done(true, null);
        }
        else {
            done(false, null);
        }
    });
};

function getBlogs(bloggerQuery, req, done) {
    BlogController.getPaginatedBlogs(bloggerQuery, req, function(blogs, pageNumber, showBack, showNext, error) {
        var page = {
            blogs: blogs,
            pageNumber: pageNumber,
            hasLess: showBack,
            hasMore: showNext
        };

        done(page, error);
    });
}

exports.register = function(newBlogger, done) {
    newBlogger.sanitize();
    newBlogger.validate(function(errors) {
        isVanityUrlTaken(newBlogger.vanityUrl, function(taken, error) {
            validateUserSubmittedUrls(newBlogger, function (brokenUrls) {
                if (error) {
                    return done(null, null, error);
                }
                else if (taken) {
                    errors.push({
                        parameter: 'vanityUrl',
                        value: newBlogger.vanityUrl,
                        message: 'Profile name is already taken by another user.'
                    });
                }
                console.log("%j", brokenUrls);

                brokenUrls.forEach(function(brokenUrl) {
                   errors.push({
                       parameter: brokenUrl.name,
                       value: brokenUrl.location,
                       message: 'URL doesnt appear to be correct, or site is broken'
                   });
                });

                console.log("%j", errors);

            	done(newBlogger, errors, null);
            });
        });
    });
};

//Done of form done(brokenUrls);
function validateUserSubmittedUrls (blogger, done) {
    //Everything is valid in terms of syntax. Now lets make sure user submitted URLs are real/live
	var brokenUrls = [];
	var urls = [{name: "feedUrl",     	    location: blogger.feedUrl},
                {name: "blogWebsiteUrl",    location: blogger.blogWebsiteUrl},
                {name: "websiteUrl",        location: blogger.websiteUrl},
                {name: "cvUrl",             location: blogger.cvUrl}];

	async.each(urls, function(url, asyncCallback) {
        if(url.location != "") {
            //Improve this by requesting headers only...
    		request(url.location, function (err, resp) {
    			if(err) {
    				brokenUrls.push(url);
    			}
    			else{
    		    	if (resp.statusCode === 200) {
    		      	    // url exists
    		    	}
    		  	  	else {
    			   	 	brokenUrls.push(url);
    		   	 	}
    	   		}
    			asyncCallback();
    		});
        }
        else {
    		asyncCallback();
        }
	},
	function(err) {
        if(err) {
            console.error("[ERROR] %j", err);
        }
	    done(brokenUrls);
	});
};<commit_msg>More logging<commit_after>"use strict";

var request = require('request');
var async = require('async')
var Blog = require('../models/blog').Blog;
var BlogController = require('./blog');
var Blogger = require('../models/blogger').Blogger;

// Callback of form done(profile, error);
exports.getUserProfile = function(passportUser, req, done) {
	if (passportUser.userProvider && passportUser.userId) {
		// This user is registered (so their profile is actually already in req.user, but we need to attach some blogs)
        getBlogs({userId: passportUser.userId, userProvider: passportUser.userProvider}, req, function(page, error) {
            if (error) {
                console.log("[ERROR] %j", error);
                done(null, null, error);
            }
            else {
                done(passportUser, page, null);
            }
        });
	}
	else {
		// Not a registered user
		done(null, null, null);
	}
};

exports.getProfileByVanityUrl = function(vanityUrl, req, done) {
	Blogger.findOne({vanityUrl: vanityUrl}, {emailAddress: 0, __v: 0}, function(error, profile) {
		if (error) {
			console.log("[ERROR] %j", error);
			done(null, null, error);
		}
		else if (profile) {
            // Attach blogs to user to create full profile
            getBlogs({userId: profile.userId, userProvider: profile.userProvider}, req, function(page, error) {
                if (error) {
                    console.log("[ERROR] %j", error);
                    done(null, null, error);
                }
                else {
                    done(profile, page, null);
                }
            });
		}
        else {
            // Not a registered user
            done(null, null, null);
        }
	});
};

exports.getAllProfiles = function(validatedOnly, done) {
	var options = {};
	if (validatedOnly) {
		options.validated = true;
	}

    Blogger.find(options, {emailAddress: 0, __v: 0}, function(error, allBloggers) {
		done(allBloggers, error);
	});
};

function isVanityUrlTaken(vanityUrl, done) {
    Blogger.findOne({vanityUrl: vanityUrl}, function(error, profile) {
        if (error) {
            console.log("[ERROR] %j", error);
            done(true, error);
        }
        else if (profile) {
            done(true, null);
        }
        else {
            done(false, null);
        }
    });
};

function getBlogs(bloggerQuery, req, done) {
    BlogController.getPaginatedBlogs(bloggerQuery, req, function(blogs, pageNumber, showBack, showNext, error) {
        var page = {
            blogs: blogs,
            pageNumber: pageNumber,
            hasLess: showBack,
            hasMore: showNext
        };

        done(page, error);
    });
}

exports.register = function(newBlogger, done) {
    newBlogger.sanitize();
    newBlogger.validate(function(errors) {
        isVanityUrlTaken(newBlogger.vanityUrl, function(taken, error) {
            validateUserSubmittedUrls(newBlogger, function (brokenUrls) {
                if (error) {
                    return done(null, null, error);
                }
                else if (taken) {
                    errors.push({
                        parameter: 'vanityUrl',
                        value: newBlogger.vanityUrl,
                        message: 'Profile name is already taken by another user.'
                    });
                }
                console.log("%j", brokenUrls);

                brokenUrls.forEach(function(brokenUrl) {
                   errors.push({
                       parameter: brokenUrl.name,
                       value: brokenUrl.location,
                       message: 'URL doesnt appear to be correct, or site is broken'
                   });
                });

                console.log("%j", errors);

            	done(newBlogger, errors, null);
            });
        });
    });
};

//Done of form done(brokenUrls);
function validateUserSubmittedUrls (blogger, done) {
    //Everything is valid in terms of syntax. Now lets make sure user submitted URLs are real/live
	var brokenUrls = [];
	var urls = [{name: "feedUrl",     	    location: blogger.feedUrl},
                {name: "blogWebsiteUrl",    location: blogger.blogWebsiteUrl},
                {name: "websiteUrl",        location: blogger.websiteUrl},
                {name: "cvUrl",             location: blogger.cvUrl}];

	async.each(urls, function(url, asyncCallback) {
        if(url.location != "") {
            //Improve this by requesting headers only...
    		request(url.location, function (err, resp) {
    			if(err) {
                    console.log("%j broken", url);
    				brokenUrls.push(url);
    			}
    			else{
    		    	if (resp.statusCode === 200) {
                        console.log("%j ok", url);
    		      	    // url exists
    		    	}
    		  	  	else {
                        console.log("%j broken", url);
    			   	 	brokenUrls.push(url);
    		   	 	}
    	   		}
    			asyncCallback();
    		});
        }
        else {
    		asyncCallback();
        }
	},
	function(err) {
        if(err) {
            console.error("[ERROR] %j", err);
        }
        console.log("BROKEN URLS %j", brokenUrls);
	    done(brokenUrls);
	});
};<|endoftext|>