<commit_before>import React from 'react';
import { NavLink } from 'fluxible-router';
import {FormattedMessage, defineMessages} from 'react-intl';
import PropTypes from 'prop-types';

class Footer extends React.Component {
    constructor(props) {
        super(props);
        this.openFacebook = this.openFacebook.bind(this);
        this.openLinkedIn = this.openLinkedIn.bind(this);
        this.openTwitter = this.openTwitter.bind(this);

    }

    openFacebook() {
        window.open('https://www.facebook.com/slidewiki/', '_blank');
    }

    openLinkedIn() {
        window.open('https://www.linkedin.com/company/slidewiki-eu', '_blank');
    }

    openTwitter() {
        window.open('https://twitter.com/slidewiki', '_blank');
    }
    render() {

        const messages = defineMessages({
            srHeader: {
                id: 'footer.sr.header',
                defaultMessage: 'Information about SlideWiki'
            },
            header: {
                id: 'footer.header',
                defaultMessage: 'About'
            },
            aboutus: {
                id: 'footer.about',
                defaultMessage: 'About Us'
            },
            contact: {
                id: 'footer.contact',
                defaultMessage: 'Contact Us'
            },
            guides: {
                id: 'footer.guides',
                defaultMessage: 'Guides and Help'
            },
            accessibility: {
                id: 'footer.accessibility',
                defaultMessage: 'Accessibility'
            },
            termsHeader: {
                id: 'footer.terms.header',
                defaultMessage: 'Terms \\u0026 Conditions'
            },
            terms: {
                id: 'footer.terms',
                defaultMessage: 'Terms'
            },
            license: {
                id: 'footer.license',
                defaultMessage: 'License'
            },
            imprint: {
                id: 'footer.imprint',
                defaultMessage: 'Imprint'
            },
            data: {
                id: 'footer.data',
                defaultMessage: 'Data Protection'
            },
            funding: {
                id: 'footer.funding',
                defaultMessage: 'Funding'
            },
            fundingtext: {
                id: 'footer.funding.text',
                defaultMessage: 'The SlideWiki project has received funding from the European Union\\u0027s Horizon 2020 research and innovation programme under grant agreement No 688095'
            },
            copyrightText: {
                id: 'footer.copyrightText',
                defaultMessage: 'Copyright'
            },
            copyrightRights: {
                id: 'footer.copyrightRights',
                defaultMessage: 'All Rights Reserved'
            },
        });

        let rowClasses = {paddingTop: '0px', paddingBottom: '0px'};
        let currentYear = new Date().getFullYear();

        return (

{this.context.intl.formatMessage(messages.srHeader)}

{this.context.intl.formatMessage(messages.header)}

{this.context.intl.formatMessage(messages.aboutus)}

{this.context.intl.formatMessage(messages.contact)}

{this.context.intl.formatMessage(messages.guides)}

{this.context.intl.formatMessage(messages.accessibility)}

Github

{this.context.intl.formatMessage(messages.termsHeader)}

<NavLink routeName='terms' href='/terms'>{this.context.intl.formatMessage(messages.terms)}</NavLink>

<NavLink routeName='license' href='/license'>{this.context.intl.formatMessage(messages.license)}</NavLink>

<NavLink routeName='imprint' href='/imprint'>{this.context.intl.formatMessage(messages.imprint)}</NavLink>

<NavLink routeName='dataprotection' href='/dataprotection'>{this.context.intl.formatMessage(messages.data)}</NavLink>

{this.context.intl.formatMessage(messages.funding)}

{this.context.intl.formatMessage(messages.fundingtext)}

                                        {this.context.intl.formatMessage(messages.copyrightText)}{' '}
                                        © 2016-{currentYear} {' - '}
                                        {this.context.intl.formatMessage(messages.copyrightRights)}

Version GIT_VERSION - Build GIT_COMMIT@GIT_BRANCH

                                   {/*

Follow us

<button className='ui circular facebook icon button' onClick={this.openFacebook}></button>

<button className='ui circular linkedin icon button' onClick={this.openLinkedIn}></button>

<button className='ui circular twitter icon button' onClick={this.openTwitter}></button>

If you would like to provide feedback or report issues, please use our Contact Form.

*/}

        );
    }
}

Footer.contextTypes = {
    intl: PropTypes.object.isRequired
};

export default Footer;
<commit_msg>Fix unnecessary content-info role<commit_after>import React from 'react';
import { NavLink } from 'fluxible-router';
import {FormattedMessage, defineMessages} from 'react-intl';
import PropTypes from 'prop-types';

class Footer extends React.Component {
    constructor(props) {
        super(props);
        this.openFacebook = this.openFacebook.bind(this);
        this.openLinkedIn = this.openLinkedIn.bind(this);
        this.openTwitter = this.openTwitter.bind(this);

    }

    openFacebook() {
        window.open('https://www.facebook.com/slidewiki/', '_blank');
    }

    openLinkedIn() {
        window.open('https://www.linkedin.com/company/slidewiki-eu', '_blank');
    }

    openTwitter() {
        window.open('https://twitter.com/slidewiki', '_blank');
    }
    render() {

        const messages = defineMessages({
            srHeader: {
                id: 'footer.sr.header',
                defaultMessage: 'Information about SlideWiki'
            },
            header: {
                id: 'footer.header',
                defaultMessage: 'About'
            },
            aboutus: {
                id: 'footer.about',
                defaultMessage: 'About Us'
            },
            contact: {
                id: 'footer.contact',
                defaultMessage: 'Contact Us'
            },
            guides: {
                id: 'footer.guides',
                defaultMessage: 'Guides and Help'
            },
            accessibility: {
                id: 'footer.accessibility',
                defaultMessage: 'Accessibility'
            },
            termsHeader: {
                id: 'footer.terms.header',
                defaultMessage: 'Terms \\u0026 Conditions'
            },
            terms: {
                id: 'footer.terms',
                defaultMessage: 'Terms'
            },
            license: {
                id: 'footer.license',
                defaultMessage: 'License'
            },
            imprint: {
                id: 'footer.imprint',
                defaultMessage: 'Imprint'
            },
            data: {
                id: 'footer.data',
                defaultMessage: 'Data Protection'
            },
            funding: {
                id: 'footer.funding',
                defaultMessage: 'Funding'
            },
            fundingtext: {
                id: 'footer.funding.text',
                defaultMessage: 'The SlideWiki project has received funding from the European Union\\u0027s Horizon 2020 research and innovation programme under grant agreement No 688095'
            },
            copyrightText: {
                id: 'footer.copyrightText',
                defaultMessage: 'Copyright'
            },
            copyrightRights: {
                id: 'footer.copyrightRights',
                defaultMessage: 'All Rights Reserved'
            },
        });

        let rowClasses = {paddingTop: '0px', paddingBottom: '0px'};
        let currentYear = new Date().getFullYear();

        return (

{this.context.intl.formatMessage(messages.srHeader)}

{this.context.intl.formatMessage(messages.header)}

{this.context.intl.formatMessage(messages.aboutus)}

{this.context.intl.formatMessage(messages.contact)}

{this.context.intl.formatMessage(messages.guides)}

{this.context.intl.formatMessage(messages.accessibility)}

Github

{this.context.intl.formatMessage(messages.termsHeader)}

<NavLink routeName='terms' href='/terms'>{this.context.intl.formatMessage(messages.terms)}</NavLink>

<NavLink routeName='license' href='/license'>{this.context.intl.formatMessage(messages.license)}</NavLink>

<NavLink routeName='imprint' href='/imprint'>{this.context.intl.formatMessage(messages.imprint)}</NavLink>

<NavLink routeName='dataprotection' href='/dataprotection'>{this.context.intl.formatMessage(messages.data)}</NavLink>

{this.context.intl.formatMessage(messages.funding)}

{this.context.intl.formatMessage(messages.fundingtext)}

                                        {this.context.intl.formatMessage(messages.copyrightText)}{' '}
                                        © 2016-{currentYear} {' - '}
                                        {this.context.intl.formatMessage(messages.copyrightRights)}

Version GIT_VERSION - Build GIT_COMMIT@GIT_BRANCH

                                   {/*

Follow us

<button className='ui circular facebook icon button' onClick={this.openFacebook}></button>

<button className='ui circular linkedin icon button' onClick={this.openLinkedIn}></button>

<button className='ui circular twitter icon button' onClick={this.openTwitter}></button>

If you would like to provide feedback or report issues, please use our Contact Form.

*/}

        );
    }
}

Footer.contextTypes = {
    intl: PropTypes.object.isRequired
};

export default Footer;
<|endoftext|>


<commit_before>var session = require('express-session');
var passport = require('passport');
var sop = require('simple-object-path');

