<commit_before>const fs = require('fs');
const Page = require('./Page');

class Sketch {
  constructor(repo, document, meta, user, pages) {
    this.repo = repo;
    this.document = document;
    this.meta = meta;
    this.user = user;
    this.pages = pages.map(page => new Page(this, page));
  }

  findLayer(type, condition) {
    for (let page of this.pages) {
      let layer = page.findLayer(type, condition);

      if (layer) {
        return layer;
      }
    }
  }

  findAllLayers(type, condition, result) {
    result = result || [];

    for (let page of this.pages) {
      page.findAllLayers(type, condition).forEach(layer => result.push(layer));
    }

    return result;
  }

  getSymbolsPage() {
    return this.pages.find(page => page.name === 'Symbols');
  }

  //Save document as sketch file
  save(file) {
    const pagesFolder = this.repo.folder('pages');

    this.document.pages = this.pages.map(page => {
      this.repo.file(`pages/${page.do_objectID}.json`, JSON.stringify(page));

      return {
        _class: 'MSJSONFileReference',
        _ref_class: 'MSImmutablePage',
        _ref: `pages/${page.do_objectID}`
      };
    });

    this.repo.file('document.json', JSON.stringify(this.document));
    this.repo.file('meta.json', JSON.stringify(this.meta));
    this.repo.file('user.json', JSON.stringify(this.user));

    return new Promise((resolve, reject) => {
      this.repo
        .generateNodeStream({
          type: 'nodebuffer',
          streamFiles: true
        })
        .pipe(fs.createWriteStream(file))
        .on('finish', () => {
          resolve(file);
        })
        .on('error', err => {
          reject(err);
        });
    });
  }
}

module.exports = Sketch;
<commit_msg>add compression to sketch file creation<commit_after>const fs = require('fs');
const Page = require('./Page');

class Sketch {
  constructor(repo, document, meta, user, pages) {
    this.repo = repo;
    this.document = document;
    this.meta = meta;
    this.user = user;
    this.pages = pages.map(page => new Page(this, page));
  }

  findLayer(type, condition) {
    for (let page of this.pages) {
      let layer = page.findLayer(type, condition);

      if (layer) {
        return layer;
      }
    }
  }

  findAllLayers(type, condition, result) {
    result = result || [];

    for (let page of this.pages) {
      page.findAllLayers(type, condition).forEach(layer => result.push(layer));
    }

    return result;
  }

  getSymbolsPage() {
    return this.pages.find(page => page.name === 'Symbols');
  }

  //Save document as sketch file
  save(file) {
    const pagesFolder = this.repo.folder('pages');

    this.document.pages = this.pages.map(page => {
      this.repo.file(`pages/${page.do_objectID}.json`, JSON.stringify(page));

      return {
        _class: 'MSJSONFileReference',
        _ref_class: 'MSImmutablePage',
        _ref: `pages/${page.do_objectID}`
      };
    });

    this.repo.file('document.json', JSON.stringify(this.document));
    this.repo.file('meta.json', JSON.stringify(this.meta));
    this.repo.file('user.json', JSON.stringify(this.user));

    return new Promise((resolve, reject) => {
      this.repo
        .generateNodeStream({
          type: 'nodebuffer',
          streamFiles: true,
          compression: 'DEFLATE'
        })
        .pipe(fs.createWriteStream(file))
        .on('finish', () => {
          resolve(file);
        })
        .on('error', err => {
          reject(err);
        });
    });
  }
}

module.exports = Sketch;
<|endoftext|>


<commit_before>(function(tree) {
tree.Rule = function Rule(name, value, important, index) {
    this.name = name;
    this.value = (value instanceof tree.Value) ?
        value : new tree.Value([value]);
    this.important = important ? ' ' + important.trim() : '';
    this.index = index;
    this.symbolizer = tree.Reference.symbolizer(this.name);

    if (name.charAt(0) === '@') {
        this.variable = true;
    } else { this.variable = false }
};

tree.Rule.prototype.toXML = function(env) {
    if (!tree.Reference.validSelector(this.name)) {
        return env.error({
            message: "Unrecognized selector: " + this.name,
            index: this.index
        });
    }

    if ((this.value instanceof tree.Value) &&
        !tree.Reference.validValue(env, this.name, this.value)) {
        return env.error({
            message: 'Invalid value for ' +
                this.name +
                ', a ' +
                tree.Reference.selector(this.name).type +
                ' is expected. ' + this.value +
                ' was given.',
            index: this.index
        });
    }

    if (this.variable) {
        return '';
    } else if (tree.Reference.isFont(this.name) && this.value.value.length > 1) {
        var f = tree._getFontSet(env, this.value.value);
        return 'fontset_name="' + f.name + '"';
    } else {
        return tree.Reference.selectorName(this.name) +
            '="' +
            this.value.toString(env, this.name) +
            '"';
    }
};

/**
 * TODO: Rule eval chain should add fontsets to env.frames
 */
tree.Rule.prototype.eval = function(context) {
    return new tree.Rule(this.name,
        this.value.eval(context),
        this.important,
        this.index);
};

tree.Shorthand = function Shorthand(a, b) {
    this.a = a;
    this.b = b;
};

tree.Shorthand.prototype = {
    toString: function(env) {
        return this.a.toString(env) + '/' + this.b.toString(env);
    },
    eval: function() { return this }
};

})(require('mess/tree'));
<commit_msg>Tweak validation fail language<commit_after>(function(tree) {
tree.Rule = function Rule(name, value, important, index) {
    this.name = name;
    this.value = (value instanceof tree.Value) ?
        value : new tree.Value([value]);
    this.important = important ? ' ' + important.trim() : '';
    this.index = index;
    this.symbolizer = tree.Reference.symbolizer(this.name);

    if (name.charAt(0) === '@') {
        this.variable = true;
    } else { this.variable = false }
};

tree.Rule.prototype.toXML = function(env) {
    if (!tree.Reference.validSelector(this.name)) {
        return env.error({
            message: "Unrecognized selector: " + this.name,
            index: this.index
        });
    }

    if ((this.value instanceof tree.Value) &&
        !tree.Reference.validValue(env, this.name, this.value)) {
        return env.error({
            message: 'Invalid value for ' +
                this.name +
                ', a valid ' +
                tree.Reference.selector(this.name).validate +
                ' is expected. ' + this.value +
                ' was given.',
            index: this.index
        });
    }

    if (this.variable) {
        return '';
    } else if (tree.Reference.isFont(this.name) && this.value.value.length > 1) {
        var f = tree._getFontSet(env, this.value.value);
        return 'fontset_name="' + f.name + '"';
    } else {
        return tree.Reference.selectorName(this.name) +
            '="' +
            this.value.toString(env, this.name) +
            '"';
    }
};

/**
 * TODO: Rule eval chain should add fontsets to env.frames
 */
tree.Rule.prototype.eval = function(context) {
    return new tree.Rule(this.name,
        this.value.eval(context),
        this.important,
        this.index);
};

tree.Shorthand = function Shorthand(a, b) {
    this.a = a;
    this.b = b;
};

tree.Shorthand.prototype = {
    toString: function(env) {
        return this.a.toString(env) + '/' + this.b.toString(env);
    },
    eval: function() { return this }
};

})(require('mess/tree'));
<|endoftext|>


<commit_before>var $ = require('jquery');

require('../css/embed.scss');

var statusTemplate = require('../tpl/status.ejs');
var newsletterTemplate = require('../tpl/newsletter.ejs');

function Embed(config) {
    this._config = config;

    if (this._config.el) {
        this.$el = $(this._config.el);
    }

    if (this._config.baseUrl) {
        this._config.api = this._config.baseUrl + this._config.api;
    }
}

