<commit_before>

(function () {
    var tokenise = function (str) {
        var tokens = []
        ,   re = {
                "float":        /^-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][-+]?[0-9]+)?|[0-9]+[Ee][-+]?[0-9]+)/
            ,   "integer":      /^-?(0([0-7]*|[Xx][0-9A-Fa-f]+)|[1-9][0-9]*)/
            ,   "identifier":   /^[A-Z_a-z][0-9A-Z_a-z]*/
            ,   "string":       /^"[^"]*"/
            ,   "whitespace":   /^[\t\n\r ]+|[\t\n\r ]*((\/\/.*|\/\*(.|\n)*?\*\/)[\t\n\r ]*)+/
            ,   "other":        /^[^\t\n\r 0-9A-Z_a-z]/
            }
        ,   types = []
        ;
        for (var k in re) types.push(k);
        while (str.length > 0) {
            var matched = false;
            for (var i = 0, n = types.length; i < n; i++) {
                var type = types[i];
                str = str.replace(re[type], function (tok) {
                    tokens.push({ type: type, value: tok });
                    matched = true;
                    return "";
                });
                if (matched) break;
            }
            if (matched) continue;
            throw new Error("Token stream not progressing.");
        }
        return tokens;
    };

    var parse = function (tokens) {
        var line = 0;
        tokens = tokens.slice();

        var error = function (str) {
            throw str + ", line " + line;
        };

        var consume = function (type, value) {
            if (!tokens.length || tokens[0].type !== type) return;
            if (typeof value === "undefined" || tokens[0].value === value) return tokens.shift();
        };

        var ws = function () {
            if (!tokens.length) return;
            if (tokens[0].type === "whitespace") {
                var t = tokens.shift();
                t.value.replace(/\n/g, function (m) { line++; return m; });
                return t;
            }
        };

        var all_ws = function () {
            var t = { type: "whitespace", value: "" };
            while (true) {
                var w = ws();
                if (!w) break;
                t.value += w.value;
            }
            if (t.value.length > 0) return t;
        };

        var integer_type = function () {
            var ret = "";
            all_ws();
            if (consume("identifier", "unsigned")) ret = "unsigned ";
            all_ws();
            if (consume("identifier", "short")) return ret + "short";
            if (consume("identifier", "long")) {
                ret += "long";
                all_ws();
                if (consume("identifier", "long")) return ret + " long";
                return ret;
            }
            if (ret) error("Failed to parse integer type");
        };

        var float_type = function () {
            var ret = "";
            all_ws();
            if (consume("identifier", "unrestricted")) ret = "unrestricted ";
            all_ws();
            if (consume("identifier", "float")) return ret + "float";
            if (consume("identifier", "double")) return ret + "double";
            if (ret) error("Failed to parse float type");
        };

        var primitive_type = function () {
            var num_type = integer_type() || float_type();
            if (num_type) return num_type;
            all_ws();
            if (consume("identifier", "boolean")) return "boolean";
            if (consume("identifier", "byte")) return "byte";
            if (consume("identifier", "octet")) return "octet";
        };

        var const_value = function () {
            if (consume("identifier", "true")) return true;
            if (consume("identifier", "false")) return false;
            if (consume("identifier", "null")) return null;
            if (consume("identifier", "Infinity")) return Infinity;
            if (consume("identifier", "NaN")) return NaN;
            var ret = consume("float") || consume("integer");
            if (ret) return 1 * ret.value;
            var tok = consume("other", "-");
            if (tok) {
                if (consume("identifier", "Infinity")) return -Infinity;
                else tokens.unshift(tok);
            }
        };

        var type_suffix = function (obj) {
            while (true) {
                all_ws();
                if (consume("other", "?")) obj.nullable = true;
                else if (consume("other", "[")) {
                    all_ws();
                    consume("other", "]") || error("Unterminated array type");
                    if (!obj.array) obj.array = 1;
                    else obj.array++;
                }
                else return;
            }
        };

        var single_type = function () {
            var prim = primitive_type()
            ,   ret = { sequence: false, nullable: false, array: false, union: false }
            ;
            if (prim) {
                ret.idlType = prim;
            }
            else if (consume("identifier", "sequence")) {
                all_ws();
                if (!consume("other", "<")) {
                    ret.idlType = "sequence";
                }
                else {
                    ret.sequence = true;
                    ret.idlType = type() || error("Error parsing sequence type");
                    all_ws();
                    if (!consume("other", ">")) error("Unterminated sequence");
                    all_ws();
                    if (consume("other", "?")) ret.nullable = true;
                    return ret;
                }
            }
            else {
                var name = consume("identifier");
                if (!name) return;
                ret.idlType = name.value;
            }
            type_suffix(ret);
            return ret;
        };

        var union_type = function () {
            all_ws();
            if (!consume("other", "(")) return;
            var ret = { sequence: false, nullable: false, array: false, union: true, idlType: [] };
            var fst = type() || error("Union type with no content");
            ret.idlType.push(fst);
            while (true) {
                all_ws();
                if (!consume("identifier", "or")) break;
                var typ = type() || error("No type after 'or' in union type");
                ret.idlType.push(typ);
            }
            if (!consume("other", ")")) error("Unterminated union type");
            type_suffix(ret);
            return ret;
        };

        var type = function () {
            return single_type() || union_type();
        };

        var argument = function () {
            var ret = { optional: false, variadic: false };
            ret.extAttrs = extended_attrs();
            all_ws();
            if (consume("identifier", "optional")) {
                ret.optional = true;
                all_ws();
            }
            ret.type = type();
            if (!ret.optional) {
                all_ws();
                if (tokens.length >= 3 &&
                    tokens[0].type === "other" && tokens[0].value === "." &&
                    tokens[1].type === "other" && tokens[1].value === "." &&
                    tokens[2].type === "other" && tokens[2].value === "."
                    ) {
                    tokens.shift();
                    tokens.shift();
                    tokens.shift();
                    ret.variadic = true;
                }
            }
            all_ws();
            var name = consume("identifier") || error("No name in argument");
            ret.name = name.value;
            if (ret.optional) {
                all_ws();
                if (consume("other", "=")) {
                    all_ws();
                    var def = const_value();
                    if (typeof def !== "undefined") {
                        ret["default"] = def;
                    }
                    else {
                        ret["default"] = consume("string") || error("No value for argument default");
                    }
                }
            }
            return ret;
        };

        var argument_list = function () {
            var arg = argument(), ret = [];
            if (!arg) return ret;
            ret.push(arg);
            while (true) {
                all_ws();
                if (!consume("other", ",")) return ret;
                all_ws();
                var nxt = argument() || error("Trailing comma in arguments list");
                ret.push(nxt);
            }
        };

        var simple_extended_attr = function () {
            all_ws();
            var name = consume("identifier");
            if (!name) return;
            var ret = {
                name: name.value
            ,   "arguments": null
            };
            all_ws();
            var eq = consume("other", "=");
            if (eq) {
                all_ws();
                ret.rhs = consume("identifier");
                if (!ret.rhs) return error("No right hand side to extended attribute assignment");
            }
            all_ws();
            if (consume("other", "(")) {
                ret["arguments"] = argument_list();
                all_ws();
                consume("other", ")") || error("Unclosed argument in extended attribute");
            }
            return ret;
        };

        // Note: we parse something simpler than the official syntax. It's all that ever
        // seems to be used
        var extended_attrs = function () {
            var eas = [];
            all_ws();
            if (!consume("other", "[")) return eas;
            eas[0] = simple_extended_attr() || error("Extended attribute with not content");
            all_ws();
            while (consume("other", ",")) {
                all_ws();
                eas.push(simple_extended_attr() || error("Trailing comma in extended attribute"));
                all_ws();
            }
            consume("other", "]") || error("No end of extended attribute");
            return eas;
        };

        var callback = function () {

        };

        var interface_ = function () {

        };

        var partial = function () {

        };

        var dictionary = function () {

        };

        var exception = function () {

        };

        var enum_ = function () {
            all_ws();
            if (!consume("identifier", "enum")) return;
            all_ws();
            var name = consume("identifier") || error("No name for enum");
            var ret = {
                type:   "enum"
            ,   name:   name.value
            ,   values: []
            };
            all_ws();
            consume("other", "{") || error("No curly for enum");
            var saw_comma = false;
            while (true) {
                all_ws();
                if (consume("other", "}")) {
                    all_ws();
                    if (saw_comma) error("Trailing comma in enum");
                    consume("other", ";") || error("No semicolon after enum");
                    return ret;
                }
                var val = consume("string") || error("Unexpected value in enum");
                ret.values.push(val.value.replace(/"/g, ""));
                all_ws();
                if (consume("other", ",")) {
                    all_ws();
                    saw_comma = true;
                }
                else {
                    saw_comma = false;
                }
            }
        };

        var typedef = function () {
            all_ws();
            if (!consume("identifier", "typedef")) return;
            var ret = {
                type:   "typedef"
            };
            all_ws();
            ret.extAttrs = extended_attrs();
            all_ws();
            ret.idlType = type() || error("No type in typedef");
            all_ws();
            var name = consume("identifier") || error("No name in typedef");
            ret.name = name.value;
            all_ws();
            consume("other", ";") || error("Unterminated typedef");
            return ret;
        };

        var implements_ = function () {
            all_ws();
            var target = consume("identifier");
            if (!target) return;
            var w = all_ws();
            if (consume("identifier", "implements")) {
                var ret = {
                    type:   "implements"
                ,   target: target.value
                };
                all_ws();
                var imp = consume("identifier") || error("Incomplete implements statement");
                ret["implements"] = imp.value;
                all_ws();
                consume("other", ";") || error("No terminating ; for implements statement");
                return ret;
            }
            else {
                // rollback
                tokens.unshift(w);
                tokens.unshift(target);
            }
        };

        var definition = function () {
            return  callback()      ||
                    interface_()    ||
                    partial()       ||
                    dictionary()    ||
                    exception()     ||
                    enum_()         ||
                    typedef()       ||
                    implements_()
                    ;
        };

        var definitions = function () {
            if (!tokens.length) return [];
            var defs = [];
            while (true) {
                var def = definition();
                if (!def) break;
                defs.push(def);
            }
            return defs;
        };

        return definitions();
    };

    var obj = {
        parse:  function (str) {
            var tokens = tokenise(str);
            console.log(tokens);
            return parse(tokens);
        }
    };
    if (typeof module !== "undefined" && module.exports) {
        module.exports = obj;
    }
    else {
        window.WebIDL2 = obj;
    }
}());
<commit_msg>progress on exceptions, const<commit_after>