function redisProtect(req, res, next) {
    res.header('Cache-Control', 'no-cache');
    const token = sop(req.session, 'passport/user/accessToken');
    console.log(req.session);
    if (!token) {
        const redirectUrl = 'https://auth.crosshj.com/';
        const redirectTo = 'https://cents.crosshj.com' + req.originalUrl;
        if(req.session){
            req.session.redirectTo = redirectTo;
        }
        return res.redirect(redirectUrl);
    }
    res.locals.token = token;
    next();
}

function redisSession(settings) {
    const RedisStore = require('connect-redis')(session);
    return session({
        secret: settings.cookieSecret,
        name: 'centsSession',
        store: new RedisStore({
            host: 'redis',
            port: 6379
        }),
        resave: false,
        saveUninitialized: true,
        cookie: {
            path: '/',
            domain: '.crosshj.com'
        }
    });
}

function fileStoreSession(settings) {
    var store = ((sess) => {
        const FileStore = require('session-file-store')(sess);
        const fileStoreOptions = {
            path: settings.folderLocation
        };
        const store = new FileStore(fileStoreOptions);
        return store;
    })(session);
    return session({
        secret: settings.cookieSecret,
        store,
        resave: false,
        saveUninitialized: false
    });
}

function mongoSession(settings) {
    var store = ((sess) => {
        var MongoDBStore = require('connect-mongodb-session')(sess);
        const connectErrorCallback = (error) => {
            if (error) {
                console.log({ mongoConnectError: error });
            }
        };
        var store = new MongoDBStore({
            uri: 'mongodb://ubuntu:27017',
            databaseName: 'cents',
            collection: 'sessions'
        }, connectErrorCallback);
        store.on('error', connectErrorCallback);
        return store;

    })(session);
    session({
        secret: settings.cookieSecret,
        store,
        resave: false,
        saveUninitialized: false
    });
}

class AppSession {
    constructor(app, store, settings) {
        this.store = store;

        const whichSession = {
            mongo: mongoSession,
            redis: redisSession,
            file: fileStoreSession
        }[store] || fileStoreSession;

        this.express = whichSession(settings);
        app.use(this.express);
        app.use(passport.initialize());
        app.use(passport.session());

        if(store === 'mongo' || store === 'file'){
            var authentication = require('./authentication');
            authentication.init(app);
        }

        const passportProtect = passport.authenticationMiddleware
            ? passport.authenticationMiddleware()
            : (req, res, next) => next('error with passport authenticationMiddleware')
        const whichProtect = {
            mongo: passportProtect,
            redis: redisProtect,
            file: passportProtect
        }[store] || passportProtect;

        this.protect = whichProtect;
    }
}

module.exports = AppSession;
<commit_msg>Update session.js<commit_after>var session = require('express-session');
var passport = require('passport');
var sop = require('simple-object-path');

function redisProtect(req, res, next) {
    res.header('Cache-Control', 'no-cache');
    const token = sop(req.session, 'passport/user/accessToken');
    console.log(req.session);
    if (!token) {
        const redirectUrl = 'https://auth.crosshj.com/';
        const redirectTo = 'https://cents.crosshj.com' + req.originalUrl;
        if(req.session){
            req.session.redirectTo = redirectTo;
        }
        return res.redirect(redirectUrl);
    }
    res.locals.token = token;
    next();
}

function redisSession(settings) {
    const RedisStore = require('connect-redis')(session);
    return session({
        secret: settings.cookieSecret,
        name: 'gAuthSess',
        store: new RedisStore({
            host: 'redis',
            port: 6379
        }),
        resave: false,
        saveUninitialized: true,
        cookie: {
            path: '/',
            domain: '.crosshj.com'
        }
    });
}

function fileStoreSession(settings) {
    var store = ((sess) => {
        const FileStore = require('session-file-store')(sess);
        const fileStoreOptions = {
            path: settings.folderLocation
        };
        const store = new FileStore(fileStoreOptions);
        return store;
    })(session);
    return session({
        secret: settings.cookieSecret,
        store,
        resave: false,
        saveUninitialized: false
    });
}

function mongoSession(settings) {
    var store = ((sess) => {
        var MongoDBStore = require('connect-mongodb-session')(sess);
        const connectErrorCallback = (error) => {
            if (error) {
                console.log({ mongoConnectError: error });
            }
        };
        var store = new MongoDBStore({
            uri: 'mongodb://ubuntu:27017',
            databaseName: 'cents',
            collection: 'sessions'
        }, connectErrorCallback);
        store.on('error', connectErrorCallback);
        return store;

    })(session);
    session({
        secret: settings.cookieSecret,
        store,
        resave: false,
        saveUninitialized: false
    });
}

class AppSession {
    constructor(app, store, settings) {
        this.store = store;

        const whichSession = {
            mongo: mongoSession,
            redis: redisSession,
            file: fileStoreSession
        }[store] || fileStoreSession;

        this.express = whichSession(settings);
        app.use(this.express);
        app.use(passport.initialize());
        app.use(passport.session());

        if(store === 'mongo' || store === 'file'){
            var authentication = require('./authentication');
            authentication.init(app);
        }

        const passportProtect = passport.authenticationMiddleware
            ? passport.authenticationMiddleware()
            : (req, res, next) => next('error with passport authenticationMiddleware')
        const whichProtect = {
            mongo: passportProtect,
            redis: redisProtect,
            file: passportProtect
        }[store] || passportProtect;

        this.protect = whichProtect;
    }
}

module.exports = AppSession;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO: Should have a GUID 'id' instead of name, since now
// you can't have two properties with the same name but
// different parents.
foam.CLASS({
  package: 'com.google.flow',
  name: 'Property',

  ids: [ 'name' ],

  properties: [
    {
      class: 'String',
      name: 'name'
    },
    {
      name: 'value',
      cloneProperty: function(o, m) {
        m[this.name ] = o.cls_.create({
          x:      o.x,
          y:      o.y,
          width:  o.width,
          height: o.height,
          radius: o.radius,
          border: o.radius,
          color:  o.color
        });
      }
    }
  ],
  actions: [
    {
      name: 'deleteRow',
      label: 'X',
      code: function deleteRow(X) {
        X.properties.remove(X.data);
      }
    }
  ]
});

// TODO(adamvy): Remove the need to store this relationship globally.
var relationship = foam.RELATIONSHIP({
  name: 'children',
  inverseName: 'parent',
  cadinality: '1:*',
  sourceModel: 'com.google.flow.Property',
  targetModel: 'com.google.flow.Property',
  targetDAOKey: 'properties'
});