Embed.prototype = {
    _config: {
        id: Number,
        api: String,
        baseUrl: String,
        texts: {
            title: String,
            formHead: String,
            body: String,
            newsletterSuccess: String
        },
        showForm: true
    },

    _price: null,
    _templates: {
        status: null,
        newsletter: null
    },
    _templateContext: {},

    _ui: {
        shares: '.js-shares',
        currentPrice: '.js-current-price',
        startPrice: '.js-start-price',
        minPrice: '.js-min-price',
        barProgress: '.js-bar-progress',
        newsletter: '.js-newsletter',
        form: '.js-form',
        textError: '.js-text-error'
    },

    $el: null,

    init: function () {
        this.initTemplates();

        this.getPrice().done(function () {
            this.render();
            this.polling();
        }.bind(this));

        console.log(this);

        return this;
    },

    getPrice: function (id) {
        if (!id) {
            id = this._config.id;
        }

        return $.get(this._config.api + '/price/' + id)
            .then(function (price) {
                this.setPrice(price);

                return price;
            }.bind(this));
    },

    setPrice: function (data) {
        var self = this;

        this._price = data;

        this._templateContext.texts = {};
        this._templateContext.texts.title = this._config.texts.title;
        this._templateContext.texts.body = this._config.texts.body.replace(/{(.*?)}/g, function (str, $1) {
            return self._price[$1];
        });
        this._templateContext.texts.formHead = this._config.texts.formHead;
        this._templateContext.texts.newsletterSuccess = this._config.texts.newsletterSuccess;
    },

    formatPrice: function (price) {
        price = Math.round(Number(price) * 100) / 100;

        return price.toString().replace(/(\d+)\.(\d+)/, function (str, $1, $2) {
            if (Number($2) < 10) {
                $2 = $2 + '0';
            }

            return $1 + ',' + $2;
        });
    },

    initTemplates: function () {
        this._templates.status = statusTemplate;
        this._templates.status.context = '_templateContext';

        if (this._config.showForm) {
            this._templates.newsletter = newsletterTemplate;
            this._templates.newsletter.context = '_templateContext';
        }
    },

    render: function () {
        var $wrapper = $('

');
        var name;

        // Render templates
        var rendered = '';

        for (name in this._templates) {
            if (!this._templates.hasOwnProperty(name) || !this._templates[name]) continue;

            var template = this._templates[name];
            var context = this[template.context] || {};

            rendered += template(context);
        }

        $wrapper.append(rendered);

        this.$el.html($wrapper);

        // Create UI
        for (name in this._ui) {
            if (!this._ui.hasOwnProperty(name)) continue;

            var selector = this._ui[name];

            this._ui[name] = $(selector);
        }

        // Bind data
        this.renderPrices();

        setTimeout(function () {
            // Show wrapper
            $wrapper.addClass('is-show')
        }, 0);

        if (this._config.showForm) {
            // Initialize form
            this.initForm();
        }
    },

    renderPrices: function () {
        var price = this._price;

        var p = Math.round((price.start_price - price.current_price) / (price.start_price - price.min_price) * 100);

        this._ui.shares.text(price.shares);
        this._ui.startPrice.text(this.formatPrice(price.start_price));
        this._ui.minPrice.text(this.formatPrice(price.min_price));

        this._ui.currentPrice.text(this.formatPrice(price.start_price));

        setTimeout(function () {
            var d = price.start_price - Math.floor(price.current_price); // distance
            var t = 800; // duration
            var v = t / d; // velocity
            var delay = v;

            for (var current_price = price.start_price; current_price >= price.current_price; current_price--) {
                setTimeout(function (newPrice) {
                    this._ui.currentPrice.text(newPrice + ',00');
                }.bind(this), delay, current_price);

                delay += v;
            }

            setTimeout(function () {
                this._ui.currentPrice.text(this.formatPrice(price.current_price));
            }.bind(this), delay + 16);

            this._ui.barProgress.width(p + '%');
        }.bind(this), 750);
    },

    initForm: function () {
        this._ui.form
            .off('submit')
            .on('submit', function () {
                this._ui.newsletter
                    .removeClass('is-error is-success')
                    .addClass('is-loading');

                $.post(this._config.api + '/subscribe', this._ui.form.serializeArray())
                    .done(function (res) {
                        if (res.success) {
                            this._ui.newsletter.addClass('is-success');
                        }
                    }.bind(this))
                    .fail(function (xhr) {
                        var res = xhr.responseJSON || {};

                        this._ui.textError.text('');

                        if (res.error) {
                            var text = 'Bei der Registrierung ist ein Fehler aufgetreten.';

                            if (res.code === 501) text = 'Bitte gib eine E-Mail Adresse an.';
                            if (res.code === 502) text = 'Du bist bereits für den Newsletter registriert.';

                            this._ui.textError.text(text);
                            this._ui.newsletter.addClass('is-error');
                        }
                    }.bind(this))
                    .always(function () {
                        this._ui.newsletter.removeClass('is-loading');
                    }.bind(this));

                return false;
            }.bind(this));
    },

    polling: function () {
        return $.get(this._config.api + '/polling')
            .done(function (response) {
                if (response.event === 'updatePrice') {
                    this.setPrice(response.data);

                    // Update properties
                    this.renderPrices();
                }
            }.bind(this))
            .always(this.polling.bind(this))
    }
};

function onInit() {
    var embed = new Embed(window.EmbedConfig || {});

    embed.init();
}

$(document).ready(onInit);<commit_msg>Optimized number formatting and animation<commit_after>var $ = require('jquery');

require('../css/embed.scss');

var statusTemplate = require('../tpl/status.ejs');
var newsletterTemplate = require('../tpl/newsletter.ejs');

function Embed(config) {
    this._config = config;

    if (this._config.el) {
        this.$el = $(this._config.el);
    }

    if (this._config.baseUrl) {
        this._config.api = this._config.baseUrl + this._config.api;
    }

    console.log(this);
}

Embed.prototype = {
    _config: {
        id: Number,
        api: String,
        baseUrl: String,
        texts: {
            title: String,
            formHead: String,
            body: String,
            newsletterSuccess: String
        },
        showForm: true
    },

    _price: null,
    _templates: {
        status: null,
        newsletter: null
    },
    _templateContext: {},

    _timeouts: [],

    _ui: {
        shares: '.js-shares',
        currentPrice: '.js-current-price',
        startPrice: '.js-start-price',
        minPrice: '.js-min-price',
        barProgress: '.js-bar-progress',
        newsletter: '.js-newsletter',
        form: '.js-form',
        textError: '.js-text-error'
    },

    $el: null,

    init: function () {
        this.initTemplates();

        this.getPrice().done(function () {
            this.render();
            this.polling();
        }.bind(this));

        return this;
    },

    getPrice: function (id) {
        if (!id) {
            id = this._config.id;
        }

        return $.get(this._config.api + '/price/' + id)
            .then(function (price) {
                this.setPrice(price);

                return price;
            }.bind(this));
    },

    setPrice: function (data) {
        var self = this;

        this._price = data;

        this._templateContext.texts = {};
        this._templateContext.texts.title = this._config.texts.title;
        this._templateContext.texts.body = this._config.texts.body.replace(/{(.*?)}/g, function (str, $1) {
            return self._price[$1];
        });
        this._templateContext.texts.formHead = this._config.texts.formHead;
        this._templateContext.texts.newsletterSuccess = this._config.texts.newsletterSuccess;
    },

    formatPrice: function (price) {
        price = Math.round(Number(price) * 100) / 100;

        price = price
            .toString()
            .replace(/(\d+)\.(\d+)|(\d+)/, function (str, $1, $2, $3) {
                var num = 0;

                if ($1 && $2) {
                    if(Number($2) < 10) {
                        $2 = $2 + '0';
                    }

                    num = $1 + ',' + $2;
                } else {
                    num = $3 + ',00';
                }

                return num;
            });

        // console.log(price);

        return price;
    },

    initTemplates: function () {
        this._templates.status = statusTemplate;
        this._templates.status.context = '_templateContext';

        if (this._config.showForm) {
            this._templates.newsletter = newsletterTemplate;
            this._templates.newsletter.context = '_templateContext';
        }
    },

    render: function () {
        var $wrapper = $('

');
        var name;

        // Render templates
        var rendered = '';

        for (name in this._templates) {
            if (!this._templates.hasOwnProperty(name) || !this._templates[name]) continue;

            var template = this._templates[name];
            var context = this[template.context] || {};

            rendered += template(context);
        }

        $wrapper.append(rendered);

        this.$el.html($wrapper);

        // Create UI
        for (name in this._ui) {
            if (!this._ui.hasOwnProperty(name)) continue;

            var selector = this._ui[name];

            this._ui[name] = $(selector);
        }

        // Bind data
        this.renderPrices();

        setTimeout(function () {
            // Show wrapper
            $wrapper.addClass('is-show')
        }, 0);

        if (this._config.showForm) {
            // Initialize form
            this.initForm();
        }
    },

    renderPrices: function () {
        var price = this._price;

        var p = Math.round((price.start_price - price.current_price) / (price.start_price - price.min_price) * 100);

        this._ui.shares.text(price.shares);
        this._ui.startPrice.text(this.formatPrice(price.start_price));
        this._ui.minPrice.text(this.formatPrice(price.min_price));

        this._ui.currentPrice.text(this.formatPrice(price.start_price));
        this._ui.barProgress.width('0%');

        for (var i = 0; i < this._timeouts.length; i++) {
            clearTimeout(this._timeouts[i]);
        }

        this._timeouts.push(
            setTimeout(function () {
                var d = price.start_price - Math.floor(price.current_price); // distance
                var t = 800; // duration
                var v = t / d; // velocity
                var delay = v;

                for (var current_price = price.start_price; current_price >= price.current_price; current_price--) {
                    this._timeouts.push(
                        setTimeout(function (newPrice) {
                            this._ui.currentPrice.text(newPrice + ',00');
                        }.bind(this), delay, current_price)
                    );

                    delay += v;
                }

                this._timeouts.push(
                    setTimeout(function () {
                        this._ui.currentPrice.text(this.formatPrice(price.current_price));

                        this._timeouts = [];
                    }.bind(this), delay + 16)
                );

                this._ui.barProgress.width(p + '%');
            }.bind(this), 750)
        );
    },

    initForm: function () {
        this._ui.form
            .off('submit')
            .on('submit', function () {
                this._ui.newsletter
                    .removeClass('is-error is-success')
                    .addClass('is-loading');

                $.post(this._config.api + '/subscribe', this._ui.form.serializeArray())
                    .done(function (res) {
                        if (res.success) {
                            this._ui.newsletter.addClass('is-success');
                        }
                    }.bind(this))
                    .fail(function (xhr) {
                        var res = xhr.responseJSON || {};

                        this._ui.textError.text('');

                        if (res.error) {
                            var text = 'Bei der Registrierung ist ein Fehler aufgetreten.';

                            if (res.code === 501) text = 'Bitte gib eine E-Mail Adresse an.';
                            if (res.code === 502) text = 'Du bist bereits für den Newsletter registriert.';

                            this._ui.textError.text(text);
                            this._ui.newsletter.addClass('is-error');
                        }
                    }.bind(this))
                    .always(function () {
                        this._ui.newsletter.removeClass('is-loading');
                    }.bind(this));

                return false;
            }.bind(this));
    },

    polling: function () {
        return $.get(this._config.api + '/polling')
            .done(function (response) {
                if (response.event === 'updatePrice') {
                    this.setPrice(response.data);

                    // Update properties
                    this.renderPrices();
                }
            }.bind(this))
            .always(this.polling.bind(this))
    }
};

function onInit() {
    var embed = new Embed(window.EmbedConfig || {});

    embed.init();
}

$(document).ready(onInit);<|endoftext|>


<commit_before>// activity.js
//
// data object representing an activity
//
// Copyright 2011, StatusNet Inc.
//
// 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.

var databank = require('databank'),
    DatabankObject = databank.DatabankObject,
    NoSuchThingError = databank.NoSuchThingError,
    Step = require('step'),
    dateFormat = require('dateformat'),
    uuid = require('node-uuid');

var UnknownTypeError = function(type) {
    Error.captureStackTrace(this, UnknownTypeError);
    this.name = 'UnknownTypeError';
    this.type = type;
    this.message = 'Unknown type: ' + type;
};

UnknownTypeError.prototype = new Error();
UnknownTypeError.prototype.constructor = UnknownTypeError;

var Activity = DatabankObject.subClass('activity');

Activity.schema = { pkey: 'id',
                    fields: ['actor',
                             'content',
                             'generator',
                             'icon',
                             'id',
                             'object',
                             'published',
                             'provider',
                             'target',
                             'title',
                             'url',
                             'uuid',
                             'updated',
                             'verb'],
                    indices: ['actor.id', 'object.id', 'uuid'] };

Activity.verbs = ['add',
                  'cancel',
                  'checkin',
                  'delete',
                  'favorite',
                  'follow',
                  'give',
                  'ignore',
                  'invite',
                  'join',
                  'leave',
                  'like',
                  'make-friend',
                  'play',
                  'post',
                  'receive',
                  'remove',
                  'remove-friend',
                  'request-friend',
                  'rsvp-maybe',
                  'rsvp-no',
                  'rsvp-yes',
                  'save',
                  'share',
                  'stop-following',
                  'tag',
                  'unfavorite',
                  'unlike',
                  'unsave',
                  'update'];

var i = 0, verb;

// Constants-like members for activity verbs

for (i = 0; i < Activity.verbs.length; i++) {
    verb = Activity.verbs[i];
    Activity[verb.toUpperCase().replace('-', '_')] = verb;
}

Activity.objectTypes = ['article',
                        'audio',
                        'badge',
                        'bookmark',
                        'collection',
                        'comment',
                        'event',
                        'file',
                        'group',
                        'image',
                        'note',
                        'person',
                        'place',
                        'product',
                        'question',
                        'review',
                        'service',
                        'video'];

var objectType;

// Constants-like members for activity object types

for (i = 0; i < Activity.objectTypes.length; i++) {
    objectType = Activity.objectTypes[i];
    Activity[objectType.toUpperCase().replace('-', '_')] = objectType;
}

Activity.init = function(inst, properties) {

    DatabankObject.init(inst, properties);

    if (!this.verb) {
        this.verb = "post";
    }

    if (inst.actor) {
        inst.actor = Activity.toObject(inst.actor, Activity.PERSON);
    }

    if (inst.object) {
        inst.object = Activity.toObject(inst.object);
    }
};

Activity.toClass = function(type) {
    var module, className;
    module = require('./' + type);
    className = type.substring(0,1).toUpperCase() + type.substring(1, type.length).toLowerCase();
    return module[className];
};

Activity.toObject = function(props, defaultType) {
    var Cls, type;

    // Try rational fallbacks
    type = props.objectType || defaultType || Activity.NOTE;

    if (Activity.objectTypes.indexOf(type) != -1) {
        Cls = Activity.toClass(type);
        return new Cls(props);
    } else {
        // XXX: is this really the best we can do?
        // XXX: extension mechanism
        // XXX: 'Other' object type
        return props;
    }
};

Activity.getObject = function(type, id, callback) {
    var Cls;
    if (Activity.objectTypes.indexOf(type) != -1) {
        Cls = Activity.toClass(type);
        Cls.get(id, callback);
    } else {
        callback(new UnknownTypeError(type), null);
    }
};

Activity.createObject = function(obj, callback) {
    var Cls, type = obj.objectType;
    if (Activity.objectTypes.indexOf(type) != -1) {
        Cls = Activity.toClass(type);
        Cls.create(obj, callback);
    } else {
        callback(new UnknownTypeError(type), null);
    }
};

Activity.ensureObject = function(obj, callback) {
    var Cls, type = obj.objectType, id = obj.id;
    if (Activity.objectTypes.indexOf(type) === -1) {
        callback(new UnknownTypeError(type), null);
    } else {
        Cls = Activity.toClass(type);
        Cls.get(id, function(err, result) {
            if (err) {
                if (err instanceof NoSuchThingError) {
                    Cls.create(obj, callback);
                } else {
                    callback(err, null);
                }
            } else {
                callback(null, result);
            }
        });
    }
};

Activity.newId = function() {
    var buf = new Buffer(16);
    uuid('binary', buf);

    var id = buf.toString('base64');

    // XXX: optimize me

    id = id.replace(/\+/g, '-');
    id = id.replace(/\//g, '_');
    id = id.replace(/=/g, '');
    return id;
};

// For now, we make HTTP URIs. Maybe someday we'll
// do something else. I like HTTP URIs, though.

Activity.makeURI = function(type, uuid) {
    return Activity.makeURL(type + '/' + uuid);
};

Activity.makeURL = function(rel) {
    // Crazy syntax to avoid circular require
    return require('../pumpapi').PumpAPI.makeURL(rel);
};

Activity.prototype.apply = function(defaultActor, callback) {

    var Edge = require('./edge').Edge;

    // Ensure an actor

    this.actor = this.actor || defaultActor;

    // XXX: Polymorphism is probably the right thing here
    // but I kinda CBA. How's this: rewrite when we get over 5 case's...?

    switch (this.verb) {
    case Activity.POST:
        // Force stub author data
        this.object.author = {objectType: this.actor.objectType,
                              id: this.actor.id};
        // Is this it...?
        Activity.createObject(this.object, function(err, result) {
            callback(err, result);
        });
        break;
    case Activity.FOLLOW:
        if (!this.actor.id || !this.object.id) {
            callback(new Error("No ID."));
        }
        // XXX: OStatus if necessary
        Edge.create({id: this.actor.id + '->' + this.object.id,
		     from: { id: this.actor.id, objectType: this.actor.objectType },
                     to: {id: this.object.id, objectType: this.object.objectType }},
                    callback);
        break;
    case Activity.STOP_FOLLOWING:
        var edges = [];
        // XXX: OStatus if necessary
        Edge.search({'from.id': this.actor.id, 'to.id': this.object.id}, function(err, edges) {
            if (err) {
                callback(err);
            } else if (edges.length === 0) { // that's bad
                callback(new Error("No such edge."));
            } else if (edges.length > 1) { // that's worse
                // XXX: Kill 'em all
                callback(new Error("Too many edges."));
            } else {
                edges[0].del(callback);
            }
        });
        break;
    default:
        // XXX: fave/unfave, join/leave, ...?
        callback(null);
        break;
    }
};

// When save()'ing an activity, ensure the actor and object
// are persisted, then save them by reference.

Activity.prototype.defaultSave = Activity.prototype.save;

Activity.prototype.save = function(callback) {

    var now = dateFormat(new Date(), "isoDateTime", true),
        act = this;

    act.updated = now;

    if (!act.published) {
        act.published = now;
    }

    if (!act.id) {
        act.uuid = Activity.newId();
        act.id   = Activity.makeURI('activity', act.uuid);
    }

    if (!act.actor) {
        callback(new Error("Activity has no actor"), null);
    }

    if (!act.object) {
        callback(new Error("Activity has no object"), null);
    }

    Activity.ensureObject(act.actor, function(err, actor) {
        if (err) {
            callback(err);
        } else {
            Activity.ensureObject(act.object, function(err, object) {
                if (err) {
                    callback(err);
                } else {
                    // slim them down to references
		    // FIXME: probably shouldn't overwrite attributes
                    act.actor = {objectType: actor.objectType,
                                 id: actor.id};
                    act.object = {objectType: object.objectType,
                                  id: object.id};
                    act.defaultSave(callback);
                }
            });
        }
    });
};

// When get()'ing an activity, also get the actor and the object,
// which are saved by reference

Activity.defaultGet = Activity.get;

Activity.get = function(id, callback) {
    Activity.defaultGet(id, function(err, activity) {
        if (err) {
            callback(err, null);
        } else {
            callback(null, activity);
        }
    });
};

Activity.prototype.expand = function(callback) {
    var act = this;

    Step(
        function() {
            act.expandActor(this.parallel());
            act.expandObject(this.parallel());
        },
        function(err) {
            if (err) {
                callback(err, null);
            } else {
                callback(null, act);
            }
        }
    );
};

Activity.prototype.expandObject = function(callback) {
    var act = this;

    Activity.getObject(this.object.objectType, this.object.id, function(err, object) {
        if (err) {
            callback(err, null);
        } else {
            // XXX: Check for the old object!
            act.object = object;
            if (act.verb == "post") {
                delete act.object.author;
            }
            callback(null, act);
        }
    });
};

Activity.prototype.expandActor = function(callback) {
    var act = this;

    Activity.getObject(this.actor.objectType, this.actor.id, function(err, actor) {
        if (err) {
            callback(err, null);
        } else {
            // XXX: Check for the old actor!
            act.actor = actor;
            callback(null, this);
        }
    });
};

exports.Activity = Activity;
<commit_msg>Use uuid.v4() for specific UUID generation method<commit_after>// activity.js
//
// data object representing an activity
//
// Copyright 2011, StatusNet Inc.
//
// 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.

var databank = require('databank'),
    DatabankObject = databank.DatabankObject,
    NoSuchThingError = databank.NoSuchThingError,
    Step = require('step'),
    dateFormat = require('dateformat'),
    uuid = require('node-uuid');

var UnknownTypeError = function(type) {
    Error.captureStackTrace(this, UnknownTypeError);
    this.name = 'UnknownTypeError';
    this.type = type;
    this.message = 'Unknown type: ' + type;
};

UnknownTypeError.prototype = new Error();
UnknownTypeError.prototype.constructor = UnknownTypeError;

var Activity = DatabankObject.subClass('activity');

Activity.schema = { pkey: 'id',
                    fields: ['actor',
                             'content',
                             'generator',
                             'icon',
                             'id',
                             'object',
                             'published',
                             'provider',
                             'target',
                             'title',
                             'url',
                             'uuid',
                             'updated',
                             'verb'],
                    indices: ['actor.id', 'object.id', 'uuid'] };

Activity.verbs = ['add',
                  'cancel',
                  'checkin',
                  'delete',
                  'favorite',
                  'follow',
                  'give',
                  'ignore',
                  'invite',
                  'join',
                  'leave',
                  'like',
                  'make-friend',
                  'play',
                  'post',
                  'receive',
                  'remove',
                  'remove-friend',
                  'request-friend',
                  'rsvp-maybe',
                  'rsvp-no',
                  'rsvp-yes',
                  'save',
                  'share',
                  'stop-following',
                  'tag',
                  'unfavorite',
                  'unlike',
                  'unsave',
                  'update'];

var i = 0, verb;

// Constants-like members for activity verbs

for (i = 0; i < Activity.verbs.length; i++) {
    verb = Activity.verbs[i];
    Activity[verb.toUpperCase().replace('-', '_')] = verb;
}

Activity.objectTypes = ['article',
                        'audio',
                        'badge',
                        'bookmark',
                        'collection',
                        'comment',
                        'event',
                        'file',
                        'group',
                        'image',
                        'note',
                        'person',
                        'place',
                        'product',
                        'question',
                        'review',
                        'service',
                        'video'];

var objectType;

// Constants-like members for activity object types

for (i = 0; i < Activity.objectTypes.length; i++) {
    objectType = Activity.objectTypes[i];
    Activity[objectType.toUpperCase().replace('-', '_')] = objectType;
}

Activity.init = function(inst, properties) {

    DatabankObject.init(inst, properties);

    if (!this.verb) {
        this.verb = "post";
    }

    if (inst.actor) {
        inst.actor = Activity.toObject(inst.actor, Activity.PERSON);
    }

    if (inst.object) {
        inst.object = Activity.toObject(inst.object);
    }
};

Activity.toClass = function(type) {
    var module, className;
    module = require('./' + type);
    className = type.substring(0,1).toUpperCase() + type.substring(1, type.length).toLowerCase();
    return module[className];
};

Activity.toObject = function(props, defaultType) {
    var Cls, type;

    // Try rational fallbacks
    type = props.objectType || defaultType || Activity.NOTE;

    if (Activity.objectTypes.indexOf(type) != -1) {
        Cls = Activity.toClass(type);
        return new Cls(props);
    } else {
        // XXX: is this really the best we can do?
        // XXX: extension mechanism
        // XXX: 'Other' object type
        return props;
    }
};

Activity.getObject = function(type, id, callback) {
    var Cls;
    if (Activity.objectTypes.indexOf(type) != -1) {
        Cls = Activity.toClass(type);
        Cls.get(id, callback);
    } else {
        callback(new UnknownTypeError(type), null);
    }
};

Activity.createObject = function(obj, callback) {
    var Cls, type = obj.objectType;
    if (Activity.objectTypes.indexOf(type) != -1) {
        Cls = Activity.toClass(type);
        Cls.create(obj, callback);
    } else {
        callback(new UnknownTypeError(type), null);
    }
};

Activity.ensureObject = function(obj, callback) {
    var Cls, type = obj.objectType, id = obj.id;
    if (Activity.objectTypes.indexOf(type) === -1) {
        callback(new UnknownTypeError(type), null);
    } else {
        Cls = Activity.toClass(type);
        Cls.get(id, function(err, result) {
            if (err) {
                if (err instanceof NoSuchThingError) {
                    Cls.create(obj, callback);
                } else {
                    callback(err, null);
                }
            } else {
                callback(null, result);
            }
        });
    }
};

Activity.newId = function() {

    var buf = new Buffer(16);

    uuid.v4({}, buf);

    var id = buf.toString('base64');

    // XXX: optimize me

    id = id.replace(/\+/g, '-');
    id = id.replace(/\//g, '_');
    id = id.replace(/=/g, '');

    return id;
};

// For now, we make HTTP URIs. Maybe someday we'll
// do something else. I like HTTP URIs, though.

Activity.makeURI = function(type, uuid) {
    return Activity.makeURL(type + '/' + uuid);
};

Activity.makeURL = function(rel) {
    // Crazy syntax to avoid circular require
    return require('../pumpapi').PumpAPI.makeURL(rel);
};

Activity.prototype.apply = function(defaultActor, callback) {

    var Edge = require('./edge').Edge;

    // Ensure an actor

    this.actor = this.actor || defaultActor;

    // XXX: Polymorphism is probably the right thing here
    // but I kinda CBA. How's this: rewrite when we get over 5 case's...?

    switch (this.verb) {
    case Activity.POST:
        // Force stub author data
        this.object.author = {objectType: this.actor.objectType,
                              id: this.actor.id};
        // Is this it...?
        Activity.createObject(this.object, function(err, result) {
            callback(err, result);
        });
        break;
    case Activity.FOLLOW:
        if (!this.actor.id || !this.object.id) {
            callback(new Error("No ID."));
        }
        // XXX: OStatus if necessary
        Edge.create({id: this.actor.id + '->' + this.object.id,
		     from: { id: this.actor.id, objectType: this.actor.objectType },
                     to: {id: this.object.id, objectType: this.object.objectType }},
                    callback);
        break;
    case Activity.STOP_FOLLOWING:
        var edges = [];
        // XXX: OStatus if necessary
        Edge.search({'from.id': this.actor.id, 'to.id': this.object.id}, function(err, edges) {
            if (err) {
                callback(err);
            } else if (edges.length === 0) { // that's bad
                callback(new Error("No such edge."));
            } else if (edges.length > 1) { // that's worse
                // XXX: Kill 'em all
                callback(new Error("Too many edges."));
            } else {
                edges[0].del(callback);
            }
        });
        break;
    default:
        // XXX: fave/unfave, join/leave, ...?
        callback(null);
        break;
    }
};

// When save()'ing an activity, ensure the actor and object
// are persisted, then save them by reference.

Activity.prototype.defaultSave = Activity.prototype.save;

Activity.prototype.save = function(callback) {

    var now = dateFormat(new Date(), "isoDateTime", true),
        act = this;

    act.updated = now;

    if (!act.published) {
        act.published = now;
    }

    if (!act.id) {
        act.uuid = Activity.newId();
        act.id   = Activity.makeURI('activity', act.uuid);
    }

    if (!act.actor) {
        callback(new Error("Activity has no actor"), null);
    }

    if (!act.object) {
        callback(new Error("Activity has no object"), null);
    }

    Activity.ensureObject(act.actor, function(err, actor) {
        if (err) {
            callback(err);
        } else {
            Activity.ensureObject(act.object, function(err, object) {
                if (err) {
                    callback(err);
                } else {
                    // slim them down to references
		    // FIXME: probably shouldn't overwrite attributes
                    act.actor = {objectType: actor.objectType,
                                 id: actor.id};
                    act.object = {objectType: object.objectType,
                                  id: object.id};
                    act.defaultSave(callback);
                }
            });
        }
    });
};

// When get()'ing an activity, also get the actor and the object,
// which are saved by reference

Activity.defaultGet = Activity.get;

Activity.get = function(id, callback) {
    Activity.defaultGet(id, function(err, activity) {
        if (err) {
            callback(err, null);
        } else {
            callback(null, activity);
        }
    });
};

Activity.prototype.expand = function(callback) {
    var act = this;

    Step(
        function() {
            act.expandActor(this.parallel());
            act.expandObject(this.parallel());
        },
        function(err) {
            if (err) {
                callback(err, null);
            } else {
                callback(null, act);
            }
        }
    );
};

Activity.prototype.expandObject = function(callback) {
    var act = this;

    Activity.getObject(this.object.objectType, this.object.id, function(err, object) {
        if (err) {
            callback(err, null);
        } else {
            // XXX: Check for the old object!
            act.object = object;
            if (act.verb == "post") {
                delete act.object.author;
            }
            callback(null, act);
        }
    });
};

Activity.prototype.expandActor = function(callback) {
    var act = this;

    Activity.getObject(this.actor.objectType, this.actor.id, function(err, actor) {
        if (err) {
            callback(err, null);
        } else {
            // XXX: Check for the old actor!
            act.actor = actor;
            callback(null, this);
        }
    });
};

exports.Activity = Activity;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var Player = require('../model/player');

router.post('', function (req, res) {

  var player = new Player();
  player.name = req.body.name;
  player.email = req.body.email;
  player.playerStats = req.body.playerStats;

  player.save(function (err) {

    if (err) {
      res.status(504).json(err);
      return;
    }

    res.status(202).json({message: 'player created'});

  });

});

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

  Player.find({}, function (err, players) {

    if (err) {
      res.json(err);
      return;
    }

    var playersList = [];

    players.forEach(function (player) {
      playersList.push(player);
    });

    res.json(playersList);
  });

});

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

  callback = function(err, players) {

    if (err) {
      res.json(err);
      return;
    }

    var playersList = [];

    players.forEach(function (player) {
      playersList.push(player);
    });

    res.json(playersList);
  };

  Player.find({}).sort([['playerStats.win', -1], ['name', 1]]).exec(callback);

});

