<commit_before>// #DROPZONE#
// This script implements the dropzone settings
'use strict';

/* globals Dropzone, Cl, django */
(function ($) {
    $(function () {
        var submitNum = 0;
        var maxSubmitNum = 0;
        var dropzoneInstances = [];
        var dropzoneBase = $('.js-filer-dropzone-base');
        var dropzoneSelector = '.js-filer-dropzone';
        var dropzones;
        var infoMessageClass = 'js-filer-dropzone-info-message';
        var infoMessage = $('.' + infoMessageClass);
        var folderName = $('.js-filer-dropzone-folder-name');
        var uploadInfoContainer = $('.js-filer-dropzone-upload-info-container');
        var uploadInfo = $('.js-filer-dropzone-upload-info');
        var uploadWelcome = $('.js-filer-dropzone-upload-welcome');
        var uploadNumber = $('.js-filer-dropzone-upload-number');
        var uploadCount = $('.js-filer-upload-count');
        var uploadText = $('.js-filer-upload-text');
        var uploadFileNameSelector = '.js-filer-dropzone-file-name';
        var uploadProgressSelector = '.js-filer-dropzone-progress';
        var uploadSuccess = $('.js-filer-dropzone-upload-success');
        var uploadCanceled = $('.js-filer-dropzone-upload-canceled');
        var cancelUpload = $('.js-filer-dropzone-cancel');
        var dragHoverClass = 'dz-drag-hover';
        var dataUploaderConnections = 'max-uploader-connections';
        var dragHoverBorder = $('.drag-hover-border');
        // var dataMaxFileSize = 'max-file-size';
        var hiddenClass = 'hidden';
        var hideMessageTimeout;
        var hasErrors = false;
        var baseUrl;
        var baseFolderTitle;
        var updateUploadNumber = function () {
            uploadNumber.text(maxSubmitNum - submitNum + '/' + maxSubmitNum);
            uploadText.removeClass('hidden');
            uploadCount.removeClass('hidden');
        };
        var destroyDropzones = function () {
            $.each(dropzoneInstances, function (index) {
                dropzoneInstances[index].destroy();
            });
        };
        var getElementByFile = function (file, url) {
            return $(document.getElementById(
                'file-' +
                encodeURIComponent(file.name) +
                file.size +
                file.lastModified +
                url
            ));
        };

        if (dropzoneBase && dropzoneBase.length) {
            baseUrl = dropzoneBase.data('url');
            baseFolderTitle = dropzoneBase.data('folder-name');

            $('body').data('url', baseUrl).data('folder-name', baseFolderTitle).addClass('js-filer-dropzone');
        }

        Cl.mediator.subscribe('filer-upload-in-progress', destroyDropzones);

        dropzones = $(dropzoneSelector);

        if (dropzones.length && Dropzone) {
            Dropzone.autoDiscover = false;
            dropzones.each(function () {
                var dropzone = $(this);
                var dropzoneUrl = $(this).data('url');
                var dropzoneInstance = new Dropzone(this, {
                    url: dropzoneUrl,
                    paramName: 'file',
                    maxFiles: 100,
                    // for now disabled as we don't have the correct file size limit
                    // maxFilesize: dropzone.data(dataMaxFileSize) || 20, // MB
                    previewTemplate: '

',
                    clickable: false,
                    addRemoveLinks: false,
                    parallelUploads: dropzone.data(dataUploaderConnections) || 3,
                    accept: function (file, done) {
                        var uploadInfoClone;

                        Cl.mediator.remove('filer-upload-in-progress', destroyDropzones);
                        Cl.mediator.publish('filer-upload-in-progress');

                        clearTimeout(hideMessageTimeout);
                        uploadWelcome.addClass(hiddenClass);
                        cancelUpload.removeClass(hiddenClass);

                        if (getElementByFile(file, dropzoneUrl).length) {
                            done('duplicate');
                        } else {
                            uploadInfoClone = uploadInfo.clone();

                            uploadInfoClone.find(uploadFileNameSelector).text(file.name);
                            uploadInfoClone.find(uploadProgressSelector).width(0);
                            uploadInfoClone
                                .attr(
                                    'id',
                                    'file-' +
                                        encodeURIComponent(file.name) +
                                        file.size +
                                        file.lastModified +
                                        dropzoneUrl
                                )
                                .appendTo(uploadInfoContainer);

                            submitNum++;
                            maxSubmitNum++;
                            updateUploadNumber();
                            done();
                        }

                        dropzones.removeClass('reset-hover');
                        infoMessage.removeClass(hiddenClass);
                        dropzones.removeClass(dragHoverClass);
                    },
                    dragover: function (dragEvent) {
                        var folderTitle = $(dragEvent.target).closest(dropzoneSelector).data('folder-name');
                        var dropzoneFolder = dropzone.hasClass('js-filer-dropzone-folder');
                        var dropzoneBoundingRect = dropzone[0].getBoundingClientRect();
                        var dropzonePosition = {
                            top: dropzoneBoundingRect.top,
                            bottom: dropzoneBoundingRect.bottom,
                            width: dropzoneBoundingRect.width,
                            height: dropzoneBoundingRect.height
                        };
                        if (dropzoneFolder) {
                            dragHoverBorder.css(dropzonePosition);
                        }

                        $(dropzones).addClass('reset-hover');
                        uploadSuccess.addClass(hiddenClass);
                        infoMessage.removeClass(hiddenClass);
                        dropzone.addClass(dragHoverClass).removeClass('reset-hover');

                        folderName.text(folderTitle);
                    },
                    dragleave: function () {
                        clearTimeout(hideMessageTimeout);
                        hideMessageTimeout = setTimeout(function () {
                            infoMessage.addClass(hiddenClass);
                        }, 1000);

                        infoMessage.removeClass(hiddenClass);
                        dropzones.removeClass(dragHoverClass);
                        dragHoverBorder.css({ top: '', bottom: '', width: '', height: ''});

                    },
                    sending: function (file) {
                        getElementByFile(file, dropzoneUrl).removeClass(hiddenClass);
                    },
                    uploadprogress: function (file, progress) {
                        getElementByFile(file, dropzoneUrl).find(uploadProgressSelector).width(progress + '%');
                    },
                    success: function (file) {
                        submitNum--;
                        updateUploadNumber();
                        getElementByFile(file, dropzoneUrl).remove();
                    },
                    queuecomplete: function () {
                        if (submitNum !== 0) {
                            return;
                        }

                        updateUploadNumber();

                        cancelUpload.addClass(hiddenClass);
                        uploadInfo.addClass(hiddenClass);

                        if (hasErrors) {
                            uploadNumber.addClass(hiddenClass);
                            setTimeout(function () {
                                window.location.reload();
                            }, 1000);
                        } else {
                            uploadSuccess.removeClass(hiddenClass);
                            window.location.reload();
                        }
                    },
                    error: function (file, errorText) {
                        updateUploadNumber();
                        if (errorText === 'duplicate') {
                            return;
                        }
                        hasErrors = true;
                        if (window.showError) {
                            window.showError(file.name + ': ' + errorText);
                        }
                    }
                });
                dropzoneInstances.push(dropzoneInstance);
                cancelUpload.on('click', function (clickEvent) {
                    clickEvent.preventDefault();
                    cancelUpload.addClass(hiddenClass);
                    uploadCanceled.removeClass(hiddenClass);
                    dropzoneInstance.removeAllFiles(true);
                });
            });
        }
    });
})(django.jQuery);
<commit_msg>reset with value 0<commit_after>// #DROPZONE#
// This script implements the dropzone settings
'use strict';