foam.CLASS({
  package: 'com.google.flow',
  name: 'FLOW',
  extends: 'foam.u2.Element',

  implements: [
    'foam.mlang.Expressions',
    'foam.memento.MementoMgr'
  ],

  requires: [
    'com.google.flow.Halo',
    'com.google.flow.Property',
    'foam.dao.EasyDAO',
    'foam.graphics.Box',
    'foam.graphics.CView',
    'foam.graphics.Circle',
    'foam.physics.Physical',
    'foam.physics.PhysicsEngine',
    'foam.u2.PopupView',
    'foam.u2.TableView',
    'foam.util.Timer',
    'foam.u2.view.TreeView',
    'com.google.flow.DetailPropertyView'
  ],

  exports: [
    'timer',
    'as data',
    'properties',
    'scope'
  ],

  axioms: [
    foam.u2.CSS.create({
      code: function() {/*
      body { overflow: hidden; user-select: none; font-family: 'Roboto', sans-serif; color: #444; }
      ^ { display: flex; }
      ^ > * { padding-left: 16px; padding-right: 16px; }
      ^tools, ^properties, ^sheet { box-shadow: 3px 3px 6px 0 gray; height: 100%; }
      ^sheet { width: 100%; overflow-y: auto; }
      ^tools thead, ^properties thead { display: none }
      ^tools tr { height: 30px }
      .foam-u2-TableView { border-collapse: collapse; }
      .foam-u2-TableView td { padding-left: 6px; }
      .foam-u2-TableView-selected { outline: 1px solid red; }
      ^ canvas { border: none; }
      ^ .foam-u2-ActionView { margin: 10px; }
      ^properties .foam-u2-view-TreeViewRow { position: relative; }
      ^properties .foam-u2-ActionView, ^properties .foam-u2-ActionView:hover { background: white; padding: 0; position: absolute; right: 2px; border: none; margin: 6px 0 0 0; }
      .foam-u2-Tabs { padding-top: 0 !important; }
      input[type="range"] { width: 150px; height: 15px; }
      input[type="color"] { width: 22px; }
      */}
    })
  ],

  properties: [
    {
      name: 'scope',
      factory: function() { return {a:42}; },
      documentation: 'Scope to run reactive formulas in.'
    },
    {
      name: 'physics',
      factory: function() {
        return this.PhysicsEngine.create({
          bounceOnWalls: true,
          bounds: this.canvas
        });
      }
    },
    {
      name: 'timer',
      factory: function() {
        return this.Timer.create();
      }
    },
    'feedback_',
    'currentTool',
    {
      class: 'foam.dao.DAOProperty',
      name: 'tools',
      view: {
        class: 'foam.u2.TableView',
        columns: [ foam.core.Model.NAME ]
      },
      factory: function() {
        var dao = foam.dao.EasyDAO.create({
          of: 'foam.core.Model',
          daoType: 'ARRAY'
        });
        dao.put(com.google.flow.Box.model_);
        dao.put(com.google.flow.Circle.model_);
        dao.put(com.google.flow.Text.model_);
        dao.put(com.google.flow.Clock.model_);
        dao.put(com.google.flow.Mushroom.model_);
        dao.put(com.google.foam.demos.robot.Robot.model_);
        dao.put(com.google.flow.Desk.model_);
        dao.put(com.google.flow.DuplexDesk.model_);
        dao.put(com.google.flow.Desks.model_);
        dao.put(foam.audio.Speak.model_);
        dao.put(foam.audio.Beep.model_);
        dao.put(com.google.flow.Cursor.model_);
        return dao;
      }
    },
    {
      name: 'value',
      view: { class: 'com.google.flow.ReactiveDetailView', showActions: true }
//      view: { class: 'foam.u2.DetailView', showActions: true }
    },
    {
      name: 'selected',
      postSet: function(o, n) { this.value = n && n.value; }
    },
    {
      name: 'properties',
      view: {
        class: 'foam.u2.view.TreeView',
        relationship: relationship,
        startExpanded: true,
        formatter: function() {
          var X = this.__subSubContext__;
          this.start('span').add(X.data.name).end().
            start('span').nbsp().style({ display: 'inline-block', width: '50px' }).end().
            start('span').add(com.google.flow.Property.DELETE_ROW).end();
        }
      },
      xview: {
        class: 'foam.u2.TableView',
        columns: [
          com.google.flow.Property.NAME,
          com.google.flow.Property.DELETE_ROW
        ]
      },
      factory: function() {
        var dao = foam.dao.EasyDAO.create({
          of: 'com.google.flow.Property',
          guid: true,
          seqProperty: this.Property.NAME,
//          daoType: 'MDAO'
          daoType: 'ARRAY'
        });

        var p;

        p = this.Property.create({name: 'canvas1', value: this.canvas});
        this.physics.setPrivate_('lpp_', p);
        dao.put(p);

        p = this.Property.create({name: 'timer', value: this.timer, parent: 'canvas1'});
        this.physics.setPrivate_('lpp_', p);
        dao.put(p);

        p = this.Property.create({name: 'physics', value: this.physics, parent: 'canvas1' });
        this.physics.setPrivate_('lpp_', p);
        dao.put(p);

        this.scope.canvas1 = this.canvas;
        this.scope.physics = this.physics;
        this.scope.timer   = this.timer;
        this.scope.cycle   = this.timer.cycle.bind(this.timer);

        return dao;
      }
    },
    {
      name: 'canvas',
      factory: function() {
        return this.Box.create({autoRepaint: true, width: 600, height: 600, color: '#f3f3f3'});
//        return this.Box.create({autoRepaint: true, width: 900, height: 870, color: '#f3f3f3'});
      }
    },
    'mouseTarget'
  ],

  methods: [

    function initE() {
      this.timer.start();

      this.properties.on.put.sub(this.onPropertyPut);
      this.properties.on.remove.sub(this.onPropertyRemove);

      var halo = this.Halo.create();
      halo.selected$.linkFrom(this.selected$);

      this.memento$.sub(function() {
        var m = this.memento;
        if ( this.feedback_ ) return;
        this.properties.skip(2).removeAll();
        if ( m ) {
          for ( var i = 0 ; i < m.length ; i++ ) {
            var p = m[i];
            this.addProperty(p.value, p.name, null, p.parent);
          }
        }
        this.selected = null;
      }.bind(this));

      this.
          cssClass(this.myCls()).
          start('div').
            cssClass(this.myCls('tools')).
            start(this.TOOLS, {selection$: this.currentTool$}).end().
          end().
          start('center').
            start(foam.u2.Tabs).
              start(foam.u2.Tab, {label: 'canvas1'}).
                start(this.canvas).
//                  on('click',       this.onClick).
                  on('mousedown',   this.onMouseDown).
                  on('mouseup',     this.onMouseUp).
                  on('mousemove',   this.onMouseMove).
                  on('contextmenu', this.onRightClick).
                end().
              end().
              start(foam.u2.Tab, {label: '+'}).
              end().
            end().
            start(this.BACK,  {label: 'Undo'}).end().
            start(this.FORTH, {label: 'Redo'}).end().
          end().
          start('div').
            cssClass(this.myCls('properties')).
            start(this.PROPERTIES, {selection$: this.selected$}).end().
          end().
          start(this.VALUE).
            cssClass(this.myCls('sheet')).
            show(this.slot(function(selected) { return !!selected; })).
          end();
    },

    function addProperty(value, opt_name, opt_i, opt_parent) {
      var self = this;
      if ( ! opt_name ) {
        var i = opt_i || 1;
        var prefix = value.cls_.name.toLowerCase();
        this.properties.find(prefix + i).then(function (o) {
          self.addProperty(value, null, i+1, opt_parent);
        }).catch(function(x) {
          self.addProperty(value, prefix+i, null, opt_parent);
        });
      } else {
        var p = this.Property.create({
          name: opt_name,
          value: value
        });
        if ( opt_parent ) p.parent = opt_parent;
        value.setPrivate_('lpp_', p);
        this.properties.put(p);
        this.selected = p;
      }
    },

    function updateMemento() {
      this.properties.skip(2).select().then(function(s) {
//        console.log('*************** updateMemento: ', s.a.length);
        this.feedback_ = true;
//        this.memento = foam.Array.clone(s.a);
        this.feedback_ = false;
      }.bind(this));
    }
  ],

  listeners: [
    function onPropertyPut(_, _, _, p) {
      var o = p.value;

      this.scope[p.name] = p.value;
      if ( this.CView.isInstance(o) ) {
        if ( ! p.parent ) {
          this.canvas.add(o);

          if ( this.Physical.isInstance(o) ) {
            this.physics.add(o);
          }
        } else {
          this.properties.find(p.parent).then(function(p2) {
            // Adjust position of object so that it stays in its current
            // location. TODO: something better with transforms as this
            // probably doesn't work with scaling and rotation.
            var parent = p2.value;
            while ( parent ) {
              o.x -= parent.x;
              o.y -= parent.y;
              parent = parent.parent;
            }

            p2.value.add(o);
          });
        }
      }
    },

    function onPropertyRemove(_, _, _, p) {
      var o = p.value;

      delete this.scope[p.name];

      if ( p === this.selected ) this.selected = null;

      if ( this.CView.isInstance(o) ) {
        if ( ! p.parent ) {
          this.canvas.remove(o);

          if ( this.Physical.isInstance(o) ) {
            this.physics.remove(o);
          }
        } else {
          this.properties.find(p.parent).then(function(p2) {
            p2.value.remove(o);
          });
        }
      }
    },

    function onMouseDown(evt) {
      this.onClick(evt);
      var x = evt.offsetX, y = evt.offsetY;
      var c = this.canvas.findFirstChildAt(x, y);
      if ( c === this.canvas ) {
        this.mouseTarget = null;
      } else {
        console.log('mouseDown: ', c && c.cls_.name);
        this.mouseTarget = c;
        if ( c && c.onMouseDown ) c.onMouseDown(evt);
      }
    },

    function onMouseUp(evt) {
      this.mouseTarget = null;
    },

    function onMouseMove(evt) {
      if ( this.mouseTarget && this.mouseTarget.onMouseMove ) this.mouseTarget.onMouseMove(evt);
    },

    function onClick(evt) {
      var x = evt.offsetX, y = evt.offsetY;
      var c = this.canvas.findFirstChildAt(x, y);

      if ( this.Halo.isInstance(c) ) return;

      if ( c === this.canvas ) {
        var tool = this.currentTool;
        if ( ! tool ) return;
        var cls = this.lookup(tool.id);
        var o = cls.create({x: x, y: y}, this.__subContext__);
        var p = this.addProperty(o, null, null, 'canvas1');
        this.updateMemento();
      } else {
        for ( ; c !== this.canvas ; c = c.parent ) {
          var p = c.getPrivate_('lpp_');
          if ( p ) {
            this.selected = p;
            break;
          }
        }
      }
    },

    function onRightClick(evt) {
      evt.preventDefault();
      if ( ! this.selected ) return;
    }
  ]
});
<commit_msg>Minor cleanup<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// TODO: Should have a GUID 'id' instead of name, since now
// you can't have two properties with the same name but
// different parents.
foam.CLASS({
  package: 'com.google.flow',
  name: 'Property',

  ids: [ 'name' ],

  properties: [
    {
      class: 'String',
      name: 'name'
    },
    {
      name: 'value',
      cloneProperty: function(o, m) {
        m[this.name ] = o.cls_.create({
          x:      o.x,
          y:      o.y,
          width:  o.width,
          height: o.height,
          radius: o.radius,
          border: o.radius,
          color:  o.color
        });
      }
    }
  ],
  actions: [
    {
      name: 'deleteRow',
      label: 'X',
      code: function deleteRow(X) {
        X.properties.remove(X.data);
      }
    }
  ]
});