(function () {
    var tokenise = function (str) {
        var tokens = []
        ,   re = {
                "float":        /^-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][-+]?[0-9]+)?|[0-9]+[Ee][-+]?[0-9]+)/
            ,   "integer":      /^-?(0([0-7]*|[Xx][0-9A-Fa-f]+)|[1-9][0-9]*)/
            ,   "identifier":   /^[A-Z_a-z][0-9A-Z_a-z]*/
            ,   "string":       /^"[^"]*"/
            ,   "whitespace":   /^[\t\n\r ]+|[\t\n\r ]*((\/\/.*|\/\*(.|\n)*?\*\/)[\t\n\r ]*)+/
            ,   "other":        /^[^\t\n\r 0-9A-Z_a-z]/
            }
        ,   types = []
        ;
        for (var k in re) types.push(k);
        while (str.length > 0) {
            var matched = false;
            for (var i = 0, n = types.length; i < n; i++) {
                var type = types[i];
                str = str.replace(re[type], function (tok) {
                    tokens.push({ type: type, value: tok });
                    matched = true;
                    return "";
                });
                if (matched) break;
            }
            if (matched) continue;
            throw new Error("Token stream not progressing.");
        }
        return tokens;
    };

    var parse = function (tokens) {
        var line = 0;
        tokens = tokens.slice();

        var error = function (str) {
            throw str + ", line " + line;
        };

        var consume = function (type, value) {
            if (!tokens.length || tokens[0].type !== type) return;
            if (typeof value === "undefined" || tokens[0].value === value) return tokens.shift();
        };

        var ws = function () {
            if (!tokens.length) return;
            if (tokens[0].type === "whitespace") {
                var t = tokens.shift();
                t.value.replace(/\n/g, function (m) { line++; return m; });
                return t;
            }
        };

        var all_ws = function () {
            var t = { type: "whitespace", value: "" };
            while (true) {
                var w = ws();
                if (!w) break;
                t.value += w.value;
            }
            if (t.value.length > 0) return t;
        };

        var integer_type = function () {
            var ret = "";
            all_ws();
            if (consume("identifier", "unsigned")) ret = "unsigned ";
            all_ws();
            if (consume("identifier", "short")) return ret + "short";
            if (consume("identifier", "long")) {
                ret += "long";
                all_ws();
                if (consume("identifier", "long")) return ret + " long";
                return ret;
            }
            if (ret) error("Failed to parse integer type");
        };

        var float_type = function () {
            var ret = "";
            all_ws();
            if (consume("identifier", "unrestricted")) ret = "unrestricted ";
            all_ws();
            if (consume("identifier", "float")) return ret + "float";
            if (consume("identifier", "double")) return ret + "double";
            if (ret) error("Failed to parse float type");
        };

        var primitive_type = function () {
            var num_type = integer_type() || float_type();
            if (num_type) return num_type;
            all_ws();
            if (consume("identifier", "boolean")) return "boolean";
            if (consume("identifier", "byte")) return "byte";
            if (consume("identifier", "octet")) return "octet";
        };

        var const_value = function () {
            if (consume("identifier", "true")) return true;
            if (consume("identifier", "false")) return false;
            if (consume("identifier", "null")) return null;
            if (consume("identifier", "Infinity")) return Infinity;
            if (consume("identifier", "NaN")) return NaN;
            var ret = consume("float") || consume("integer");
            if (ret) return 1 * ret.value;
            var tok = consume("other", "-");
            if (tok) {
                if (consume("identifier", "Infinity")) return -Infinity;
                else tokens.unshift(tok);
            }
        };

        var type_suffix = function (obj) {
            while (true) {
                all_ws();
                if (consume("other", "?")) obj.nullable = true;
                else if (consume("other", "[")) {
                    all_ws();
                    consume("other", "]") || error("Unterminated array type");
                    if (!obj.array) obj.array = 1;
                    else obj.array++;
                }
                else return;
            }
        };

        var single_type = function () {
            var prim = primitive_type()
            ,   ret = { sequence: false, nullable: false, array: false, union: false }
            ;
            if (prim) {
                ret.idlType = prim;
            }
            else if (consume("identifier", "sequence")) {
                all_ws();
                if (!consume("other", "<")) {
                    ret.idlType = "sequence";
                }
                else {
                    ret.sequence = true;
                    ret.idlType = type() || error("Error parsing sequence type");
                    all_ws();
                    if (!consume("other", ">")) error("Unterminated sequence");
                    all_ws();
                    if (consume("other", "?")) ret.nullable = true;
                    return ret;
                }
            }
            else {
                var name = consume("identifier");
                if (!name) return;
                ret.idlType = name.value;
            }
            type_suffix(ret);
            return ret;
        };

        var union_type = function () {
            all_ws();
            if (!consume("other", "(")) return;
            var ret = { sequence: false, nullable: false, array: false, union: true, idlType: [] };
            var fst = type() || error("Union type with no content");
            ret.idlType.push(fst);
            while (true) {
                all_ws();
                if (!consume("identifier", "or")) break;
                var typ = type() || error("No type after 'or' in union type");
                ret.idlType.push(typ);
            }
            if (!consume("other", ")")) error("Unterminated union type");
            type_suffix(ret);
            return ret;
        };

        var type = function () {
            return single_type() || union_type();
        };

        var argument = function () {
            var ret = { optional: false, variadic: false };
            ret.extAttrs = extended_attrs();
            all_ws();
            if (consume("identifier", "optional")) {
                ret.optional = true;
                all_ws();
            }
            ret.type = type();
            if (!ret.optional) {
                all_ws();
                if (tokens.length >= 3 &&
                    tokens[0].type === "other" && tokens[0].value === "." &&
                    tokens[1].type === "other" && tokens[1].value === "." &&
                    tokens[2].type === "other" && tokens[2].value === "."
                    ) {
                    tokens.shift();
                    tokens.shift();
                    tokens.shift();
                    ret.variadic = true;
                }
            }
            all_ws();
            var name = consume("identifier") || error("No name in argument");
            ret.name = name.value;
            if (ret.optional) {
                all_ws();
                if (consume("other", "=")) {
                    all_ws();
                    var def = const_value();
                    if (typeof def !== "undefined") {
                        ret["default"] = def;
                    }
                    else {
                        ret["default"] = consume("string") || error("No value for argument default");
                    }
                }
            }
            return ret;
        };

        var argument_list = function () {
            var arg = argument(), ret = [];
            if (!arg) return ret;
            ret.push(arg);
            while (true) {
                all_ws();
                if (!consume("other", ",")) return ret;
                all_ws();
                var nxt = argument() || error("Trailing comma in arguments list");
                ret.push(nxt);
            }
        };

        var simple_extended_attr = function () {
            all_ws();
            var name = consume("identifier");
            if (!name) return;
            var ret = {
                name: name.value
            ,   "arguments": null
            };
            all_ws();
            var eq = consume("other", "=");
            if (eq) {
                all_ws();
                ret.rhs = consume("identifier");
                if (!ret.rhs) return error("No right hand side to extended attribute assignment");
            }
            all_ws();
            if (consume("other", "(")) {
                ret["arguments"] = argument_list();
                all_ws();
                consume("other", ")") || error("Unclosed argument in extended attribute");
            }
            return ret;
        };

        // Note: we parse something simpler than the official syntax. It's all that ever
        // seems to be used
        var extended_attrs = function () {
            var eas = [];
            all_ws();
            if (!consume("other", "[")) return eas;
            eas[0] = simple_extended_attr() || error("Extended attribute with not content");
            all_ws();
            while (consume("other", ",")) {
                all_ws();
                eas.push(simple_extended_attr() || error("Trailing comma in extended attribute"));
                all_ws();
            }
            consume("other", "]") || error("No end of extended attribute");
            return eas;
        };

        var const_ = function () {
            all_ws();
            if (!consume("identifier", "const")) return;
            // XXX
        };

        var callback = function () {

        };

        var interface_ = function () {

        };

        var partial = function () {

        };

        var dictionary = function () {

        };

        var exception = function () {
            all_ws();
            if (!consume("identifier", "exception")) return;
            all_ws();
            var name = consume("identifier") || error("No name for exception");
            var ret = {
                type:   "exception"
            ,   name:   name.value
            ,   inheritance: null
            ,   members:    []
            };
            all_ws();
            if (consume("other", ":")) {
                all_ws();
                ret.inheritance = consume("identifier") || error ("No type in exception inheritance");
                all_ws();
            }
            consume("other", "{") || error("Bodyless exception");
            while (true) {
                all_ws();
                if (consume("other", "}")) {
                    all_ws();
                    consume("other", ";") || error("Missing semicolon after exception");
                    return ret;
                }
                var ea = extended_attrs();
                all_ws();
                var cnt = const_();
                if (cnt) {
                    cnt.extAttrs = ea;
                    ret.members.push(cnt);
                }
                else {
                    var typ = type();
                    all_ws();
                    var name = consume("identifier");
                    all_ws();
                    if (!typ || !name || !consume("other", ";")) error("Unknown member in exception body");
                    ret.members.push({
                        type:       "field"
                    ,   name:       name.value
                    ,   idlType:    typ
                    ,   extAttrs:   ea
                    });
                }
            }
        };
        // {
        //   "type": "exception",
        //   "name": "E",
        //   "members": [
        //     {
        //       "type": "field",
        //       "extAttrs": "",
        //       "idlType": {
        //         "sequence": false,
        //         "array": false,
        //         "idlType": "unsigned short",
        //         "nullable": false
        //       },
        //       "name": "code"
        //     }
        //   ],
        //   "extAttrs": ""
        // },

        var enum_ = function () {
            all_ws();
            if (!consume("identifier", "enum")) return;
            all_ws();
            var name = consume("identifier") || error("No name for enum");
            var ret = {
                type:   "enum"
            ,   name:   name.value
            ,   values: []
            };
            all_ws();
            consume("other", "{") || error("No curly for enum");
            var saw_comma = false;
            while (true) {
                all_ws();
                if (consume("other", "}")) {
                    all_ws();
                    if (saw_comma) error("Trailing comma in enum");
                    consume("other", ";") || error("No semicolon after enum");
                    return ret;
                }
                var val = consume("string") || error("Unexpected value in enum");
                ret.values.push(val.value.replace(/"/g, ""));
                all_ws();
                if (consume("other", ",")) {
                    all_ws();
                    saw_comma = true;
                }
                else {
                    saw_comma = false;
                }
            }
        };

        var typedef = function () {
            all_ws();
            if (!consume("identifier", "typedef")) return;
            var ret = {
                type:   "typedef"
            };
            all_ws();
            ret.extAttrs = extended_attrs();
            all_ws();
            ret.idlType = type() || error("No type in typedef");
            all_ws();
            var name = consume("identifier") || error("No name in typedef");
            ret.name = name.value;
            all_ws();
            consume("other", ";") || error("Unterminated typedef");
            return ret;
        };

        var implements_ = function () {
            all_ws();
            var target = consume("identifier");
            if (!target) return;
            var w = all_ws();
            if (consume("identifier", "implements")) {
                var ret = {
                    type:   "implements"
                ,   target: target.value
                };
                all_ws();
                var imp = consume("identifier") || error("Incomplete implements statement");
                ret["implements"] = imp.value;
                all_ws();
                consume("other", ";") || error("No terminating ; for implements statement");
                return ret;
            }
            else {
                // rollback
                tokens.unshift(w);
                tokens.unshift(target);
            }
        };

        var definition = function () {
            return  callback()      ||
                    interface_()    ||
                    partial()       ||
                    dictionary()    ||
                    exception()     ||
                    enum_()         ||
                    typedef()       ||
                    implements_()
                    ;
        };

        var definitions = function () {
            if (!tokens.length) return [];
            var defs = [];
            while (true) {
                var ea = extended_attrs()
                ,   def = definition();
                if (!def) {
                    if (ea) error("Stray extended attributes");
                    break;
                }
                def.extAttrs = ea;
                defs.push(def);
            }
            return defs;
        };

        return definitions();
    };

    var obj = {
        parse:  function (str) {
            var tokens = tokenise(str);
            console.log(tokens);
            return parse(tokens);
        }
    };
    if (typeof module !== "undefined" && module.exports) {
        module.exports = obj;
    }
    else {
        window.WebIDL2 = obj;
    }
}());
<|endoftext|>


