all files / src/ codec.js

81.06% Statements 184/227
75.95% Branches 60/79
68.89% Functions 31/45
81.25% Lines 182/224
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611                                                                                                                                              1× 1× 1× 1× 1×                         1×               1×                   1×                   1× 24× 24× 24× 24× 23× 23× 23× 1×   22×     22×       22× 6× 25× 25×   25× 25× 25× 25× 25×     25×       6×         22× 222× 222× 12× 12× 12× 34×   12×         22× 222×       22× 210× 210× 188× 188× 50×   188×     22×               1×               24×                       1× 200× 928× 928× 200×                           1× 12× 12× 110× 110× 34×     12×                           1× 21×   21×     21× 21× 206× 206× 21×     21× 21× 21×                                   1× 14× 14×     14×     14×         14×   14× 19× 116× 116× 116×   116×       14× 14× 14×                                 1× 8× 8× 8× 8×         8×         8× 45× 45× 17×     45×   350× 45× 305× 305× 305× 305× 305×     45×     45× 718× 718× 718× 718×         8×   8× 8×   8× 8×   8× 134×                       8× 49×                       8×                   8× 45× 45× 17×     45×     45× 718×               45× 17×                       45× 28×                     8× 8× 8×             1×                                                                                             1× 4× 4× 4×     4×     4× 4× 4×   4×       4× 42×   39× 265×   39× 226× 226× 226× 226× 226×         39× 20× 20×   39×     42× 42× 19× 19×   23×           4×     4× 4× 23× 23× 21× 21×       23×   4×   4× 4× 2× 19×   19×       2×   2×                             1×        
/* convert a mxgraph xml to a graphml xml file
 
1. Load XML
2. Add all nodes as children to the layers (unpack the <mxCell> from the <object> tag)
    the <object> tag is used to wrap an mxCell with its attributes
3. Remove groups
4. Edges (There will be no edge without token -> drop layer information)
    - edges don't work inter groups, but they can be intra groups
        -> they have to be unwrapped as well
5. Flatten the hierarchical tree
    - merge mxCells with their layers to obtain the layer-attributes
6. Collect all possible attributes
 
(1) Drop following attributes
 
- Graph
    - grid
    - gridSize
    - guides
    - toolTips
    - connect
    - arrows
    - fold
    - page
    - pageScale
 
 
(2) Parse the style attribute in order to retrieve the following attributes
 
 - MxCell
    - tokenType
 
 
 -> first: read the saved mxgraph with xml2js into a javscript object
 -> then make the validity checks
    - is the structure of the xml correct
        - mxGraph
            - root
                - cell
                    - geometry
                - object
                    - cell
                        - geometry
 
    - are all necessary attributes at hand
        - mxGraphModel
            - dx
            - dy
            - pageWidth
            - pageHeight
        - mxCell
            - id
            - parent
 -> then drop unnecessary attributes
 -> export as GraphML (http://graphml.graphdrawing.org/primer/graphml-primer.html)
 
 
MAKE SOME TDD Test Driven Development here.
 
 
 */
 
/**
* XML Handling
*
* mxGraph xml
*
* @module Codec
* @requires xml2js
*/
 
var log = require('electron-log');
var fs = require('fs');
var xml2js = require('xml2js');
var database = require('./database');
var utils = require('./utils');
 
 
 
/**
 *
 * Codec
 * --------
 * Contains all the methods to convert a mxGraph into a GraphML or to neo4j
 * <br>
*
 * @class Codec
*/
var Codec = Codec || {};
 
/**
 * The xml2js parser
 *
 * @property parser
 * @type {Object}
 */
Codec.parser = new xml2js.Parser();
 
/**
 * The xml2js builder
 *
 * This object can create xml files
 *
 * @property builder
 * @type {Object}
 */
Codec.builder = new xml2js.Builder({'attrkey':'@', 'charkey': '#'});
 
 
 