module.exports = router;
<commit_msg>Removes email from player response<commit_after>var express = require('express');
var router = express.Router();
var Player = require('../model/player');

router.post('', function (req, res) {

  var player = new Player();
  player.name = req.body.name;
  player.email = req.body.email;
  player.playerStats = req.body.playerStats;

  player.save(function (err) {

    if (err) {
      res.status(504).json(err);
      return;
    }

    res.status(202).json({message: 'player created'});

  });

});

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

  Player.find({})
    .select('_id name')
    .then(function (err, players) {

      if (err) {
        res.json(err);
        return;
      }

      var playersList = [];

      players.forEach(function (player) {
        playersList.push(player);
      });

      res.json(playersList);
    });

});

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

  Player.find({})
    .select('name playerStats')
    .sort([['playerStats.win', -1], ['name', 1]])
    .then(function (err, players) {

      if (err) {
        res.json(err);
        return;
      }

      var playersList = [];

      players.forEach(function (player) {
        playersList.push(player);
      });

      res.json(playersList);
    });

});

module.exports = router;
<|endoftext|>


<commit_before><commit_msg>add angular lib<commit_after><|endoftext|>


<commit_before>'use strict';

// Mode
if (window.mode)var mode = window.mode;
else var mode = urlParam('mode');
if (window.urlencodedXML) var urlencodedXML = window.urlencodedXML;
else var urlencodedXML = urlParam('diagramXML');