// TODO(adamvy): Remove the need to store this relationship globally.
var relationship = foam.RELATIONSHIP({
  name: 'children',
  inverseName: 'parent',
  cadinality: '1:*',
  sourceModel: 'com.google.flow.Property',
  targetModel: 'com.google.flow.Property',
  targetDAOKey: 'properties'
});

foam.CLASS({
  package: 'com.google.flow',
  name: 'FLOW',
  extends: 'foam.u2.Element',

  implements: [
    'foam.mlang.Expressions',
    'foam.memento.MementoMgr'
  ],

  requires: [
    'com.google.flow.Halo',
    'com.google.flow.Property',
    'foam.dao.EasyDAO',
    'foam.graphics.Box',
    'foam.graphics.CView',
    'foam.graphics.Circle',
    'foam.physics.Physical',
    'foam.physics.PhysicsEngine',
    'foam.u2.PopupView',
    'foam.u2.TableView',
    'foam.util.Timer',
    'foam.u2.view.TreeView',
    'com.google.flow.DetailPropertyView'
  ],

  exports: [
    'timer',
    'as data',
    'properties',
    'scope'
  ],

  axioms: [
    foam.u2.CSS.create({
      code: function() {/*
      body { overflow: hidden; user-select: none; font-family: 'Roboto', sans-serif; color: #444; }
      ^ { display: flex; }
      ^ > * { padding-left: 16px; padding-right: 16px; }
      ^tools, ^properties, ^sheet { box-shadow: 3px 3px 6px 0 gray; height: 100%; }
      ^sheet { width: 100%; overflow-y: auto; }
      ^tools thead, ^properties thead { display: none }
      ^tools tr { height: 30px }
      .foam-u2-TableView { border-collapse: collapse; }
      .foam-u2-TableView td { padding-left: 6px; }
      .foam-u2-TableView-selected { outline: 1px solid red; }
      ^ canvas { border: none; }
      ^ .foam-u2-ActionView { margin: 10px; }
      ^properties .foam-u2-view-TreeViewRow { position: relative; }
      ^properties .foam-u2-ActionView, ^properties .foam-u2-ActionView:hover { background: white; padding: 0; position: absolute; right: 2px; border: none; margin: 6px 0 0 0; }
      .foam-u2-Tabs { padding-top: 0 !important; }
      input[type="range"] { width: 150px; height: 15px; }
      input[type="color"] { width: 22px; }
      */}
    })
  ],

  properties: [
    {
      name: 'scope',
      factory: function() { return {a:42}; },
      documentation: 'Scope to run reactive formulas in.'
    },
    {
      name: 'physics',
      factory: function() {
        return this.PhysicsEngine.create({
          bounceOnWalls: true,
          bounds: this.canvas
        });
      }
    },
    {
      name: 'timer',
      factory: function() {
        return this.Timer.create();
      }
    },
    'feedback_',
    'currentTool',
    {
      class: 'foam.dao.DAOProperty',
      name: 'tools',
      view: {
        class: 'foam.u2.TableView',
        columns: [ foam.core.Model.NAME ]
      },
      factory: function() {
        var dao = foam.dao.EasyDAO.create({
          of: 'foam.core.Model',
          daoType: 'ARRAY'
        });
        dao.put(com.google.flow.Box.model_);
        dao.put(com.google.flow.Circle.model_);
        dao.put(com.google.flow.Text.model_);
        dao.put(com.google.flow.Clock.model_);
        dao.put(com.google.flow.Mushroom.model_);
        dao.put(com.google.foam.demos.robot.Robot.model_);
        dao.put(com.google.flow.Desk.model_);
        dao.put(com.google.flow.DuplexDesk.model_);
        dao.put(com.google.flow.Desks.model_);
        dao.put(foam.audio.Speak.model_);
        dao.put(foam.audio.Beep.model_);
        dao.put(com.google.flow.Cursor.model_);
        return dao;
      }
    },
    {
      name: 'value',
      view: { class: 'com.google.flow.ReactiveDetailView', showActions: true }
//      view: { class: 'foam.u2.DetailView', showActions: true }
    },
    {
      name: 'selected',
      postSet: function(o, n) { this.value = n && n.value; }
    },
    {
      name: 'properties',
      view: {
        class: 'foam.u2.view.TreeView',
        relationship: relationship,
        startExpanded: true,
        formatter: function() {
          var X = this.__subSubContext__;
          this.start('span').add(X.data.name).end().
            start('span').nbsp().style({ display: 'inline-block', width: '50px' }).end().
            start('span').add(com.google.flow.Property.DELETE_ROW).end();
        }
      },
      factory: function() {
        var dao = foam.dao.EasyDAO.create({
          of: 'com.google.flow.Property',
          guid: true,
          seqProperty: this.Property.NAME,
//          daoType: 'MDAO'
          daoType: 'ARRAY'
        });

        var p;

        p = this.Property.create({name: 'canvas1', value: this.canvas});
        this.physics.setPrivate_('lpp_', p);
        dao.put(p);

        p = this.Property.create({name: 'timer', value: this.timer, parent: 'canvas1'});
        this.physics.setPrivate_('lpp_', p);
        dao.put(p);

        p = this.Property.create({name: 'physics', value: this.physics, parent: 'canvas1' });
        this.physics.setPrivate_('lpp_', p);
        dao.put(p);

        this.scope.canvas1 = this.canvas;
        this.scope.physics = this.physics;
        this.scope.timer   = this.timer;
        this.scope.cycle   = this.timer.cycle.bind(this.timer);

        return dao;
      }
    },
    {
      name: 'canvas',
      factory: function() {
        return this.Box.create({autoRepaint: true, width: 600, height: 600, color: '#f3f3f3'});
//        return this.Box.create({autoRepaint: true, width: 900, height: 870, color: '#f3f3f3'});
      }
    },
    'mouseTarget'
  ],

  methods: [

    function initE() {
      this.timer.start();

      this.properties.on.put.sub(this.onPropertyPut);
      this.properties.on.remove.sub(this.onPropertyRemove);

      var halo = this.Halo.create();
      halo.selected$.linkFrom(this.selected$);

      this.memento$.sub(function() {
        var m = this.memento;
        if ( this.feedback_ ) return;
        this.properties.skip(2).removeAll();
        if ( m ) {
          for ( var i = 0 ; i < m.length ; i++ ) {
            var p = m[i];
            this.addProperty(p.value, p.name, null, p.parent);
          }
        }
        this.selected = null;
      }.bind(this));

      this.
          cssClass(this.myCls()).
          start('div').
            cssClass(this.myCls('tools')).
            start(this.TOOLS, {selection$: this.currentTool$}).end().
          end().
          start('center').
            start(foam.u2.Tabs).
              start(foam.u2.Tab, {label: 'canvas1'}).
                start(this.canvas).
//                  on('click',       this.onClick).
                  on('mousedown',   this.onMouseDown).
                  on('mouseup',     this.onMouseUp).
                  on('mousemove',   this.onMouseMove).
                  on('contextmenu', this.onRightClick).
                end().
              end().
              start(foam.u2.Tab, {label: '+'}).
              end().
            end().
            start(this.BACK,  {label: 'Undo'}).end().
            start(this.FORTH, {label: 'Redo'}).end().
          end().
          start('div').
            cssClass(this.myCls('properties')).
            start(this.PROPERTIES, {selection$: this.selected$}).end().
          end().
          start(this.VALUE).
            cssClass(this.myCls('sheet')).
            show(this.slot(function(selected) { return !!selected; })).
          end();
    },

    function addProperty(value, opt_name, opt_i, opt_parent) {
      var self = this;
      if ( ! opt_name ) {
        var i = opt_i || 1;
        var prefix = value.cls_.name.toLowerCase();
        this.properties.find(prefix + i).then(function (o) {
          self.addProperty(value, null, i+1, opt_parent);
        }).catch(function(x) {
          self.addProperty(value, prefix+i, null, opt_parent);
        });
      } else {
        var p = this.Property.create({
          name: opt_name,
          value: value
        });
        if ( opt_parent ) p.parent = opt_parent;
        value.setPrivate_('lpp_', p);
        this.properties.put(p);
        this.selected = p;
      }
    },

    function updateMemento() {
      this.properties.skip(2).select().then(function(s) {
//        console.log('*************** updateMemento: ', s.a.length);
        this.feedback_ = true;
//        this.memento = foam.Array.clone(s.a);
        this.feedback_ = false;
      }.bind(this));
    }
  ],

  listeners: [
    function onPropertyPut(_, _, _, p) {
      var o = p.value;

      this.scope[p.name] = p.value;
      if ( this.CView.isInstance(o) ) {
        if ( ! p.parent ) {
          this.canvas.add(o);

          if ( this.Physical.isInstance(o) ) {
            this.physics.add(o);
          }
        } else {
          this.properties.find(p.parent).then(function(p2) {
            // Adjust position of object so that it stays in its current
            // location. TODO: something better with transforms as this
            // probably doesn't work with scaling and rotation.
            var parent = p2.value;
            while ( parent ) {
              o.x -= parent.x;
              o.y -= parent.y;
              parent = parent.parent;
            }

            p2.value.add(o);
          });
        }
      }
    },

    function onPropertyRemove(_, _, _, p) {
      var o = p.value;

      delete this.scope[p.name];

      if ( p === this.selected ) this.selected = null;

      if ( this.CView.isInstance(o) ) {
        if ( ! p.parent ) {
          this.canvas.remove(o);

          if ( this.Physical.isInstance(o) ) {
            this.physics.remove(o);
          }
        } else {
          this.properties.find(p.parent).then(function(p2) {
            p2.value.remove(o);
          });
        }
      }
    },

    function onMouseDown(evt) {
      this.onClick(evt);
      var x = evt.offsetX, y = evt.offsetY;
      var c = this.canvas.findFirstChildAt(x, y);
      if ( c === this.canvas ) {
        this.mouseTarget = null;
      } else {
        console.log('mouseDown: ', c && c.cls_.name);
        this.mouseTarget = c;
        if ( c && c.onMouseDown ) c.onMouseDown(evt);
      }
    },

    function onMouseUp(evt) {
      this.mouseTarget = null;
    },

    function onMouseMove(evt) {
      if ( this.mouseTarget && this.mouseTarget.onMouseMove ) this.mouseTarget.onMouseMove(evt);
    },

    function onClick(evt) {
      var x = evt.offsetX, y = evt.offsetY;
      var c = this.canvas.findFirstChildAt(x, y);

      if ( this.Halo.isInstance(c) ) return;

      if ( c === this.canvas ) {
        var tool = this.currentTool;
        if ( ! tool ) return;
        var cls = this.lookup(tool.id);
        var o = cls.create({x: x, y: y}, this.__subContext__);
        var p = this.addProperty(o, null, null, 'canvas1');
        this.updateMemento();
      } else {
        for ( ; c !== this.canvas ; c = c.parent ) {
          var p = c.getPrivate_('lpp_');
          if ( p ) {
            this.selected = p;
            break;
          }
        }
      }
    },

    function onRightClick(evt) {
      evt.preventDefault();
      if ( ! this.selected ) return;
    }
  ]
});
<|endoftext|>