/* globals Dropzone, Cl, django */
(function ($) {
    $(function () {
        var submitNum = 0;
        var maxSubmitNum = 0;
        var dropzoneInstances = [];
        var dropzoneBase = $('.js-filer-dropzone-base');
        var dropzoneSelector = '.js-filer-dropzone';
        var dropzones;
        var infoMessageClass = 'js-filer-dropzone-info-message';
        var infoMessage = $('.' + infoMessageClass);
        var folderName = $('.js-filer-dropzone-folder-name');
        var uploadInfoContainer = $('.js-filer-dropzone-upload-info-container');
        var uploadInfo = $('.js-filer-dropzone-upload-info');
        var uploadWelcome = $('.js-filer-dropzone-upload-welcome');
        var uploadNumber = $('.js-filer-dropzone-upload-number');
        var uploadCount = $('.js-filer-upload-count');
        var uploadText = $('.js-filer-upload-text');
        var uploadFileNameSelector = '.js-filer-dropzone-file-name';
        var uploadProgressSelector = '.js-filer-dropzone-progress';
        var uploadSuccess = $('.js-filer-dropzone-upload-success');
        var uploadCanceled = $('.js-filer-dropzone-upload-canceled');
        var cancelUpload = $('.js-filer-dropzone-cancel');
        var dragHoverClass = 'dz-drag-hover';
        var dataUploaderConnections = 'max-uploader-connections';
        var dragHoverBorder = $('.drag-hover-border');
        // var dataMaxFileSize = 'max-file-size';
        var hiddenClass = 'hidden';
        var hideMessageTimeout;
        var hasErrors = false;
        var baseUrl;
        var baseFolderTitle;
        var updateUploadNumber = function () {
            uploadNumber.text(maxSubmitNum - submitNum + '/' + maxSubmitNum);
            uploadText.removeClass('hidden');
            uploadCount.removeClass('hidden');
        };
        var destroyDropzones = function () {
            $.each(dropzoneInstances, function (index) {
                dropzoneInstances[index].destroy();
            });
        };
        var getElementByFile = function (file, url) {
            return $(document.getElementById(
                'file-' +
                encodeURIComponent(file.name) +
                file.size +
                file.lastModified +
                url
            ));
        };

        if (dropzoneBase && dropzoneBase.length) {
            baseUrl = dropzoneBase.data('url');
            baseFolderTitle = dropzoneBase.data('folder-name');

            $('body').data('url', baseUrl).data('folder-name', baseFolderTitle).addClass('js-filer-dropzone');
        }

        Cl.mediator.subscribe('filer-upload-in-progress', destroyDropzones);

        dropzones = $(dropzoneSelector);

        if (dropzones.length && Dropzone) {
            Dropzone.autoDiscover = false;
            dropzones.each(function () {
                var dropzone = $(this);
                var dropzoneUrl = $(this).data('url');
                var dropzoneInstance = new Dropzone(this, {
                    url: dropzoneUrl,
                    paramName: 'file',
                    maxFiles: 100,
                    // for now disabled as we don't have the correct file size limit
                    // maxFilesize: dropzone.data(dataMaxFileSize) || 20, // MB
                    previewTemplate: '

',
                    clickable: false,
                    addRemoveLinks: false,
                    parallelUploads: dropzone.data(dataUploaderConnections) || 3,
                    accept: function (file, done) {
                        var uploadInfoClone;

                        Cl.mediator.remove('filer-upload-in-progress', destroyDropzones);
                        Cl.mediator.publish('filer-upload-in-progress');

                        clearTimeout(hideMessageTimeout);
                        uploadWelcome.addClass(hiddenClass);
                        cancelUpload.removeClass(hiddenClass);

                        if (getElementByFile(file, dropzoneUrl).length) {
                            done('duplicate');
                        } else {
                            uploadInfoClone = uploadInfo.clone();

                            uploadInfoClone.find(uploadFileNameSelector).text(file.name);
                            uploadInfoClone.find(uploadProgressSelector).width(0);
                            uploadInfoClone
                                .attr(
                                    'id',
                                    'file-' +
                                        encodeURIComponent(file.name) +
                                        file.size +
                                        file.lastModified +
                                        dropzoneUrl
                                )
                                .appendTo(uploadInfoContainer);

                            submitNum++;
                            maxSubmitNum++;
                            updateUploadNumber();
                            done();
                        }

                        dropzones.removeClass('reset-hover');
                        infoMessage.removeClass(hiddenClass);
                        dropzones.removeClass(dragHoverClass);
                    },
                    dragover: function (dragEvent) {
                        var folderTitle = $(dragEvent.target).closest(dropzoneSelector).data('folder-name');
                        var dropzoneFolder = dropzone.hasClass('js-filer-dropzone-folder');
                        var dropzoneBoundingRect = dropzone[0].getBoundingClientRect();
                        var dropzonePosition = {
                            top: dropzoneBoundingRect.top,
                            bottom: dropzoneBoundingRect.bottom,
                            width: dropzoneBoundingRect.width,
                            height: dropzoneBoundingRect.height
                        };
                        if (dropzoneFolder) {
                            dragHoverBorder.css(dropzonePosition);
                        }

                        $(dropzones).addClass('reset-hover');
                        uploadSuccess.addClass(hiddenClass);
                        infoMessage.removeClass(hiddenClass);
                        dropzone.addClass(dragHoverClass).removeClass('reset-hover');

                        folderName.text(folderTitle);
                    },
                    dragleave: function () {
                        clearTimeout(hideMessageTimeout);
                        hideMessageTimeout = setTimeout(function () {
                            infoMessage.addClass(hiddenClass);
                        }, 1000);

                        infoMessage.removeClass(hiddenClass);
                        dropzones.removeClass(dragHoverClass);
                        dragHoverBorder.css({ top: '0', bottom: '0', width: '0', height: '0' });

                    },
                    sending: function (file) {
                        getElementByFile(file, dropzoneUrl).removeClass(hiddenClass);
                    },
                    uploadprogress: function (file, progress) {
                        getElementByFile(file, dropzoneUrl).find(uploadProgressSelector).width(progress + '%');
                    },
                    success: function (file) {
                        submitNum--;
                        updateUploadNumber();
                        getElementByFile(file, dropzoneUrl).remove();
                    },
                    queuecomplete: function () {
                        if (submitNum !== 0) {
                            return;
                        }

                        updateUploadNumber();

                        cancelUpload.addClass(hiddenClass);
                        uploadInfo.addClass(hiddenClass);

                        if (hasErrors) {
                            uploadNumber.addClass(hiddenClass);
                            setTimeout(function () {
                                window.location.reload();
                            }, 1000);
                        } else {
                            uploadSuccess.removeClass(hiddenClass);
                            window.location.reload();
                        }
                    },
                    error: function (file, errorText) {
                        updateUploadNumber();
                        if (errorText === 'duplicate') {
                            return;
                        }
                        hasErrors = true;
                        if (window.showError) {
                            window.showError(file.name + ': ' + errorText);
                        }
                    }
                });
                dropzoneInstances.push(dropzoneInstance);
                cancelUpload.on('click', function (clickEvent) {
                    clickEvent.preventDefault();
                    cancelUpload.addClass(hiddenClass);
                    uploadCanceled.removeClass(hiddenClass);
                    dropzoneInstance.removeAllFiles(true);
                });
            });
        }
    });
})(django.jQuery);
<|endoftext|>


<commit_before>import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './components/app'
import configureStore from './store/configureStore'
import injectTapEventPlugin from 'react-tap-event-plugin'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'
import getMuiTheme from 'material-ui/styles/getMuiTheme'
import { addRequest, addResponse } from './actions'
import perf from 'react-addons-perf'
import { ipcRenderer } from 'electron'
import { Router, IndexRoute, Route, createMemoryHistory } from 'react-router'
import RequestsContainer from './components/requests'
import RequestDetailsContainer from './components/response-details'
import title from './components/title'

injectTapEventPlugin()

title()

ipcRenderer.on('add-request', (e, request) => {
  store.dispatch(addRequest(request))
})

ipcRenderer.on('add-response', (e, response) => {
  store.dispatch(addResponse(response))
})

Object.defineProperty(window, 'perf', { get: () => perf })
const store = configureStore()

const theme = getMuiTheme(darkBaseTheme)
console.log(theme)
theme.appBar.height = 32
theme.toolbar.backgroundColor = theme.palette.canvasColor
theme.svgIcon.color = theme.palette.primary3Color

const history = createMemoryHistory('/requests')
render(
  <Provider store={store}>
    <MuiThemeProvider muiTheme={theme}>
      <Router history={history}>
        <Route path='/' component={App}>
          <Route path='requests'>
            <IndexRoute component={RequestsContainer} label='Requests' />
            <Route path=':id' component={RequestDetailsContainer} label='Details' />
          </Route>
        </Route>
      </Router>
    </MuiThemeProvider>
  </Provider>, document.getElementById('mount')
)
<commit_msg>Remove log statement.<commit_after>import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './components/app'
import configureStore from './store/configureStore'
import injectTapEventPlugin from 'react-tap-event-plugin'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'
import getMuiTheme from 'material-ui/styles/getMuiTheme'
import { addRequest, addResponse } from './actions'
import perf from 'react-addons-perf'
import { ipcRenderer } from 'electron'
import { Router, IndexRoute, Route, createMemoryHistory } from 'react-router'
import RequestsContainer from './components/requests'
import RequestDetailsContainer from './components/response-details'
import title from './components/title'

injectTapEventPlugin()

title()

ipcRenderer.on('add-request', (e, request) => {
  store.dispatch(addRequest(request))
})

ipcRenderer.on('add-response', (e, response) => {
  store.dispatch(addResponse(response))
})

Object.defineProperty(window, 'perf', { get: () => perf })
const store = configureStore()

const theme = getMuiTheme(darkBaseTheme)
theme.appBar.height = 32
theme.toolbar.backgroundColor = theme.palette.canvasColor
theme.svgIcon.color = theme.palette.primary3Color

const history = createMemoryHistory('/requests')
render(
  <Provider store={store}>
    <MuiThemeProvider muiTheme={theme}>
      <Router history={history}>
        <Route path='/' component={App}>
          <Route path='requests'>
            <IndexRoute component={RequestsContainer} label='Requests' />
            <Route path=':id' component={RequestDetailsContainer} label='Details' />
          </Route>
        </Route>
      </Router>
    </MuiThemeProvider>
  </Provider>, document.getElementById('mount')
)
<|endoftext|>


<commit_before>/**
* This function configures the routes of the entire application.
* @param  {express} app An instance of the express app to be configured.
* @ignore
*/

var AuthController = require('../controllers/AuthController');
var log            = require('../middlewares/LogMiddleware');
var CommitteeController = require('../controllers/CommitteeController');

module.exports = function(app) {

    /* initializing the log record */
    app.use(log.init);

    /************************
    *                       *
    * Authentication routes *
    *                       *
    ************************/
    require('./AuthResource')(app);

    /**************
    *             *
    * User routes *
    *             *
    ***************/
    require('./UserResource')(app);

    /***************************
    *                          *
    * CommitteeResource routes *
    *                          *
    ****************************/

    require('./CommitteeResource')(app);
    /*====================================================================================================================================*/

    /* any other request will be treated as not found (404) */
    app.use(function(req, res, next) {
        if(!res.headersSent){
            res.status(404).json({
                status:'failed',
                message: 'The requested route was not found.'
            });
        }

        next();
    });

    /* saving the log record */
    app.use(log.save);
};
<commit_msg>allowed localhost to make cross origin requests<commit_after>/**
* This function configures the routes of the entire application.
* @param  {express} app An instance of the express app to be configured.
* @ignore
*/

var AuthController = require('../controllers/AuthController');
var log            = require('../middlewares/LogMiddleware');
var CommitteeController = require('../controllers/CommitteeController');