// Includes
var fs = require('fs');
var $ = require('jquery'),
    BpmnModeler = require('bpmn-js/lib/Modeler'),
    BpmnViewer = require('bpmn-js/lib/Viewer');

var forEach = require('lodash/collection/forEach');
var container = $('#js-drop-zone');
var canvas = $('#js-canvas');

// Reference to the custom Modules
var AofCustomizationModules = require('./../aof-customization/index'), // affects activities
    aofModdleExtention = require('./../aof-customization/moddleExtensions/aof');

// Helper Functions

function openDiagram(renderer, xml) {
    renderer.importXML(xml, function (err) {

        if (err) {
            container
                .removeClass('with-diagram')
                .addClass('with-error');

            container.find('.error pre').text(err.message);

            console.error(err);
        } else {
            container
                .removeClass('with-error')
                .addClass('with-diagram');

            var elementRegistry = renderer.get('elementRegistry');
            var canvasObject = renderer.get('canvas');

            // Mark AppEnsembleApps grey
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:UserTask" && element.businessObject.isAppEnsembleApp == true )//&& element.businessObject.$attrs['aof:realizedBy'] && element.businessObject.$attrs['aof:realizedBy'] != "")
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensembleapp');
                }
            );

            // Mark AppEnsembles
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:Participant" && (element.businessObject.$attrs['aof:isAppEnsemble'] && element.businessObject.$attrs['aof:isAppEnsemble'] == "true") || (element.businessObject.isAppEnsemble == true))
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensemble');
                }
            );

            // Load available Apps for UserTasks
            if(mode!="view") {
                var ProviderObject = renderer.get('propertiesProvider');
                ProviderObject.getAppURLs();
            }
        }

    });
}