<commit_before>// Takes care of updating the picture to cloudinary after the item has been saved

var Q = require('q');
var request = require('request');
var crypto = require('crypto');

function cloudPost(public_id, photoUrl, cloudinaryInfo) {

  return Q.Promise(function(resolve, reject, notify) {

    var unixTimeInSeconds = Math.floor(Date.now() / 1000);
    var apikey = cloudinaryInfo.apikey
    var secret = cloudinaryInfo.secret

    // These are the values tha need to be signed:
    // callback, eager, format, public_id, tags, timestamp, transformation, type
    // Anything else should be added later, after calculating the signature.
    // http://cloudinary.com/documentation/upload_images#request_authentication

    var params = {
      timestamp: unixTimeInSeconds,
      format: "jpg",
      transformation: "w_200,h_200,c_thumb,g_face",
      public_id: public_id
    }

    var signItems = []
    Object.keys(params).sort().forEach(function(key) {
      signItems.push(key + '=' + params[key])
    })
    var signString = signItems.join('&') + secret;
    var signature = crypto.createHash('sha1').update(signString).digest('hex')

    //not signing params:
    params.file = photoUrl;
    params.signature = signature;
    params.api_key = apikey;

    var reqOpts = {
      method: "POST",
      url: cloudinaryInfo.uploadurl,
      json: true,
      body: params
    };

    request(reqOpts, function(err, response, body) {
      if (err) {
        reject({
          err: err,
          response: response,
          body: body
        })
      } else {
        if (body.error) {
          reject({
            err: body.error,
            body: body
          })
        } else {
          resolve(body)
        }
      }
    })

  });

}

function createCloudinaryImageForPerson(person, popitInfo, cloudinaryInfo) {
  return Q.Promise(function(resolve, reject, notify) {
    var public_id = popitInfo.instanceName + "/" + person.id;
    cloudPost(public_id, person.image, cloudinaryInfo)
      .then(function(result) {

        person.image_original = person.image;
        person.image = result.secure_url;
        delete person.images;

        updatePerson(person, popitInfo)
          .then(function(result) {
            resolve(result)
          })
          .catch(function(err) {
            console.log("error updating person", person, err)
            reject({
              message: "error updating person",
              person: person,
              err: err
            });
          })

      })
      .catch(function(err) {
        console.log("error creating cloudinary", person, err)
        reject({
          message: "error creating cloudinary",
          person: person,
          err: err
        });
      });
  });
}

function updatePerson(person, popitInfo) {

  return Q.promise(function(resolve, reject, notify) {

    var url = "https://" + popitInfo.instanceName + ".popit.mysociety.org/api/v0.1/persons/" + person.id;

    var options = {
      url: url,
      method: 'PUT',
      body: person,
      json: true,
      headers: {
        'Apikey': popitInfo.apikey
      }
    }

    request(options, function(err, httpResponse, body) {
      if (err) {
        console.log(err)
        reject(err);
      } else {
        resolve(body);
      }
    })

  });
}

function getPersonFromPopit(personId, popitInfo){
	return Q.promise(function(resolve, reject, notify) {

	    var url = "https://" + popitInfo.instanceName + ".popit.mysociety.org/api/v0.1/persons/" + personId + "?embed=";

	    var options = {
	      url: url,
	      method: 'GET',
	      headers: {
	        'Apikey': popitInfo.apikey
	      }
	    }

	    request(options, function(err, httpResponse, body) {
	      if (err) {
	        console.log(err)
	        reject(err);
	      } else {
	        resolve(JSON.parse(body).result);
	      }
	    })

	});
}

function updateCloudinaryImage(personId, popitInfo, cloudinaryInfo){
	// popitInfo: { instanceName : '' , apikey : '' }
	// cloudinaryInfo: { apikey : '' , uploadurl : '' , secret }

	var cloudRE = /^(?:http\:|https\:|)\/\/res\.cloudinary\.com/

	getPersonFromPopit(personId, popitInfo).then(function(person){
		if (person.image && !cloudRE.test(person.image)) {
			createCloudinaryImageForPerson(person, popitInfo, cloudinaryInfo).then(function(result){
				//
			}).catch(function(err){
				console.log('error updating picture')
			})
		}	})
	.catch(function(err){
		console.log("ERROR", err)
	})

}

module.exports = {
	updateCloudinaryImage: updateCloudinaryImage
};<commit_msg>Fix dates validations when updating person.<commit_after>// Takes care of updating the picture to cloudinary after the item has been saved

var Q = require('q');
var request = require('request');
var crypto = require('crypto');

function cloudPost(public_id, photoUrl, cloudinaryInfo) {

  return Q.Promise(function(resolve, reject, notify) {

    var unixTimeInSeconds = Math.floor(Date.now() / 1000);
    var apikey = cloudinaryInfo.apikey
    var secret = cloudinaryInfo.secret

    // These are the values tha need to be signed:
    // callback, eager, format, public_id, tags, timestamp, transformation, type
    // Anything else should be added later, after calculating the signature.
    // http://cloudinary.com/documentation/upload_images#request_authentication

    var params = {
      timestamp: unixTimeInSeconds,
      format: "jpg",
      transformation: "w_200,h_200,c_thumb,g_face",
      public_id: public_id
    }

    var signItems = []
    Object.keys(params).sort().forEach(function(key) {
      signItems.push(key + '=' + params[key])
    })
    var signString = signItems.join('&') + secret;
    var signature = crypto.createHash('sha1').update(signString).digest('hex')

    //not signing params:
    params.file = photoUrl;
    params.signature = signature;
    params.api_key = apikey;

    var reqOpts = {
      method: "POST",
      url: cloudinaryInfo.uploadurl,
      json: true,
      body: params
    };

    request(reqOpts, function(err, response, body) {
      if (err) {
        reject({
          err: err,
          response: response,
          body: body
        })
      } else {
        if (body.error) {
          reject({
            err: body.error,
            body: body
          })
        } else {
          resolve(body)
        }
      }
    })

  });

}

function createCloudinaryImageForPerson(person, popitInfo, cloudinaryInfo) {
  return Q.Promise(function(resolve, reject, notify) {
    var public_id = popitInfo.instanceName + "/" + person.id;
    cloudPost(public_id, person.image, cloudinaryInfo)
      .then(function(result) {

        person.image_original = person.image;
        person.image = result.secure_url;
        delete person.images;

        updatePerson(person, popitInfo)
          .then(function(result) {
            resolve(result)
          })
          .catch(function(err) {
            console.log("error updating person", person, err)
            reject({
              message: "error updating person",
              person: person,
              err: err
            });
          })

      })
      .catch(function(err) {
        console.log("error creating cloudinary", person, err)
        reject({
          message: "error creating cloudinary",
          person: person,
          err: err
        });
      });
  });
}

function updatePerson(person, popitInfo) {

  return Q.promise(function(resolve, reject, notify) {

    var url = "https://" + popitInfo.instanceName + ".popit.mysociety.org/api/v0.1/persons/" + person.id;
    var dateRE = /^[0-9]{4}(-[0-9]{2}){0,2}$/;

    if( typeof person.birth_date !== 'undefined' && !dateRE.test(person.birth_date)){
    	delete person.birth_date
    }

    if( typeof person.death_date !== 'undefined' && !dateRE.test(person.death_date)){
    	delete person.death_date
    }

    var options = {
      url: url,
      method: 'PUT',
      body: person,
      json: true,
      headers: {
        'Apikey': popitInfo.apikey
      }
    }

    request(options, function(err, httpResponse, body) {
      if (err) {
        console.log(err)
        reject(err);
      } else {
        resolve(body);
      }
    })

  });
}

function getPersonFromPopit(personId, popitInfo){
	return Q.promise(function(resolve, reject, notify) {

	    var url = "https://" + popitInfo.instanceName + ".popit.mysociety.org/api/v0.1/persons/" + personId + "?embed=";

	    var options = {
	      url: url,
	      method: 'GET',
	      headers: {
	        'Apikey': popitInfo.apikey
	      }
	    }

	    request(options, function(err, httpResponse, body) {
	      if (err) {
	        console.log(err)
	        reject(err);
	      } else {
	        resolve(JSON.parse(body).result);
	      }
	    })

	});
}

function updateCloudinaryImage(personId, popitInfo, cloudinaryInfo){
	// popitInfo: { instanceName : '' , apikey : '' }
	// cloudinaryInfo: { apikey : '' , uploadurl : '' , secret }

	var cloudRE = /^(?:http\:|https\:|)\/\/res\.cloudinary\.com/

	getPersonFromPopit(personId, popitInfo).then(function(person){
		if (person.image && !cloudRE.test(person.image)) {
			createCloudinaryImageForPerson(person, popitInfo, cloudinaryInfo).then(function(result){
				console.log("IMAGE UPLOADED");
				console.log(result);
				//updatePerson(person, popitInfo)
			}).catch(function(err){
				console.log('error updating picture')
			})
		}	})
	.catch(function(err){
		console.log("ERROR", err)
	})

}