/**
* Get the database driver
 *
 * @method mxgraph_to_object
 * @param filename the resource to load
*/
Codec.mxgraph_to_object = function(filename) {
    var promise = new Promise(function(resolve, reject){
        try {
            fs.readFile(__dirname + '/' + filename, function(err, data) {
                if (!err) {
                    try {
                        Codec.parser.parseString(data, function (err, result) {
                            if (err) {
                                return reject(err);
                            } else {
                                Iif (result === undefined) {
                                    return reject('ParseString was not able to parse the xml');
                                }
                                var root = result.mxGraphModel.root[0];
 
                                // unwrap the <object>s
                                // The objects under root (<object>)
                                if (root.object) {
                                    for (var j = 0; j < root.object.length; j++) {
                                        var node2 = root.object[j].mxCell[0];
                                        Eif (node2.$.parent) {
                                            // merge the object and the node into a new one
                                            var merged = {};
                                            Object.assign(merged, root.object[j].mxCell[0], root.object[j]);
                                            Object.assign(merged.$, root.object[j].mxCell[0].$);
                                            delete merged.mxCell;
                                            Iif (!root.mxCell) {
                                                root.mxCell = [];
                                            }
                                            root.mxCell.push(merged);
                                        }
                                    }
 
                                    delete root.object;
                                }
 
                                // remove groups
                                // rewire the children to the parent of the group
                                for (var i = 0; i < root.mxCell.length; i++) {
                                    var node = root.mxCell[i];
                                    if (node.$.style && node.$.style === "group") {
                                        var parent = Codec.get_node_by_id(root, node.$.parent);
                                        var children = Codec.get_nodes_by_parent_id(root, node.$.id);
                                        for (var j = 0; j < children.length; j++) {
                                            children[j].$.parent = parent.$.id;
                                        }
                                        root.mxCell[i] = 'x';
                                    }
                                }
 
                                // remove all TO DELETE entries
                                root.mxCell = root.mxCell.filter(function (cell) {
                                    return (cell !== 'x')
                                });
 
                                // The cells in the root (<mxCell>)
                                for (var i = 0; i < root.mxCell.length; i++) {
                                    var node = root.mxCell[i];
                                    if (node.$.parent) {
                                        var parent = Codec.get_node_by_id(root, node.$.parent);
                                        if (!parent.children) {
                                            parent.children = []
                                        }
                                        parent.children.push(node);
                                    }
                                }
                                resolve(result);
                            }
 
                        });
                    } catch (e) {
                        return reject(err);
                    }
                } else {
                    return reject(err);
                }
            });
        } catch (e) {
            reject(e);
        }
 
    });
    return promise;
};
 
/**
 * Works on a mxGraph xml2js-object
 * Finds a node given an id
 *
 * @method get_node_by_id
 * @param root mxGraph tree
 * @param id
 * @returns {node}
 */
Codec.get_node_by_id = function(root, id) {
    for (var i = 0; i<root.mxCell.length; i++) {
        var node = root.mxCell[i];
        if (node.$.id === id) {
            return node;
        }
    }
};
 
/**
 * Works on a mxGraph xml2js-object
 * Gets all nodes with a given parent
 *
 * @method get_nodes_by_parent_id
 * @param root
 * @param parent_id
 * @returns {Array}
 */
Codec.get_nodes_by_parent_id = function(root, parent_id) {
    var nodes = [];
    for (var i = 0; i<root.mxCell.length; i++) {
        var node = root.mxCell[i];
        if (node.$ && node.$.parent === parent_id) {
            nodes.push(node);
        }
    }
    return nodes;
};
 
 
/**
 * Converts the mxGraph to an object structured ad follows
 *
 * obj.mxGraphModel.layer1.node1
 *
 * It removes groups
 *
 * @method mxgraph_to_layered_object
 * @param filename
 */
Codec.mxgraph_to_layered_object = function(filename) {
    return Codec.mxgraph_to_object(filename).then(
        function(result) {
            Iif (!result) {
                return Promise.reject('empty result');
            }
            var temp;
            for (var l = 0; l < result.mxGraphModel.root[0].mxCell.length; l++) {
                var node = result.mxGraphModel.root[0].mxCell[l];
                if (node.$.id === "0") {
                    temp = node;
                }
            }
            result.mxGraphModel.root[0].mxCell = [temp];
            delete result.mxGraphModel.root[0].object;
            return Promise.resolve(result);
        },
        function(err) {
            log.error(err);
            return err;
        });
};
 
/**
 * Converts an mxGraph to a flat object structured as follows
 *
 * graph.mxGraphModel.data.token1
 * graph.mxGraphModel.data.token2
 * graph.mxGraphModel.data.edge1
 *
 * @method mxgraph_to_flattened_object
 * @param filename
 */