function saveSVG(done) {
    renderer.saveSVG(done);
}

function saveDiagram(done) {
    renderer.saveXML({format: true}, function (err, xml) {
        done(err, xml);
    });
}

function urlParam(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) {
        return null;
    }
    else {
        return results[1] || 0;
    }
}

// Mode and data processing
if (mode == "view") {
    var renderer = new BpmnViewer({container: canvas});
}
else {

    var propertiesPanelModule = require('bpmn-js-properties-panel');
    var propertiesProviderModule = require('bpmn-js-properties-panel/lib/provider/aof');

    var renderer = new BpmnModeler({
        container: canvas,
        additionalModules: [propertiesPanelModule, propertiesProviderModule, AofCustomizationModules],
        moddleExtensions: {aof: aofModdleExtention},
        propertiesPanel: {
            parent: '#js-properties-panel'
        }
    });
}
if (mode == "view" || mode == "edit") {
    var newDiagramXML = decodeURIComponent(urlencodedXML);
}
else {
    var newDiagramXML = fs.readFileSync(__dirname + '/../../resources/newDiagram.bpmn', 'utf-8');
}

// bootstrap diagram functions

$(document).on('ready', function () {
    openDiagram(renderer, newDiagramXML);
    window.onbeforeunload = function () {
        return "Do you really want to leave this page? There might be a loss of unsaved data!"
    }
});

// jQuery references
var downloadSvgLink = $('#js-download-svg');
var saveandCloseLink = $('#js-save-appensemble-and-close');
var saveLink = $('#js-save-appensemble');
var closeLink = $('#close-modeler');

// actions definition
if (mode == "view") {
    saveLink.remove();
    saveandCloseLink.remove();
    downloadSvgLink.remove();
}
else {
    saveLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
');
                    setTimeout(function () {
                        $.when($('.alert-box').fadeOut(500))
                            .done(function () {
                                $('.alert-box').remove();
                            });
                    }, 2000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (jqXHR, status, error) {
                    container.before('
There was a Problem saving the Appensemble×
');
                }
            });
        }
    });

    saveandCloseLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
 Closing Modeler in 3 seconds.×
');
                    window.onbeforeunload = function () {
                    }
                    setTimeout(function () {
                        $('#close-seconds').text("2")
                    }, 1000);
                    setTimeout(function () {
                        $('#close-seconds').text("1")
                    }, 2000);
                    setTimeout(function () {
                        window.location.href = document.referrer
                    }, 3000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (jqXHR, status, error) {
                    container.before('
There was a Problem saving the Appensemble×
');
                }
            });
        }
    });
}

closeLink.click(function () {
    window.location.href = document.referrer;
})

$('.top-bar-section .right a').click(function (e) {
    if (!$(this).is('.active')) {
        e.preventDefault();
        e.stopPropagation();
    }
});

// export helper functions
function setEncoded_dl(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

function setEncoded(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': '/api/actions/app-ensembles/add?data=' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

// Update routine
var _ = require('lodash');

var exportArtifacts = _.debounce(function () {
    saveDiagram(function (err, xml) {
        setEncoded(saveLink, 'diagram.bpmn', err ? null : xml);
    });
    saveDiagram(function (err, xml) {
        setEncoded(saveandCloseLink, 'diagram.bpmn', err ? null : xml);
    });
    saveSVG(function (err, svg) {
        setEncoded_dl(downloadSvgLink, 'diagram.svg', err ? null : svg);
    });
}, 500);

renderer.on('commandStack.changed', exportArtifacts);<commit_msg>More detailed Ajax Error<commit_after>'use strict';

// Mode
if (window.mode)var mode = window.mode;
else var mode = urlParam('mode');
if (window.urlencodedXML) var urlencodedXML = window.urlencodedXML;
else var urlencodedXML = urlParam('diagramXML');

// Includes
var fs = require('fs');
var $ = require('jquery'),
    BpmnModeler = require('bpmn-js/lib/Modeler'),
    BpmnViewer = require('bpmn-js/lib/Viewer');

var forEach = require('lodash/collection/forEach');
var container = $('#js-drop-zone');
var canvas = $('#js-canvas');

// Reference to the custom Modules
var AofCustomizationModules = require('./../aof-customization/index'), // affects activities
    aofModdleExtention = require('./../aof-customization/moddleExtensions/aof');

// Helper Functions

function openDiagram(renderer, xml) {
    renderer.importXML(xml, function (err) {

        if (err) {
            container
                .removeClass('with-diagram')
                .addClass('with-error');

            container.find('.error pre').text(err.message);

            console.error(err);
        } else {
            container
                .removeClass('with-error')
                .addClass('with-diagram');

            var elementRegistry = renderer.get('elementRegistry');
            var canvasObject = renderer.get('canvas');

            // Mark AppEnsembleApps grey
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:UserTask" && element.businessObject.isAppEnsembleApp == true )//&& element.businessObject.$attrs['aof:realizedBy'] && element.businessObject.$attrs['aof:realizedBy'] != "")
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensembleapp');
                }
            );

            // Mark AppEnsembles
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:Participant" && (element.businessObject.$attrs['aof:isAppEnsemble'] && element.businessObject.$attrs['aof:isAppEnsemble'] == "true") || (element.businessObject.isAppEnsemble == true))
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensemble');
                }
            );

            // Load available Apps for UserTasks
            if(mode!="view") {
                var ProviderObject = renderer.get('propertiesProvider');
                ProviderObject.getAppURLs();
            }
        }

    });
}