module.exports = {
	updateCloudinaryImage: updateCloudinaryImage
};<|endoftext|>


<commit_before>import DS from 'ember-data';
import Ember from 'ember';

let Statement = DS.Model.extend({
    steps: DS.hasMany('step', {async: true}),

    //Data types
    identityData: DS.attr('boolean', {default: false}),
    locationData: DS.attr('boolean', {default: false}),
    userBehaviourData: DS.attr('boolean', {default: false}),
    computerNetworkData: DS.attr('boolean', {default: false}),
    financialData: DS.attr('boolean', {default: false}),
    otherData: DS.attr('boolean', {default: false}),
    otherDataInfo: DS.attr('string'),
    noData: DS.attr('boolean', {default: false}),

    //Data Sources
    userDataSource: DS.attr('boolean', {default: false}),
    publicDataSource: DS.attr('boolean', {default: false}),
    thirdPartyDataSource: DS.attr('boolean', {default: false}),
    otherDataSource: DS.attr('boolean'),
    otherDataSourceInfo: DS.attr('string'),

    //why
    extraReasons: Ember.A(),
    onlyTheseReasons: DS.attr('boolean', {default: false}),

    //Sharing
    sharingParties: Ember.A(),

});

Statement.reopenClass({
  FIXTURES: [{
    id: 1,
    businessName: 'Spacely Sprockets'
  }]
});

export default Statement;
<commit_msg>extra optional info added to statement model<commit_after>import DS from 'ember-data';
import Ember from 'ember';

let Statement = DS.Model.extend({
    steps: DS.hasMany('step', {async: true}),

    //Data types
    identityData: DS.attr('boolean', {default: false}),
    locationData: DS.attr('boolean', {default: false}),
    userBehaviourData: DS.attr('boolean', {default: false}),
    computerNetworkData: DS.attr('boolean', {default: false}),
    financialData: DS.attr('boolean', {default: false}),
    otherData: DS.attr('boolean', {default: false}),
    otherDataInfo: DS.attr('string'),
    noData: DS.attr('boolean', {default: false}),

    //Data Sources
    userDataSource: DS.attr('boolean', {default: false}),
    publicDataSource: DS.attr('boolean', {default: false}),
    thirdPartyDataSource: DS.attr('boolean', {default: false}),
    otherDataSource: DS.attr('boolean'),
    otherDataSourceInfo: DS.attr('string'),

    //why
    extraReasons: Ember.A(),
    onlyTheseReasons: DS.attr('boolean', {default: false}),

    //Sharing
    sharingParties: Ember.A(),

    //Optional Info
    extraOptionalInfo: Ember.A(),

});

Statement.reopenClass({
  FIXTURES: [{
    id: 1,
    businessName: 'Spacely Sprockets'
  }]
});

export default Statement;
<|endoftext|>


<commit_before>export default class Matrix4 {

    constructor (array = new Float32Array([1,0,0,0,
        0,1,0,0,
        0,0,1,0,
        0,0,0,1])) {
        this.setMatrix(array);
    }

    setMatrix (array) {
        this.raw = array;
        this.rawCol1 = [this.raw[0], this.raw[4], this.raw[8], this.raw[12]];
        this.rawCol2 = [this.raw[1], this.raw[5], this.raw[9], this.raw[13]];
        this.rawCol3 = [this.raw[2], this.raw[6], this.raw[10], this.raw[14]];
        this.rawCol4 = [this.raw[3], this.raw[7], this.raw[11], this.raw[15]];
        this.rawRow1 = [this.raw[0], this.raw[1], this.raw[2], this.raw[3]];
        this.rawRow2 = [this.raw[4], this.raw[5], this.raw[6], this.raw[7]];
        this.rawRow3 = [this.raw[8], this.raw[9], this.raw[10], this.raw[11]];
        this.rawRow4 = [this.raw[12], this.raw[13], this.raw[14], this.raw[15]];
    }

    static dot (a,b) {
        var dots = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
        return dots;
    }

    static multiply(a,b, outputMatrix = new Matrix4()) {
        let matrix = new Float32Array(16);
        //let matrix = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
        matrix[0] = Matrix4.dot(a.column1, b.row1);
        matrix[1] = Matrix4.dot(a.column2, b.row1);
        matrix[2] = Matrix4.dot(a.column3, b.row1);
        matrix[3] = Matrix4.dot(a.column4, b.row1);

        matrix[4] = Matrix4.dot(a.column1, b.row2);
        matrix[5] = Matrix4.dot(a.column2, b.row2);
        matrix[6] = Matrix4.dot(a.column3, b.row2);
        matrix[7] = Matrix4.dot(a.column4, b.row2);

        matrix[8] = Matrix4.dot(a.column1, b.row3);
        matrix[9] = Matrix4.dot(a.column2, b.row3);
        matrix[10] = Matrix4.dot(a.column3, b.row3);
        matrix[11] = Matrix4.dot(a.column4, b.row3);

        matrix[12] = Matrix4.dot(a.column1, b.row4);
        matrix[13] = Matrix4.dot(a.column2, b.row4);
        matrix[14] = Matrix4.dot(a.column3, b.row4);
        matrix[15] = Matrix4.dot(a.column4, b.row4);
        outputMatrix.setMatrix(matrix);
        return outputMatrix;
    }

    multiply(matrix) {
        Matrix4.multiply(this, matrix, this);
    }

    get column1 () {
        return this.rawCol1;
    }
    get column2 () {
        return this.rawCol2;
    }
    get column3 () {
        return this.rawCol3;
    }
    get column4 () {
        return this.rawCol4;
    }
    get row1 () {
        return this.rawRow1;
    }
    get row2 () {
        return this.rawRow2;
    }
    get row3 () {
        return this.rawRow3;
    }
    get row4 () {
        return this.rawRow4;
    }
}
<commit_msg>fastest matrix multiply I can do with this configuration<commit_after>export default class Matrix4 {

    constructor (array = new Float32Array([1,0,0,0,
        0,1,0,0,
        0,0,1,0,
        0,0,0,1])) {
        this.setMatrix(array);
    }

    setMatrix (array) {
        this.raw = array;
    }

    static dot (c1, c2, c3, c4, r1, r2, r3, r4) {
        return c1 * r1 + c2 * r2 + c3 * r3 + c4 * r4;
    }

    transpose () {
        var row1 = [this.raw[0], this.raw[1], this.raw[2], this.raw[3]];
        var row2 = [this.raw[4], this.raw[5], this.raw[6], this.raw[7]];
        var row3 = [this.raw[8], this.raw[9], this.raw[10], this.raw[11]];
        var row4 = [this.raw[12], this.raw[13], this.raw[14], this.raw[15]];

        this.raw[0]  = row1[0];
        this.raw[4]  = row1[1];
        this.raw[8]  = row1[2];
        this.raw[12] = row1[3];

        this.raw[1]  = row2[0];
        this.raw[5]  = row2[1];
        this.raw[9]  = row2[2];
        this.raw[13] = row2[3];

        this.raw[2]  = row3[0];
        this.raw[6]  = row3[1];
        this.raw[10] = row3[2];
        this.raw[14] = row3[3];

        this.raw[3]  = row4[0];
        this.raw[7]  = row4[1];
        this.raw[11] = row4[2];
        this.raw[15] = row4[3];

    }

    static multiply(a,b, outputMatrix = new Matrix4()) {
        let matrix = new Float32Array(16);
        //let matrix = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
        matrix[0] = Matrix4.dot(a.raw[0], a.raw[4], a.raw[8], a.raw[12], b.raw[0], b.raw[1], b.raw[2], b.raw[3]);
        matrix[1] = Matrix4.dot(a.raw[1], a.raw[5], a.raw[9], a.raw[13], b.raw[0], b.raw[1], b.raw[2], b.raw[3]);
        matrix[2] = Matrix4.dot(a.raw[2], a.raw[6], a.raw[10], a.raw[14], b.raw[0], b.raw[1], b.raw[2], b.raw[3]);
        matrix[3] = Matrix4.dot(a.raw[3], a.raw[7], a.raw[11], a.raw[15], b.raw[0], b.raw[1], b.raw[2], b.raw[3]);

        matrix[4] = Matrix4.dot(a.raw[0], a.raw[4], a.raw[8], a.raw[12], b.raw[4], b.raw[5], b.raw[6], b.raw[7]);
        matrix[5] = Matrix4.dot(a.raw[1], a.raw[5], a.raw[9], a.raw[13], b.raw[4], b.raw[5], b.raw[6], b.raw[7]);
        matrix[6] = Matrix4.dot(a.raw[2], a.raw[6], a.raw[10], a.raw[14], b.raw[4], b.raw[5], b.raw[6], b.raw[7]);
        matrix[7] = Matrix4.dot(a.raw[3], a.raw[7], a.raw[11], a.raw[15], b.raw[4], b.raw[5], b.raw[6], b.raw[7]);

        matrix[8] = Matrix4.dot(a.raw[0], a.raw[4], a.raw[8], a.raw[12], b.raw[8], b.raw[9], b.raw[10], b.raw[11]);
        matrix[9] = Matrix4.dot(a.raw[1], a.raw[5], a.raw[9], a.raw[13], b.raw[8], b.raw[9], b.raw[10], b.raw[11]);
        matrix[10] = Matrix4.dot(a.raw[2], a.raw[6], a.raw[10], a.raw[14], b.raw[8], b.raw[9], b.raw[10], b.raw[11]);
        matrix[11] = Matrix4.dot(a.raw[3], a.raw[7], a.raw[11], a.raw[15], b.raw[8], b.raw[9], b.raw[10], b.raw[11]);

        matrix[12] = Matrix4.dot(a.raw[0], a.raw[4], a.raw[8], a.raw[12], b.raw[12], b.raw[13], b.raw[14], b.raw[15]);
        matrix[13] = Matrix4.dot(a.raw[1], a.raw[5], a.raw[9], a.raw[13], b.raw[12], b.raw[13], b.raw[14], b.raw[15]);
        matrix[14] = Matrix4.dot(a.raw[2], a.raw[6], a.raw[10], a.raw[14], b.raw[12], b.raw[13], b.raw[14], b.raw[15]);
        matrix[15] = Matrix4.dot(a.raw[3], a.raw[7], a.raw[11], a.raw[15], b.raw[12], b.raw[13], b.raw[14], b.raw[15]);
        //console.log(outputMatrix);
        outputMatrix.setMatrix(matrix);
        return outputMatrix;
    }

    multiply(matrix) {
        Matrix4.multiply(this, matrix, this);
    }

}
<|endoftext|>


<commit_before>// import required modules
var app_detect		= require('./neoip_app_detect');
var url_builder_oload_t	= require('./url_builder_oload_t');