<commit_before>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    lint: {
      files: ['grunt.js', 'src/**/*.js', 'test/**/*.js']
    },
    qunit: {
      files: ['test/**/*.html']
    },
    concat: {
      dist: {
        src: ['<banner:meta.banner>', 'src/**/*.js'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    min: {
      dist: {
        src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    watch: {
      files: ['<config:lint.files>', 'index.html'],
      tasks: 'lint qunit concat reload'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {}
    },
    uglify: {},
    server: {
      port: 8999,
      base: '.'
    },
    reload: {
      port: 8001,
      proxy: {
        port: 8999,
        host: 'localhost'
      }
    }
  });

  // Default task.
  grunt.registerTask('default', 'lint qunit concat min');

  grunt.loadNpmTasks('grunt-reload');
};
<commit_msg>Update default task to server, reload and watch.<commit_after>/*global module:false*/
module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: '<json:package.json>',
    meta: {
      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
    },
    lint: {
      files: ['grunt.js', 'src/**/*.js', 'test/**/*.js']
    },
    qunit: {
      files: ['test/**/*.html']
    },
    concat: {
      dist: {
        src: ['<banner:meta.banner>', 'src/**/*.js'],
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    min: {
      dist: {
        src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= pkg.name %>.min.js'
      }
    },
    watch: {
      files: ['<config:lint.files>', 'index.html'],
      tasks: 'lint qunit concat reload'
    },
    jshint: {
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        undef: true,
        boss: true,
        eqnull: true,
        browser: true
      },
      globals: {}
    },
    uglify: {},
    server: {
      port: 8999,
      base: '.'
    },
    reload: {
      port: 8001,
      proxy: {
        port: 8999,
        host: 'localhost'
      }
    }
  });

  // Default task.
  grunt.registerTask('default', 'server reload watch');

  grunt.loadNpmTasks('grunt-reload');
};
<|endoftext|>


<commit_before>// ------------------------------------------------------------------------------------------------
// Simplenote Database interface.
// ------------------------------------------------------------------------------------------------