Codec.mxgraph_to_flattened_object = function(filename) {
    return Codec.mxgraph_to_layered_object(filename).then(function (graph) {
        Iif (!(graph && graph.mxGraphModel)) {
            return Promise.reject('Graph is empty');
        }
        graph.mxGraphModel.data = graph.mxGraphModel.root[0].mxCell[0].children;
 
        // remove the locked background layer which is the first element
        graph.mxGraphModel.data.shift();
 
        // so far there is only the 'value' attribute which is interesting for the children
        // -> therefore we don't choose a general approach and only copy it to the children
 
        var only_children = [];
 
        graph.mxGraphModel.data.forEach(function(layer){
            layer.children.forEach(function(child){
                child.$.hand = layer.$.value;
                Eif (child.hasOwnProperty('mxGeometry')) {
                    Object.assign(child.$, child.mxGeometry[0].$);
                }
                only_children.push(child);
            });
        });
 
        graph.mxGraphModel.data = only_children;
        delete graph.mxGraphModel.root;
        return graph;
    })
        .catch(function(err) {
            log.error(err);
            return err;
    });
};
 
/**
 * Converts a mxGraph into the GraphML format
 *
 * It removes groups and is not necessary for the code
 * Only nice to have
 *
 * @method mxgraph_to_graphml
 * @param filename
 */
Codec.mxgraph_to_graphml = function(filename) {
    return Codec.mxgraph_to_flattened_object(filename).then(function(graph) {
            var graphml = JSON.parse(JSON.stringify(graph));
            graphml.graphml = graphml.mxGraphModel;
            delete graphml.mxGraphModel;
            //graphml.graphml.xmlns = "http://graphml.graphdrawing.org/xmlns";
            //graphml.graphml['xmlns:xsi'] = "http://www.w3.org/2001/XMLSchema-instance";
            //graphml.graphml['xsi:schemaLocation'] = "http://graphml.graphdrawing.org/xmlns\nhttp://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd";
 
            var keys = {
                'edge': {},
                'node': {}
            };
 
            graphml.graphml.data.forEach(function(cell){
                var for_ = "node";
                if (cell.$.edge) {
                    for_ = "edge";
                }
 
                Eif (cell.$.style) {
                    // split style
                    var styles = cell.$.style.split(';').filter(function(a){return (a.length > 0)})
                    styles.forEach(function(style) {
                        var splits = style.split('=');
                        var key = splits[0];
                        var value = splits[1];
                        Eif (! cell.$.hasOwnProperty(key)) {
                            cell.$[key] = value;
                        }
                    });
                    delete cell.$.style;
                }
 
                for (var k in cell.$){
                    Eif (cell.$.hasOwnProperty(k)) {
                        var key = k;
                        var value = cell.$[k];
                        keys[for_][key] = value;
                    }
                }
            });
 
            var data = graphml.graphml.data;
 
            graphml.graphml = {};
            graphml.graphml.key = [];
 
            var node_keys = Object.keys(keys.node);
            var edge_keys = Object.keys(keys.edge);
 
            node_keys.forEach(function(k) {
                graphml.graphml.key.push(
                    {
                        '@': {
                            'id': k,
                            'for': 'node',
                            'attr.name': k,
                            'attr.type': 'string'
                        }
 
                    });
            });
 
            edge_keys.forEach(function(k) {
                graphml.graphml.key.push(
                    {
                        '@': {
                            'id': k,
                            'for': 'edge',
                            'attr.name': k,
                            'attr.type': 'string'
                        }
 
                    });
            });
 
            graphml.graphml.graph = {
                '@': {
                    'id': 'G',
                    'edgedefault': 'directed'
                },
                'node': [],
                'edge': []
            };
 
 
            data.forEach(function(cell){
                var type = "node";
                if (cell.$.edge) {
                    type = "edge";
                }
 
                var data_list = [];
 
 
                for (var attr in cell.$) {
                    data_list.push({
                        '@': {
                            'key': attr
                        },
                        '#': cell.$[attr]
                    });
                }
 
                if (type === 'edge') {
                    graphml.graphml.graph.edge.push(
                        {
                            '@': {
                                'id': cell.$.id,
                                'source': cell.$.source,
                                'target': cell.$.target
                            },
                            'data': data_list
                        }
                    );
                }
 
                if (type === 'node') {
                    graphml.graphml.graph.node.push(
                        {
                            '@': {
                                'id': cell.$.id
                            },
                            'data':data_list
                        }
                    );
                }
            });
 
            Codec.builder.attrkey = '@';
            var xml = Codec.builder.buildObject(graphml);
            return xml;
        }).catch(function(err){
            log.error(err);
            return err;
        })
};
 