function saveSVG(done) {
    renderer.saveSVG(done);
}

function saveDiagram(done) {
    renderer.saveXML({format: true}, function (err, xml) {
        done(err, xml);
    });
}

function urlParam(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) {
        return null;
    }
    else {
        return results[1] || 0;
    }
}

// Mode and data processing
if (mode == "view") {
    var renderer = new BpmnViewer({container: canvas});
}
else {

    var propertiesPanelModule = require('bpmn-js-properties-panel');
    var propertiesProviderModule = require('bpmn-js-properties-panel/lib/provider/aof');

    var renderer = new BpmnModeler({
        container: canvas,
        additionalModules: [propertiesPanelModule, propertiesProviderModule, AofCustomizationModules],
        moddleExtensions: {aof: aofModdleExtention},
        propertiesPanel: {
            parent: '#js-properties-panel'
        }
    });
}
if (mode == "view" || mode == "edit") {
    var newDiagramXML = decodeURIComponent(urlencodedXML);
}
else {
    var newDiagramXML = fs.readFileSync(__dirname + '/../../resources/newDiagram.bpmn', 'utf-8');
}

// bootstrap diagram functions

$(document).on('ready', function () {
    openDiagram(renderer, newDiagramXML);
    window.onbeforeunload = function () {
        return "Do you really want to leave this page? There might be a loss of unsaved data!"
    }
});

// jQuery references
var downloadSvgLink = $('#js-download-svg');
var saveandCloseLink = $('#js-save-appensemble-and-close');
var saveLink = $('#js-save-appensemble');
var closeLink = $('#close-modeler');

// actions definition
if (mode == "view") {
    saveLink.remove();
    saveandCloseLink.remove();
    downloadSvgLink.remove();
}
else {
    saveLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            /*$.ajax({
                url: '/api/app-ensembles/Test-1/details',
                statusCode: {
                    404: function() {
                        $.ajax($(this).attr('href'), {
                            success: function (data, status, jqXHR) {
                                container.before('
' + data + '
');
                                setTimeout(function () {
                                    $.when($('.alert-box').fadeOut(500))
                                        .done(function () {
                                            $('.alert-box').remove();
                                        });
                                }, 2000);
                            },
                            method: "GET",
                            async: false,
                            timeout: 1000,
                            error: function (jqXHR, status, error) {
                                container.before('
There was a Problem saving the Appensemble×
');
                            }
                        });
                    },
                    200: function(){
                        alert("File already exists... choose another name!")
                    }
                }
            });*/

            $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
');
                    setTimeout(function () {
                        $.when($('.alert-box').fadeOut(500))
                            .done(function () {
                                $('.alert-box').remove();
                            });
                    }, 2000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (responseObject, status, error) {
                    container.before('
There was a Problem saving the App-Ensemble: '+responseObject.responseText +' ('+responseObject.statusText+') ×
');
                }
            });

        }
    });

    saveandCloseLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
 Closing Modeler in 3 seconds.×
');
                    window.onbeforeunload = function () {
                    }
                    setTimeout(function () {
                        $('#close-seconds').text("2")
                    }, 1000);
                    setTimeout(function () {
                        $('#close-seconds').text("1")
                    }, 2000);
                    setTimeout(function () {
                        window.location.href = document.referrer
                    }, 3000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (responseObject, status, error) {
                    container.before('
There was a Problem saving the App-Ensemble: '+responseObject.responseText +' ('+responseObject.statusText+') ×
');
                }
            });
        }
    });
}

closeLink.click(function () {
    window.location.href = document.referrer;
})

$('.top-bar-section .right a').click(function (e) {
    if (!$(this).is('.active')) {
        e.preventDefault();
        e.stopPropagation();
    }
});