var SimplenoteDB = {
    offlineKey : "_offline",

    isDebug : true,

    log : function(s) {
        if (this.isDebug)
            logGeneral(s,"SimplenoteDB");
    },

    isOffline : function() {
        return $.storage.get(this.offlineKey) == "true";
    },

    offline : function(isOffline) {

        if(isOffline==undefined)
            throw("SimplenoteDB.offline: please query via .isOffline()");

        var oldIsOffline = this.isOffline();

        if (isOffline != oldIsOffline) {
            this.log("offline:mode change to offline=" + isOffline);
            uiEvent("offlinechanged", {status:isOffline});
            $.storage.set(this.offlineKey,isOffline==true);
        }
    },
    _setSyncInProgress: function(val) {
        this.log("_setSyncInProgress:" + val);
        this.isSyncInProgress = val;
    },
    getSyncInProgress: function() {
        return this.isSyncInProgress;
    },
    _reset : function() {
        this.log("_reset");
        this._setSyncInProgress(false);
        this.syncCallbackChunk = undefined;
        this.syncCallbackFinished = undefined;
        this._indexKeysTemp = [];
        this._indexKeysChanged = {hadchanges: false, added:[],changed:[],deleted:[]};
    },
    // jsut to detect whether we actually had a sync
    hadSync : function() {
        return localStorage[SimplenoteLS.indexTimeKey] != undefined;
    },

    sync : function(fullSync, callbackFinished, callbackChunk) {
        if (this.getSyncInProgress()) {
            log("sync: sync already in progress, returning");
            return;
        }

        this._reset();
        this._setSyncInProgress(true);

        var syncKeys = SimplenoteLS.getSyncKeys();
        var note;

        this.log("sync: fullSync = " + fullSync);

        this.syncCallbackChunk = callbackChunk;
        this.syncCallbackFinished = callbackFinished;

        // push local changes
        $.each(syncKeys, function(i,key) {
            note = SimplenoteLS.getNote(key);
            if (note != undefined) {
                if (note.key.match(/creatednote(\d+)/))
                    SimplenoteDB.createNote(note, undefined, true);
                else
                    SimplenoteDB.updateNote(note, undefined, true);
            }
        });

        // get index
        var apioptions = {};
        if (!fullSync) {
            var indexTime = SimplenoteLS.indexTime();
            if (indexTime) {
                this.log("sync:using lastIndexTime from storage: " + dateAgo(indexTime));
                apioptions.since = indexTime;
            }
        }
        apioptions.length = 100;

        uiEvent("sync", {status: "started", changes : this._indexKeysChanged});

        this.getIndex(apioptions, fullSync);

    },
    //  count: 20
    //  data: Array[20]
    //  mark: "agtzaW1wbGUtbm90ZXINCxIETm90ZRiElc0HDB"
    //  time: "1302261452.277224"
    _gotIndexChunk : function(indexData, havemore, fullSync) {

        if (!indexData) {
            if (this.syncCallbackFinished)
                this.syncCallbackFinished(false);
            this.log("_gotIndexChunk: error getting index from server.");
            this.offline(true);
            this._setSyncInProgress(false);
            uiEvent("sync", {status: "error", changes : this._indexKeysChanged});
        } else {
            var thisHadChanges = false, note;

            for (var i=0; i<indexData.data.length; i++) {
                note = indexData.data[i];

                if (fullSync)
                    this._indexKeysTemp.push(note.key);

                if (!SimplenoteLS.haveNote(note.key)) {
                    SimplenoteLS.addNote(note);
                    this._indexKeysChanged.hadchanges = true;
                    this._indexKeysChanged.added.push(note.key);
                } else {
                    thisHadChanges = SimplenoteLS.updateNote(note,"index");
                    if (thisHadChanges.hadChanges) {
                        this._indexKeysChanged.hadchanges = true;
                        this._indexKeysChanged.changed.push(note.key);
                    }
                }
            }

            if (this.syncCallbackChunk)
                this.syncCallbackChunk(indexData);

            if (!havemore) {
                if (indexData.data.length > 0) // check for indextime sync, most often we get 0 back
                    SimplenoteLS.indexTime(indexData.time);

                if (fullSync) {
                    // check for deletions
                    var lskeys = SimplenoteLS.getKeys(), key;
                    this.log("_gotIndexChunk: checking for remote deletions (got " + SimplenoteDB._indexKeysTemp.length + " notes, have " + SimplenoteLS.getKeys().length + ")");
                    for (i=0; i<lskeys.length;i++) {
                        key = lskeys[i];
                        if (this._indexKeysTemp.indexOf(key)<0) {
                            SimplenoteLS.delNote(key);
                            this._indexKeysChanged.hadchanges = true;
                            this._indexKeysChanged.deleted.push(key);
                        }
                    }
                    if (this._indexKeysChanged.deleted.length > 0)
                        this.log("_gotIndexChunk: had remote deletions.");
                    else
                        this.log("_gotIndexChunk: no remote deletions.");
                }

                if (this.syncCallbackFinished)
                    this.syncCallbackFinished(true);

                this._setSyncInProgress(false);

                uiEvent("sync", {status: "done", changes : this._indexKeysChanged});
            }
        }

        if (!havemore) {
            if (this._indexKeysChanged.added.length > 0)
                this.log("_gotIndexChunk: added " + this._indexKeysChanged.added.length);
            if (this._indexKeysChanged.changed.length > 0)
                this.log("_gotIndexChunk: changed " + this._indexKeysChanged.changed.length);
            if (this._indexKeysChanged.deleted.length > 0)
                this.log("_gotIndexChunk: deleted " + this._indexKeysChanged.deleted.length);

            delete this._indexKeysChanged;
        }
    },

    // callback : function(noteData), called after every index chunk
    // mark : (optional) marked note for more
    getIndex : function(apioptions, fullSync) {

        var callbacks = {

            //  count: 20
            //  data: Array[20]
            //  mark: "agtzaW1wbGUtbm90ZXINCxIETm90ZRiElc0HDB"
            //  time: "1302261452.277224"
            success :       function(indexData) {
                SimplenoteDB.offline(false);

                SimplenoteDB.log("getIndex:success:got " + indexData.count + " keys from server.");

                if (indexData.mark != undefined) {
                    SimplenoteDB.log("getIndex:success:have mark, getting more.");
                    apioptions.mark = indexData.mark;
                    SimplenoteDB._gotIndexChunk(indexData, true, fullSync);

                    SimplenoteDB.getIndex(apioptions, fullSync);

                } else {
                    SimplenoteDB.log("getIndex:success:no mark, done.");
                    SimplenoteDB._gotIndexChunk(indexData, false, fullSync);
                }
            },
            loginInvalid:   function() {
                SimplenoteDB.log("getIndex:loginInvalid");
                alert("SimplenoteDB::getIndex:loginInvalid");
                SimplenoteDB._gotIndexChunk(undefined, false);
            },
            repeat:         function() {
                SimplenoteDB.log("getIndex:repeat");
                alert("SimplenoteDB::getIndex:repeat");
                SimplenoteDB._gotIndexChunk(undefined, false);
            },
            timeout:        function() {
                SimplenoteDB.log("getIndex:timeout");
                SimplenoteDB.offline(true);
                //alert("SimplenoteDB::getIndex:timeout");
                SimplenoteDB._gotIndexChunk(undefined, false);
            }
        };

        // set defaults
        if (!apioptions) apioptions = {};
        if (!apioptions.length) apioptions.length = 100;

        SimplenoteAPI2.index(apioptions,callbacks);
    },

    getNote : function(key,callback) {
        var note = SimplenoteLS.getNote(key);
        if (note && note.content) {
            this.log("getNote:returning note from storage:" + key);
            if (callback)
                callback(note);
        } else {
            this.log("getNote:getting note from server:" + key);
            var callbacks = {
                success :       function(note) {
                    SimplenoteDB.offline(false);
                    SimplenoteLS.updateNote(note,"getnote");
                    if (callback)
                        callback(note);
                },
                loginInvalid:   function() {
                    SimplenoteDB.offline(false);
                    SimplenoteDB.log('getNote::loginInvalid');
                    alert('SimplenoteDB::getNote::loginInvalid');
                    if (callback)
                        callback();
                },
                repeat:         function() {
                    SimplenoteDB.offline(false);
                    SimplenoteDB.log('getNote::repeat');
                    alert('SimplenoteDB::getNote::repeat');
                    if (callback)
                        callback();
                },
                noteNotExist:  function(key) {
                    SimplenoteDB.offline(false);
                    SimplenoteDB.log('getNote::noteNotExists');
                    SimplenoteLS.removeFromSyncList(key);
                    SimplenoteLS.delNote(key);
                    //alert('SimplenoteDB::getNote::noteNoteExist');
                    if (callback)
                        callback();
                },
                timeout: function(options) {
                    SimplenoteDB.offline(true);
                    SimplenoteDB.log('getNote::timeout');
                    //alert('SimplenoteDB::getNote::timeout');
                    if (callback)
                        callback();
                }
            };
            SimplenoteAPI2.retrieve(key, callbacks);
        }
    },

    updateNote : function(data,callback,syncmode) {
        this.log("updateNote, syncMode = " + syncmode + " update data:");
        this.log(data);

        if (!syncmode) {
            // get local note version
            var note = SimplenoteLS.getNote(data.key);
            if (!note)
                throw "unknown or missing note, cannot update";

            delete data.action;

            // client updateable properties:
            if (data.content != undefined)      note.content = data.content;
            if (data.deleted != undefined)      note.deleted = data.deleted;
            if (data.tags != undefined)         note.tags = data.tags;
            if (data.systemtags != undefined)   note.systemtags = data.systemtags;

            if (data.content) {
                note.modifydate = (new Date())/1000;
                data.modifydate = note.modifydate;
                // needed for merging
                data.version = note.version;
            }

            SimplenoteLS.updateNote(note, "local");
            SimplenoteLS.addToSyncList(note.key);
        }

        var callbacks = {
            success :       function(note) {
                SimplenoteDB.offline(false);
                SimplenoteLS.updateNote(note,"updateresponse");
                SimplenoteLS.removeFromSyncList(note.key);
                if (callback)
                    callback(note);
            },
            loginInvalid:   function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log('updateNote::loginInvalid');
                alert('SimplenoteDB::updateNote::loginInvalid');
            },
            repeat:         function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log('updateNote::repeat');
                alert('SimplenoteDB::updateNote::repeat');
            },
            noteNotExists:  function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log('updateNote::noteNoteExists');
                alert('SimplenoteDB::updateNote::noteNoteExists');
            },
            timeout: function(note) {
                SimplenoteDB.offline(true);
                SimplenoteDB.log('updateNote::timeout');
                //alert('SimplenoteDB::updateNote::timeout');
                if (callback)
                    callback(note);
            }
        };
        SimplenoteAPI2.update(data, callbacks);

    },

    createNote : function(note,callback,syncmode) {
        this.log("createNote, note data below, syncmode = " +  syncmode);
        this.log(note2str(note,true));
        delete note.action;
        var tempkey;
        if (!syncmode) {
            note.createdate = (new Date())/1000;
            note.modifydate = note.createdate;
            // set things needed for operation
            tempkey = SimplenoteLS.getCreatedNoteTempKey();
            note.key = tempkey;
            note.deleted = 0;
            if (!note.tags)
                note.tags = [];
            if (!note.systemtags)
                note.systemtags = [];

            SimplenoteLS.addNote(note);
            SimplenoteLS.addToSyncList(note.key);
        } else {
            tempkey = note.key;
        }

        var callbacks = {
            success :       function(newnote) {
                SimplenoteDB.offline(false);

                newnote.content = note.content;
                SimplenoteLS.addNote(newnote);

                SimplenoteLS.delNote(tempkey);
                SimplenoteLS.removeFromSyncList(tempkey);

                if (callback)
                    callback(newnote);
            },
            loginInvalid:   function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("createNote::loginInvalid")
                alert('SimplenoteDB::createNote::loginInvalid');
            },
            repeat:         function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("createNote::repeat")
                alert('SimplenoteDB::createNote::repeat');
            },
            noteNotExists:  function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("createNote::noteNotExists")
                alert('SimplenoteDB::createNote::noteNotExists');
            },
            timeout: function(note) {
                SimplenoteDB.offline(true);
                SimplenoteDB.log("createNote::timeout")
                //alert('SimplenoteDB::createNote::timeout');
                if (callback)
                    callback();
            }
        };
        delete note.key; // remove temp key
        SimplenoteAPI2.create(note, callbacks);
    },

    deleteNote : function(key, callback) {
        var callbacks = {
            success :       function(data) {
                SimplenoteDB.offline(false);
                SimplenoteLS.delNote(key);
                if (callback)
                    callback(true);
            },
            loginInvalid:   function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("deleteNote::loginInvalid")
                alert('SimplenoteDB::deleteNote::loginInvalid');
            },
            repeat:         function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("deleteNote::repeat")
                alert('SimplenoteDB::deleteNote::repeat');
            },
            noteNotExists:  function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("deleteNote::noteNotExists")
                alert('SimplenoteDB::deleteNote::noteNotExists');
            },
            timeout: function(key) {
                SimplenoteDB.offline(true);
                SimplenoteDB.log("deleteNote::timeout")
                alert('SimplenoteDB::deleteNote::timeout');
                if (callback)
                    callback(false);
            }
        };
        SimplenoteAPI2.destroy(key, callbacks);
    },

    _deleteAllRemote : function() {
        var note;
        $.each(SimplenoteLS.getKeys(), function(i,key) {
            note = SimplenoteLS.getNote(key);
            note.deleted = 1;
            SimplenoteDB.updateNote(note, function(note) {SimplenoteDB.deleteNote(note.key);}, true);
        });
    }
}