var verbose	= 1;
var webpeer	= {};

/**
 * probe webpeer and notify the callback once completed
 *
 * @param completed_cb {function} callback notified on completion completed(avail){}
*/
webpeer.ready	= function(completed_cb){
	// discover neoip-webpeer
	app_detect.webpeer_probe({
		completed_cb	: function(status){
			if( status == "toinstall" )	completed_cb(false);
			else if( status == "toupgrade")	completed_cb(true);
			else if( status == "installed")	completed_cb(true);
			else console.assert(false);
		}
	})
};

/**
 * @returns {boolean} true if webpeer is available, false otherwise
*/
webpeer.avail	= function(){
	return app_detect.webpeer_status() == "installed";
}

/**
 * webpeerify a url to static file
 * - this is an minimal helper on top of url_builder_oload_t
 * - url_builder_oload_t implementation is complete and much more complex
 *
 * @param url {string} original url to webpeerify
*/
webpeer.url	= function(url){
	if( !webpeer.avail() )	return url;
	return url_builder_oload_t.create(url)
			.set('outter_uri', app_detect.cache_get('oload').root_url)
			.to_string();
}

/**
 * Continuously probe webpeer and notify on status change
*/
webpeer.monitor	= function(ctor_opts){
	if( typeof(ctor_opts) == "function" )	ctor_opts = {completed_cb: ctor_opts};
	// copy ctor_opts + set default values if needed
	var completed_cb= ctor_opts.completed_cb	|| function(){};
	var delay	= ctor_opts.delay		|| 1*1000;
	// class variables
	var prev_status	= null;
	var timer_cb	= function(){
		app_detect.webpeer_probe({
			completed_cb	: function(status){
				if( status != prev_status ){
					prev_status	= status;
					completed_cb(status);
				}
				setTimeout(timer_cb, delay);
			},
			nocache		: true
		})
	}
	// launch initial timer
	setTimeout(timer_cb, 0);
}

/**
 * - this function is web-only
 * @param {string} the dom element id of the img tag
*/
webpeer.badge	= function(elem_id){
	webpeer.monitor(function(){
		var elem	= document.getElementById("webpeer_badge");
		elem.src	= "http://webpeer.it/images/badge/" + (webpeer.avail() ? 'accept.png' : 'exclamation.png');
		if( webpeer.avail() ){
			elem.title	= "You are a web peer. Welcome!";
		}else{
			elem.title	= "You are not yet a web peer. Click to be one.";
		}
	});
}

// exports public functions
exports.ready	= webpeer.ready;
exports.avail	= webpeer.avail;
exports.url	= webpeer.url;
exports.badge	= webpeer.badge;
<commit_msg>lib/webpeer.js: webpeer.badge() uses .ready() and no more .monitor() 	modified:   lib/webpeer.js<commit_after>// import required modules
var app_detect		= require('./neoip_app_detect');
var url_builder_oload_t	= require('./url_builder_oload_t');

var verbose	= 1;
var webpeer	= {};

/**
 * probe webpeer and notify the callback once completed
 *
 * @param completed_cb {function} callback notified on completion completed(avail){}
*/
webpeer.ready	= function(completed_cb){
	// discover neoip-webpeer
	app_detect.webpeer_probe({
		completed_cb	: function(status){
			if( status == "toinstall" )	completed_cb(false);
			else if( status == "toupgrade")	completed_cb(true);
			else if( status == "installed")	completed_cb(true);
			else console.assert(false);
		}
	})
};

/**
 * @returns {boolean} true if webpeer is available, false otherwise
*/
webpeer.avail	= function(){
	return app_detect.webpeer_status() == "installed";
}

/**
 * webpeerify a url to static file
 * - this is an minimal helper on top of url_builder_oload_t
 * - url_builder_oload_t implementation is complete and much more complex
 *
 * @param url {string} original url to webpeerify
*/
webpeer.url	= function(url){
	if( !webpeer.avail() )	return url;
	return url_builder_oload_t.create(url)
			.set('outter_uri', app_detect.cache_get('oload').root_url)
			.to_string();
}

/**
 * Continuously probe webpeer and notify on status change
*/
webpeer.monitor	= function(ctor_opts){
	if( typeof(ctor_opts) == "function" )	ctor_opts = {completed_cb: ctor_opts};
	// copy ctor_opts + set default values if needed
	var completed_cb= ctor_opts.completed_cb	|| function(){};
	var delay	= ctor_opts.delay		|| 1*1000;
	// class variables
	var prev_status	= null;
	var timer_cb	= function(){
		app_detect.webpeer_probe({
			completed_cb	: function(status){
				if( status != prev_status ){
					prev_status	= status;
					completed_cb(status);
				}
				setTimeout(timer_cb, delay);
			},
			nocache		: true
		})
	}
	// launch initial timer
	setTimeout(timer_cb, 0);
}

/**
 * - this function is web-only
 * @param {string} the dom element id of the img tag
*/
webpeer.badge	= function(elem_id){
	webpeer.ready(function(){
		var elem	= document.getElementById("webpeer_badge");
		elem.src	= "http://webpeer.it/images/badge/" + (webpeer.avail() ? 'accept.png' : 'exclamation.png');
		if( webpeer.avail() ){
			elem.title	= "You are a web peer. Welcome!";
		}else{
			elem.title	= "You are not yet a web peer. Click to be one.";
		}
	});
}

// exports public functions
exports.ready	= webpeer.ready;
exports.avail	= webpeer.avail;
exports.url	= webpeer.url;
exports.badge	= webpeer.badge;
<|endoftext|>


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

var AWS = require('aws-sdk');
AWS.config.update({accessKeyId: settings.s3.awsAccessKey, secretAccessKey: settings.s3.awsSecretKey});

/**
 * @api {post} /projects/project_id/resource_type/resource_type_id/resources Upload
 * @apiName UploadResource
 * @apiGroup Resources
 *
 * @apiDescription Upload parcel, party, or relationship project resource
 *
 * @apiParam (Required path parameters) {Number} [project_id] Project id
 * @apiParam (Required path parameters) {String} [resource_type] Options: project, parcel, party, relationship
 * @apiParam (Required path parameters) {Number} [resource_type_id] id of resource_type
 * @apiParam (Required multipart body parameters) {File} [filedata] file data
 * @apiParam (Required multipart body parameters) {String} [filename] file name
 *
 * @apiSuccess {Object} response an Object message property
 *
 * @apiExample {curl} Example usage:
 *     curl -i -F filename=test -F filedata=@newfile.rtf http://localhost:9000/project/3/parcel/3/resources
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *     {"message":"Success"}
 */

// Upload Resource
router.post('/:project_id/:type/:type_id/resources', upload.single('filedata'), function (req, res, next) {

    // grab all req params
    var project_id = parseInt(req.params.project_id);
    var resource_type = req.params.type;
    var resource_type_id = parseInt(req.params.type_id);

    if ( req.body.filename === undefined ) {
        return next(new Error('Missing POST body form field: "filename"'))
    }
    var file_name = req.body.filename.replace(/ /g, "").replace(/%20/g, "");  // remove white space

    var file = req.file.buffer;
    var path;

    var deferred = Q.defer();

    getOrg(project_id)
        .then(function (res) {

            var org_id = res[0].id;
            path = org_id + '/' + project_id + '/' + resource_type + '/' + resource_type_id + '-' + file_name;

            return uploadS3(path,file);
        }).then(function (s3response) {

            console.log('Successfully uploaded resource to S3.');
            //create resource in DB
            return createResource(project_id, resource_type, resource_type_id, s3response.path,file_name);

        }).then(function(result){

            //console.log('Successfully uploaded resource id:' + result[0].cd_create_resource + ' to DB.');
            res.status(200).json({message: "Success"});

        }).catch(function(err){

            // do not delete if already exists in DB
            if (err.constraint == 'resource_url_key'){
                res.status(400).json({ error:err, type:"duplicate", message:err.detail });
            } else {
                // delete from S3 if DB throws error
                deleteS3(path)
                    .then(function(resp){
                        res.status(400).json({message:err.message, error:err});
                    })
                    .catch(function(err){
                        res.status(400).json({message:err.message, error:err});
                    })
            }

        }).done();

    return deferred.promise;

});

/**
 * Upload file to s3
 * @param path
 * @param file
 * @returns {*|promise}
 */
function uploadS3 (path,file){

    var deferred = Q.defer();

    var s3 = new AWS.S3();
    s3.putObject({
        Bucket: settings.s3.bucket,
        Key: path,
        Body: file,
        ACL: 'public-read'
    }, function (err, data) {

        if (err instanceof Error) {
            console.log(err);
            deferred.reject(err);
            //return res.status(500).json(resp);
        }

        deferred.resolve({s3:data,path:path});
    });

    return deferred.promise;

}

/**
 *
 * @param path - s3 path to file
 * @returns {*|promise}
 */

function deleteS3(path){

    var deferred = Q.defer();

    var s3 = new AWS.S3();

    var params = {
        Bucket: settings.s3.bucket,
        Key: path
    };

    s3.deleteObject(params, function (err, data) {
        if (err) {
            console.log(err, err.stack);
            deferred.reject({message: "File not deleted; " + err});

        }  // error
        else {
            console.log(path, " deleted from S3.");                 // deleted
            deferred.resolve({message: "File deleted from S3."});
        }
    });

    return deferred.promise;

}

function createResource(p_id, type, type_id, path, filename) {

    var deferred = Q.defer();

    var rootURL = 'https://s3.amazonaws.com/' + settings.s3.bucket + '/';
    var url = rootURL + path;
    var sql = "SELECT * FROM cd_create_resource('" + p_id + "','" + type + "'," + type_id + ",'" + url + "',null, '" + filename + "')";

    pgb.queryDeferred(sql)
        .then(function(res){
            deferred.resolve(res);
        })
        .catch(function(err){
            deferred.reject(err);
        });

    return deferred.promise;
}

/**
 * Get org id, title and project title
 * @param p_id
 * @returns {*|promise}
 */
function getOrg(p_id) {
    var deferred = Q.defer();

    var sql = 'SELECT o.id,o.title,p.title as project_title FROM organization o, project p WHERE o.id = (SELECT organization_id FROM project where id = ' + p_id + ') and p.organization_id = o.id and p.id = ' + p_id;

    pgb.queryDeferred(sql)
        .then(function(res){
            deferred.resolve(res);
        })
        .catch(function(err){
            deferred.reject(err);
        });

    return deferred.promise;
}