// export helper functions
function setEncoded_dl(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

function setEncoded(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': '/api/actions/app-ensembles/add?data=' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

// Update routine
var _ = require('lodash');

var exportArtifacts = _.debounce(function () {
    saveDiagram(function (err, xml) {
        setEncoded(saveLink, 'diagram.bpmn', err ? null : xml);
    });
    saveDiagram(function (err, xml) {
        setEncoded(saveandCloseLink, 'diagram.bpmn', err ? null : xml);
    });
    saveSVG(function (err, svg) {
        setEncoded_dl(downloadSvgLink, 'diagram.svg', err ? null : svg);
    });
}, 500);

renderer.on('commandStack.changed', exportArtifacts);<|endoftext|>


<commit_before>module.exports = function config(grunt, config) {
    var ghPagesDir = '._tmp/gh-pages';
    var ghPagesTmp = '._tmp/gh-pages-tmp';

    config['gh-pages'] = {
        options: {
            base:  ghPagesTmp,
            clone: ghPagesDir,
            only:  'api',

            user: {
                name:  'Webino, s. r. o.',
                email: 'info@webino.sk'
            }
        },
        src: ['**']
    };

    if (process.env.GH_REF) {
        config['gh-pages'].options.repo = 'https://' + process.env.GH_TOKEN + '@' + process.env.GH_REF;
        config['gh-pages'].options.silent = true;
    }

    config.clean['gh-pages'] = {src: [ghPagesDir, ghPagesTmp]};

    config.copy['gh-pages-api'] = {
        files: [{
            expand: true,
            cwd:   '._api',
            src:   ['**'],
            dest:  ghPagesTmp + '/api'
        }]
    };

    config.tasks['publish-gh-pages'] = {
        description: 'Publish GitHub pages',
        function: [
            'clean:gh-pages',
            'copy:gh-pages-api',
            'gh-pages'
        ]
    };

    config.tasks.publish = {
        description: 'Publish module to a GitHub repository',
        function: function () {
            // Recreate github repo
            grunt.task.run([
                'exec:github_delete_repo',
                'exec:github_create_repo'
            ]);

            // Initialize git & push
            grunt.task.run([
                'clean:git',
                'exec:git_add:.',
                'exec:git_flow_init:.',
                'exec:git_remote_add_origin:.:<%= github.webino.ssh  %>/<%= pkg.camelCase %>.git',
                'exec:git_push_origin_develop:.',
                'exec:git_push_origin_master:.'
            ]);
        }
    };
};
<commit_msg>Updated github.js, added README.md to gh-pages index.md automation<commit_after>module.exports = function config(grunt, config) {
    var ghPagesDir = '._tmp/gh-pages';
    var ghPagesTmp = '._tmp/gh-pages-tmp';

    config['gh-pages'] = {
        options: {
            base:  ghPagesTmp,
            clone: ghPagesDir,
            only:  'api',

            user: {
                name:  'Webino, s. r. o.',
                email: 'info@webino.sk'
            }
        },
        src: ['**']
    };

    if (process.env.GH_REF) {
        config['gh-pages'].options.repo = 'https://' + process.env.GH_TOKEN + '@' + process.env.GH_REF;
        config['gh-pages'].options.silent = true;
    }

    config.clean['gh-pages'] = {src: [ghPagesDir, ghPagesTmp]};

    config.exec.gh_pages_index = {cmd: 'cp -f README.md ' + ghPagesTmp + '/index.md'};

    config.copy['gh-pages-index'] = {
        files: [{
            expand: true,
            cwd:   '.',
            src:   ['README.md'],
            dest:  ghPagesTmp + '/index.md'
        }]
    };

    config.copy['gh-pages-api'] = {
        files: [{
            expand: true,
            cwd:   '._api',
            src:   ['**'],
            dest:  ghPagesTmp + '/api'
        }]
    };

    config.tasks['publish-gh-pages'] = {
        description: 'Publish GitHub pages',
        function: [
            'clean:gh-pages',
            'exec:gh_pages_index',
            'copy:gh-pages-api',
            'gh-pages'
        ]
    };

    config.tasks.publish = {
        description: 'Publish module to a GitHub repository',
        function: function () {
            // Recreate github repo
            grunt.task.run([
                'exec:github_delete_repo',
                'exec:github_create_repo'
            ]);

            // Initialize git & push
            grunt.task.run([
                'clean:git',
                'exec:git_add:.',
                'exec:git_flow_init:.',
                'exec:git_remote_add_origin:.:<%= github.webino.ssh  %>/<%= pkg.camelCase %>.git',
                'exec:git_push_origin_develop:.',
                'exec:git_push_origin_master:.'
            ]);
        }
    };
};
<|endoftext|>


<commit_before>"use strict";
angular.module("typeaheadDropdown.tpl", [])
        .run(["$templateCache",
            function (a) {
                a.put("templates/typeaheadDropdown.tpl.html",
                    "
" +
                    //"
Loading options...
" +
                    "
" +
                    "
" +
                    "<input class=form-control placeholder=\"Select or type...\" ng-model=mdl typeahead=\"op[config.optionLabel] for op in options | filter:$viewValue\" typeahead-editable=false typeahead-on-select=\"onSelect($item, $model, $label)\" ng-required=\"required\"> " +
                    "" +
                    "<button class=\"btn btn-default dropdown-toggle\" dropdown-toggle>" +
                    "" +
                    "" +
                    "</button>" +
                    "" +
                    "
" +
                    "
" +
                    "
" +
                    "{{op[config.optionLabel]}}" +
                    "
" +
                    "
" +
                    "
" +
                    "
");
            }
        ]),
    angular.module("apg.typeaheadDropdown", ["typeaheadDropdown.tpl", "ui.bootstrap"])
        .directive("typeaheadDropdown", function() {
            return {
                templateUrl: "templates/typeaheadDropdown.tpl.html",
                scope: { mdl: "=ngModel", options: "=",  config: "=?", events: "=", required: "=?ngRequired" },
                require: "ngModel",
                replace: true,
                link: function($scope, $element, $attrs) {
                    $scope.externalEvents = {
                        onItemSelect: angular.noop
                    };

                    angular.extend($scope.externalEvents, $scope.events || []);
                },

                controller: ["$scope",
                    function (a) {
                        a.config = angular.extend({ modelLabel: "name", optionLabel: "name" }, a.config),

                        a.onSelect = function (i) {
                            if (a.mdl === undefined) {
                                a.mdl = [];
                            }
                            angular.extend(a.mdl, i);
                            a.mdl[a.config.modelLabel] = i[a.config.optionLabel];
                            if (a.events !== undefined) {
                                a.events.onItemSelect(i);
                            }
                        }
                    }
                ]
            }
        });<commit_msg>model fix?<commit_after>"use strict";
angular.module("typeaheadDropdown.tpl", [])
        .run(["$templateCache",
            function (a) {
                a.put("templates/typeaheadDropdown.tpl.html",
                    "
" +
                    //"
Loading options...
" +
                    "
" +
                    "
" +
                    "<input class=form-control placeholder=\"Select or type...\" ng-model=mdl typeahead=\"op[config.optionLabel] for op in options | filter:$viewValue\" typeahead-editable=false typeahead-on-select=\"onSelect($item, $model, $label)\" ng-required=\"required\"> " +
                    "" +
                    "<button class=\"btn btn-default dropdown-toggle\" dropdown-toggle>" +
                    "" +
                    "" +
                    "</button>" +
                    "" +
                    "
" +
                    "
" +
                    "
" +
                    "{{op[config.optionLabel]}}" +
                    "
" +
                    "
" +
                    "
" +
                    "
");
            }
        ]),
    angular.module("apg.typeaheadDropdown", ["typeaheadDropdown.tpl", "ui.bootstrap"])
        .directive("typeaheadDropdown", function() {
            return {
                templateUrl: "templates/typeaheadDropdown.tpl.html",
                scope: { mdl: "=ngModel", options: "=",  config: "=?", events: "=", required: "=?ngRequired" },
                require: "ngModel",
                replace: true,
                link: function($scope, $element, $attrs) {
                    $scope.externalEvents = {
                        onItemSelect: angular.noop
                    };

                    angular.extend($scope.externalEvents, $scope.events || []);
                },

                controller: ["$scope",
                    function (a) {
                        a.config = angular.extend({ modelLabel: "name", optionLabel: "name" }, a.config),

                        a.onSelect = function (i) {
                            if (a.mdl === undefined) {
                                a.mdl = [];
                            }
                            angular.extend(a.mdl, i);
                            a.mdl = i[a.config.optionLabel];
                            if (a.events !== undefined) {
                                a.events.onItemSelect(i);
                            }
                        }
                    }
                ]
            }
        });<|endoftext|>


<commit_before>var express = require('express'),
    router = express.Router(),
    passport = require('../auth'),
    Twitter = require('twitter');

var config = require('../_config');

var client = new Twitter({
  consumer_key: config.twitterConsumerKey,
  consumer_secret: config.twitterConsumerSecret,
  access_token_key: config.twitterAccessTokenKey,
  access_token_secret: config.twitterAccessTokenSecret
});

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

  var params = {screen_name: 'refactoru'};
  client.get('statuses/user_timeline', params, function(error, tweets, response){
    if (!error) {
      res.send(tweets);
    }
  });

});

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

  var params = {screen_name: 'refactoru'};
  client.get('statuses/user_timeline', params, function(error, tweets, response){
    if (!error) {
      var responseArr = [];
      var responseObj = {};
      for (var i = 0; i < tweets.length; i++) {
        responseObj = {};
        responseObj.text = tweets[i].text;
        responseArr.push(responseObj);
      }
      res.render('tweets', {response:responseArr});
    }
  });

});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/');
}

module.exports = router;<commit_msg>add route to send only tweets son<commit_after>var express = require('express'),
    router = express.Router(),
    passport = require('../auth'),
    Twitter = require('twitter');

var config = require('../_config');

var client = new Twitter({
  consumer_key: config.twitterConsumerKey,
  consumer_secret: config.twitterConsumerSecret,
  access_token_key: config.twitterAccessTokenKey,
  access_token_secret: config.twitterAccessTokenSecret
});

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

  var params = {screen_name: 'refactoru'};
  client.get('statuses/user_timeline', params, function(error, tweets, response){
    if (!error) {
      res.send(tweets);
    }
  });

});

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

  var params = {screen_name: 'refactoru'};
  client.get('statuses/user_timeline', params, function(error, tweets, response){
    if (!error) {
      var responseArr = [];
      var responseObj = {};
      for (var i = 0; i < tweets.length; i++) {
        responseObj = {};
        responseObj.text = tweets[i].text;
        responseArr.push(responseObj);
      }
      res.render('tweets', {response:responseArr});
    }
  });

});

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

  var params = {screen_name: 'refactoru'};
  client.get('statuses/user_timeline', params, function(error, tweets, response){
    if (!error) {
      var responseArr = [];
      var responseObj = {};
      for (var i = 0; i < tweets.length; i++) {
        responseObj = {};
        responseObj.text = tweets[i].text;
        responseArr.push(responseObj);
      }
      res.send({response:responseArr, data: req.body});
    }
  });

});

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/');
}

module.exports = router;<|endoftext|>


<commit_before>'use strict';

// Mode
if (window.mode)var mode = window.mode;
else var mode = urlParam('mode');
if (window.urlencodedXML) var urlencodedXML = window.urlencodedXML;
else var urlencodedXML = urlParam('diagramXML');

// Includes
var fs = require('fs');
var $ = require('jquery'),
    BpmnModeler = require('bpmn-js/lib/Modeler'),
    BpmnViewer = require('bpmn-js/lib/Viewer');

var forEach = require('lodash/collection/forEach');
var container = $('#js-drop-zone');
var canvas = $('#js-canvas');

// Reference to the custom Modules
var AofCustomizationModules = require('./../aof-customization/index'), // affects activities
    aofModdleExtention = require('./../aof-customization/moddleExtensions/aof');

// Helper Functions

function openDiagram(renderer, xml) {
    renderer.importXML(xml, function (err) {

        if (err) {
            container
                .removeClass('with-diagram')
                .addClass('with-error');

            container.find('.error pre').text(err.message);

            console.error(err);
        } else {
            container
                .removeClass('with-error')
                .addClass('with-diagram');

            var elementRegistry = renderer.get('elementRegistry');
            var canvasObject = renderer.get('canvas');

            // Mark AppEnsembleApps grey
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:UserTask" && element.businessObjectisAppEnsembleApp == true )//&& element.businessObject.$attrs['aof:realizedBy'] && element.businessObject.$attrs['aof:realizedBy'] != "")
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensembleapp');
                }
            );

            // Mark AppEnsembles
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:Participant" && (element.businessObject.$attrs['aof:isAppEnsemble'] && element.businessObject.$attrs['aof:isAppEnsemble'] == "true") || (element.businessObject.isAppEnsemble == true))
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensemble');
                }
            );

            // Load available Apps for UserTasks
            if(mode!="view") {
                var appAssignerObject = renderer.get('appAssigner');
                appAssignerObject.getOptionEntities();
            }
        }

    });
}

function saveSVG(done) {
    renderer.saveSVG(done);
}

function saveDiagram(done) {
    renderer.saveXML({format: true}, function (err, xml) {
        done(err, xml);
    });
}

function urlParam(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) {
        return null;
    }
    else {
        return results[1] || 0;
    }
}