SimplenoteDB._reset();<commit_msg>fixed a NASTY bug: this.syncCallbackFinished throws error if popup was closed before, leaving syncInProgress=true<commit_after>// ------------------------------------------------------------------------------------------------
// Simplenote Database interface.
// ------------------------------------------------------------------------------------------------

var SimplenoteDB = {
    offlineKey : "_offline",

    isDebug : true,

    log : function(s) {
        if (this.isDebug)
            logGeneral(s,"SimplenoteDB");
    },

    isOffline : function() {
        return $.storage.get(this.offlineKey) == "true";
    },

    offline : function(isOffline) {

        if(isOffline==undefined)
            throw("SimplenoteDB.offline: please query via .isOffline()");

        var oldIsOffline = this.isOffline();

        if (isOffline != oldIsOffline) {
            this.log("offline:mode change to offline=" + isOffline);
            uiEvent("offlinechanged", {status:isOffline});
            $.storage.set(this.offlineKey,isOffline==true);
        }
    },
    _setSyncInProgress: function(val) {
        this.log("_setSyncInProgress:" + val);
        this.isSyncInProgress = val;
    },
    getSyncInProgress: function() {
        return this.isSyncInProgress;
    },
    _reset : function() {
        this.log("_reset");
        this._setSyncInProgress(false);
        this.syncCallbackChunk = undefined;
        this.syncCallbackFinished = undefined;
        this._indexKeysTemp = [];
        this._indexKeysChanged = {hadchanges: false, added:[],changed:[],deleted:[]};
    },
    // jsut to detect whether we actually had a sync
    hadSync : function() {
        return localStorage[SimplenoteLS.indexTimeKey] != undefined;
    },

    sync : function(fullSync, callbackFinished, callbackChunk) {
        if (this.getSyncInProgress()) {
            log("sync: sync already in progress, returning");
            return;
        }

        this._reset();
        this._setSyncInProgress(true);

        var syncKeys = SimplenoteLS.getSyncKeys();
        var note;

        this.log("sync: fullSync = " + fullSync);

        this.syncCallbackChunk = callbackChunk;
        this.syncCallbackFinished = callbackFinished;

        // push local changes
        $.each(syncKeys, function(i,key) {
            note = SimplenoteLS.getNote(key);
            if (note != undefined) {
                if (note.key.match(/creatednote(\d+)/))
                    SimplenoteDB.createNote(note, undefined, true);
                else
                    SimplenoteDB.updateNote(note, undefined, true);
            }
        });

        // get index
        var apioptions = {};
        if (!fullSync) {
            var indexTime = SimplenoteLS.indexTime();
            if (indexTime) {
                this.log("sync:using lastIndexTime from storage: " + dateAgo(indexTime));
                apioptions.since = indexTime;
            }
        }
        apioptions.length = 100;

        uiEvent("sync", {status: "started", changes : this._indexKeysChanged});

        this.getIndex(apioptions, fullSync);

    },
    //  count: 20
    //  data: Array[20]
    //  mark: "agtzaW1wbGUtbm90ZXINCxIETm90ZRiElc0HDB"
    //  time: "1302261452.277224"
    _gotIndexChunk : function(indexData, havemore, fullSync) {

        if (!indexData) {
            if (this.syncCallbackFinished)
                this.syncCallbackFinished(false);
            this.log("_gotIndexChunk: error getting index from server.");
            this.offline(true);
            this._setSyncInProgress(false);
            uiEvent("sync", {status: "error", changes : this._indexKeysChanged});
        } else {
            var thisHadChanges = false, note;

            for (var i=0; i<indexData.data.length; i++) {
                note = indexData.data[i];

                if (fullSync)
                    this._indexKeysTemp.push(note.key);

                if (!SimplenoteLS.haveNote(note.key)) {
                    SimplenoteLS.addNote(note);
                    this._indexKeysChanged.hadchanges = true;
                    this._indexKeysChanged.added.push(note.key);
                } else {
                    thisHadChanges = SimplenoteLS.updateNote(note,"index");
                    if (thisHadChanges.hadChanges) {
                        this._indexKeysChanged.hadchanges = true;
                        this._indexKeysChanged.changed.push(note.key);
                    }
                }
            }

            if (this.syncCallbackChunk)
                this.syncCallbackChunk(indexData);

            if (!havemore) {
                if (indexData.data.length > 0) // check for indextime sync, most often we get 0 back
                    SimplenoteLS.indexTime(indexData.time);

                if (fullSync) {
                    // check for deletions
                    var lskeys = SimplenoteLS.getKeys(), key;
                    this.log("_gotIndexChunk: checking for remote deletions (got " + SimplenoteDB._indexKeysTemp.length + " notes, have " + SimplenoteLS.getKeys().length + ")");
                    for (i=0; i<lskeys.length;i++) {
                        key = lskeys[i];
                        if (this._indexKeysTemp.indexOf(key)<0) {
                            SimplenoteLS.delNote(key);
                            this._indexKeysChanged.hadchanges = true;
                            this._indexKeysChanged.deleted.push(key);
                        }
                    }
                    if (this._indexKeysChanged.deleted.length > 0)
                        this.log("_gotIndexChunk: had remote deletions.");
                    else
                        this.log("_gotIndexChunk: no remote deletions.");
                }

                this._setSyncInProgress(false);

                if (this.syncCallbackFinished)
                    this.syncCallbackFinished(true);

                uiEvent("sync", {status: "done", changes : this._indexKeysChanged});
            }
        }

        if (!havemore) {
            if (this._indexKeysChanged.added.length > 0)
                this.log("_gotIndexChunk: added " + this._indexKeysChanged.added.length);
            if (this._indexKeysChanged.changed.length > 0)
                this.log("_gotIndexChunk: changed " + this._indexKeysChanged.changed.length);
            if (this._indexKeysChanged.deleted.length > 0)
                this.log("_gotIndexChunk: deleted " + this._indexKeysChanged.deleted.length);

            delete this._indexKeysChanged;
        }
    },

    // callback : function(noteData), called after every index chunk
    // mark : (optional) marked note for more
    getIndex : function(apioptions, fullSync) {

        var callbacks = {

            //  count: 20
            //  data: Array[20]
            //  mark: "agtzaW1wbGUtbm90ZXINCxIETm90ZRiElc0HDB"
            //  time: "1302261452.277224"
            success :       function(indexData) {
                SimplenoteDB.offline(false);

                SimplenoteDB.log("getIndex:success:got " + indexData.count + " keys from server.");

                if (indexData.mark != undefined) {
                    SimplenoteDB.log("getIndex:success:have mark, getting more.");
                    apioptions.mark = indexData.mark;
                    SimplenoteDB._gotIndexChunk(indexData, true, fullSync);

                    SimplenoteDB.getIndex(apioptions, fullSync);

                } else {
                    SimplenoteDB.log("getIndex:success:no mark, done.");
                    SimplenoteDB._gotIndexChunk(indexData, false, fullSync);
                }
            },
            loginInvalid:   function() {
                SimplenoteDB.log("getIndex:loginInvalid");
                alert("SimplenoteDB::getIndex:loginInvalid");
                SimplenoteDB._gotIndexChunk(undefined, false);
            },
            repeat:         function() {
                SimplenoteDB.log("getIndex:repeat");
                alert("SimplenoteDB::getIndex:repeat");
                SimplenoteDB._gotIndexChunk(undefined, false);
            },
            timeout:        function() {
                SimplenoteDB.log("getIndex:timeout");
                SimplenoteDB.offline(true);
                //alert("SimplenoteDB::getIndex:timeout");
                SimplenoteDB._gotIndexChunk(undefined, false);
            }
        };

        // set defaults
        if (!apioptions) apioptions = {};
        if (!apioptions.length) apioptions.length = 100;

        SimplenoteAPI2.index(apioptions,callbacks);
    },

    getNote : function(key,callback) {
        var note = SimplenoteLS.getNote(key);
        if (note && note.content) {
            this.log("getNote:returning note from storage:" + key);
            if (callback)
                callback(note);
        } else {
            this.log("getNote:getting note from server:" + key);
            var callbacks = {
                success :       function(note) {
                    SimplenoteDB.offline(false);
                    SimplenoteLS.updateNote(note,"getnote");
                    if (callback)
                        callback(note);
                },
                loginInvalid:   function() {
                    SimplenoteDB.offline(false);
                    SimplenoteDB.log('getNote::loginInvalid');
                    alert('SimplenoteDB::getNote::loginInvalid');
                    if (callback)
                        callback();
                },
                repeat:         function() {
                    SimplenoteDB.offline(false);
                    SimplenoteDB.log('getNote::repeat');
                    alert('SimplenoteDB::getNote::repeat');
                    if (callback)
                        callback();
                },
                noteNotExist:  function(key) {
                    SimplenoteDB.offline(false);
                    SimplenoteDB.log('getNote::noteNotExists');
                    SimplenoteLS.removeFromSyncList(key);
                    SimplenoteLS.delNote(key);
                    //alert('SimplenoteDB::getNote::noteNoteExist');
                    if (callback)
                        callback();
                },
                timeout: function(options) {
                    SimplenoteDB.offline(true);
                    SimplenoteDB.log('getNote::timeout');
                    //alert('SimplenoteDB::getNote::timeout');
                    if (callback)
                        callback();
                }
            };
            SimplenoteAPI2.retrieve(key, callbacks);
        }
    },

    updateNote : function(data,callback,syncmode) {
        this.log("updateNote, syncMode = " + syncmode + " update data:");
        this.log(data);

        if (!syncmode) {
            // get local note version
            var note = SimplenoteLS.getNote(data.key);
            if (!note)
                throw "unknown or missing note, cannot update";

            delete data.action;

            // client updateable properties:
            if (data.content != undefined)      note.content = data.content;
            if (data.deleted != undefined)      note.deleted = data.deleted;
            if (data.tags != undefined)         note.tags = data.tags;
            if (data.systemtags != undefined)   note.systemtags = data.systemtags;

            if (data.content) {
                note.modifydate = (new Date())/1000;
                data.modifydate = note.modifydate;
                // needed for merging
                data.version = note.version;
            }

            SimplenoteLS.updateNote(note, "local");
            SimplenoteLS.addToSyncList(note.key);
        }

        var callbacks = {
            success :       function(note) {
                SimplenoteDB.offline(false);
                SimplenoteLS.updateNote(note,"updateresponse");
                SimplenoteLS.removeFromSyncList(note.key);
                if (callback)
                    callback(note);
            },
            loginInvalid:   function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log('updateNote::loginInvalid');
                alert('SimplenoteDB::updateNote::loginInvalid');
            },
            repeat:         function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log('updateNote::repeat');
                alert('SimplenoteDB::updateNote::repeat');
            },
            noteNotExists:  function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log('updateNote::noteNoteExists');
                alert('SimplenoteDB::updateNote::noteNoteExists');
            },
            timeout: function(note) {
                SimplenoteDB.offline(true);
                SimplenoteDB.log('updateNote::timeout');
                //alert('SimplenoteDB::updateNote::timeout');
                if (callback)
                    callback(note);
            }
        };
        SimplenoteAPI2.update(data, callbacks);

    },

    createNote : function(note,callback,syncmode) {
        this.log("createNote, note data below, syncmode = " +  syncmode);
        this.log(note2str(note,true));
        delete note.action;
        var tempkey;
        if (!syncmode) {
            note.createdate = (new Date())/1000;
            note.modifydate = note.createdate;
            // set things needed for operation
            tempkey = SimplenoteLS.getCreatedNoteTempKey();
            note.key = tempkey;
            note.deleted = 0;
            if (!note.tags)
                note.tags = [];
            if (!note.systemtags)
                note.systemtags = [];

            SimplenoteLS.addNote(note);
            SimplenoteLS.addToSyncList(note.key);
        } else {
            tempkey = note.key;
        }

        var callbacks = {
            success :       function(newnote) {
                SimplenoteDB.offline(false);

                newnote.content = note.content;
                SimplenoteLS.addNote(newnote);

                SimplenoteLS.delNote(tempkey);
                SimplenoteLS.removeFromSyncList(tempkey);

                if (callback)
                    callback(newnote);
            },
            loginInvalid:   function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("createNote::loginInvalid")
                alert('SimplenoteDB::createNote::loginInvalid');
            },
            repeat:         function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("createNote::repeat")
                alert('SimplenoteDB::createNote::repeat');
            },
            noteNotExists:  function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("createNote::noteNotExists")
                alert('SimplenoteDB::createNote::noteNotExists');
            },
            timeout: function(note) {
                SimplenoteDB.offline(true);
                SimplenoteDB.log("createNote::timeout")
                //alert('SimplenoteDB::createNote::timeout');
                if (callback)
                    callback();
            }
        };
        delete note.key; // remove temp key
        SimplenoteAPI2.create(note, callbacks);
    },

    deleteNote : function(key, callback) {
        var callbacks = {
            success :       function(data) {
                SimplenoteDB.offline(false);
                SimplenoteLS.delNote(key);
                if (callback)
                    callback(true);
            },
            loginInvalid:   function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("deleteNote::loginInvalid")
                alert('SimplenoteDB::deleteNote::loginInvalid');
            },
            repeat:         function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("deleteNote::repeat")
                alert('SimplenoteDB::deleteNote::repeat');
            },
            noteNotExists:  function() {
                SimplenoteDB.offline(false);
                SimplenoteDB.log("deleteNote::noteNotExists")
                alert('SimplenoteDB::deleteNote::noteNotExists');
            },
            timeout: function(key) {
                SimplenoteDB.offline(true);
                SimplenoteDB.log("deleteNote::timeout")
                alert('SimplenoteDB::deleteNote::timeout');
                if (callback)
                    callback(false);
            }
        };
        SimplenoteAPI2.destroy(key, callbacks);
    },

    _deleteAllRemote : function() {
        var note;
        $.each(SimplenoteLS.getKeys(), function(i,key) {
            note = SimplenoteLS.getNote(key);
            note.deleted = 1;
            SimplenoteDB.updateNote(note, function(note) {SimplenoteDB.deleteNote(note.key);}, true);
        });
    }
}