// READ
//router.get('/resources/:id/', function (req, res, next) {
//
//    //  Use ID to get S3 bucket file path and file name; to be built, just pasting in filename
//    var s3File = 'upload-me.txt';
//    var downloadFileName = "theFile.txt";
//
//    var s3 = new AWS.S3();
//
//    s3.getObject({
//        Bucket: settings.s3.bucket,
//        Key: s3File
//    }, function (err, data) {
//        res.set('Content-disposition', 'attachment; filename=' + downloadFileName);
//        res.set('Content-type', 'text/plain');
//        res.charset = 'UTF-8';
//        res.write(data.Body);
//        res.end();
//    });
//
//});

// DELETE
//router.delete('/resources/:id', function (req, res, next) {
//
//    //  Use ID to get S3 bucket file path and file name; to be built, just pasting in filename
//    var s3File = 'upload-me.txt';
//
//    var s3 = new AWS.S3();
//
//    var params = {
//        Bucket: settings.s3.bucket,
//        Key: s3File
//    };
//
//    s3.deleteObject(params, function (err, data) {
//        if (err) {
//            console.log(err, err.stack);
//            res.status(200).json({message: "File not deleted; " + err})
//
//        }  // error
//        else {
//            console.log(s3File, " deleted.");                 // deleted
//            res.status(200).json({message: "File deleted."});
//        }
//    });
//
//});

module.exports = router;
<commit_msg>[#71]: remove filename from post data<commit_after>var express = require('express');
var router = express.Router();
var multer = require('multer');
var common = require('../common.js');
var upload = multer();
var settings = require('../settings/settings.js');
var ctrlCommon = require('../controllers/common.js');
var Q = require('q');
var pgb = require('../pg-binding.js');

var AWS = require('aws-sdk');
AWS.config.update({accessKeyId: settings.s3.awsAccessKey, secretAccessKey: settings.s3.awsSecretKey});

/**
 * @api {post} /projects/project_id/resource_type/resource_type_id/resources Upload
 * @apiName UploadResource
 * @apiGroup Resources
 *
 * @apiDescription Upload parcel, party, or relationship project resource
 *
 * @apiParam (Required path parameters) {Number} [project_id] Project id
 * @apiParam (Required path parameters) {String} [resource_type] Options: project, parcel, party, relationship
 * @apiParam (Required path parameters) {Number} [resource_type_id] id of resource_type
 * @apiParam (Required multipart body parameters) {File} [filedata] file data
 *
 * @apiSuccess {Object} response an Object message property
 *
 * @apiExample {curl} Example usage:
 *     curl -i -F filename=test -F filedata=@newfile.rtf http://localhost:9000/project/3/parcel/3/resources
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *     {"message":"Success"}
 */

// Upload Resource
router.post('/:project_id/:type/:type_id/resources', upload.single('filedata'), function (req, res, next) {

    // grab all req params
    var project_id = parseInt(req.params.project_id);
    var resource_type = req.params.type;
    var resource_type_id = parseInt(req.params.type_id);
    var file_name = req.file.originalname.replace(/ /g, "").replace(/%20/g, "");  // remove white space
    var file = req.file.buffer;
    var path;

    var deferred = Q.defer();

    getOrg(project_id)
        .then(function (res) {

            var org_id = res[0].id;
            path = org_id + '/' + project_id + '/' + resource_type + '/' + resource_type_id + '-' + file_name;

            return uploadS3(path,file);
        }).then(function (s3response) {

            console.log('Successfully uploaded resource to S3.');
            //create resource in DB
            return createResource(project_id, resource_type, resource_type_id, s3response.path,file_name);

        }).then(function(result){

            //console.log('Successfully uploaded resource id:' + result[0].cd_create_resource + ' to DB.');
            res.status(200).json({message: "Success"});

        }).catch(function(err){

            // do not delete if already exists in DB
            if (err.constraint == 'resource_url_key'){
                res.status(400).json({ error:err, type:"duplicate", message:err.detail });
            } else {
                // delete from S3 if DB throws error
                deleteS3(path)
                    .then(function(resp){
                        res.status(400).json({message:err.message, error:err});
                    })
                    .catch(function(err){
                        res.status(400).json({message:err.message, error:err});
                    })
            }

        }).done();

    return deferred.promise;

});

/**
 * Upload file to s3
 * @param path
 * @param file
 * @returns {*|promise}
 */
function uploadS3 (path,file){

    var deferred = Q.defer();

    var s3 = new AWS.S3();
    s3.putObject({
        Bucket: settings.s3.bucket,
        Key: path,
        Body: file,
        ACL: 'public-read'
    }, function (err, data) {

        if (err instanceof Error) {
            console.log(err);
            deferred.reject(err);
            //return res.status(500).json(resp);
        }

        deferred.resolve({s3:data,path:path});
    });

    return deferred.promise;

}

/**
 *
 * @param path - s3 path to file
 * @returns {*|promise}
 */

function deleteS3(path){

    var deferred = Q.defer();

    var s3 = new AWS.S3();

    var params = {
        Bucket: settings.s3.bucket,
        Key: path
    };

    s3.deleteObject(params, function (err, data) {
        if (err) {
            console.log(err, err.stack);
            deferred.reject({message: "File not deleted; " + err});

        }  // error
        else {
            console.log(path, " deleted from S3.");                 // deleted
            deferred.resolve({message: "File deleted from S3."});
        }
    });

    return deferred.promise;

}

function createResource(p_id, type, type_id, path, filename) {

    var deferred = Q.defer();

    var rootURL = 'https://s3.amazonaws.com/' + settings.s3.bucket + '/';
    var url = rootURL + path;
    var sql = "SELECT * FROM cd_create_resource('" + p_id + "','" + type + "'," + type_id + ",'" + url + "',null, '" + filename + "')";

    pgb.queryDeferred(sql)
        .then(function(res){
            deferred.resolve(res);
        })
        .catch(function(err){
            deferred.reject(err);
        });

    return deferred.promise;
}

/**
 * Get org id, title and project title
 * @param p_id
 * @returns {*|promise}
 */
function getOrg(p_id) {
    var deferred = Q.defer();

    var sql = 'SELECT o.id,o.title,p.title as project_title FROM organization o, project p WHERE o.id = (SELECT organization_id FROM project where id = ' + p_id + ') and p.organization_id = o.id and p.id = ' + p_id;

    pgb.queryDeferred(sql)
        .then(function(res){
            deferred.resolve(res);
        })
        .catch(function(err){
            deferred.reject(err);
        });

    return deferred.promise;
}

// READ
//router.get('/resources/:id/', function (req, res, next) {
//
//    //  Use ID to get S3 bucket file path and file name; to be built, just pasting in filename
//    var s3File = 'upload-me.txt';
//    var downloadFileName = "theFile.txt";
//
//    var s3 = new AWS.S3();
//
//    s3.getObject({
//        Bucket: settings.s3.bucket,
//        Key: s3File
//    }, function (err, data) {
//        res.set('Content-disposition', 'attachment; filename=' + downloadFileName);
//        res.set('Content-type', 'text/plain');
//        res.charset = 'UTF-8';
//        res.write(data.Body);
//        res.end();
//    });
//
//});

// DELETE
//router.delete('/resources/:id', function (req, res, next) {
//
//    //  Use ID to get S3 bucket file path and file name; to be built, just pasting in filename
//    var s3File = 'upload-me.txt';
//
//    var s3 = new AWS.S3();
//
//    var params = {
//        Bucket: settings.s3.bucket,
//        Key: s3File
//    };
//
//    s3.deleteObject(params, function (err, data) {
//        if (err) {
//            console.log(err, err.stack);
//            res.status(200).json({message: "File not deleted; " + err})
//
//        }  // error
//        else {
//            console.log(s3File, " deleted.");                 // deleted
//            res.status(200).json({message: "File deleted."});
//        }
//    });
//
//});

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

var selectedItems = [];

var reloadListing = function(callback) {
    let request = new XMLHttpRequest();
    request.open('GET', window.location);
    request.setRequestHeader('Minimal', 'true');
    request.send();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                document.querySelector('body main').innerHTML = request.responseText;
                addNewDirEvents();

                if (typeof callback == 'function') {
                    callback();
                }
            }
        }
    }
}

// Rename file event
var renameEvent = function(event) {
    if (this.classList.contains('disabled') || !selectedItems.length) {
        return false;
    }

    // This mustn't happen
    if (selectedItems.length > 1) {
        alert("Something went wrong. Please refresh the page.");
        location.refresh();
    }

    let item = document.getElementById(selectedItems[0]),
        link = item.dataset.url,
        span = item.getElementsByTagName('span')[0],
        name = span.innerHTML;

    span.setAttribute('contenteditable', 'true');
    span.focus();

    let keyDownEvent = (event) => {
        if (event.keyCode == 13) {
            let newName = span.innerHTML,
                newLink = removeLastDirectoryPartOf(toWebDavURL(link)) + newName,
                html = document.getElementById('rename').changeToLoading(),
                request = new XMLHttpRequest();

            request.open('MOVE', toWebDavURL(link));
            request.setRequestHeader('Destination', newLink);
            request.setRequestHeader('Content-type', 'text/plain; charset=utf-8');
            request.send();
            request.onreadystatechange = function() {
                // TODO: redirect if it's moved to another folder

                if (request.readyState == 4) {
                    if (request.status != 201 && request.status != 204) {
                        span.innerHTML = name;
                    } else {
                        let newLink = encodeURI(link.replace(name, newName));
                        console.log(request.body)
                        reloadListing(() => {
                            newName = btoa(newName);
                            selectedItems = [newName];
                            document.getElementById(newName).setAttribute("aria-selected", true);
                            document.sendCostumEvent('changed-selected');
                        });
                    }

                    document.getElementById('rename').changeToDone((request.status != 201 && request.status != 204), html);
                }
            }
        }

        if (event.KeyCode == 27) {
            span.innerHTML = name;
        }

        if (event.keyCode == 13 || event.keyCode == 27) {
            span.setAttribute('contenteditable', 'false');
            span.removeEventListener('keydown', keyDownEvent);
            event.preventDefault();
        }

        return false;
    }

    span.addEventListener('keydown', keyDownEvent);
    span.addEventListener('blur', (event) => {
        span.innerHTML = name;
        span.setAttribute('contenteditable', 'false');
        span.removeEventListener('keydown', keyDownEvent);
        item.removeEventListener('click', preventDefault);
    });

    return false;
}

// Upload files
var handleFiles = function(files, base) {
    let button = document.getElementById("upload");
    let html = button.changeToLoading();

    for (let i = 0; i < files.length; i++) {
        let request = new XMLHttpRequest();
        request.open('PUT', toWebDavURL(window.location.pathname + base + files[i].name));

        request.send(files[i]);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                if (request.status == 201) {
                    reloadListing();
                }

                button.changeToDone((request.status != 201), html);
            }
        }
    }

    return false;
}