module.exports = function(app) {

    /* allowing cross origin requests */
    app.use(function(req, res, next) {
        res.header('Access-Control-Allow-Origin', "localhost");
    });

    /* initializing the log record */
    app.use(log.init);

    /************************
    *                       *
    * Authentication routes *
    *                       *
    ************************/
    require('./AuthResource')(app);

    /**************
    *             *
    * User routes *
    *             *
    ***************/
    require('./UserResource')(app);

    /***************************
    *                          *
    * CommitteeResource routes *
    *                          *
    ****************************/

    require('./CommitteeResource')(app);
    /*====================================================================================================================================*/

    /* any other request will be treated as not found (404) */
    app.use(function(req, res, next) {
        if(!res.headersSent){
            res.status(404).json({
                status:'failed',
                message: 'The requested route was not found.'
            });
        }

        next();
    });

    /* saving the log record */
    app.use(log.save);
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var pgb = require('../pg-binding');
var common = require('../common.js');
var ctrlCommon = require('../controllers/common.js');

var Q = require('q');

/**
 * @api {get} /custom/get_parcels_list Parcel/Num relationships List
 * @apiName custom_get_parcels_list
 * @apiGroup Custom
 *
 * @apiParam {String} tenure_type Options: own, lease, occupy, informal occupy
 * @apiParamExample  Query String Example:
 *  curl -i http://localhost/custom/get_parcels_list?tenure_type=own,lease
 * @apiSuccess {Object} response A feature collection with zero to many features
 * @apiSuccess {String} response.type "Feature Collection"
 * @apiSuccess {Object[]} response.features An array of feature objects
 * @apiSuccess {String} response.features.type "Feature"
 * @apiSuccess {Object} response.features.geometry GeoJSON geometry object
 * @apiSuccess {Object} response.features.properties GeoJSON feature's properties
 * @apiSuccess {Integer} response.features.properties.id parcel id
 * @apiSuccess {Timestamp} response.features.properties.time_created timestamp with timezone
 * @apiSuccess {Numeric} response.features.properties.area area of parcel geometry
 * @apiSuccess {String} response.features.properties.tenure_type type of relationship tenure
 * @apiSuccess {Integer} response.features.properties.num_relationships number of associated relationships
 * @apiExample {curl} Example usage:
 *     curl -i http://localhost/custom_get_parcels_list
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *
 * {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": null,
            "properties": {
                "id": 45,
                "time_created": "2015-08-24T14:03:27.144363-07:00",
                "area": null,
                "tenure_type": "own",
                "num_relationships": 6
            }
        },
        {
            "type": "Feature",
            "geometry": null,
            "properties": {
                "id": 44,
                "time_created": "2015-08-24T14:03:27.144363-07:00",
                "area": null,
                "tenure_type": "lease",
                "num_relationships": 5
            }
        },
        {
            "type": "Feature",
            "geometry": null,
            "properties": {
                "id": 43,
                "time_created": "2015-08-24T14:03:27.144363-07:00",
                "area": null,
                "tenure_type": "occupy",
                "num_relationships": 2
            }
        }
    ]
}
 *
 * */
router.get('/get_parcels_list', common.parseQueryOptions, function(req, res, next) {

    var args = common.getArguments(req);
    var whereClause = '';
    var obj = {};

    if (args.tenure_type) {
        obj = createTenureTypeWhereClause(args.tenure_type);
        whereClause = 'WHERE ' + obj.str + '';
    } else {
        obj.uriList = [];
    }

    req.queryModifiers.sort_by = req.queryModifiers.sort_by || "time_created,id";
    req.queryModifiers.sort_dir = req.queryModifiers.sort_dir || "DESC";

    ctrlCommon.getAll("show_parcels_list", {queryModifiers: req.queryModifiers, outputFormat: 'GeoJSON', whereClause: whereClause, whereClauseValues: obj.uriList})
        .then(function(result){

            res.status(200).json(result[0].response);

        })
        .catch(function(err){
            next(err);
        })
        .done();

});

function createTenureTypeWhereClause(arr) {

    var obj = {};

    obj.uriList = arr.split(',');

    obj.str = obj.uriList.map(function (val, i) {

            return 'tenure_type::text[] @> ARRAY[$' + (i + 1) + ']';

        })
        .join(' OR ');

    return obj;
}

/**
 * @api {get} /custom/get_parcel_details/:id Request parcel details for UI rendering
 * @apiName GetParcelDetails
 * @apiGroup Custom
 *
 * @apiParam {Number} id parcel's unique ID.
 *
 *
 * @apiSuccess {Object} response A feature collection with one feature representing a parcel
 * @apiSuccess {String} response.type "Feature Collection"
 * @apiSuccess {Object[]} response.features An array of feature objects
 * @apiSuccess {String} response.features.type "Feature"
 * @apiSuccess {Object} response.features.geometry GeoJSON geometry object (always null here)
 * @apiSuccess {Object} response.features.properties GeoJSON feature's properties
 * @apiSuccess {Number} response.features.properties.id history id
 * @apiSuccess {Number} response.features.properties.parcel_id parcel id
 * @apiSuccess {Number} response.features.properties.origin_id origin id
 * @apiSuccess {Number} response.features.properties.parent_id parent id
 * @apiSuccess {String} response.features.properties.version version
 * @apiSuccess {String} response.features.properties.description description
 * @apiSuccess {String} response.features.properties.date_modified YYYY-MM-DD of last update
 * @apiSuccess {Boolean} response.features.properties.active active/archived flag
 * @apiSuccess {String} response.features.properties.time_created Time stamp of creation
 * @apiSuccess {String} response.features.properties.time_updated Time stamp of last update
 * @apiSuccess {Number} response.features.properties.created_by id of creator
 * @apiSuccess {Number} response.features.properties.updated_by id of updater
 * @apiSuccess {Array} response.features.properties.parcel_history
 * @apiSuccess {Number} response.features.properties.parcel_history.id history id
 * @apiSuccess {Number} response.features.properties.parcel_history.parcel_id parcel id
 * @apiSuccess {Number} response.features.properties.parcel_history.origin_id origin id
 * @apiSuccess {Number} response.features.properties.parcel_history.parent_id parent id
 * @apiSuccess {String} response.features.properties.parcel_history.version version
 * @apiSuccess {String} response.features.properties.parcel_history.description description
 * @apiSuccess {String} response.features.properties.parcel_history.date_modified YYYY-MM-DD of last update
 * @apiSuccess {Boolean} response.features.properties.parcel_history.active active/archived flag
 * @apiSuccess {String} response.features.properties.parcel_history.time_created Time stamp of creation
 * @apiSuccess {String} response.features.properties.parcel_history.time_updated Time stamp of last update
 * @apiSuccess {Number} response.features.properties.parcel_history.created_by id of creator
 * @apiSuccess {Number} response.features.properties.parcel_history.updated_by id of updater
 * @apiSuccess {Array} response.features.properties.relationships
 * @apiSuccess {Number} response.features.properties.relationships.id
 * @apiSuccess {Number} response.features.properties.relationships.parcel_id
 * @apiSuccess {Number} response.features.properties.relationships.party_id
 * @apiSuccess {Number} response.features.properties.relationships.geom_id
 * @apiSuccess {Number} response.features.properties.relationships.tenure_type
 * @apiSuccess {Number} response.features.properties.relationships.acquired_date
 * @apiSuccess {Number} response.features.properties.relationships.how_acquired
 * @apiSuccess {Number} response.features.properties.relationships.active
 * @apiSuccess {Number} response.features.properties.relationships.time_created
 * @apiSuccess {Number} response.features.properties.relationships.time_updated
 * @apiSuccess {Number} response.features.properties.relationships.created_by
 * @apiSuccess {Number} response.features.properties.relationships.updated_by
 *
 * @apiExample {curl} Example usage:
 *     curl -i http://localhost/custom/get_parcel_detailss/1
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *     {
          "type": "FeatureCollection",
          "features": [
            {
              "type": "Feature",
              "geometry": {
                "type": "Point",
                "coordinates": [
                  -73.724739,
                  40.588342
                ]
              },
              "properties": {
                "id": 1,
                "spatial_source": 1,
                "user_id": "11",
                "area": null,
                "land_use": null,
                "gov_pin": null,
                "active": true,
                "sys_delete": false,
                "time_created": "2015-09-01T09:53:16.466337-07:00",
                "time_updated": null,
                "created_by": 11,
                "updated_by": null,
                "parcel_history": [
                  {
                    "id": 1,
                    "parcel_id": 1,
                    "origin_id": 1,
                    "parent_id": null,
                    "version": 1,
                    "description": "new description",
                    "date_modified": "2015-09-01T07:00:00.000Z",
                    "active": true,
                    "time_created": "2015-09-01T16:53:16.466Z",
                    "time_updated": null,
                    "created_by": 11,
                    "updated_by": null
                  }
                ],
                "relationships": [
                  {
                    "id": 1,
                    "parcel_id": 1,
                    "party_id": 1,
                    "geom_id": null,
                    "tenure_type": 1,
                    "acquired_date": null,
                    "how_acquired": null,
                    "active": true,
                    "sys_delete": false,
                    "time_created": "2015-09-01T16:53:16.466Z",
                    "time_updated": null,
                    "created_by": 11,
                    "updated_by": null
                  }
                ]
              }
            }
          ]
        }
 */
router.get('/get_parcel_details/:id', common.parseQueryOptions, function(req, res, next) {

    Q.allSettled([
        ctrlCommon.getWithId('parcel', 'id', req.params.id, {queryModifiers: {returnGeometry: true}, outputFormat: "GeoJSON"}),
        ctrlCommon.getWithId('parcel_history', 'parcel_id', req.params.id),
        ctrlCommon.getWithId('relationship', 'parcel_id', req.params.id)
        ])
        .then(function (results) {

            //Process results: Add parcel history and relationships to Parcel GeoJSON
            var geoJSON = results[0].value[0].response;

            // If Id return no parcel, message the user
            if(geoJSON.features.length === 0) {
                return res.status(200).json({message: "no parcel"});
            }

            // Add properties to parcel's geojson
            geoJSON.features[0].properties.parcel_history = results[1].value;
            geoJSON.features[0].properties.relationships = results[2].value;

            res.status(200).json(geoJSON);
        })
        .catch(function(err){
            next(err)
        })
        .done();

});

module.exports = router;
<commit_msg>Limit parcel_history and relationships by 10 and descending sort on time_updated.<commit_after>var express = require('express');
var router = express.Router();
var pgb = require('../pg-binding');
var common = require('../common.js');
var ctrlCommon = require('../controllers/common.js');

var Q = require('q');

/**
 * @api {get} /custom/get_parcels_list Parcel/Num relationships List
 * @apiName custom_get_parcels_list
 * @apiGroup Custom
 *
 * @apiParam {String} tenure_type Options: own, lease, occupy, informal occupy
 * @apiParamExample  Query String Example:
 *  curl -i http://localhost/custom/get_parcels_list?tenure_type=own,lease
 * @apiSuccess {Object} response A feature collection with zero to many features
 * @apiSuccess {String} response.type "Feature Collection"
 * @apiSuccess {Object[]} response.features An array of feature objects
 * @apiSuccess {String} response.features.type "Feature"
 * @apiSuccess {Object} response.features.geometry GeoJSON geometry object
 * @apiSuccess {Object} response.features.properties GeoJSON feature's properties
 * @apiSuccess {Integer} response.features.properties.id parcel id
 * @apiSuccess {Timestamp} response.features.properties.time_created timestamp with timezone
 * @apiSuccess {Numeric} response.features.properties.area area of parcel geometry
 * @apiSuccess {String} response.features.properties.tenure_type type of relationship tenure
 * @apiSuccess {Integer} response.features.properties.num_relationships number of associated relationships
 * @apiExample {curl} Example usage:
 *     curl -i http://localhost/custom_get_parcels_list
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *
 * {
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": null,
            "properties": {
                "id": 45,
                "time_created": "2015-08-24T14:03:27.144363-07:00",
                "area": null,
                "tenure_type": "own",
                "num_relationships": 6
            }
        },
        {
            "type": "Feature",
            "geometry": null,
            "properties": {
                "id": 44,
                "time_created": "2015-08-24T14:03:27.144363-07:00",
                "area": null,
                "tenure_type": "lease",
                "num_relationships": 5
            }
        },
        {
            "type": "Feature",
            "geometry": null,
            "properties": {
                "id": 43,
                "time_created": "2015-08-24T14:03:27.144363-07:00",
                "area": null,
                "tenure_type": "occupy",
                "num_relationships": 2
            }
        }
    ]
}
 *
 * */
router.get('/get_parcels_list', common.parseQueryOptions, function(req, res, next) {

    var args = common.getArguments(req);
    var whereClause = '';
    var obj = {};

    if (args.tenure_type) {
        obj = createTenureTypeWhereClause(args.tenure_type);
        whereClause = 'WHERE ' + obj.str + '';
    } else {
        obj.uriList = [];
    }

    req.queryModifiers.sort_by = req.queryModifiers.sort_by || "time_created,id";
    req.queryModifiers.sort_dir = req.queryModifiers.sort_dir || "DESC";

    ctrlCommon.getAll("show_parcels_list", {queryModifiers: req.queryModifiers, outputFormat: 'GeoJSON', whereClause: whereClause, whereClauseValues: obj.uriList})
        .then(function(result){

            res.status(200).json(result[0].response);

        })
        .catch(function(err){
            next(err);
        })
        .done();

});

function createTenureTypeWhereClause(arr) {

    var obj = {};

    obj.uriList = arr.split(',');

    obj.str = obj.uriList.map(function (val, i) {

            return 'tenure_type::text[] @> ARRAY[$' + (i + 1) + ']';

        })
        .join(' OR ');

    return obj;
}

/**
 * @api {get} /custom/get_parcel_details/:id Request parcel details for UI rendering; limits relationships and history to 10 items
 * @apiName GetParcelDetails
 * @apiGroup Custom
 *
 * @apiParam {Number} id parcel's unique ID.
 *
 *
 * @apiSuccess {Object} response A feature collection with one feature representing a parcel
 * @apiSuccess {String} response.type "Feature Collection"
 * @apiSuccess {Object[]} response.features An array of feature objects
 * @apiSuccess {String} response.features.type "Feature"
 * @apiSuccess {Object} response.features.geometry GeoJSON geometry object (always null here)
 * @apiSuccess {Object} response.features.properties GeoJSON feature's properties
 * @apiSuccess {Number} response.features.properties.id history id
 * @apiSuccess {Number} response.features.properties.parcel_id parcel id
 * @apiSuccess {Number} response.features.properties.origin_id origin id
 * @apiSuccess {Number} response.features.properties.parent_id parent id
 * @apiSuccess {String} response.features.properties.version version
 * @apiSuccess {String} response.features.properties.description description
 * @apiSuccess {String} response.features.properties.date_modified YYYY-MM-DD of last update
 * @apiSuccess {Boolean} response.features.properties.active active/archived flag
 * @apiSuccess {String} response.features.properties.time_created Time stamp of creation
 * @apiSuccess {String} response.features.properties.time_updated Time stamp of last update
 * @apiSuccess {Number} response.features.properties.created_by id of creator
 * @apiSuccess {Number} response.features.properties.updated_by id of updater
 * @apiSuccess {Array} response.features.properties.parcel_history
 * @apiSuccess {Number} response.features.properties.parcel_history.id history id
 * @apiSuccess {Number} response.features.properties.parcel_history.parcel_id parcel id
 * @apiSuccess {Number} response.features.properties.parcel_history.origin_id origin id
 * @apiSuccess {Number} response.features.properties.parcel_history.parent_id parent id
 * @apiSuccess {String} response.features.properties.parcel_history.version version
 * @apiSuccess {String} response.features.properties.parcel_history.description description
 * @apiSuccess {String} response.features.properties.parcel_history.date_modified YYYY-MM-DD of last update
 * @apiSuccess {Boolean} response.features.properties.parcel_history.active active/archived flag
 * @apiSuccess {String} response.features.properties.parcel_history.time_created Time stamp of creation
 * @apiSuccess {String} response.features.properties.parcel_history.time_updated Time stamp of last update
 * @apiSuccess {Number} response.features.properties.parcel_history.created_by id of creator
 * @apiSuccess {Number} response.features.properties.parcel_history.updated_by id of updater
 * @apiSuccess {Array} response.features.properties.relationships
 * @apiSuccess {Number} response.features.properties.relationships.id
 * @apiSuccess {Number} response.features.properties.relationships.parcel_id
 * @apiSuccess {Number} response.features.properties.relationships.party_id
 * @apiSuccess {Number} response.features.properties.relationships.geom_id
 * @apiSuccess {Number} response.features.properties.relationships.tenure_type
 * @apiSuccess {Number} response.features.properties.relationships.acquired_date
 * @apiSuccess {Number} response.features.properties.relationships.how_acquired
 * @apiSuccess {Number} response.features.properties.relationships.active
 * @apiSuccess {Number} response.features.properties.relationships.time_created
 * @apiSuccess {Number} response.features.properties.relationships.time_updated
 * @apiSuccess {Number} response.features.properties.relationships.created_by
 * @apiSuccess {Number} response.features.properties.relationships.updated_by
 *
 * @apiExample {curl} Example usage:
 *     curl -i http://localhost/custom/get_parcel_detailss/1
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *     {
          "type": "FeatureCollection",
          "features": [
            {
              "type": "Feature",
              "geometry": {
                "type": "Point",
                "coordinates": [
                  -73.724739,
                  40.588342
                ]
              },
              "properties": {
                "id": 1,
                "spatial_source": 1,
                "user_id": "11",
                "area": null,
                "land_use": null,
                "gov_pin": null,
                "active": true,
                "sys_delete": false,
                "time_created": "2015-09-01T09:53:16.466337-07:00",
                "time_updated": null,
                "created_by": 11,
                "updated_by": null,
                "parcel_history": [
                  {
                    "id": 1,
                    "parcel_id": 1,
                    "origin_id": 1,
                    "parent_id": null,
                    "version": 1,
                    "description": "new description",
                    "date_modified": "2015-09-01T07:00:00.000Z",
                    "active": true,
                    "time_created": "2015-09-01T16:53:16.466Z",
                    "time_updated": null,
                    "created_by": 11,
                    "updated_by": null
                  }
                ],
                "relationships": [
                  {
                    "id": 1,
                    "parcel_id": 1,
                    "party_id": 1,
                    "geom_id": null,
                    "tenure_type": 1,
                    "acquired_date": null,
                    "how_acquired": null,
                    "active": true,
                    "sys_delete": false,
                    "time_created": "2015-09-01T16:53:16.466Z",
                    "time_updated": null,
                    "created_by": 11,
                    "updated_by": null
                  }
                ]
              }
            }
          ]
        }
 */
router.get('/get_parcel_details/:id', common.parseQueryOptions, function(req, res, next) {

    Q.all([
        ctrlCommon.getWithId('parcel', 'id', req.params.id, {queryModifiers: {returnGeometry: true}, outputFormat: "GeoJSON"}),
        ctrlCommon.getWithId('parcel_history', 'parcel_id', req.params.id, {queryModifiers: {limit: 'LIMIT 10', sort_by: 'time_updated', sort_dir: 'DESC'}}),
        ctrlCommon.getWithId('relationship', 'parcel_id', req.params.id, {queryModifiers: {limit: 'LIMIT 10', sort_by: 'time_updated', sort_dir: 'DESC'}})
        ])
        .then(function (results) {

            //Process results: Add parcel history and relationships to Parcel GeoJSON
            var geoJSON = results[0][0].response;

            // If Id return no parcel, message the user
            if(geoJSON.features.length === 0) {
                return res.status(200).json({message: "no parcel"});
            }

            // Add properties to parcel's geojson
            geoJSON.features[0].properties.parcel_history = results[1][0];
            geoJSON.features[0].properties.relationships = results[2][0];

            res.status(200).json(geoJSON);
        })
        .catch(function(err){
            next(err)
        })
        .done();

});

module.exports = router;
<|endoftext|>


<commit_before>var requestify      = require('requestify');
var slack           = require('../controllers/botkit');
var util            = require('util');

module.exports = function(app) {

    app.get('/', function(req, res) {
        console.log("root");

        res.render('root'); // load view/root.html file
    });

    app.get('/new', function(req, res) {
        console.log("================== START TEAM REGISTRATION ==================")

        var auth_code = req.query.code;

        if (!auth_code) {
            res.redirect('/');
        }
        else {
            console.log("New user auth code " + auth_code);
            perform_auth(auth_code, res);
        }
    });

    var perform_auth = function(auth_code, res) {
        var base_url = 'https://slack.com/api/oauth.access?client_id=%s&client_secret=%s&code=%s&redirect_uri=%snew';
        var auth_adresse = util.format(base_url, process.env.SLACK_ID, process.env.SLACK_SECRET, auth_code, process.env.SLACK_REDIRECT);

        console.log(auth_adresse);

        requestify.get(auth_adresse).then((res) => {
            var auth = JSON.parse(body);
            console.log("New user auth");
            console.log(auth);

            register_team(auth, res);
        });
    }

    var register_team = function(auth, res) {
        var url = util.format('https://slack.com/api/auth.test?token=%s', auth.access_token);

        requestify.get(url).then((res) => {

            try {
                var identity = JSON.parse(body)
                console.log(identity)

                var team = {
                    id: identity.team_id,
                    bot:{
                        token: auth.bot.bot_access_token,
                        user_id: auth.bot.bot_user_id,
                        createdBy: identity.user_id
                    },
                    createdBy: identity.user_id,
                    url: identity.url,
                    name: identity.team
                }

                startBot(team);
                res.send("Your bot has been installed")

                saveUser(auth, identity)
            }
            catch (e) {
                console.log(e);
            }
        });
    }

    var startBot = function(team) {
        console.log(team.name + " start bot");

        slack.connect(team);
    }

    var saveUser = function(auth, identity) {
        var scopes = auth.scope.split(/\,/);

        slack.controller.storage.users.get(identity.user_id, function(err, user) {
            isnew = false;

            if (!user) {
                isnew = true;
                user = {
                    id: identity.user_id,
                    access_token: auth.access_token,
                    scopes: scopes,
                    team_id: identity.team_id,
                    user: identity.user,
                };
            }

            slack.controller.storage.users.save(user, function(err, id) {
                if (err) {
                    console.log('An error occurred while saving a user: ', err);
                    slack.controller.trigger('error', [err]);
                }
                else {
                    if (isnew) {
                        console.log("New user " + id.toString() + " saved");
                    }
                    else {
                        console.log("User " + id.toString() + " updated");
                    }
                    console.log("================== END TEAM REGISTRATION ==================")
                }
            });
        });
    }
}
<commit_msg>fixing some bugs<commit_after>var Request          = require('request')
var slack           = require('../controllers/botkit')

// frontend routes =========================================================
module.exports = function(app) {

  //public pages=============================================
  //root
  app.get('/', function(req, res) {
    console.log("root")

    res.render('root'); // load view/root.html file
  });

  //new user creation - redirection from Slack
  app.get('/new', function(req, res) {
    console.log("================== START TEAM REGISTRATION ==================")
    //temporary authorization code
    var auth_code = req.query.code

    if(!auth_code){
      //user refused auth
      res.redirect('/')
    }
    else{
      console.log("New user auth code " + auth_code)
      perform_auth(auth_code, res)
    }
  })

  //CREATION ===================================================

  var perform_auth = function(auth_code, res){
    //post code, app ID, and app secret, to get token
    var auth_adresse = 'https://slack.com/api/oauth.access?'
    auth_adresse += 'client_id=' + process.env.SLACK_ID
    auth_adresse += '&client_secret=' + process.env.SLACK_SECRET
    auth_adresse += '&code=' + auth_code
    auth_adresse += '&redirect_uri=' + process.env.SLACK_REDIRECT + "new"

    Request.get(auth_adresse, function (error, response, body) {
      if (error){
        console.log(error)
        res.sendStatus(500)
      }

      else{
        var auth = JSON.parse(body)
        console.log("New user auth")
        console.log(auth)

        register_team(auth,res)
      }
    })
  }

  var register_team = function(auth, res){
    //first, get authenticating user ID
    var url = 'https://slack.com/api/auth.test?'
    url += 'token=' + auth.access_token

    Request.get(url, function (error, response, body) {
      if (error){
        console.log(error)
        res.sendStatus(500)
      }
      else{
        try{
          var identity = JSON.parse(body)
          console.log(identity)

          var team = {
            id: identity.team_id,
            bot:{
              token: auth.bot.bot_access_token,
              user_id: auth.bot.bot_user_id,
              createdBy: identity.user_id
            },
            createdBy: identity.user_id,
            url: identity.url,
            name: identity.team
          }
          startBot(team)
          res.send("Your bot has been installed")

          saveUser(auth, identity)
        }
        catch(e){
          console.log(e)
        }
      }
    })
  }

  var startBot = function(team){
    console.log(team.name + " start bot")

    slack.connect(team)
  }

  var saveUser = function(auth, identity){
    // what scopes did we get approved for?
    var scopes = auth.scope.split(/\,/);

    slack.controller.storage.users.get(identity.user_id, function(err, user) {
      isnew = false;
      if (!user) {
          isnew = true;
          user = {
              id: identity.user_id,
              access_token: auth.access_token,
              scopes: scopes,
              team_id: identity.team_id,
              user: identity.user,
          };
      }
      slack.controller.storage.users.save(user, function(err, id) {
        if (err) {
          console.log('An error occurred while saving a user: ', err);
          slack.controller.trigger('error', [err]);
        }
        else {
          if (isnew) {
            console.log("New user " + id.toString() + " saved");
          }
          else {
            console.log("User " + id.toString() + " updated");
          }
          console.log("================== END TEAM REGISTRATION ==================")
        }
      });
    });
  }
}
<|endoftext|>


<commit_before>import html from 'choo/html';
import header from '../components/header';
import styles from './single.css';
import backArrow from './back-arrow.svg';
import {toArray, getValue} from '../utils';

export default function single(state, emit) {
  const itemID = state.params.id;
  const item = getValue(state, 'store', itemID);

  if (Object.keys(item).length === 0) {
    emit('getItem', itemID);
    return renderLoader();
  }

  return renderPage(item);

  function renderPage(item) {
    const title = getValue(item, 'titles', 'short-title');
    const imageSrc = getValue(item, 'coverimages', 'coverimage')[1];
    const genres = toArray(getValue(item, 'genres', 'genre'));
    const formats = toArray(getValue(item, 'formats', 'format'));
    const summaries = toArray(getValue(item, 'summaries', 'summary'));
    const specifications = toArray(getValue(item, 'description', 'physical-description'));

    const availability = item.availability;
    const reviews = item.reviews;
    const isbn = getValue(item, 'identifiers', 'isbn-id');

    if (!availability) {
      emit('getAvailability', itemID);
    }

    if (!reviews) {
      emit('getReviews', {itemID, isbn});
    }

    return html`

        ${header(state, emit)}

          terug

${title}

            ${imageSrc.startsWith('https://v19.nbc.bibliotheek.nl') ?
              html`<img class=${styles.cover} src="${imageSrc}" />` :  html`<p>Geen afbeelding beschikbaar</p>`
            }

${specifications}

Korte beschrijving

${summaries}

          ${renderAvailability(availability)}
          ${renderReviews(reviews)}
          ${formats.length > 0 ? renderList('Formats', formats) : null}
          ${genres.length > 0 ? renderList('Genres', genres) : null}

    `;

    function renderList(title, values) {
      return html`

${title}

${values.map(value => renderLI(value))}

      `;

      function renderLI(value) {
        return html`<li><p>${value}</p></li>`;
      }
    }

    function renderAvailability(availability) {
      if (availability && availability.length > 0) {
        return html`

Beschikbaarheid

              Klik hier om de beschikbaarheid te bekijken

${availability.map(({name, available}) => html`<li class="${styles.location}" data-available="${available}">${name}</li>`)}

        `;
      }

      return null;
    }

    function renderReviews(reviews) {
      if (reviews && reviews.length > 0) {
        return html`

Reviews van Boekenliefde.nl

              ${reviews.map(({link, username, dateadded, ratingtitle, rating, review}) => html`

${username} ${dateadded}

"${ratingtitle}" Cijfer: ${rating}

                    Lees de review

${review}

              `)}

        `;
      }

      return null;
    }
  }

  function renderLoader() {
    return html`

        ${header(state, emit)}

    `;
  }
}
<commit_msg>Feature/single scroll position (#179)<commit_after>import html from 'choo/html';
import header from '../components/header';
import styles from './single.css';
import backArrow from './back-arrow.svg';
import {toArray, getValue} from '../utils';

export default function single(state, emit) {
  const itemID = state.params.id;
  const item = getValue(state, 'store', itemID);

  if (Object.keys(item).length === 0) {
    emit('getItem', itemID);
    return renderLoader();
  }

  return renderPage(item);

  function renderPage(item) {
    window.scrollTo(0, 0);
    const title = getValue(item, 'titles', 'short-title');
    const imageSrc = getValue(item, 'coverimages', 'coverimage')[1];
    const genres = toArray(getValue(item, 'genres', 'genre'));
    const formats = toArray(getValue(item, 'formats', 'format'));
    const summaries = toArray(getValue(item, 'summaries', 'summary'));
    const specifications = toArray(getValue(item, 'description', 'physical-description'));

    const availability = item.availability;
    const reviews = item.reviews;
    const isbn = getValue(item, 'identifiers', 'isbn-id');

    if (!availability) {
      emit('getAvailability', itemID);
    }

    if (!reviews) {
      emit('getReviews', {itemID, isbn});
    }

    return html`

        ${header(state, emit)}

          terug

${title}

            ${imageSrc.startsWith('https://v19.nbc.bibliotheek.nl') ?
              html`<img class=${styles.cover} src="${imageSrc}" />` :  html`<p>Geen afbeelding beschikbaar</p>`
            }

${specifications}

Korte beschrijving

${summaries}

          ${renderAvailability(availability)}
          ${renderReviews(reviews)}
          ${formats.length > 0 ? renderList('Formats', formats) : null}
          ${genres.length > 0 ? renderList('Genres', genres) : null}

    `;

    function renderList(title, values) {
      return html`

${title}

${values.map(value => renderLI(value))}

      `;

      function renderLI(value) {
        return html`<li><p>${value}</p></li>`;
      }
    }

    function renderAvailability(availability) {
      if (availability && availability.length > 0) {
        return html`

Beschikbaarheid

              Klik hier om de beschikbaarheid te bekijken

${availability.map(({name, available}) => html`<li class="${styles.location}" data-available="${available}">${name}</li>`)}

        `;
      }

      return null;
    }

    function renderReviews(reviews) {
      if (reviews && reviews.length > 0) {
        return html`

Reviews van Boekenliefde.nl

              ${reviews.map(({link, username, dateadded, ratingtitle, rating, review}) => html`

${username} ${dateadded}

"${ratingtitle}" Cijfer: ${rating}

                    Lees de review

${review}

              `)}

        `;
      }

      return null;
    }
  }

  function renderLoader() {
    return html`

        ${header(state, emit)}

    `;
  }
}
<|endoftext|>


<commit_before>module.exports = function (iface) {

    var {mqttPub, mqttSub, mqttStatus, log, newAccessory, Service, Characteristic} = iface;

    return function createAccessory_GarageDoorOpener(settings) {
        /* Required Characteristics
         this.addCharacteristic(Characteristic.CurrentDoorState);
         this.addCharacteristic(Characteristic.TargetDoorState);
         this.addCharacteristic(Characteristic.ObstructionDetected);

         // Optional Characteristics
         this.addOptionalCharacteristic(Characteristic.LockCurrentState);
         this.addOptionalCharacteristic(Characteristic.LockTargetState);
         this.addOptionalCharacteristic(Characteristic.Name);*/

        var garage = newAccessory(settings);
        garage.addService(Service.GarageDoorOpener, settings.name)
            .getCharacteristic(Characteristic.TargetDoorState)
            .on('set', function (value, callback) {
                log.debug('< hap set', settings.name, 'TargetDoorState', value);
                if (value == Characteristic.TargetDoorState.OPEN) {
                    log.debug('> mqtt publish', settings.topic.setDoor, settings.payload.doorOpen);
                    mqttPub(settings.topic.setDoor, settings.payload.doorOpen);

                    callback();
                } else if (value == Characteristic.TargetDoorState.CLOSED) {
                    log.debug('> mqtt publish', settings.topic.setDoor, settings.payload.doorClosed);
                    mqttPub(settings.topic.setDoor, settings.payload.doorClosed);

                    callback();
                }
            });

        if (settings.topic.statusDoor) {
            var initial = true;

            /* TODO opening/closing/stopped
             Characteristic.CurrentDoorState.OPEN = 0;
             Characteristic.CurrentDoorState.CLOSED = 1;
             Characteristic.CurrentDoorState.OPENING = 2;
             Characteristic.CurrentDoorState.CLOSING = 3;
             Characteristic.CurrentDoorState.STOPPED = 4;
             */

            mqttSub(settings.topic.statusDoor, function (val) {
                if (val === settings.payload.doorClosed) {
                    log.debug('> hap set', settings.name, 'CurrentDoorState.CLOSED');
                    garage.getService(Service.GarageDoorOpener)
                        .setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.CLOSED);
                    if (initial) {
                        log.debug('> hap set', settings.name, 'CurrentDoorState.CLOSED');
                        garage.getService(Service.GarageDoorOpener)
                            .setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.CLOSED);
                        initial = false;
                    }
                } else {
                    log.debug('> hap set', settings.name, 'CurrentDoorState.OPEN');
                    garage.getService(Service.GarageDoorOpener)
                        .setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.OPEN);
                    if (initial) {
                        log.debug('> hap set', settings.name, 'CurrentDoorState.OPEN');
                        garage.getService(Service.GarageDoorOpener)
                            .setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.OPEN);
                        initial = false;
                    }
                }
            });

            garage.getService(Service.GarageDoorOpener)
                .getCharacteristic(Characteristic.CurrentDoorState)
                .on('get', function(callback) {
                    log.debug('< hap get', settings.name, 'CurrentDoorState');

                    if (mqttStatus[settings.topic.statusDoor] === settings.payload.doorClosed) {
                        log.debug('> hap re_get', settings.name, 'CurrentDoorState.CLOSED');
                        callback(null, Characteristic.CurrentDoorState.SECURED);
                    } else {
                        log.debug('> hap re_get', settings.name, 'CurrentDoorState.OPEN');
                        callback(null, Characteristic.CurrentDoorState.UNSECURED);
                    }
                });
        }

        garage.getService(Service.GarageDoorOpener, settings.name)
            .getCharacteristic(Characteristic.ObstructionDetected)
            .on('get', function (callback) {
                log.debug('< hap get', settings.name, 'ObstructionDetected');
                var obstruction = mqttStatus[settings.topic.statusObstruction] === settings.payload.onObstructionDetected;
                log.debug('> hap re_get', settings.name, 'ObstructionDetected', obstruction);
                callback(null, obstruction);
            });

        if (settings.topic.statusObstruction) {
            mqttSub(settings.topic.statusObstruction, function (val) {
                var obstruction = val === settings.payload.onObstructionDetected;
                log.debug('> hap set', settings.name, 'ObstructionDetected', obstruction);
                garage.getService(Service.GarageDoorOpener)
                    .setCharacteristic(Characteristic.ObstructionDetected, obstruction)
            });
        }

        if (settings.topic.setLock) {
            garage.getService(Service.GarageDoorOpener, settings.name)
                .getCharacteristic(Characteristic.LockTargetState)
                .on('set', function(value, callback) {
                    log.debug('< hap set', settings.name, 'LockTargetState', value);
                    if (value == Characteristic.LockTargetState.UNSECURED) {
                        log.debug('> mqtt publish', settings.topic.setLock, settings.payload.lockUnsecured);
                        mqttPub(settings.topic.setLock, settings.payload.lockUnsecured);
                        callback();
                    } else if (value == Characteristic.LockTargetState.SECURED) {
                        log.debug('> mqtt publish', settings.topic.setLock, settings.payload.lockSecured);
                        mqttPub(settings.topic.setLock, settings.payload.lockSecured);
                        callback();
                    }
                });
        }

        if (settings.topic.statusLock) {

            var initialLock = true;

            mqttSub(settings.topic.statusLock, function (val) {
                if (val === settings.payload.lockSecured) {
                    log.debug('> hap set', settings.name, 'LockCurrentState.SECURED');
                    garage.getService(Service.LockMechanism)
                        .setCharacteristic(Characteristic.LockCurrentState, Characteristic.LockCurrentState.SECURED);
                    if (initialLock) {
                        log.debug('> hap set', settings.name, 'LockTargetState.SECURED');
                        garage.getService(Service.LockMechanism)
                            .setCharacteristic(Characteristic.LockTargetState, Characteristic.LockTargetState.SECURED);
                        initialLock = false;
                    }
                } else {
                    log.debug('> hap set', settings.name, 'LockCurrentState.UNSECURED');
                    garage.getService(Service.LockMechanism)
                        .setCharacteristic(Characteristic.LockCurrentState, Characteristic.LockCurrentState.UNSECURED);
                    if (initialLock) {
                        log.debug('> hap set', settings.name, 'LockTargetState.UNSECURED');
                        garage.getService(Service.LockMechanism)
                            .setCharacteristic(Characteristic.LockTargetState, Characteristic.LockTargetState.UNSECURED);
                        initialLock = false;
                    }
                }
            });

            garage.getService(Service.GarageDoorOpener)
                .getCharacteristic(Characteristic.LockCurrentState)
                .on('get', function (callback) {
                    log.debug('< hap get', settings.name, 'LockCurrentState');

                    if (mqttStatus[settings.topic.statusLock] === settings.payload.lockSecured) {
                        log.debug('> hap re_get', settings.name, 'LockCurrentState.SECURED');
                        callback(null, Characteristic.LockCurrentState.SECURED);
                    } else {
                        log.debug('> hap re_get', settings.name, 'LockCurrentState.UNSECURED');
                        callback(null, Characteristic.LockCurrentState.UNSECURED);
                    }
                });
        }

        return garage;

    }

};<commit_msg>fixes targetDoorState update<commit_after>module.exports = function (iface) {

    var {mqttPub, mqttSub, mqttStatus, log, newAccessory, Service, Characteristic} = iface;

    return function createAccessory_GarageDoorOpener(settings) {
        /* Required Characteristics
         this.addCharacteristic(Characteristic.CurrentDoorState);
         this.addCharacteristic(Characteristic.TargetDoorState);
         this.addCharacteristic(Characteristic.ObstructionDetected);

         // Optional Characteristics
         this.addOptionalCharacteristic(Characteristic.LockCurrentState);
         this.addOptionalCharacteristic(Characteristic.LockTargetState);
         this.addOptionalCharacteristic(Characteristic.Name);*/

        var garage = newAccessory(settings);
        garage.addService(Service.GarageDoorOpener, settings.name)
            .getCharacteristic(Characteristic.TargetDoorState)
            .on('set', function (value, callback) {
                log.debug('< hap set', settings.name, 'TargetDoorState', value);
                if (value == Characteristic.TargetDoorState.OPEN) {
                    log.debug('> mqtt publish', settings.topic.setDoor, settings.payload.doorOpen);
                    mqttPub(settings.topic.setDoor, settings.payload.doorOpen);

                    callback();
                } else if (value == Characteristic.TargetDoorState.CLOSED) {
                    log.debug('> mqtt publish', settings.topic.setDoor, settings.payload.doorClosed);
                    mqttPub(settings.topic.setDoor, settings.payload.doorClosed);

                    callback();
                }
            });

        if (settings.topic.statusDoor) {

            /* TODO opening/closing/stopped
             Characteristic.CurrentDoorState.OPEN = 0;
             Characteristic.CurrentDoorState.CLOSED = 1;
             Characteristic.CurrentDoorState.OPENING = 2;
             Characteristic.CurrentDoorState.CLOSING = 3;
             Characteristic.CurrentDoorState.STOPPED = 4;
             */

            mqttSub(settings.topic.statusDoor, function (val) {
                if (val === settings.payload.doorClosed) {
                    log.debug('> hap set', settings.name, 'CurrentDoorState.CLOSED');
                    garage.getService(Service.GarageDoorOpener)
                        .setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.CLOSED);
                    log.debug('> hap update', settings.name, 'TargetDoorState.CLOSED');
                    garage.getService(Service.GarageDoorOpener)
                        .updateCharacteristic(Characteristic.TargetDoorState, Characteristic.CurrentDoorState.CLOSED);

                } else {
                    log.debug('> hap set', settings.name, 'CurrentDoorState.OPEN');
                    garage.getService(Service.GarageDoorOpener)
                        .setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.OPEN);
                    log.debug('> hap update', settings.name, 'TargetDoorState.OPEN');
                    garage.getService(Service.GarageDoorOpener)
                        .updateCharacteristic(Characteristic.TargetDoorState, Characteristic.CurrentDoorState.OPEN);

                }
            });

            garage.getService(Service.GarageDoorOpener)
                .getCharacteristic(Characteristic.CurrentDoorState)
                .on('get', function(callback) {
                    log.debug('< hap get', settings.name, 'CurrentDoorState');

                    if (mqttStatus[settings.topic.statusDoor] === settings.payload.doorClosed) {
                        log.debug('> hap re_get', settings.name, 'CurrentDoorState.CLOSED');
                        callback(null, Characteristic.CurrentDoorState.SECURED);
                    } else {
                        log.debug('> hap re_get', settings.name, 'CurrentDoorState.OPEN');
                        callback(null, Characteristic.CurrentDoorState.UNSECURED);
                    }
                });
        }

        garage.getService(Service.GarageDoorOpener, settings.name)
            .getCharacteristic(Characteristic.ObstructionDetected)
            .on('get', function (callback) {
                log.debug('< hap get', settings.name, 'ObstructionDetected');
                var obstruction = mqttStatus[settings.topic.statusObstruction] === settings.payload.onObstructionDetected;
                log.debug('> hap re_get', settings.name, 'ObstructionDetected', obstruction);
                callback(null, obstruction);
            });

        if (settings.topic.statusObstruction) {
            mqttSub(settings.topic.statusObstruction, function (val) {
                var obstruction = val === settings.payload.onObstructionDetected;
                log.debug('> hap set', settings.name, 'ObstructionDetected', obstruction);
                garage.getService(Service.GarageDoorOpener)
                    .setCharacteristic(Characteristic.ObstructionDetected, obstruction)
            });
        }

        if (settings.topic.setLock) {
            garage.getService(Service.GarageDoorOpener, settings.name)
                .getCharacteristic(Characteristic.LockTargetState)
                .on('set', function(value, callback) {
                    log.debug('< hap set', settings.name, 'LockTargetState', value);
                    if (value == Characteristic.LockTargetState.UNSECURED) {
                        log.debug('> mqtt publish', settings.topic.setLock, settings.payload.lockUnsecured);
                        mqttPub(settings.topic.setLock, settings.payload.lockUnsecured);
                        callback();
                    } else if (value == Characteristic.LockTargetState.SECURED) {
                        log.debug('> mqtt publish', settings.topic.setLock, settings.payload.lockSecured);
                        mqttPub(settings.topic.setLock, settings.payload.lockSecured);
                        callback();
                    }
                });
        }

        if (settings.topic.statusLock) {

            mqttSub(settings.topic.statusLock, function (val) {
                if (val === settings.payload.lockSecured) {
                    log.debug('> hap set', settings.name, 'LockCurrentState.SECURED');
                    garage.getService(Service.LockMechanism)
                        .setCharacteristic(Characteristic.LockCurrentState, Characteristic.LockCurrentState.SECURED);
                    log.debug('> hap update', settings.name, 'LockCurrentState.SECURED');
                    garage.getService(Service.LockMechanism)
                        .updateCharacteristic(Characteristic.LockTargetState, Characteristic.LockCurrentState.SECURED);

                } else {
                    log.debug('> hap set', settings.name, 'LockCurrentState.UNSECURED');
                    garage.getService(Service.LockMechanism)
                        .setCharacteristic(Characteristic.LockCurrentState, Characteristic.LockCurrentState.UNSECURED);
                    log.debug('> hap update', settings.name, 'LockCurrentState.UNSECURED');
                    garage.getService(Service.LockMechanism)
                        .updateCharacteristic(Characteristic.LockTargetState, Characteristic.LockCurrentState.UNSECURED);

                }
            });

            garage.getService(Service.GarageDoorOpener)
                .getCharacteristic(Characteristic.LockCurrentState)
                .on('get', function (callback) {
                    log.debug('< hap get', settings.name, 'LockCurrentState');

                    if (mqttStatus[settings.topic.statusLock] === settings.payload.lockSecured) {
                        log.debug('> hap re_get', settings.name, 'LockCurrentState.SECURED');
                        callback(null, Characteristic.LockCurrentState.SECURED);
                    } else {
                        log.debug('> hap re_get', settings.name, 'LockCurrentState.UNSECURED');
                        callback(null, Characteristic.LockCurrentState.UNSECURED);
                    }
                });
        }

        return garage;

    }

};<|endoftext|>