// Mode and data processing
if (mode == "view") {
    var renderer = new BpmnViewer({container: canvas});
}
else {

    var propertiesPanelModule = require('bpmn-js-properties-panel');
    var propertiesProviderModule = require('bpmn-js-properties-panel/lib/provider/aof');

    var renderer = new BpmnModeler({
        container: canvas,
        additionalModules: [propertiesPanelModule, propertiesProviderModule, AofCustomizationModules],
        moddleExtensions: {aof: aofModdleExtention},
        propertiesPanel: {
            parent: '#js-properties-panel'
        }
    });
}
if (mode == "view" || mode == "edit") {
    var newDiagramXML = decodeURIComponent(urlencodedXML);
}
else {
    var newDiagramXML = fs.readFileSync(__dirname + '/../../resources/newDiagram.bpmn', 'utf-8');
}

// bootstrap diagram functions

$(document).on('ready', function () {
    openDiagram(renderer, newDiagramXML);
    window.onbeforeunload = function () {
        return "Do you really want to leave this page? There might be a loss of unsaved data!"
    }
});

// jQuery references
var downloadSvgLink = $('#js-download-svg');
var saveandCloseLink = $('#js-save-appensemble-and-close');
var saveLink = $('#js-save-appensemble');
var closeLink = $('#close-modeler');

// actions definition
if (mode == "view") {
    saveLink.remove();
    saveandCloseLink.remove();
    downloadSvgLink.remove();
}
else {
    saveLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
');
                    setTimeout(function () {
                        $.when($('.alert-box').fadeOut(500))
                            .done(function () {
                                $('.alert-box').remove();
                            });
                    }, 2000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (jqXHR, status, error) {
                    container.before('
There was a Problem saving the Appensemble×
');
                }
            });
        }
    });

    saveandCloseLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
 Closing Modeler in 3 seconds.×
');
                    window.onbeforeunload = function () {
                    }
                    setTimeout(function () {
                        $('#close-seconds').text("2")
                    }, 1000);
                    setTimeout(function () {
                        $('#close-seconds').text("1")
                    }, 2000);
                    setTimeout(function () {
                        window.location.href = document.referrer
                    }, 3000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (jqXHR, status, error) {
                    container.before('
There was a Problem saving the Appensemble×
');
                }
            });
        }
    });
}

closeLink.click(function () {
    window.location.href = document.referrer;
})

$('.top-bar-section .right a').click(function (e) {
    if (!$(this).is('.active')) {
        e.preventDefault();
        e.stopPropagation();
    }
});

// export helper functions
function setEncoded_dl(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

function setEncoded(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': '/api/actions/app-ensembles/add?data=' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

// Update routine
var _ = require('lodash');

var exportArtifacts = _.debounce(function () {
    saveDiagram(function (err, xml) {
        setEncoded(saveLink, 'diagram.bpmn', err ? null : xml);
    });
    saveDiagram(function (err, xml) {
        setEncoded(saveandCloseLink, 'diagram.bpmn', err ? null : xml);
    });
    saveSVG(function (err, svg) {
        setEncoded_dl(downloadSvgLink, 'diagram.svg', err ? null : svg);
    });
}, 500);

renderer.on('commandStack.changed', exportArtifacts);<commit_msg>Edited AppEnsembleApp-Marking rules<commit_after>'use strict';

// Mode
if (window.mode)var mode = window.mode;
else var mode = urlParam('mode');
if (window.urlencodedXML) var urlencodedXML = window.urlencodedXML;
else var urlencodedXML = urlParam('diagramXML');

// Includes
var fs = require('fs');
var $ = require('jquery'),
    BpmnModeler = require('bpmn-js/lib/Modeler'),
    BpmnViewer = require('bpmn-js/lib/Viewer');

var forEach = require('lodash/collection/forEach');
var container = $('#js-drop-zone');
var canvas = $('#js-canvas');

// Reference to the custom Modules
var AofCustomizationModules = require('./../aof-customization/index'), // affects activities
    aofModdleExtention = require('./../aof-customization/moddleExtensions/aof');

// Helper Functions

function openDiagram(renderer, xml) {
    renderer.importXML(xml, function (err) {

        if (err) {
            container
                .removeClass('with-diagram')
                .addClass('with-error');

            container.find('.error pre').text(err.message);

            console.error(err);
        } else {
            container
                .removeClass('with-error')
                .addClass('with-diagram');

            var elementRegistry = renderer.get('elementRegistry');
            var canvasObject = renderer.get('canvas');

            // Mark AppEnsembleApps grey
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:UserTask" && element.businessObject.isAppEnsembleApp == true )//&& element.businessObject.$attrs['aof:realizedBy'] && element.businessObject.$attrs['aof:realizedBy'] != "")
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensembleapp');
                }
            );

            // Mark AppEnsembles
            forEach(elementRegistry.filter(
                    function (element, gfx) {
                        return (element.type == "bpmn:Participant" && (element.businessObject.$attrs['aof:isAppEnsemble'] && element.businessObject.$attrs['aof:isAppEnsemble'] == "true") || (element.businessObject.isAppEnsemble == true))
                    }),
                function (element) {
                    canvasObject.addMarker(element.id, 'color-appensemble');
                }
            );

            // Load available Apps for UserTasks
            if(mode!="view") {
                var appAssignerObject = renderer.get('appAssigner');
                appAssignerObject.getOptionEntities();
            }
        }

    });
}

function saveSVG(done) {
    renderer.saveSVG(done);
}

function saveDiagram(done) {
    renderer.saveXML({format: true}, function (err, xml) {
        done(err, xml);
    });
}

function urlParam(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) {
        return null;
    }
    else {
        return results[1] || 0;
    }
}

// Mode and data processing
if (mode == "view") {
    var renderer = new BpmnViewer({container: canvas});
}
else {

    var propertiesPanelModule = require('bpmn-js-properties-panel');
    var propertiesProviderModule = require('bpmn-js-properties-panel/lib/provider/aof');

    var renderer = new BpmnModeler({
        container: canvas,
        additionalModules: [propertiesPanelModule, propertiesProviderModule, AofCustomizationModules],
        moddleExtensions: {aof: aofModdleExtention},
        propertiesPanel: {
            parent: '#js-properties-panel'
        }
    });
}
if (mode == "view" || mode == "edit") {
    var newDiagramXML = decodeURIComponent(urlencodedXML);
}
else {
    var newDiagramXML = fs.readFileSync(__dirname + '/../../resources/newDiagram.bpmn', 'utf-8');
}

// bootstrap diagram functions

$(document).on('ready', function () {
    openDiagram(renderer, newDiagramXML);
    window.onbeforeunload = function () {
        return "Do you really want to leave this page? There might be a loss of unsaved data!"
    }
});

// jQuery references
var downloadSvgLink = $('#js-download-svg');
var saveandCloseLink = $('#js-save-appensemble-and-close');
var saveLink = $('#js-save-appensemble');
var closeLink = $('#close-modeler');

// actions definition
if (mode == "view") {
    saveLink.remove();
    saveandCloseLink.remove();
    downloadSvgLink.remove();
}
else {
    saveLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
');
                    setTimeout(function () {
                        $.when($('.alert-box').fadeOut(500))
                            .done(function () {
                                $('.alert-box').remove();
                            });
                    }, 2000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (jqXHR, status, error) {
                    container.before('
There was a Problem saving the Appensemble×
');
                }
            });
        }
    });

    saveandCloseLink.click(function (e) {
        if ($(this).is('.active')) {
            e.preventDefault();
            e.stopPropagation();
            var request = $.ajax($(this).attr('href'), {
                success: function (data, status, jqXHR) {
                    container.before('
' + data + '
 Closing Modeler in 3 seconds.×
');
                    window.onbeforeunload = function () {
                    }
                    setTimeout(function () {
                        $('#close-seconds').text("2")
                    }, 1000);
                    setTimeout(function () {
                        $('#close-seconds').text("1")
                    }, 2000);
                    setTimeout(function () {
                        window.location.href = document.referrer
                    }, 3000);
                },
                method: "GET",
                async: false,
                timeout: 1000,
                error: function (jqXHR, status, error) {
                    container.before('
There was a Problem saving the Appensemble×
');
                }
            });
        }
    });
}

closeLink.click(function () {
    window.location.href = document.referrer;
})

$('.top-bar-section .right a').click(function (e) {
    if (!$(this).is('.active')) {
        e.preventDefault();
        e.stopPropagation();
    }
});

// export helper functions
function setEncoded_dl(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

function setEncoded(link, name, data) {
    var encodedData = encodeURIComponent(data);

    if (data) {
        link.addClass('active').attr({
            'href': '/api/actions/app-ensembles/add?data=' + encodedData,
            'download': name
        });
    } else {
        link.removeClass('active');
    }
}

// Update routine
var _ = require('lodash');

var exportArtifacts = _.debounce(function () {
    saveDiagram(function (err, xml) {
        setEncoded(saveLink, 'diagram.bpmn', err ? null : xml);
    });
    saveDiagram(function (err, xml) {
        setEncoded(saveandCloseLink, 'diagram.bpmn', err ? null : xml);
    });
    saveSVG(function (err, svg) {
        setEncoded_dl(downloadSvgLink, 'diagram.svg', err ? null : svg);
    });
}, 500);

renderer.on('commandStack.changed', exportArtifacts);<|endoftext|>