// Handles the back button event
var backEvent = function(event) {
    var items = document.getElementsByClassName('item');
    Array.from(items).forEach(link => {
        link.setAttribute("aria-selected", false);
    });
    selectedItems = [];

    var event = new CustomEvent('changed-selected');
    document.dispatchEvent(event);
    return false;
}

// Toggles the view mode
var viewEvent = function(event) {
    let cookie = document.getCookie('view-list');
    let listing = document.getElementById('listing');

    if (cookie != 'true') {
        document.cookie = 'view-list=true';
    } else {
        document.cookie = 'view-list=false';
    }

    handleViewType(document.getCookie('view-list'));
    return false;
}

// Handles the view mode change
var handleViewType = function(viewList) {
    let listing = document.getElementById('listing');
    let button = document.getElementById('view');

    if (viewList == "true") {
        listing.classList.add('list');
        button.innerHTML = 'view_module Switch view';
        return false;
    }

    button.innerHTML = 'view_list Switch view';
    listing.classList.remove('list');
    return false;
}

var addNewDirEvents = function() {
    document.getElementById('new').addEventListener('click', event => {
        let newdir = document.getElementById('newdir');
        newdir.classList.add('enabled');
        newdir.focus();
    });

    document.getElementById('newdir').addEventListener('blur', event => {
        document.getElementById('newdir').classList.remove('enabled');
    });

    document.getElementById('newdir').addEventListener('keydown', newDirEvent);
}

// Handles the new directory event
var newDirEvent = function(event) {
    // TODO: create new dir button and new file button
    if (event.keyCode == 27) {
        document.getElementById('newdir').classList.toggle('enabled');
        setTimeout(() => {
            document.getElementById('newdir').value = '';
        }, 200);
    }

    if (event.keyCode == 13) {
        event.preventDefault();

        let button = document.getElementById('new');
        let html = button.changeToLoading();
        let request = new XMLHttpRequest();
        let name = document.getElementById('newdir').value;

        request.open((name.endsWith("/") ? "MKCOL" : "PUT"), toWebDavURL(window.location.pathname + name));

        request.send();
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                button.changeToDone((request.status != 201), html);
                reloadListing(() => {
                    addNewDirEvents();
                });
            }
        }
    }

    return false;
}

// Handles the event when there is change on selected elements
document.addEventListener("changed-selected", function(event) {
    redefineDownloadURLs();

    let selectedNumber = selectedItems.length,
        fileAction = document.getElementById("file-only");

    if (selectedNumber) {
        fileAction.classList.remove("disabled");

        if (selectedNumber > 1) {
            document.getElementById("open").classList.add("disabled");
            document.getElementById("rename").classList.add("disabled");
        }

        if (selectedNumber == 1) {
            document.getElementById("open").classList.remove("disabled");
            document.getElementById("rename").classList.remove("disabled");
        }

        return false;
    }

    fileAction.classList.add("disabled");
    return false;
});

var redefineDownloadURLs = function() {
    let files = "";

    for (let i = 0; i < selectedItems.length; i++) {
        let url = document.getElementById(selectedItems[i]).dataset.url;
        files += url.replace(window.location.pathname, "") + ",";
    }

    files = files.substring(0, files.length - 1);
    files = encodeURIComponent(files);

    let links = document.querySelectorAll("#download ul a");
    Array.from(links).forEach(link => {
        link.href = "?download=" + link.dataset.format + "&files=" + files;
    });
}

document.addEventListener('DOMContentLoaded', event => {
    // Handles the current view mode and adds the event to the button
    handleViewType(document.getCookie("view-list"));
    document.getElementById("view").addEventListener("click", viewEvent);

    let updateColumns = () => {
        let columns = Math.floor(document.getElementById('listing').offsetWidth / 300),
            itens = getCSSRule('#listing .item');

        itens.style.width = `calc(${100/columns}% - 1em)`;
    }

    updateColumns();
    window.addEventListener("resize", () => {
        updateColumns();
    });

    // Add event to back button and executes back event on ESC
    document.addEventListener('keydown', (event) => {
        if (event.keyCode == 27) {
            backEvent(event);
        }
    });

    if (user.AllowEdit) {
        // Enables rename button
        document.getElementById("rename").addEventListener("click", renameEvent);
    }

    if (user.AllowNew) {
        // Enables upload button
        document.getElementById("upload").addEventListener("click", (event) => {
            document.getElementById("upload-input").click();
        });

        addNewDirEvents();

        // Drag and Drop
        let items = document.getElementsByClassName('item');
        document.addEventListener("dragover", function(event) {
            event.preventDefault();
        }, false);

        document.addEventListener("dragenter", (event) => {
            Array.from(items).forEach(file => {
                file.style.opacity = 0.5;
            });
        }, false);

        document.addEventListener("dragend", (event) => {
            Array.from(items).forEach(file => {
                file.style.opacity = 1;
            });
        }, false);

        document.addEventListener("drop", function(event) {
            event.preventDefault();
            var dt = event.dataTransfer;
            var files = dt.files;

            let el = event.target;

            for (let i = 0; i < 5; i++) {
                if (el != null && !el.classList.contains('item')) {
                    el = el.parentElement;
                }
            }

            if (files.length > 0) {
                if (el != null && el.classList.contains('item') && el.dataset.dir == "true") {
                    handleFiles(files, el.querySelector('.name').innerHTML + "/");
                    return;
                }

                handleFiles(files, "");
            } else {
                Array.from(items).forEach(file => {
                    file.style.opacity = 1;
                });
            }

        }, false);
    }
});

function itemDragStart(event) {
    let el = event.target;

    for (let i = 0; i < 5; i++) {
        if (!el.classList.contains('item')) {
            el = el.parentElement;
        }
    }

    event.dataTransfer.setData("id", el.id);
    event.dataTransfer.setData("name", el.querySelector('.name').innerHTML);
}

function itemDragOver(event) {
    event.preventDefault();
    let el = event.target;

    for (let i = 0; i < 5; i++) {
        if (!el.classList.contains('item')) {
            el = el.parentElement;
        }
    }

    el.style.opacity = 1;
}

function itemDrop(e) {
    e.preventDefault();

    let el = e.target,
        id = e.dataTransfer.getData("id"),
        name = e.dataTransfer.getData("name");

    if (id == "" || name == "") return;

    for (let i = 0; i < 5; i++) {
        if (!el.classList.contains('item')) {
            el = el.parentElement;
        }
    }

    if (el.id === id) return;

    let oldLink = toWebDavURL(document.getElementById(id).dataset.url),
        newLink = toWebDavURL(el.dataset.url + name),
        request = new XMLHttpRequest();

    request.open('MOVE', oldLink);
    request.setRequestHeader('Destination', newLink);
    request.send();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 201 || request.status == 204) {
                reloadListing();
            }
        }
    }
}

function openItem(event) {
    window.location = event.currentTarget.dataset.url;
}

function selectItem(event) {
    let el = event.currentTarget;

    if (selectedItems.length != 0) event.preventDefault();
    if (selectedItems.indexOf(el.id) == -1) {
        if (!event.ctrlKey) backEvent(event);

        el.setAttribute("aria-selected", true);
        selectedItems.push(el.id);
    } else {
        el.setAttribute("aria-selected", false);
        selectedItems.removeElement(el.id);
    }

    document.sendCostumEvent("changed-selected");
    return false;
}<commit_msg>Cleaning listing.js<commit_after>'use strict';

var selectedItems = [];

var reloadListing = function(callback) {
    let request = new XMLHttpRequest();
    request.open('GET', window.location);
    request.setRequestHeader('Minimal', 'true');
    request.send();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                document.querySelector('body main').innerHTML = request.responseText;
                addNewDirEvents();

                if (typeof callback == 'function') {
                    callback();
                }
            }
        }
    }
}

// Rename file event
var renameEvent = function(event) {
    if (this.classList.contains('disabled') || !selectedItems.length) {
        return false;
    }

    // This mustn't happen
    if (selectedItems.length > 1) {
        alert("Something went wrong. Please refresh the page.");
        location.refresh();
    }

    let item = document.getElementById(selectedItems[0]),
        link = item.dataset.url,
        span = item.getElementsByTagName('span')[0],
        name = span.innerHTML;

    span.setAttribute('contenteditable', 'true');
    span.focus();

    let keyDownEvent = (event) => {
        if (event.keyCode == 13) {
            let newName = span.innerHTML,
                newLink = removeLastDirectoryPartOf(toWebDavURL(link)) + newName,
                html = document.getElementById('rename').changeToLoading(),
                request = new XMLHttpRequest();

            request.open('MOVE', toWebDavURL(link));
            request.setRequestHeader('Destination', newLink);
            request.setRequestHeader('Content-type', 'text/plain; charset=utf-8');
            request.send();
            request.onreadystatechange = function() {
                // TODO: redirect if it's moved to another folder

                if (request.readyState == 4) {
                    if (request.status != 201 && request.status != 204) {
                        span.innerHTML = name;
                    } else {
                        let newLink = encodeURI(link.replace(name, newName));
                        console.log(request.body)
                        reloadListing(() => {
                            newName = btoa(newName);
                            selectedItems = [newName];
                            document.getElementById(newName).setAttribute("aria-selected", true);
                            document.sendCostumEvent('changed-selected');
                        });
                    }

                    document.getElementById('rename').changeToDone((request.status != 201 && request.status != 204), html);
                }
            }
        }

        if (event.KeyCode == 27) {
            span.innerHTML = name;
        }

        if (event.keyCode == 13 || event.keyCode == 27) {
            span.setAttribute('contenteditable', 'false');
            span.removeEventListener('keydown', keyDownEvent);
            event.preventDefault();
        }

        return false;
    }

    span.addEventListener('keydown', keyDownEvent);
    span.addEventListener('blur', (event) => {
        span.innerHTML = name;
        span.setAttribute('contenteditable', 'false');
        span.removeEventListener('keydown', keyDownEvent);
        item.removeEventListener('click', preventDefault);
    });

    return false;
}

// Upload files
var handleFiles = function(files, base) {
    let button = document.getElementById("upload"),
        html = button.changeToLoading();

    for (let i = 0; i < files.length; i++) {
        let request = new XMLHttpRequest();
        request.open('PUT', toWebDavURL(window.location.pathname + base + files[i].name));

        request.send(files[i]);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                if (request.status == 201) {
                    reloadListing();
                }

                button.changeToDone((request.status != 201), html);
            }
        }
    }

    return false;
}