SimplenoteDB._reset();<|endoftext|>


<commit_before>/**
 * Created by sven on 11-09-15.
 */
<commit_msg>Add docker plugin<commit_after>var _ = require('underscore');
var CheckEvent = require('../../models/checkEvent');
var Docker = require('dockerode');

exports.initWebApp = function(options) {
  var config = options.config.docker;

  CheckEvent.on('afterInsert', function(checkEvent) {
    checkEvent.findCheck(function (err, check) {
      if (err) return console.error(err);

      // Only reboot when it's down
      if(checkEvent.message == "down") {

        _.each(checkEvent.tags, function(tag){
          var tagparts = tag.split(";");
          if(tagparts[0] == "host") {
            var docker = new Docker({host: tagparts[1], port: 2375});
            var container = docker.getContainer('askbackend');
            if(container) {
              container.restart(function (err, data) {
                if(err) console.err("Failed to restart container: ",err);
                else console.log(data);
              });
            }
          }
        });
      }
    });
  });
  console.log('Enabled Docker actions');
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import { Col } from 'react-bootstrap'

class MyTargetVerse extends Component {

  render() {
    let { chapter, verse, verseText, styles} = this.props
    return (
      <Col md={12} sm={12} xs={12} lg={12} style={styles}>

          {chapter + ":" + verse + " "}
          {verseText}

      </Col>
    )
  }
}

MyTargetVerse.propTypes = {
  chapter: PropTypes.number,
  verse: PropTypes.number,
  verseText: PropTypes.string,
  styles: PropTypes.object
}

export default MyTargetVerse
<commit_msg>Update MyTargetVerse.js<commit_after>import React, { Component, PropTypes } from 'react'
import { Col } from 'react-bootstrap'

class MyTargetVerse extends Component {

  render() {
    let { chapter, verse, verseText, styles} = this.props

    return (
      <Col md={12} sm={12} xs={12} lg={12} style={styles}>

          {chapter + ":" + verse + " "}
          {verseText}

      </Col>
    )
  }
}

MyTargetVerse.propTypes = {
  chapter: PropTypes.number,
  verse: PropTypes.number,
  verseText: PropTypes.string,
  styles: PropTypes.object
}

export default MyTargetVerse
<|endoftext|>