<commit_before>'use strict';

////////////////////////
// Selector variables //
////////////////////////

var fb = new Firebase('https://exandoh.firebaseio.com/'),
    createUsers,
    board = [['', '', ''], ['', '', ''], ['', '', '']],
    playerOne = 'X',
    playerTwo = 'O',
    playerTurn = true,
    turns = 0;

////////////////////////////////
// Create Player //////////////
////////////////////////////////

  $('#createUser').click(function(event){
    event.preventDefault();

    createUsers = {
        username: $('#newUser').val()
      }
     addUser(createUsers, function(data){});
     $('.welcomePlayers').attr('data-uuid', data.username);
  });

  function addUser(data, cb) {
    cb(fb.push(data));
  }

//APPEND DATA TO PAGE
function appendPlayersToPage(data) {
  $('.welcomePlayers').append('
 Welcome ' + data.username + '
');
}

//PULL DATA FROM FIREBASE
fb.on('child_added', function(snap){
  var data = snap.val();
  appendPlayersToPage(data);
});

// $('.output').on('click', function() {
//   $('.clickOutput').html(event.target.className);
//   console.log("You have clicked on the table.")
// })

$('.newGame').on('click', function() {
  createBoard(board);
  console.log('clicking button!')
})

function createBoard(board) {
  board = [['', '', ''], ['', '', ''], ['', '', '']];
  var $table = $('

');
  board.forEach(function(row) {
    var $tr = $('

');
    row.forEach(function(cell) {
      $tr.append('' + cell + '	');
    });
    $table.append($tr);
  });
  $('.output').append($table);
}

$('.output').on('click', function () {
  console.log('one click is working!')
  var index = $('.cell').index(this);
  $('.clickOutput').text("Index #" + index);
  if(playerTurn === true) {
    $('.cell').append(playerOne);
    playerTurn = false;
    turns += 1;
    turnCount();
  }
  else {
    $('.cell').append(playerTwo);
    playerTurn = true;
    turns  += 1;
    turnCount();
  }
})

function turnCount() {
  if (turns === 9) {
    $('.clickOutput').append('
GAME OVER!!!
')
  }
}

  //if authenticated, go to app page

  // fb.child('users').once('value', function(snap){
  //   if (fb.getAuth()) {
  //     $('.loginForm').toggleClass('hidden');
  //     $('.gameBoard').toggleClass('hidden');
  //   }
  // });<commit_msg>added index function<commit_after>'use strict';

////////////////////////
// Selector variables //
////////////////////////

var fb = new Firebase('https://exandoh.firebaseio.com/'),
    createUsers,
    board = [['', '', ''], ['', '', ''], ['', '', '']],
    playerOne = 'X',
    playerTwo = 'O',
    playerTurn = true,
    turns = 0;

////////////////////////////////
// Create Player //////////////
////////////////////////////////

  $('#createUser').click(function(event){
    event.preventDefault();

    createUsers = {
        username: $('#newUser').val()
      }
     addUser(createUsers, function(data){});
     $('.welcomePlayers').attr('data-uuid', data.username);
  });

  function addUser(data, cb) {
    cb(fb.push(data));
  }

//APPEND DATA TO PAGE
function appendPlayersToPage(data) {
  $('.welcomePlayers').append('
 Welcome ' + data.username + '
');
}

//PULL DATA FROM FIREBASE
fb.on('child_added', function(snap){
  var data = snap.val();
  appendPlayersToPage(data);
});

// $('.output').on('click', function() {
//   $('.clickOutput').html(event.target.className);
//   console.log("You have clicked on the table.")
// })

$('.newGame').on('click', function() {
  createBoard(board);
  console.log('clicking button!')
})

function createBoard(board) {
  board = [['', '', ''], ['', '', ''], ['', '', '']];
  var $table = $('

');
  board.forEach(function(row) {
    var $tr = $('

');
    row.forEach(function(cell) {
      $tr.append('' + cell + '	');
    });
    $table.append($tr);
  });
  $('.output').append($table);
}

$('.output').on('click', function() {
  console.log('one click is working!')
  findCellIndex();
  if(playerTurn === true) {
    $('.cell').append(playerOne);
    playerTurn = false;
    turns += 1;
    turnCount();
  }
  else {
    $('.cell').append(playerTwo);
    playerTurn = true;
    turns  += 1;
    turnCount();
  }
})

function findCellIndex(){
  $('td').on('click', function(){
    var index = $('td').index(this);
    $('.clickOutput').text("Index #" + index);
    console.log('td click working!')
  });
}

function turnCount() {
  if (turns === 9) {
    $('.clickOutput').append('
GAME OVER!!!
')
  }
}

  //if authenticated, go to app page

  // fb.child('users').once('value', function(snap){
  //   if (fb.getAuth()) {
  //     $('.loginForm').toggleClass('hidden');
  //     $('.gameBoard').toggleClass('hidden');
  //   }
  // });<|endoftext|>


<commit_before>// hypestore - HYPErtext STORage Engine
//
// rfc2616 server supporting transparent content
// storage and retrieval over HTTP

var express = require('express');
var fs = require('fs');

var app = express();

var path = require('path');
var server = require('http').createServer(app);
var util = require('util');
var getRawBody = require('raw-body');

var spawn = require('child_process').spawn;

app.use(express.static(__dirname + '/static'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(express.static(__dirname + '/public'));

var config = loadConfig();

if (!config) {
    console.log("FATAL: No config.json in current directory, exiting.");
} else {

    fs.exists(config.storage.contentLocation, function (exists) {

	if (exists) {
	    console.log("found content directory " + config.storage.contentLocation);
	    server.listen(config.port);
	    console.log("Listening on port: " + config.port);
	} else {
	    console.log("WARNING: location " + config.storage.contentLocation + " specified in config.json could not be found.  Trying to create...");

	    fs.mkdir(config.storage.contentLocation, function (exception) {

		if (exception) {
		    console.log("FATAL: Could not create directory " + config.storage.contentLocation);
		} else {
		    console.log("created directory " + config.storage.contentLocation);
		    server.listen(config.port);
		    console.log("Listening on port: " + config.port);
		}

	    });

	}

    });
}

// GET
app.get("/:resource", function (req, res) {

    console.log("req: " + util.inspect(req));

    var requestState = {};

    requestState.headers = req.headers;
    requestState.url = req.url;
    requestState.method = req.method;

    var file;
    if (req.params.resource == undefined) {
	file = config.storage.contentLocation + "/index.html";
    } else {
	file = config.storage.contentLocation + "/" + req.params.resource;
    }

    requestState.requestedFile = file;

    console.log("requestState: " + requestState);

    fs.readFile(file, function (err, data) {

	if (err) {
	    console.log("error opening file: " + file + ": " + util.inspect(err));

	    if (err.errno == 34) { // No such file or directory
		requestState.responseCode = 404;
		res.json(404, requestState);
	    } else {
		res.json(500, err);
	    }

	} else {
	    console.log("found data in " + file);

	    console.log("\n\n" + util.inspect(data));

	    // TODO:

	    // lookup content type of file from original submission
	    // set content-type header

	    res.send(200, data);

	}

    });

});

// PUT
app.put("/:resource", function (req, res) {

    // TODO:
    //
    // - map file extension to MIME
    // - validate known MIME types against client Accept header, 4xx Not Acceptable if no match
    // - handle hierarchical directory traversal

    var requestState = {};

    requestState.headers = req.headers;
    requestState.url = req.url;
    requestState.method = req.method;

    var file;
    if (!req.params.resource) {
	file = config.storage.contentLocation + "/index.html";
    } else {
	file = config.storage.contentLocation + "/" + req.params.resource;
    }

    requestState.requestedFile = file;

    console.log("requestState: " + util.inspect(requestState));
    console.log("contents of file: " + util.inspect(req));
    console.log("content type: " + req.get('Content-Type'));

    getRawBody(req, { length: req.headers['Content-Length'] }, function(err, buffer) {

	if (err) {

	    console.log("error getting raw body: " + util.inspect(err));
	    res.json(500, err);

	} else {

	    fs.writeFile(file, buffer, { flag: 'w' }, function (err) {

		if (err) {
		    console.log("error writing to file: " + file);
		    res.json(500, err);
		} else {
		    res.send(204);
		}

	    });

	}

    });

});

// POST -> should this even exist?
app.post("/:resource", function (req, res) {

    res.json(405, { message: "Hypestore supports HTTP methods: GET, PUT, DELETE" });

});

function loadConfig() {
    console.log("Loading configuration for " + "./config.json");
    if (fs.existsSync("./config.json")) {
	var cfg = fs.readFileSync("./config.json", 'utf-8');
	return JSON.parse(cfg);
    } else {
	console.log("loadConfig: no config.json found");
	return undefined;
    }
}

<commit_msg>added dirs for client and test<commit_after>// hypestore - HYPErtext STORage Engine
//
// rfc2616 server supporting transparent content
// storage and retrieval over HTTP

var express = require('express');
var fs = require('fs');

var app = express();

var path = require('path');
var server = require('http').createServer(app);
var util = require('util');
var getRawBody = require('raw-body');

var spawn = require('child_process').spawn;

app.use(express.static(__dirname + '/static'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({ secret: 'keyboard cat' }));
app.use(express.static(__dirname + '/public'));

var config = loadConfig();

if (!config) {
    console.log("FATAL: No config.json in current directory, exiting.");
} else {

    fs.exists(config.storage.contentLocation, function (exists) {

	if (exists) {
	    console.log("found content directory " + config.storage.contentLocation);
	    server.listen(config.port);
	    console.log("Listening on port: " + config.port);
	} else {
	    console.log("WARNING: location " + config.storage.contentLocation + " specified in config.json could not be found.  Trying to create...");

	    fs.mkdir(config.storage.contentLocation, function (exception) {

		if (exception) {
		    console.log("FATAL: Could not create directory " + config.storage.contentLocation);
		} else {
		    console.log("created directory " + config.storage.contentLocation);
		    server.listen(config.port);
		    console.log("Listening on port: " + config.port);
		}

	    });

	}

    });
}

// GET
app.get("/:resource", function (req, res) {

    console.log("req: " + util.inspect(req));

    var requestState = {};

    requestState.headers = req.headers;
    requestState.url = req.url;
    requestState.method = req.method;

    var file;
    if (req.params.resource == undefined) {
	file = config.storage.contentLocation + "/index.html";
    } else {
	file = config.storage.contentLocation + "/" + req.params.resource;
    }

    requestState.requestedFile = file;

    console.log("requestState: " + requestState);

    fs.readFile(file, function (err, data) {

	if (err) {
	    console.log("error opening file: " + file + ": " + util.inspect(err));

	    if (err.errno == 34) { // No such file or directory
		requestState.responseCode = 404;
		res.json(404, requestState);
	    } else {
		res.json(500, err);
	    }

	} else {
	    console.log("found data in " + file);

	    console.log("\n\n" + util.inspect(data));

	    // TODO:

	    // lookup content type of file from original submission
	    // set content-type header

	    res.send(200, data);

	}

    });

});

// PUT
app.put("/:resource", function (req, res) {

    // TODO:
    //
    // - map file extension to MIME
    // - validate known MIME types against client Accept header, 4xx Not Acceptable if no match
    // - handle hierarchical directory traversal

    var requestState = {};

    requestState.headers = req.headers;
    requestState.url = req.url;
    requestState.method = req.method;

    var file;
    if (!req.params.resource) {
	file = config.storage.contentLocation + "/index.html";
    } else {
	file = config.storage.contentLocation + "/" + req.params.resource;
    }

    requestState.requestedFile = file;

    console.log("file to write to: " + file);
    //console.log("requestState: " + util.inspect(requestState));
    //console.log("contents of file: " + util.inspect(req));
    //console.log("content type: " + req.get('Content-Type'));

    getRawBody(req, { length: req.headers['Content-Length'] }, function(err, buffer) {

	//console.log("getRawBody callback, err: " + util.inspect(err) + ", buffer: " + util.inspect(buffer));

	if (err) {

	    console.log("error getting raw body: " + util.inspect(err));
	    res.json(500, err);

	} else {

	    console.log("processed request body, attempting to save as " + file);

	    fs.writeFile(file, buffer, { flag: 'w' }, function (err) {

		if (err) {
		    console.log("error writing to file: " + file);
		    res.json(500, err);
		} else {
		    console.log("request body saved to " + file);
		    res.send(204);
		}

	    });

	}

    });

});

// POST -> should this even exist?
app.post("/:resource", function (req, res) {

    res.json(405, { message: "Hypestore supports HTTP methods: GET, PUT, DELETE" });

});

function loadConfig() {
    console.log("Loading configuration for " + "./config.json");
    if (fs.existsSync("./config.json")) {
	var cfg = fs.readFileSync("./config.json", 'utf-8');
	return JSON.parse(cfg);
    } else {
	console.log("loadConfig: no config.json found");
	return undefined;
    }
}

<|endoftext|>


<commit_before>var express = require("express");
var bodyParser = require("body-parser");
var elasticsearch = require("elasticsearch");
var root = express();
var app = express();

var esservice = require("./elasticsearch.js");

var applicantConfig = {
  url: "172.31.61.189:9200",
  index: "sample_json",
  type: "applicant"
};

var labelConfig = {
  url: "172.31.61.189:9200",
  index: "labels",
  type: "label"
};

app.use(express.static("client"));

app.use(express.static("node_modules"));

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());

app.get("/service/applicants", function(req, res) {

  // var query = "name:Dave Mezzetti";
  esservice.query(labelConfig, req, res, "*", function(res, hits){
    //var ids = map source -> _id
    var query = '*';
    if (hits && hits.length > 0) {
      var ids = hits.map(function(hit) { return hit.id; })
      //same query logic * or NOT id ()
      if (ids && ids.length > 0) {
        query = "NOT id:(" + ids.join(",") + ")";
      }
   }

    esservice.query(applicantConfig, req, res, query, null);
  });

},function (error, response) {
  console.log(error);
});

//code for favorites, changes between favorite and archive--REQUIRED
app.post("/service/favorites", function(req, res) {
    var client = new elasticsearch.Client({
      host: 'interns.dataworks-inc.com/elasticsearch'
    });

    var id = req.body.id;
    var type = req.body.type;

    client.index({
    index: 'labels',
    type: 'label',
    id: id,
    body: {
      id: id,
      type: type,
    }
  }, function (error, response) {
    console.log(error);
  });
});

//get code for favorites
app.get("/service/favorites", function(req, res) {
  // var query = "name:Dave Mezzetti";
  esservice.query(labelConfig, req, res, "type: favorite", function(res, hits){
    //var ids = map source -> _id
    var query = '*';
    if (hits && hits.length > 0) {
      var ids = hits.map(function(hit) { return hit.id; })

      //same query logic * or NOT id ()
      if (ids && ids.length > 0) {
        query = "id:(" + ids.join(",") + ")"
      }
   }

    esservice.query(applicantConfig, req, res, query, null);
  });
},function (error, response) {
  console.log(error);
});

//get code for archive
app.get("/service/favorites", function(req, res) {
  // var query = "name:Dave Mezzetti";
  esservice.query(labelConfig, req, res, "type: archive", function(res, hits){
    //var ids = map source -> _id
    var query = '*';
    if (hits && hits.length > 0) {
      var ids = hits.map(function(hit) { return hit.id; })

      //same query logic * or NOT id ()
      if (ids && ids.length > 0) {
        query = "id:(" + ids.join(",") + ")"
      }
   }

    esservice.query(applicantConfig, req, res, query, null);
  });

},function (error, response) {
  console.log(error);
});

root.get("/", function(req, res) {
  res.redirect("/app");
});

root.use('/app', app);

//HTML5 mode
app.all('/*', function(req, res) {
  res.sendFile('index.html', {root: __dirname + "/../client/"});
});

var server = root.listen(8082, function () {
  var host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", host, port)

});

//   res.json([{
//     "name": "Joe Schweitzer",
//     "score": 0.99,
//     "currentEntity": "Data Works Inc.",
//     "currentLocation": "Reston, VA",
//     "skills": ["Grails", "Groovy", "Ext JS"]
//   }, {
//     "name": "Laura Schweitzer",
//     "score": 0.98,
//     "currentEntity": "Data Works Inc.",
//     "currentLocation": "Reston, VA",
//     "skills": ["Pentaho", "Ruby on Rails", "Javascript"]
//   }, {
//     "name": "Dave Mezzetti",
//     "score": 0.30,
//     "currentEntity": "Data Works Inc.",
//     "currentLocation": "Reston, VA",
//     "skills": ["Scala", "Spark", "Tweeting"]
//   }, {
//     "name": "Dennis Schweitzer",
//     "score": 0.58,
//     "currentEntity": "Data Works Inc.",
//     "currentLocation": "Reston, VA",
//     "skills": ["Pentaho", "Ruby on Rails", "Javascript"]
//   }]);
// });<commit_msg>fixed url for archive get method<commit_after>var express = require("express");
var bodyParser = require("body-parser");
var elasticsearch = require("elasticsearch");
var root = express();
var app = express();

var esservice = require("./elasticsearch.js");

var applicantConfig = {
  url: "172.31.61.189:9200",
  index: "sample_json",
  type: "applicant"
};

var labelConfig = {
  url: "172.31.61.189:9200",
  index: "labels",
  type: "label"
};

app.use(express.static("client"));

app.use(express.static("node_modules"));

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());

app.get("/service/applicants", function(req, res) {

  // var query = "name:Dave Mezzetti";
  esservice.query(labelConfig, req, res, "*", function(res, hits){
    //var ids = map source -> _id
    var query = '*';
    if (hits && hits.length > 0) {
      var ids = hits.map(function(hit) { return hit.id; })
      //same query logic * or NOT id ()
      if (ids && ids.length > 0) {
        query = "NOT id:(" + ids.join(",") + ")";
      }
   }

    esservice.query(applicantConfig, req, res, query, null);
  });

},function (error, response) {
  console.log(error);
});

//code for favorites, changes between favorite and archive--REQUIRED
app.post("/service/favorites", function(req, res) {
    var client = new elasticsearch.Client({
      host: 'interns.dataworks-inc.com/elasticsearch'
    });

    var id = req.body.id;
    var type = req.body.type;

    client.index({
    index: 'labels',
    type: 'label',
    id: id,
    body: {
      id: id,
      type: type,
    }
  }, function (error, response) {
    console.log(error);
  });
});

//get code for favorites
app.get("/service/favorites", function(req, res) {
  // var query = "name:Dave Mezzetti";
  esservice.query(labelConfig, req, res, "type: favorite", function(res, hits){
    //var ids = map source -> _id
    var query = '*';
    if (hits && hits.length > 0) {
      var ids = hits.map(function(hit) { return hit.id; })

      //same query logic * or NOT id ()
      if (ids && ids.length > 0) {
        query = "id:(" + ids.join(",") + ")"
      }
   }

    esservice.query(applicantConfig, req, res, query, null);
  });
},function (error, response) {
  console.log(error);
});

//get code for archive
app.get("/service/archive", function(req, res) {
  // var query = "name:Dave Mezzetti";
  esservice.query(labelConfig, req, res, "type: archive", function(res, hits){
    //var ids = map source -> _id
    var query = '*';
    if (hits && hits.length > 0) {
      var ids = hits.map(function(hit) { return hit.id; })

      //same query logic * or NOT id ()
      if (ids && ids.length > 0) {
        query = "id:(" + ids.join(",") + ")"
      }
   }

    esservice.query(applicantConfig, req, res, query, null);
  });

},function (error, response) {
  console.log(error);
});

root.get("/", function(req, res) {
  res.redirect("/app");
});

root.use('/app', app);

//HTML5 mode
app.all('/*', function(req, res) {
  res.sendFile('index.html', {root: __dirname + "/../client/"});
});

var server = root.listen(8082, function () {
  var host = server.address().address
  var port = server.address().port

  console.log("Example app listening at http://%s:%s", host, port)

});

//   res.json([{
//     "name": "Joe Schweitzer",
//     "score": 0.99,
//     "currentEntity": "Data Works Inc.",
//     "currentLocation": "Reston, VA",
//     "skills": ["Grails", "Groovy", "Ext JS"]
//   }, {
//     "name": "Laura Schweitzer",
//     "score": 0.98,
//     "currentEntity": "Data Works Inc.",
//     "currentLocation": "Reston, VA",
//     "skills": ["Pentaho", "Ruby on Rails", "Javascript"]
//   }, {
//     "name": "Dave Mezzetti",
//     "score": 0.30,
//     "currentEntity": "Data Works Inc.",
//     "currentLocation": "Reston, VA",
//     "skills": ["Scala", "Spark", "Tweeting"]
//   }, {
//     "name": "Dennis Schweitzer",
//     "score": 0.58,
//     "currentEntity": "Data Works Inc.",
//     "currentLocation": "Reston, VA",
//     "skills": ["Pentaho", "Ruby on Rails", "Javascript"]
//   }]);
// });<|endoftext|>