// Handles the back button event
var backEvent = function(event) {
    var items = document.getElementsByClassName('item');
    Array.from(items).forEach(link => {
        link.setAttribute("aria-selected", false);
    });
    selectedItems = [];

    var event = new CustomEvent('changed-selected');
    document.dispatchEvent(event);
    return false;
}

// Toggles the view mode
var viewEvent = function(event) {
    let cookie = document.getCookie('view-list'),
        listing = document.getElementById('listing');

    if (cookie != 'true') {
        document.cookie = 'view-list=true';
    } else {
        document.cookie = 'view-list=false';
    }

    handleViewType(document.getCookie('view-list'));
    return false;
}

// Handles the view mode change
var handleViewType = function(viewList) {
    let listing = document.getElementById('listing'),
        button = document.getElementById('view');

    if (viewList == "true") {
        listing.classList.add('list');
        button.innerHTML = 'view_module Switch view';
        return false;
    }

    button.innerHTML = 'view_list Switch view';
    listing.classList.remove('list');
    return false;
}

var addNewDirEvents = function() {
    document.getElementById('new').addEventListener('click', event => {
        let newdir = document.getElementById('newdir');
        newdir.classList.add('enabled');
        newdir.focus();
    });

    document.getElementById('newdir').addEventListener('blur', event => {
        document.getElementById('newdir').classList.remove('enabled');
    });

    document.getElementById('newdir').addEventListener('keydown', newDirEvent);
}

// Handles the new directory event
var newDirEvent = function(event) {
    // TODO: create new dir button and new file button
    if (event.keyCode == 27) {
        document.getElementById('newdir').classList.toggle('enabled');
        setTimeout(() => {
            document.getElementById('newdir').value = '';
        }, 200);
    }

    if (event.keyCode == 13) {
        event.preventDefault();

        let button = document.getElementById('new'),
            html = button.changeToLoading(),
            request = new XMLHttpRequest(),
            name = document.getElementById('newdir').value;

        request.open((name.endsWith("/") ? "MKCOL" : "PUT"), toWebDavURL(window.location.pathname + name));

        request.send();
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                button.changeToDone((request.status != 201), html);
                reloadListing(() => {
                    addNewDirEvents();
                });
            }
        }
    }

    return false;
}

// Handles the event when there is change on selected elements
document.addEventListener("changed-selected", function(event) {
    redefineDownloadURLs();

    let selectedNumber = selectedItems.length,
        fileAction = document.getElementById("file-only");

    if (selectedNumber) {
        fileAction.classList.remove("disabled");

        if (selectedNumber > 1) {
            document.getElementById("open").classList.add("disabled");
            document.getElementById("rename").classList.add("disabled");
        }

        if (selectedNumber == 1) {
            document.getElementById("open").classList.remove("disabled");
            document.getElementById("rename").classList.remove("disabled");
        }

        return false;
    }

    fileAction.classList.add("disabled");
    return false;
});

var redefineDownloadURLs = function() {
    let files = "";

    for (let i = 0; i < selectedItems.length; i++) {
        let url = document.getElementById(selectedItems[i]).dataset.url;
        files += url.replace(window.location.pathname, "") + ",";
    }

    files = files.substring(0, files.length - 1);
    files = encodeURIComponent(files);

    let links = document.querySelectorAll("#download ul a");
    Array.from(links).forEach(link => {
        link.href = "?download=" + link.dataset.format + "&files=" + files;
    });
}

document.addEventListener('DOMContentLoaded', event => {
    // Handles the current view mode and adds the event to the button
    handleViewType(document.getCookie("view-list"));
    document.getElementById("view").addEventListener("click", viewEvent);

    let updateColumns = () => {
        let columns = Math.floor(document.getElementById('listing').offsetWidth / 300),
            itens = getCSSRule('#listing .item');

        itens.style.width = `calc(${100/columns}% - 1em)`;
    }

    updateColumns();
    window.addEventListener("resize", () => {
        updateColumns();
    });

    // Add event to back button and executes back event on ESC
    document.addEventListener('keydown', (event) => {
        if (event.keyCode == 27) {
            backEvent(event);
        }
    });

    if (user.AllowEdit) {
        // Enables rename button
        document.getElementById("rename").addEventListener("click", renameEvent);
    }

    if (user.AllowNew) {
        // Enables upload button
        document.getElementById("upload").addEventListener("click", (event) => {
            document.getElementById("upload-input").click();
        });

        addNewDirEvents();

        // Drag and Drop
        let items = document.getElementsByClassName('item');
        document.addEventListener("dragover", function(event) {
            event.preventDefault();
        }, false);

        document.addEventListener("dragenter", (event) => {
            Array.from(items).forEach(file => {
                file.style.opacity = 0.5;
            });
        }, false);

        document.addEventListener("dragend", (event) => {
            Array.from(items).forEach(file => {
                file.style.opacity = 1;
            });
        }, false);

        document.addEventListener("drop", function(event) {
            event.preventDefault();
            var dt = event.dataTransfer;
            var files = dt.files;

            let el = event.target;

            for (let i = 0; i < 5; i++) {
                if (el != null && !el.classList.contains('item')) {
                    el = el.parentElement;
                }
            }

            if (files.length > 0) {
                if (el != null && el.classList.contains('item') && el.dataset.dir == "true") {
                    handleFiles(files, el.querySelector('.name').innerHTML + "/");
                    return;
                }

                handleFiles(files, "");
            } else {
                Array.from(items).forEach(file => {
                    file.style.opacity = 1;
                });
            }

        }, false);
    }
});

function itemDragStart(event) {
    let el = event.target;

    for (let i = 0; i < 5; i++) {
        if (!el.classList.contains('item')) {
            el = el.parentElement;
        }
    }

    event.dataTransfer.setData("id", el.id);
    event.dataTransfer.setData("name", el.querySelector('.name').innerHTML);
}

function itemDragOver(event) {
    event.preventDefault();
    let el = event.target;

    for (let i = 0; i < 5; i++) {
        if (!el.classList.contains('item')) {
            el = el.parentElement;
        }
    }

    el.style.opacity = 1;
}

function itemDrop(e) {
    e.preventDefault();

    let el = e.target,
        id = e.dataTransfer.getData("id"),
        name = e.dataTransfer.getData("name");

    if (id == "" || name == "") return;

    for (let i = 0; i < 5; i++) {
        if (!el.classList.contains('item')) {
            el = el.parentElement;
        }
    }

    if (el.id === id) return;

    let oldLink = toWebDavURL(document.getElementById(id).dataset.url),
        newLink = toWebDavURL(el.dataset.url + name),
        request = new XMLHttpRequest();

    request.open('MOVE', oldLink);
    request.setRequestHeader('Destination', newLink);
    request.send();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 201 || request.status == 204) {
                reloadListing();
            }
        }
    }
}

function openItem(event) {
    window.location = event.currentTarget.dataset.url;
}

function selectItem(event) {
    let el = event.currentTarget;

    if (selectedItems.length != 0) event.preventDefault();
    if (selectedItems.indexOf(el.id) == -1) {
        if (!event.ctrlKey) backEvent(event);

        el.setAttribute("aria-selected", true);
        selectedItems.push(el.id);
    } else {
        el.setAttribute("aria-selected", false);
        selectedItems.removeElement(el.id);
    }

    document.sendCostumEvent("changed-selected");
    return false;
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import AuthenticatedUi from '../../mixins/authenticated-ui';

export default Ember.Route.extend(AuthenticatedUi, {
  i18n: Ember.inject.service(),
  flashMessages: Ember.inject.service(),

  activate: function () {
    this.set('title', this.get('i18n').t('attendedevents'));

    this.controllerFor('application').set('mobileMenuLeft',
      'nav/dashboard/left-items');

    this._super();
  },

  actions: {
    updateCurrentUser: function () {
      var store = this.get('store');

      store.find('user', 0).then(user => {
        user.save().then(_ => {
          this.get('flashMessages').success('Profile updated!');
        }, error => {
          this.get('flashMessages').alert('Profile did not update.');
        });
      });
    },

    deactivateAccount: function () {
      var store = this.get('store');

      store.find('user', 0).then((user) => {
        user.deleteRecord();
        user.save().then(() => {
          this.send('invalidateSession');
        });
      });
    },
  },
});
<commit_msg>close the modal upon cancelling of account<commit_after>import Ember from 'ember';
import AuthenticatedUi from '../../mixins/authenticated-ui';

export default Ember.Route.extend(AuthenticatedUi, {
  i18n: Ember.inject.service(),
  flashMessages: Ember.inject.service(),

  activate: function () {
    this.set('title', this.get('i18n').t('attendedevents'));

    this.controllerFor('application').set('mobileMenuLeft',
      'nav/dashboard/left-items');

    this._super();
  },

  actions: {
    updateCurrentUser: function () {
      var store = this.get('store');

      store.find('user', 0).then(user => {
        user.save().then(_ => {
          this.get('flashMessages').success('Profile updated!');
        }, error => {
          this.get('flashMessages').alert('Profile did not update.');
        });
      });
    },

    deactivateAccount: function () {
      var store = this.get('store');

      store.find('user', 0).then((user) => {
        user.deleteRecord();
        user.save().then(() => {
          Ember.$('.close-reveal-modal').click();
          this.send('invalidateSession');
        });
      });
    },
  },
});
<|endoftext|>


<commit_before>var branches = new Vue({
  el: '#branches',
  data: {
    payload: [],
    branchData: {

    }
  },
  methods: {
    payload = [];
    buildBranches: function (data, payload) {
      name = '',
      isStale = '',
      status = ''
      $.each(data, function (_, v) {
        payload.push({
          name: name,
          isStale: isStale,
          status: status
        });
      });
      return payload;
    }
  }
});<commit_msg>create the branches call<commit_after>var branches = new Vue({
  el: '#branches',
  data: {
    payload: [],
    branchData: {

    }
  },
  methods: {
    payload = [];

    make_gh_call: function() {
      vt = this;
      auth_data = this.creds().username + ":" + this.creds().token;
      jQuery.ajax
      ({
        type: "GET",
        url: "https://api.github.com/repos/" + this.creds().org + "/"+ this.creds().repo +"/branches"
        dataType: 'json',
        headers: {"Authorization": "Basic " + btoa(auth_data)},
        success: function (data){
          vt.payload = vt.buildBranches(data, vt.payload);
        },
        error: function() {
          alert('error');
        }
       });
    },

    creds: function() {
      return github_details();
    },

    buildBranches: function (data, payload) {
      $.each(data, function (_, v) {
        name = v.name;
        isStale = '',
        status = ''
        payload.push({
          name: name,
          isStale: isStale,
          status: status
        });
      });
      return payload;
    }
  }
});
<|endoftext|>