Codec.add_all_completed_fragments_to_neo4j = function() {
    var all_promises = [];
    var num_changed = 0;
    var num_not_changed = 0;
    var p = new Promise(function(resolve, reject){
        database.get_all_completed_fragments().then(
            function(records) {
                records.forEach(function(record){
                    var image_id = record.get('image_id');
                    var fragment_id = record.get('fragment_id');
                    var hash = record.get('hash');
                    var file_hash = utils.hash_xml_fragment(fragment_id);
                    if (hash && file_hash && file_hash === hash) {
                        num_not_changed++;
                    } else {
                        num_changed++;
                        database.remove_fragment(image_id, fragment_id, true).then(function (success) {
                            all_promises.push(Codec.mxgraph_to_neo4j(image_id, fragment_id));
                        }, function (err) {
                            log.error(err);
                            reject(err);
                        });
                    }
                });
                Promise.all(all_promises).then(function(all) {
                    resolve({'num_changed':num_changed, 'num_not_changed':num_not_changed});
                }).catch(function(err) {
                    reject(err);
                })
            },
            function(err) {
                log.error(err);
                reject(err);
            }
        );
    });
    return p;
};
 
/**
 * Loads an mxGraph over the flat xml2js-object into the neo4j database
 *
 * @method mxgraph_to_neo4j
 * @param image_id
 * @param fragment_id
 * @param overwrite_xml_path if you don't want to load the standard xml file_path for the fragment use this
 */
Codec.mxgraph_to_neo4j = function(image_id, fragment_id, overwrite_xml_path) {
    Iif (overwrite_xml_path === undefined) {overwrite_xml_path = false;}
    var xml_path;
    Iif (!overwrite_xml_path) {
        xml_path = '../media/uploaded_xmls/' + fragment_id + '.xml';
    } else {
        xml_path = overwrite_xml_path;
    }
 
    return Codec.mxgraph_to_flattened_object(xml_path).then(function (graph) {
        var nodes = [];
        var edges = [];
 
        Iif (!(graph && graph.mxGraphModel)) {
            return Promise.reject('Graph is empty');
        }
 
        graph.mxGraphModel.data.forEach(function (cell) {
            if (cell.$.style) {
                // split style
                var styles = cell.$.style.split(';').filter(function (a) {
                    return (a.length > 0)
                });
                styles.forEach(function (style) {
                    var splits = style.split('=');
                    var key = splits[0];
                    var value = splits[1];
                    Eif (!cell.$.hasOwnProperty(key)) {
                        cell.$[key] = value;
                    }
                });
                // some times the text is in the property label and other times in value
                // => we want it every time in value
                if (cell.$.hasOwnProperty('label')) {
                    cell.$['value'] = cell.$['label'];
                    delete cell.$['label'];
                }
                delete cell.$.style;
            }
 
            var for_ = "node";
            if (cell.$.edge) {
                for_ = "edge";
                edges.push(cell);
            } else {
                nodes.push(cell);
            }
 
 
        });
        // create all the nodes
        var all_node_promises = [];
        // a graph can contain a frame
        // These frames need to be connected to the 'meta frames'
        var is_frame = false;
        nodes.forEach(function (cell) {
            var label = 'Group';
            if (cell.$.hasOwnProperty('tokenType')) {
                label = 'Token';
                Iif (cell.$.tokenType === 'frame') {
                    is_frame = true;
                }
            }
            all_node_promises.push(function() {return database.add_node(image_id, fragment_id, label, cell.$)})
        });
        return utils.chain_promises(all_node_promises).then(function (values) {
            // create all the edges
            var all_edge_promises = [];
            if (edges.length > 0) {
                edges.forEach(function (cell) {
                    all_edge_promises.push(
                        function() {
                            return database.add_edge(image_id, fragment_id, cell.$.source, cell.$.target, cell.$)
                        }
                    );
                });
                return utils.chain_promises(all_edge_promises);
            } else {
                return values
            }
        },
        function(err){
            log.error(err);
            return err;
        });
    }, function(err){
        log.error(err);
        return err;
    });
};
 
 
 
module.exports = Codec;