<commit_before>    angular.module('container', [])
    .controller('ContainerController', ['$scope', '$routeParams', '$location', 'Container', 'ContainerCommit', 'Image', 'Messages', 'ViewSpinner', '$timeout',
        function ($scope, $routeParams, $location, Container, ContainerCommit, Image, Messages, ViewSpinner, $timeout) {
            $scope.changes = [];
            $scope.editEnv = false;
            $scope.editPorts = false;
            $scope.editBinds = false;
            $scope.newCfg = {
                Env: [],
                Ports: {}
            };

            var update = function () {
                ViewSpinner.spin();
                Container.get({id: $routeParams.id}, function (d) {
                    $scope.container = d;
                    $scope.container.edit = false;
                    $scope.container.newContainerName = d.Name;

                    // fill up env
                    if (d.Config.Env) {
                        $scope.newCfg.Env = d.Config.Env.map(function (entry) {
                            return {name: entry.split('=')[0], value: entry.split('=')[1]};
                        });
                    }

                    // fill up ports
                    $scope.newCfg.Ports = {};
                    angular.forEach(d.Config.ExposedPorts, function(i, port) {
                        if (d.HostConfig.PortBindings && port in d.HostConfig.PortBindings) {
                            $scope.newCfg.Ports[port] = d.HostConfig.PortBindings[port];
                        }
                        else {
                            $scope.newCfg.Ports[port] = [];
                        }
                    });

                    // fill up bindings
                    $scope.newCfg.Binds = [];
                    var defaultBinds = {};
                    angular.forEach(d.Config.Volumes, function(value, vol) {
                        defaultBinds[vol] = { ContPath: vol, HostPath: '', ReadOnly: false, DefaultBind: true };
                    });
                    angular.forEach(d.HostConfig.Binds, function(binding, i) {
                        var mountpoint = binding.split(':')[0];
                        var vol = binding.split(':')[1] || '';
                        var ro = binding.split(':').length > 2 && binding.split(':')[2] === 'ro';
                        var defaultBind = false;
                        if (vol === '') {
                            vol = mountpoint;
                            mountpoint = '';
                        }

                        if (vol in defaultBinds) {
                            delete defaultBinds[vol];
                            defaultBind = true;
                        }
                        $scope.newCfg.Binds.push({ ContPath: vol, HostPath: mountpoint, ReadOnly: ro, DefaultBind: defaultBind });
                    });
                    angular.forEach(defaultBinds, function(bind) {
                        $scope.newCfg.Binds.push(bind);
                    });

                    ViewSpinner.stop();
                }, function (e) {
                    if (e.status === 404) {
                        $('.detail').hide();
                        Messages.error("Not found", "Container not found.");
                    } else {
                        Messages.error("Failure", e.data);
                    }
                    ViewSpinner.stop();
                });

            };

            $scope.start = function () {
                ViewSpinner.spin();
                Container.start({
                    id: $scope.container.Id,
                }, {}, function (d) {
                    update();
                    Messages.send("Container started", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to start." + e.data);
                });
            };

            $scope.stop = function () {
                ViewSpinner.spin();
                Container.stop({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container stopped", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to stop." + e.data);
                });
            };

            $scope.kill = function () {
                ViewSpinner.spin();
                Container.kill({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container killed", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to die." + e.data);
                });
            };

            $scope.restartEnv = function () {
                var config = angular.copy($scope.container.Config);

                config.Env = $scope.newCfg.Env.map(function(entry) {
                    return entry.name+"="+entry.value;
                });

                var portBindings = angular.copy($scope.newCfg.Ports);
                angular.forEach(portBindings, function(item, key) {
                    if (item.length === 0) {
                        delete portBindings[key];
                    }
                });

                var binds = [];
                angular.forEach($scope.newCfg.Binds, function(b) {
                    if (b.ContPath !== '') {
                        var bindLine = '';
                        if (b.HostPath !== '') {
                            bindLine = b.HostPath + ':';
                        }
                        bindLine += b.ContPath;
                        if (b.ReadOnly) {
                            bindLine += ':ro';
                        }
                        if (b.HostPath !== '' || !b.DefaultBind) {
                            binds.push(bindLine);
                        }
                    }
                });

                ViewSpinner.spin();
                ContainerCommit.commit({id: $routeParams.id, tag: $scope.container.Config.Image, config: config }, function (d) {
                    if ('Id' in d) {
                        var imageId = d.Id;
                        Image.inspect({id: imageId}, function(imageData) {
                            // Append current host config to image with new port bindings
                            imageData.Config.HostConfig = angular.copy($scope.container.HostConfig);
                            imageData.Config.HostConfig.PortBindings = portBindings;
                            imageData.Config.HostConfig.Binds = binds;
                            if (imageData.Config.HostConfig.NetworkMode === 'host') {
                                imageData.Config.Hostname = '';
                            }

                            Container.create(imageData.Config, function(containerData) {
                                if (!('Id' in containerData)) {
                                    Messages.error("Failure", "Container failed to create.");
                                    return;
                                }
                                // Stop current if running
                                if ($scope.container.State.Running) {
                                    Container.stop({id: $routeParams.id}, function (d) {
                                        Messages.send("Container stopped", $routeParams.id);
                                        // start new
                                        Container.start({
                                            id: containerData.Id
                                        }, function (d) {
                                            $location.url('/containers/' + containerData.Id + '/');
                                            Messages.send("Container started", $routeParams.id);
                                        }, function (e) {
                                            update();
                                            Messages.error("Failure", "Container failed to start." + e.data);
                                        });
                                    }, function (e) {
                                        update();
                                        Messages.error("Failure", "Container failed to stop." + e.data);
                                    });
                                } else {
                                    // start new
                                    Container.start({
                                        id: containerData.Id
                                    }, function (d) {
                                        $location.url('/containers/'+containerData.Id+'/');
                                        Messages.send("Container started", $routeParams.id);
                                    }, function (e) {
                                        update();
                                        Messages.error("Failure", "Container failed to start." + e.data);
                                    });
                                }

                            }, function(e) {
                                update();
                                Messages.error("Failure", "Image failed to get." + e.data);
                            });
                        }, function (e) {
                            update();
                            Messages.error("Failure", "Image failed to get." + e.data);
                        });

                    } else {
                        update();
                        Messages.error("Failure", "Container commit failed.");
                    }

                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to commit." + e.data);
                });
            };

            $scope.commit = function () {
                ViewSpinner.spin();
                ContainerCommit.commit({id: $routeParams.id, repo: $scope.container.Config.Image}, function (d) {
                    update();
                    Messages.send("Container commited", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to commit." + e.data);
                });
            };
            $scope.pause = function () {
                ViewSpinner.spin();
                Container.pause({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container paused", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to pause." + e.data);
                });
            };

            $scope.unpause = function () {
                ViewSpinner.spin();
                Container.unpause({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container unpaused", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to unpause." + e.data);
                });
            };

            $scope.remove = function () {
                ViewSpinner.spin();
                Container.remove({id: $routeParams.id}, function (d) {
                    update();
                    $location.path('/containers');
                    Messages.send("Container removed", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to remove." + e.data);
                });
            };

            $scope.restart = function () {
                ViewSpinner.spin();
                Container.restart({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container restarted", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to restart." + e.data);
                });
            };

            $scope.hasContent = function (data) {
                return data !== null && data !== undefined;
            };

            $scope.getChanges = function () {
                ViewSpinner.spin();
                Container.changes({id: $routeParams.id}, function (d) {
                    $scope.changes = d;
                    ViewSpinner.stop();
                });
            };

            $scope.renameContainer = function () {
                // #FIXME fix me later to handle http status to show the correct error message
                Container.rename({id: $routeParams.id, 'name': $scope.container.newContainerName}, function (data) {
                    if (data.name) {
                        $scope.container.Name = data.name;
                        Messages.send("Container renamed", $routeParams.id);
                    } else {
                        $scope.container.newContainerName = $scope.container.Name;
                        Messages.error("Failure", "Container failed to rename.");
                    }
                });
                $scope.container.edit = false;
            };

            $scope.addEntry = function (array, entry) {
                array.push(entry);
            };
            $scope.rmEntry = function (array, entry) {
                var idx = array.indexOf(entry);
                array.splice(idx, 1);
            };

            $scope.toggleEdit = function() {
                $scope.edit = !$scope.edit;
            };

            update();
            $scope.getChanges();
        }]);
<commit_msg>Fix broken build (#251)<commit_after>    angular.module('container', [])
    .controller('ContainerController', ['$scope', '$routeParams', '$location', 'Container', 'ContainerCommit', 'Image', 'Messages', 'ViewSpinner', '$timeout',
        function ($scope, $routeParams, $location, Container, ContainerCommit, Image, Messages, ViewSpinner, $timeout) {
            $scope.changes = [];
            $scope.editEnv = false;
            $scope.editPorts = false;
            $scope.editBinds = false;
            $scope.newCfg = {
                Env: [],
                Ports: {}
            };

            var update = function () {
                ViewSpinner.spin();
                Container.get({id: $routeParams.id}, function (d) {
                    $scope.container = d;
                    $scope.container.edit = false;
                    $scope.container.newContainerName = d.Name;

                    // fill up env
                    if (d.Config.Env) {
                        $scope.newCfg.Env = d.Config.Env.map(function (entry) {
                            return {name: entry.split('=')[0], value: entry.split('=')[1]};
                        });
                    }

                    // fill up ports
                    $scope.newCfg.Ports = {};
                    angular.forEach(d.Config.ExposedPorts, function(i, port) {
                        if (d.HostConfig.PortBindings && port in d.HostConfig.PortBindings) {
                            $scope.newCfg.Ports[port] = d.HostConfig.PortBindings[port];
                        }
                        else {
                            $scope.newCfg.Ports[port] = [];
                        }
                    });

                    // fill up bindings
                    $scope.newCfg.Binds = [];
                    var defaultBinds = {};
                    angular.forEach(d.Config.Volumes, function(value, vol) {
                        defaultBinds[vol] = { ContPath: vol, HostPath: '', ReadOnly: false, DefaultBind: true };
                    });
                    angular.forEach(d.HostConfig.Binds, function(binding, i) {
                        var mountpoint = binding.split(':')[0];
                        var vol = binding.split(':')[1] || '';
                        var ro = binding.split(':').length > 2 && binding.split(':')[2] === 'ro';
                        var defaultBind = false;
                        if (vol === '') {
                            vol = mountpoint;
                            mountpoint = '';
                        }

                        if (vol in defaultBinds) {
                            delete defaultBinds[vol];
                            defaultBind = true;
                        }
                        $scope.newCfg.Binds.push({ ContPath: vol, HostPath: mountpoint, ReadOnly: ro, DefaultBind: defaultBind });
                    });
                    angular.forEach(defaultBinds, function(bind) {
                        $scope.newCfg.Binds.push(bind);
                    });

                    ViewSpinner.stop();
                }, function (e) {
                    if (e.status === 404) {
                        $('.detail').hide();
                        Messages.error("Not found", "Container not found.");
                    } else {
                        Messages.error("Failure", e.data);
                    }
                    ViewSpinner.stop();
                });

            };

            $scope.start = function () {
                ViewSpinner.spin();
                Container.start({
                    id: $scope.container.Id
                }, {}, function (d) {
                    update();
                    Messages.send("Container started", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to start." + e.data);
                });
            };

            $scope.stop = function () {
                ViewSpinner.spin();
                Container.stop({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container stopped", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to stop." + e.data);
                });
            };

            $scope.kill = function () {
                ViewSpinner.spin();
                Container.kill({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container killed", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to die." + e.data);
                });
            };

            $scope.restartEnv = function () {
                var config = angular.copy($scope.container.Config);

                config.Env = $scope.newCfg.Env.map(function(entry) {
                    return entry.name+"="+entry.value;
                });

                var portBindings = angular.copy($scope.newCfg.Ports);
                angular.forEach(portBindings, function(item, key) {
                    if (item.length === 0) {
                        delete portBindings[key];
                    }
                });

                var binds = [];
                angular.forEach($scope.newCfg.Binds, function(b) {
                    if (b.ContPath !== '') {
                        var bindLine = '';
                        if (b.HostPath !== '') {
                            bindLine = b.HostPath + ':';
                        }
                        bindLine += b.ContPath;
                        if (b.ReadOnly) {
                            bindLine += ':ro';
                        }
                        if (b.HostPath !== '' || !b.DefaultBind) {
                            binds.push(bindLine);
                        }
                    }
                });

                ViewSpinner.spin();
                ContainerCommit.commit({id: $routeParams.id, tag: $scope.container.Config.Image, config: config }, function (d) {
                    if ('Id' in d) {
                        var imageId = d.Id;
                        Image.inspect({id: imageId}, function(imageData) {
                            // Append current host config to image with new port bindings
                            imageData.Config.HostConfig = angular.copy($scope.container.HostConfig);
                            imageData.Config.HostConfig.PortBindings = portBindings;
                            imageData.Config.HostConfig.Binds = binds;
                            if (imageData.Config.HostConfig.NetworkMode === 'host') {
                                imageData.Config.Hostname = '';
                            }

                            Container.create(imageData.Config, function(containerData) {
                                if (!('Id' in containerData)) {
                                    Messages.error("Failure", "Container failed to create.");
                                    return;
                                }
                                // Stop current if running
                                if ($scope.container.State.Running) {
                                    Container.stop({id: $routeParams.id}, function (d) {
                                        Messages.send("Container stopped", $routeParams.id);
                                        // start new
                                        Container.start({
                                            id: containerData.Id
                                        }, function (d) {
                                            $location.url('/containers/' + containerData.Id + '/');
                                            Messages.send("Container started", $routeParams.id);
                                        }, function (e) {
                                            update();
                                            Messages.error("Failure", "Container failed to start." + e.data);
                                        });
                                    }, function (e) {
                                        update();
                                        Messages.error("Failure", "Container failed to stop." + e.data);
                                    });
                                } else {
                                    // start new
                                    Container.start({
                                        id: containerData.Id
                                    }, function (d) {
                                        $location.url('/containers/'+containerData.Id+'/');
                                        Messages.send("Container started", $routeParams.id);
                                    }, function (e) {
                                        update();
                                        Messages.error("Failure", "Container failed to start." + e.data);
                                    });
                                }

                            }, function(e) {
                                update();
                                Messages.error("Failure", "Image failed to get." + e.data);
                            });
                        }, function (e) {
                            update();
                            Messages.error("Failure", "Image failed to get." + e.data);
                        });

                    } else {
                        update();
                        Messages.error("Failure", "Container commit failed.");
                    }

                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to commit." + e.data);
                });
            };

            $scope.commit = function () {
                ViewSpinner.spin();
                ContainerCommit.commit({id: $routeParams.id, repo: $scope.container.Config.Image}, function (d) {
                    update();
                    Messages.send("Container commited", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to commit." + e.data);
                });
            };
            $scope.pause = function () {
                ViewSpinner.spin();
                Container.pause({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container paused", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to pause." + e.data);
                });
            };

            $scope.unpause = function () {
                ViewSpinner.spin();
                Container.unpause({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container unpaused", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to unpause." + e.data);
                });
            };

            $scope.remove = function () {
                ViewSpinner.spin();
                Container.remove({id: $routeParams.id}, function (d) {
                    update();
                    $location.path('/containers');
                    Messages.send("Container removed", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to remove." + e.data);
                });
            };

            $scope.restart = function () {
                ViewSpinner.spin();
                Container.restart({id: $routeParams.id}, function (d) {
                    update();
                    Messages.send("Container restarted", $routeParams.id);
                }, function (e) {
                    update();
                    Messages.error("Failure", "Container failed to restart." + e.data);
                });
            };

            $scope.hasContent = function (data) {
                return data !== null && data !== undefined;
            };

            $scope.getChanges = function () {
                ViewSpinner.spin();
                Container.changes({id: $routeParams.id}, function (d) {
                    $scope.changes = d;
                    ViewSpinner.stop();
                });
            };

            $scope.renameContainer = function () {
                // #FIXME fix me later to handle http status to show the correct error message
                Container.rename({id: $routeParams.id, 'name': $scope.container.newContainerName}, function (data) {
                    if (data.name) {
                        $scope.container.Name = data.name;
                        Messages.send("Container renamed", $routeParams.id);
                    } else {
                        $scope.container.newContainerName = $scope.container.Name;
                        Messages.error("Failure", "Container failed to rename.");
                    }
                });
                $scope.container.edit = false;
            };

            $scope.addEntry = function (array, entry) {
                array.push(entry);
            };
            $scope.rmEntry = function (array, entry) {
                var idx = array.indexOf(entry);
                array.splice(idx, 1);
            };

            $scope.toggleEdit = function() {
                $scope.edit = !$scope.edit;
            };

            update();
            $scope.getChanges();
        }]);
<|endoftext|>


<commit_before>
var CFBundleUnloaded                = 0,
    CFBundleLoading                 = 1 << 0,
    CFBundleLoadingInfoPlist        = 1 << 1,
    CFBundleLoadingExecutable       = 1 << 2,
    CFBundleLoadingSpritedImages    = 1 << 3,
    CFBundleLoaded                  = 1 << 4;

var CFBundlesForPaths   = { },
    CFBundlesForClasses = { },
    CFCacheBuster = new Date().getTime();

function CFBundle(/*String*/ aPath)
{
    aPath = FILE.absolute(aPath);

    var existingBundle = CFBundlesForPaths[aPath];

    if (existingBundle)
        return existingBundle;

    CFBundlesForPaths[aPath] = this;

    this._path = aPath;
    this._name = FILE.basename(aPath);
    this._staticResourceNode = NULL;

    this._loadStatus = CFBundleUnloaded;
    this._loadRequests = [];

    this._infoDictionary = NULL;
    this._URIMap = { };

    this._eventDispatcher = new EventDispatcher(this);
}

CFBundle.bundleContainingPath = function(/*String*/ aPath)
{
    aPath = FILE.absolute(aPath);

    while (aPath !== "/")
    {
        var bundle = CFBundlesForPaths[aPath];

        if (bundle)
            return bundle;

        aPath = FILE.dirname(aPath);
    }

    return NULL;
}

CFBundle.mainBundle = function()
{
    return new CFBundle(FILE.cwd());
}

function addClassToBundle(aClass, aBundle)
{
    if (aBundle)
        CFBundlesForClasses[aClass.name] = aBundle;
}

CFBundle.bundleForClass = function(/*Class*/ aClass)
{
    return CFBundlesForClasses[aClass.name] || CFBundle.mainBundle();
}

CFBundle.prototype.path = function()
{
    return this._path;
}

CFBundle.prototype.infoDictionary = function()
{
    return this._infoDictionary;
}

CFBundle.prototype.valueForInfoDictionary = function(/*String*/ aKey)
{
    return this._infoDictionary.valueForKey(aKey);
}

CFBundle.prototype.resourcesPath = function()
{
    return FILE.join(this.path(), "Resources");
}

CFBundle.prototype.pathForResource = function(/*String*/ aPath)
{
    var mappedPath = this._URIMap[FILE.join("Resources", aPath)];

    if (mappedPath)
        return mappedPath;

    // If not, return the trivial path.
    return FILE.join(this.resourcesPath(), aPath);
}

CFBundle.prototype.executablePath = function()
{
    var executableSubPath = this._infoDictionary.valueForKey("CPBundleExecutable");

    if (executableSubPath)
        return FILE.join(this.path(), this.mostEligibleEnvironment() + ".environment", executableSubPath);

    return NULL;
}

CFBundle.prototype.hasSpritedImages = function()
{
    var environments = this._infoDictionary.valueForKey("CPBundleEnvironmentsWithImageSprites") || [],
        index = environments.length,
        mostEligibleEnvironment = this.mostEligibleEnvironment();

    while (index--)
        if (environments[index] === mostEligibleEnvironment)
            return YES;

    return NO;
}

CFBundle.prototype.environments = function()
{
    return this._infoDictionary.valueForKey("CPBundleEnvironments") || ["ObjJ"];
}

CFBundle.prototype.mostEligibleEnvironment = function(/*Array*/ environments)
{
    environments = environments || this.environments();

    var objj_environments = exports.environments(),
        index = 0,
        count = objj_environments.length,
        innerCount = environments.length;

    // Ugh, no indexOf, no objects-in-common.
    for(; index < count; ++index)
    {
        var innerIndex = 0,
            environment = objj_environments[index];

        for (; innerIndex < innerCount; ++innerIndex)
            if(environment === environments[innerIndex])
                return environment;
    }

    return NULL;
}

CFBundle.prototype.isLoading = function()
{
    return this._loadStatus & CFBundleLoading;
}

CFBundle.prototype.load = function(/*BOOL*/ shouldExecute)
{
    if (this._loadStatus !== CFBundleUnloaded)
        return;

    var self = this;

    self._loadStatus = CFBundleLoading | CFBundleLoadingInfoPlist;

    rootNode.resolveSubPath(FILE.dirname(self.path()), StaticResourceNode.DirectoryType, function(aStaticResourceNode)
    {
        self._staticResourceNode = new StaticResourceNode(FILE.basename(self.path()), aStaticResourceNode, StaticResourceNode.DirectoryType, NO);

        function onsuccess(/*Event*/ anEvent)
        {
            self._loadStatus &= ~CFBundleLoadingInfoPlist;
            self._infoDictionary = anEvent.request.responsePropertyList();

            if (!self._infoDictionary)
            {
                self._eventDispatcher.dispatchEvent(
                {
                    type:"error",
                    error: new Error("Could not load bundle at \"" + self.path() + "\"")
                });

                return;
            }

            loadExecutableAndResources(self, shouldExecute);
        }

        function onfailure()
        {
            self._staticResourceNode._isResolved = YES;
            self._loadStatus = CFBundleUnloaded;
            self._eventDispatcher.dispatchEvent(
            {
                type:"error",
                error: new Error("Could not load bundle at \"" + self.path() + "\"")
            });
        }

        new FileRequest(FILE.join(self.path(), "Info.plist"), onsuccess, onfailure);
    });
}

function loadExecutableAndResources(/*Bundle*/ aBundle, /*BOOL*/ shouldExecute)
{
    if (!aBundle.mostEligibleEnvironment())
        return failure();

    loadExecutableForBundle(aBundle, success, failure);
    loadSpritedImagesForBundle(aBundle, success, failure);

    if (aBundle._loadStatus === CFBundleLoading)
        return success();

    function failure()
    {
        var loadRequests = aBundle._loadRequests,
            count = loadRequests.length;

        while (count--)
            loadRequests[count].abort();

        this._loadRequests = [];

        aBundle._loadStatus = CFBundleUnloaded;

        resolveStaticResourceNode(aBundle._staticResourceNode, NO);

        aBundle._eventDispatcher.dispatchEvent(
        {
            type:"error",
            error:new Error("Could not recognize executable code format in Bundle " + aBundle),
            bundle:aBundle
        });

        resolveStaticResourceNode(aBundle._staticResourceNode, YES);
    }

    function success()
    {
        if (aBundle._loadStatus === CFBundleLoading)
            aBundle._loadStatus = CFBundleLoaded;
        else
            return;

        // Set resolved to true here in case during evaluation this bundle
        // needs to resolve another bundle which in turn needs it to be resolved (cycle).
        resolveStaticResourceNode(aBundle._staticResourceNode, NO);

        function complete()
        {
            aBundle._eventDispatcher.dispatchEvent(
            {
                type:"load",
                bundle:aBundle
            });

            resolveStaticResourceNode(aBundle._staticResourceNode, YES);
        }

        if (shouldExecute)
            executeBundle(aBundle, complete);
        else
            complete();
    }
}

function loadExecutableForBundle(/*Bundle*/ aBundle, success, failure)
{
    if (!aBundle.executablePath())
        return;

    aBundle._loadStatus |= CFBundleLoadingExecutable;

    new FileRequest(aBundle.executablePath(), function(/*Event*/ anEvent)
    {
        try
        {
            decompileStaticFile(aBundle, anEvent.request.responseText())
            aBundle._loadStatus &= ~CFBundleLoadingExecutable;
            success();
        }
        catch(anException)
        {
            failure(anException);
        }
    }, failure);
}

function loadSpritedImagesForBundle(/*Bundle*/ aBundle, success, failure)
{
    if (!aBundle.hasSpritedImages())
        return;

    aBundle._loadStatus |= CFBundleLoadingSpritedImages;

    if (!CFBundleHasTestedSpriteSupport())
        return CFBundleTestSpriteSupport(spritedImagesTestPathForBundle(aBundle), function()
        {
            loadSpritedImagesForBundle(aBundle, success, failure);
        });

    var spritedImagesPath = spritedImagesPathForBundle(aBundle);

    if (!spritedImagesPath)
    {
        aBundle._loadStatus &= ~CFBundleLoadingSpritedImages;
        return success();
    }

    new FileRequest(spritedImagesPath, function(/*Event*/ anEvent)
    {
        try
        {
            decompileStaticFile(aBundle, anEvent.request.responseText());
            aBundle._loadStatus &= ~CFBundleLoadingSpritedImages;
            success();
        }
        catch(anException)
        {
            failure(anException);
        }
    }, failure);
}

var CFBundleSpriteSupportListeners  = [],
    CFBundleSupportedSpriteType     = -1,
    CFBundleNoSpriteType            = 0,
    CFBundleDataURLSpriteType       = 1,
    CFBundleMHTMLSpriteType         = 2,
    CFBundleMHTMLUncachedSpriteType = 3;

function CFBundleHasTestedSpriteSupport()
{
    return CFBundleSupportedSpriteType !== -1;
}

function CFBundleTestSpriteSupport(/*String*/ MHTMLPath, /*Function*/ aCallback)
{
    if (CFBundleHasTestedSpriteSupport())
        return;

    CFBundleSpriteSupportListeners.push(aCallback);

    if (CFBundleSpriteSupportListeners.length > 1)
        return;

    CFBundleTestSpriteTypes([
        CFBundleDataURLSpriteType,
        "data:image/gif;base64,R0lGODlhAQABAIAAAMc9BQAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        CFBundleMHTMLSpriteType,
        MHTMLPath,
        CFBundleMHTMLUncachedSpriteType,
        MHTMLPath+"?"+CFCacheBuster]);
}

function CFBundleNotifySpriteSupportListeners()
{
    var count = CFBundleSpriteSupportListeners.length;

    while (count--)
        CFBundleSpriteSupportListeners[count]();
}

function CFBundleTestSpriteTypes(/*Array*/ spriteTypes)
{
    var image = new Image();

    image.onload = function()
    {
        if (image.width === 1 && image.height === 1)
        {
            CFBundleSupportedSpriteType = spriteTypes[0];
            CFBundleNotifySpriteSupportListeners();
        }
        else
            image.onerror();
    }

    image.onerror = function()
    {
        if (spriteTypes.length === 2)
        {
            CFBundleSupportedSpriteType = CFBundleNoSpriteType;
            CFBundleNotifySpriteSupportListeners();
        }
        else
            CFBundleTestSpriteType(spriteTypes.slice(2));
    }

    image.src = spriteTypes[1];
}

function spritedImagesTestPathForBundle(/*Bundle*/ aBundle)
{
    return FILE.join(aBundle.path(), aBundle.mostEligibleEnvironment() + ".environment", "MHTMLTest.txt");
}

function spritedImagesPathForBundle(/*Bundle*/ aBundle)
{
    if (CFBundleSupportedSpriteType === CFBundleDataURLSpriteType)
        return FILE.join(aBundle.path(), aBundle.mostEligibleEnvironment() + ".environment", "dataURLs.txt");

    if (CFBundleSupportedSpriteType === CFBundleMHTMLSpriteType)
        return FILE.join(aBundle.path(), aBundle.mostEligibleEnvironment() + ".environment", "MHTML.txt");

    if (CFBundleSupportedSpriteType === CFBundleMHTMLUncachedSpriteType)
        return FILE.join(aBundle.path(), aBundle.mostEligibleEnvironment() + ".environment", "MHTML.txt?" + CFCacheBuster);

    return NULL;
}

CFBundle.dataContentsAtPath = function(/*String*/ aPath)
{
    var data = new CFMutableData();

    data.setEncodedString(rootNode.nodeAtSubPath(aPath).contents());

    return data;
}

function executeBundle(/*Bundle*/ aBundle)
{
    var staticResources = [aBundle._staticResourceNode];

    function executeStaticResources(staticResources, index)
    {
        for (; index < staticResources.length; ++index)
        {
            var staticResource = staticResources[index];

            if (staticResource.type() === StaticResourceNode.FileType)
            {
                var executable = new FileExecutable(staticResource.path());

                if (staticResource.hasLoadedFileDependencies())
                    executable.execute();

                else
                {
                    executable.addEventListeners("dependenciesload", function()
                    {
                        executeStaticResources(index);
                    });
                    return;
                }
            }
            else
                staticResources = staticResources.concat(staticResource.children());
        }
    }

    executeStaticResources(0);
}

var STATIC_MAGIC_NUMBER     = "@STATIC",
    MARKER_PATH             = "p",
    MARKER_URI              = "u",
    MARKER_CODE             = "c",
    MARKER_TEXT             = "t",
    MARKER_IMPORT_STD       = 'I',
    MARKER_IMPORT_LOCAL     = 'i';

function decompileStaticFile(/*Bundle*/ aBundle, /*String*/ aString)
{
    var stream = new MarkedStream(aString);

    if (stream.magicNumber() !== STATIC_MAGIC_NUMBER)
        throw new Error("Could not read static file.");

    if (stream.version() !== "1.0")
        throw new Error("Could not read static file.");

    var marker,
        bundlePath = aBundle.path();

    while (marker = stream.getMarker())
    {
        var text = stream.getString();

        if (marker === MARKER_PATH)
        {
            var absolutePath = FILE.join(bundlePath, text),
                parentNode = rootNode.nodeAtSubPath(FILE.dirname(absolutePath), YES);

            fileNode = new StaticResourceNode(FILE.basename(absolutePath), parentNode, StaticResourceNode.FileType, YES);
        }

        else if (marker === MARKER_URI)
        {
            var URI = stream.getString();

            if (URI.toLowerCase().indexOf("mhtml:") === 0)
                URI = "mhtml:" + FILE.join(bundlePath, URI.substr("mhtml:".length));

            aBundle._URIMap[text] = URI;

            // The unresolved directories must not be bundles.
            rootNode.nodeAtSubPath(FILE.join(bundlePath, FILE.dirname(text)), YES);
        }

        else if (marker === MARKER_TEXT)
            fileNode.write(text);
    }
}

// Event Managament

CFBundle.prototype.addEventListener = function(/*String*/ anEventName, /*Function*/ anEventListener)
{
    this._eventDispatcher.addEventListener(anEventName, anEventListener);
}

CFBundle.prototype.removeEventListener = function(/*String*/ anEventName, /*Function*/ anEventListener)
{
    this._eventDispatcher.removeEventListener(anEventName, anEventListener);
}

CFBundle.prototype.onerror = function(/*Event*/ anEvent)
{
    throw anEvent.error;
}

exports.CFBundle = CFBundle;
<commit_msg>Better error reporting.<commit_after>
var CFBundleUnloaded                = 0,
    CFBundleLoading                 = 1 << 0,
    CFBundleLoadingInfoPlist        = 1 << 1,
    CFBundleLoadingExecutable       = 1 << 2,
    CFBundleLoadingSpritedImages    = 1 << 3,
    CFBundleLoaded                  = 1 << 4;

var CFBundlesForPaths   = { },
    CFBundlesForClasses = { },
    CFCacheBuster = new Date().getTime();

function CFBundle(/*String*/ aPath)
{
    aPath = FILE.absolute(aPath);

    var existingBundle = CFBundlesForPaths[aPath];

    if (existingBundle)
        return existingBundle;

    CFBundlesForPaths[aPath] = this;

    this._path = aPath;
    this._name = FILE.basename(aPath);
    this._staticResourceNode = NULL;

    this._loadStatus = CFBundleUnloaded;
    this._loadRequests = [];

    this._infoDictionary = NULL;
    this._URIMap = { };

    this._eventDispatcher = new EventDispatcher(this);
}

CFBundle.bundleContainingPath = function(/*String*/ aPath)
{
    aPath = FILE.absolute(aPath);

    while (aPath !== "/")
    {
        var bundle = CFBundlesForPaths[aPath];

        if (bundle)
            return bundle;

        aPath = FILE.dirname(aPath);
    }

    return NULL;
}

CFBundle.mainBundle = function()
{
    return new CFBundle(FILE.cwd());
}

function addClassToBundle(aClass, aBundle)
{
    if (aBundle)
        CFBundlesForClasses[aClass.name] = aBundle;
}

CFBundle.bundleForClass = function(/*Class*/ aClass)
{
    return CFBundlesForClasses[aClass.name] || CFBundle.mainBundle();
}

CFBundle.prototype.path = function()
{
    return this._path;
}

CFBundle.prototype.infoDictionary = function()
{
    return this._infoDictionary;
}

CFBundle.prototype.valueForInfoDictionary = function(/*String*/ aKey)
{
    return this._infoDictionary.valueForKey(aKey);
}

CFBundle.prototype.resourcesPath = function()
{
    return FILE.join(this.path(), "Resources");
}

CFBundle.prototype.pathForResource = function(/*String*/ aPath)
{
    var mappedPath = this._URIMap[FILE.join("Resources", aPath)];

    if (mappedPath)
        return mappedPath;

    // If not, return the trivial path.
    return FILE.join(this.resourcesPath(), aPath);
}

CFBundle.prototype.executablePath = function()
{
    var executableSubPath = this._infoDictionary.valueForKey("CPBundleExecutable");

    if (executableSubPath)
        return FILE.join(this.path(), this.mostEligibleEnvironment() + ".environment", executableSubPath);

    return NULL;
}

CFBundle.prototype.hasSpritedImages = function()
{
    var environments = this._infoDictionary.valueForKey("CPBundleEnvironmentsWithImageSprites") || [],
        index = environments.length,
        mostEligibleEnvironment = this.mostEligibleEnvironment();

    while (index--)
        if (environments[index] === mostEligibleEnvironment)
            return YES;

    return NO;
}

CFBundle.prototype.environments = function()
{
    return this._infoDictionary.valueForKey("CPBundleEnvironments") || ["ObjJ"];
}

CFBundle.prototype.mostEligibleEnvironment = function(/*Array*/ environments)
{
    environments = environments || this.environments();

    var objj_environments = exports.environments(),
        index = 0,
        count = objj_environments.length,
        innerCount = environments.length;

    // Ugh, no indexOf, no objects-in-common.
    for(; index < count; ++index)
    {
        var innerIndex = 0,
            environment = objj_environments[index];

        for (; innerIndex < innerCount; ++innerIndex)
            if(environment === environments[innerIndex])
                return environment;
    }

    return NULL;
}

CFBundle.prototype.isLoading = function()
{
    return this._loadStatus & CFBundleLoading;
}

CFBundle.prototype.load = function(/*BOOL*/ shouldExecute)
{
    if (this._loadStatus !== CFBundleUnloaded)
        return;

    var self = this;

    self._loadStatus = CFBundleLoading | CFBundleLoadingInfoPlist;

    rootNode.resolveSubPath(FILE.dirname(self.path()), StaticResourceNode.DirectoryType, function(aStaticResourceNode)
    {
        self._staticResourceNode = new StaticResourceNode(FILE.basename(self.path()), aStaticResourceNode, StaticResourceNode.DirectoryType, NO);

        function onsuccess(/*Event*/ anEvent)
        {
            self._loadStatus &= ~CFBundleLoadingInfoPlist;
            self._infoDictionary = anEvent.request.responsePropertyList();

            if (!self._infoDictionary)
            {
                self._eventDispatcher.dispatchEvent(
                {
                    type:"error",
                    error: new Error("Could not load bundle at \"" + self.path() + "\"")
                });

                return;
            }

            loadExecutableAndResources(self, shouldExecute);
        }

        function onfailure()
        {
            self._staticResourceNode._isResolved = YES;
            self._loadStatus = CFBundleUnloaded;
            self._eventDispatcher.dispatchEvent(
            {
                type:"error",
                error: new Error("Could not load bundle at \"" + self.path() + "\"")
            });
        }

        new FileRequest(FILE.join(self.path(), "Info.plist"), onsuccess, onfailure);
    });
}

function loadExecutableAndResources(/*Bundle*/ aBundle, /*BOOL*/ shouldExecute)
{
    if (!aBundle.mostEligibleEnvironment())
        return failure();

    loadExecutableForBundle(aBundle, success, failure);
    loadSpritedImagesForBundle(aBundle, success, failure);

    if (aBundle._loadStatus === CFBundleLoading)
        return success();

    function failure(/*Error*/ anError)
    {
        var loadRequests = aBundle._loadRequests,
            count = loadRequests.length;

        while (count--)
            loadRequests[count].abort();

        this._loadRequests = [];

        aBundle._loadStatus = CFBundleUnloaded;

        resolveStaticResourceNode(aBundle._staticResourceNode, NO);

        aBundle._eventDispatcher.dispatchEvent(
        {
            type:"error",
            error:anError || new Error("Could not recognize executable code format in Bundle " + aBundle),
            bundle:aBundle
        });

        resolveStaticResourceNode(aBundle._staticResourceNode, YES);
    }

    function success()
    {
        if (aBundle._loadStatus === CFBundleLoading)
            aBundle._loadStatus = CFBundleLoaded;
        else
            return;

        // Set resolved to true here in case during evaluation this bundle
        // needs to resolve another bundle which in turn needs it to be resolved (cycle).
        resolveStaticResourceNode(aBundle._staticResourceNode, NO);

        function complete()
        {
            aBundle._eventDispatcher.dispatchEvent(
            {
                type:"load",
                bundle:aBundle
            });

            resolveStaticResourceNode(aBundle._staticResourceNode, YES);
        }

        if (shouldExecute)
            executeBundle(aBundle, complete);
        else
            complete();
    }
}

function loadExecutableForBundle(/*Bundle*/ aBundle, success, failure)
{
    if (!aBundle.executablePath())
        return;

    aBundle._loadStatus |= CFBundleLoadingExecutable;

    new FileRequest(aBundle.executablePath(), function(/*Event*/ anEvent)
    {
        try
        {
            decompileStaticFile(aBundle, anEvent.request.responseText())
            aBundle._loadStatus &= ~CFBundleLoadingExecutable;
            success();
        }
        catch(anException)
        {
            failure(anException);
        }
    }, failure);
}

function loadSpritedImagesForBundle(/*Bundle*/ aBundle, success, failure)
{
    if (!aBundle.hasSpritedImages())
        return;

    aBundle._loadStatus |= CFBundleLoadingSpritedImages;

    if (!CFBundleHasTestedSpriteSupport())
        return CFBundleTestSpriteSupport(spritedImagesTestPathForBundle(aBundle), function()
        {
            loadSpritedImagesForBundle(aBundle, success, failure);
        });

    var spritedImagesPath = spritedImagesPathForBundle(aBundle);

    if (!spritedImagesPath)
    {
        aBundle._loadStatus &= ~CFBundleLoadingSpritedImages;
        return success();
    }

    new FileRequest(spritedImagesPath, function(/*Event*/ anEvent)
    {
        try
        {
            decompileStaticFile(aBundle, anEvent.request.responseText());
            aBundle._loadStatus &= ~CFBundleLoadingSpritedImages;
            success();
        }
        catch(anException)
        {
            failure(anException);
        }
    }, failure);
}

var CFBundleSpriteSupportListeners  = [],
    CFBundleSupportedSpriteType     = -1,
    CFBundleNoSpriteType            = 0,
    CFBundleDataURLSpriteType       = 1,
    CFBundleMHTMLSpriteType         = 2,
    CFBundleMHTMLUncachedSpriteType = 3;

function CFBundleHasTestedSpriteSupport()
{
    return CFBundleSupportedSpriteType !== -1;
}

function CFBundleTestSpriteSupport(/*String*/ MHTMLPath, /*Function*/ aCallback)
{
    if (CFBundleHasTestedSpriteSupport())
        return;

    CFBundleSpriteSupportListeners.push(aCallback);

    if (CFBundleSpriteSupportListeners.length > 1)
        return;

    CFBundleTestSpriteTypes([
        CFBundleDataURLSpriteType,
        "data:image/gif;base64,R0lGODlhAQABAIAAAMc9BQAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==",
        CFBundleMHTMLSpriteType,
        MHTMLPath,
        CFBundleMHTMLUncachedSpriteType,
        MHTMLPath+"?"+CFCacheBuster]);
}

function CFBundleNotifySpriteSupportListeners()
{
    var count = CFBundleSpriteSupportListeners.length;

    while (count--)
        CFBundleSpriteSupportListeners[count]();
}

function CFBundleTestSpriteTypes(/*Array*/ spriteTypes)
{
    var image = new Image();

    image.onload = function()
    {
        if (image.width === 1 && image.height === 1)
        {
            CFBundleSupportedSpriteType = spriteTypes[0];
            CFBundleNotifySpriteSupportListeners();
        }
        else
            image.onerror();
    }

    image.onerror = function()
    {
        if (spriteTypes.length === 2)
        {
            CFBundleSupportedSpriteType = CFBundleNoSpriteType;
            CFBundleNotifySpriteSupportListeners();
        }
        else
            CFBundleTestSpriteType(spriteTypes.slice(2));
    }

    image.src = spriteTypes[1];
}

function spritedImagesTestPathForBundle(/*Bundle*/ aBundle)
{
    return FILE.join(aBundle.path(), aBundle.mostEligibleEnvironment() + ".environment", "MHTMLTest.txt");
}

function spritedImagesPathForBundle(/*Bundle*/ aBundle)
{
    if (CFBundleSupportedSpriteType === CFBundleDataURLSpriteType)
        return FILE.join(aBundle.path(), aBundle.mostEligibleEnvironment() + ".environment", "dataURLs.txt");

    if (CFBundleSupportedSpriteType === CFBundleMHTMLSpriteType)
        return FILE.join(aBundle.path(), aBundle.mostEligibleEnvironment() + ".environment", "MHTML.txt");

    if (CFBundleSupportedSpriteType === CFBundleMHTMLUncachedSpriteType)
        return FILE.join(aBundle.path(), aBundle.mostEligibleEnvironment() + ".environment", "MHTML.txt?" + CFCacheBuster);

    return NULL;
}

CFBundle.dataContentsAtPath = function(/*String*/ aPath)
{
    var data = new CFMutableData();

    data.setEncodedString(rootNode.nodeAtSubPath(aPath).contents());

    return data;
}

function executeBundle(/*Bundle*/ aBundle)
{
    var staticResources = [aBundle._staticResourceNode];

    function executeStaticResources(staticResources, index)
    {
        for (; index < staticResources.length; ++index)
        {
            var staticResource = staticResources[index];

            if (staticResource.type() === StaticResourceNode.FileType)
            {
                var executable = new FileExecutable(staticResource.path());

                if (staticResource.hasLoadedFileDependencies())
                    executable.execute();

                else
                {
                    executable.addEventListeners("dependenciesload", function()
                    {
                        executeStaticResources(index);
                    });
                    return;
                }
            }
            else
                staticResources = staticResources.concat(staticResource.children());
        }
    }

    executeStaticResources(0);
}

var STATIC_MAGIC_NUMBER     = "@STATIC",
    MARKER_PATH             = "p",
    MARKER_URI              = "u",
    MARKER_CODE             = "c",
    MARKER_TEXT             = "t",
    MARKER_IMPORT_STD       = 'I',
    MARKER_IMPORT_LOCAL     = 'i';

function decompileStaticFile(/*Bundle*/ aBundle, /*String*/ aString)
{
    var stream = new MarkedStream(aString);

    if (stream.magicNumber() !== STATIC_MAGIC_NUMBER)
        throw new Error("Could not read static file.");

    if (stream.version() !== "1.0")
        throw new Error("Could not read static file.");

    var marker,
        bundlePath = aBundle.path();

    while (marker = stream.getMarker())
    {
        var text = stream.getString();

        if (marker === MARKER_PATH)
        {
            var absolutePath = FILE.join(bundlePath, text),
                parentNode = rootNode.nodeAtSubPath(FILE.dirname(absolutePath), YES);

            fileNode = new StaticResourceNode(FILE.basename(absolutePath), parentNode, StaticResourceNode.FileType, YES);
        }

        else if (marker === MARKER_URI)
        {
            var URI = stream.getString();

            if (URI.toLowerCase().indexOf("mhtml:") === 0)
                URI = "mhtml:" + FILE.join(bundlePath, URI.substr("mhtml:".length));

            aBundle._URIMap[text] = URI;

            // The unresolved directories must not be bundles.
            rootNode.nodeAtSubPath(FILE.join(bundlePath, FILE.dirname(text)), YES);
        }

        else if (marker === MARKER_TEXT)
            fileNode.write(text);
    }
}

// Event Managament

CFBundle.prototype.addEventListener = function(/*String*/ anEventName, /*Function*/ anEventListener)
{
    this._eventDispatcher.addEventListener(anEventName, anEventListener);
}

CFBundle.prototype.removeEventListener = function(/*String*/ anEventName, /*Function*/ anEventListener)
{
    this._eventDispatcher.removeEventListener(anEventName, anEventListener);
}

CFBundle.prototype.onerror = function(/*Event*/ anEvent)
{
    throw anEvent.error;
}

exports.CFBundle = CFBundle;
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Animeitem = mongoose.model('Animeitem'),
    //uuid = require('node-uuid'),
    multiparty = require('multiparty'),
    fs = require('fs'),
	_ = require('lodash');

/**
 * Upload image.
 */
exports.postImage = function(req, res) {
    var form = new multiparty.Form();
    //console.log(req);
    form.parse(req, function(err, fields, files) {
        var file = files.file[0];
//        console.log(file);
        var contentType = file.headers['content-type'];
        var tmpPath = file.path;
        var extIndex = tmpPath.lastIndexOf('.');
        var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex);

        //uuid for unique filenames.
        //var filename = uuid.v4() + extension;
        var filename = file.originalFilename;
        var destPath = 'public/modules/animeitems/img/' + filename;

        //server-side file type check.
        if (contentType !== 'image/png' && contentType !== 'image/jpeg') {
            fs.unlink(tmpPath);
            return res.status(400).send('File type not supported.');
        }

        fs.rename(tmpPath, destPath, function(err) {
            if (err) {
                return res.status(400).send('Image not saved.');
            }
//            console.log(destPath);
            return res.json(destPath);
        });
    });
};

/**
 * Create a Animeitem
 */
exports.create = function(req, res) {
	var animeitem = new Animeitem(req.body);
	animeitem.user = req.user;

	animeitem.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(animeitem);
		}
	});
};

/**
 * Show the current Animeitem
 */
exports.read = function(req, res) {
	res.jsonp(req.animeitem);
};

/**
 * Update a Animeitem
 */
exports.update = function(req, res) {
	var animeitem = req.animeitem ;

	animeitem = _.extend(animeitem , req.body);
    animeitem.meta.updated = Date.now();

	animeitem.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(animeitem);
		}
	});
};

/**
 * Delete an Animeitem
 */
exports.delete = function(req, res) {
	var animeitem = req.animeitem ;

	animeitem.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(animeitem);
		}
	});
};

/**
 * List of Animeitems
 */
exports.list = function(req, res) {
    var current = [false], all = [true, false],
        status = (req.query.status === '0') ? current : all;

	Animeitem.find({ $or: [ { status: {$in: status } }, { reWatching: true } ] }).sort('-created').populate('user', 'displayName').populate('manga', 'title').exec(function(err, animeitems) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(animeitems);
		}
	});
};

/**
 * History list of anime
 */
exports.history = function(req, res) {
    var latest = req.params.latest;

    Animeitem.find({ latest: { $gte: latest }}).sort('-created')
        .populate('user', 'displayName')
        .populate('manga', 'title')
        .exec(function(err, animeitems) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(animeitems);
		}
	});
};

/**
 * Animeitem middleware
 */
exports.animeitemByID = function(req, res, next, id) {
	Animeitem.findById(id).populate('user', 'displayName').populate('manga', 'title').exec(function(err, animeitem) {
		if (err) return next(err);
		if (! animeitem) return next(new Error('Failed to load Animeitem ' + id));
		var baseUrl = 'C:/Users/Steven/Videos/',
				seriesName = animeitem.title.toLowerCase().replace(/\(.+?\)/g, '').replace(/[^a-z0-9+]+/gi, '-'),
				location = baseUrl + seriesName,
				index = 0;
		fs.readdir(location, function (err, files) {
			animeitem.video.location = location + '/';
			if(files) {
				for(var i = 0, len = files.length; i < len; i++) {
					index = files[i].lastIndexOf('.');
					animeitem.video.files.push({
						file: files[i],
						number: files[i].substring(index - 3, index)
					});
				}
			}
			req.animeitem = animeitem ;
			next();
		});

	});
};

/**
 * Animeitem authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.animeitem.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<commit_msg>fix video with number issue. fix none mp4 issue.<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Animeitem = mongoose.model('Animeitem'),
    //uuid = require('node-uuid'),
    multiparty = require('multiparty'),
    fs = require('fs'),
	_ = require('lodash');

/**
 * Upload image.
 */
exports.postImage = function(req, res) {
    var form = new multiparty.Form();
    //console.log(req);
    form.parse(req, function(err, fields, files) {
        var file = files.file[0];
//        console.log(file);
        var contentType = file.headers['content-type'];
        var tmpPath = file.path;
        var extIndex = tmpPath.lastIndexOf('.');
        var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex);

        //uuid for unique filenames.
        //var filename = uuid.v4() + extension;
        var filename = file.originalFilename;
        var destPath = 'public/modules/animeitems/img/' + filename;

        //server-side file type check.
        if (contentType !== 'image/png' && contentType !== 'image/jpeg') {
            fs.unlink(tmpPath);
            return res.status(400).send('File type not supported.');
        }

        fs.rename(tmpPath, destPath, function(err) {
            if (err) {
                return res.status(400).send('Image not saved.');
            }
//            console.log(destPath);
            return res.json(destPath);
        });
    });
};

/**
 * Create a Animeitem
 */
exports.create = function(req, res) {
	var animeitem = new Animeitem(req.body);
	animeitem.user = req.user;

	animeitem.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(animeitem);
		}
	});
};

/**
 * Show the current Animeitem
 */
exports.read = function(req, res) {
	res.jsonp(req.animeitem);
};

/**
 * Update a Animeitem
 */
exports.update = function(req, res) {
	var animeitem = req.animeitem ;

	animeitem = _.extend(animeitem , req.body);
    animeitem.meta.updated = Date.now();

	animeitem.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(animeitem);
		}
	});
};

/**
 * Delete an Animeitem
 */
exports.delete = function(req, res) {
	var animeitem = req.animeitem ;

	animeitem.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(animeitem);
		}
	});
};

/**
 * List of Animeitems
 */
exports.list = function(req, res) {
    var current = [false], all = [true, false],
        status = (req.query.status === '0') ? current : all;

	Animeitem.find({ $or: [ { status: {$in: status } }, { reWatching: true } ] }).sort('-created').populate('user', 'displayName').populate('manga', 'title').exec(function(err, animeitems) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(animeitems);
		}
	});
};

/**
 * History list of anime
 */
exports.history = function(req, res) {
    var latest = req.params.latest;

    Animeitem.find({ latest: { $gte: latest }}).sort('-created')
        .populate('user', 'displayName')
        .populate('manga', 'title')
        .exec(function(err, animeitems) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(animeitems);
		}
	});
};

/**
 * Animeitem middleware
 */
exports.animeitemByID = function(req, res, next, id) {
	Animeitem.findById(id).populate('user', 'displayName').populate('manga', 'title').exec(function(err, animeitem) {
		if (err) return next(err);
		if (! animeitem) return next(new Error('Failed to load Animeitem ' + id));
		var baseUrl = 'C:/Users/Steven/Videos/',
				seriesName = animeitem.title.toLowerCase().replace(/\(.+?\)/g, '').replace(/[^a-z0-9+]+/gi, '-'),
				location = baseUrl + seriesName,
				index = 0,
				pad = '000';
		fs.readdir(location, function (err, files) {
			animeitem.video.location = location + '/';
			if(files) {
				for(var i = 0, len = files.length; i < len; i++) {
					var file = files[i],
							number = file.substring(index - 3, index);
					if(file.indexOf('.mp4') > -1) {
						index = file.lastIndexOf('.');
						animeitem.video.files.push({
							file: file,
							number: isNaN(number) ? ('000' + i.toString()).substring(i.length) + i : number
						});
					}
				}
			}
			req.animeitem = animeitem ;
			next();
		});

	});
};

/**
 * Animeitem authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.animeitem.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';

import BlankLayout from 'react/components/UI/Layouts/BlankLayout';
import GlobalNavElements from 'react/components/GlobalNavElements';

export default class TopBarLayout extends PureComponent {
  static propTypes = {
    children: PropTypes.node.isRequired,
    scheme: PropTypes.oneOf(['DEFAULT', 'GROUP']),
  }

  static defaultProps = {
    scheme: 'DEFAULT',
  }

  render() {
    const { children, scheme, ...rest } = this.props;

    return (
      <BlankLayout {...rest}>
        <GlobalNavElements />

        {children}
      </BlankLayout>
    );
  }
}
<commit_msg>Passes along scheme<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';

import BlankLayout from 'react/components/UI/Layouts/BlankLayout';
import GlobalNavElements from 'react/components/GlobalNavElements';

export default class TopBarLayout extends PureComponent {
  static propTypes = {
    children: PropTypes.node.isRequired,
    scheme: PropTypes.oneOf(['DEFAULT', 'GROUP']),
  }

  static defaultProps = {
    scheme: 'DEFAULT',
  }

  render() {
    const { children, scheme, ...rest } = this.props;

    return (
      <BlankLayout {...rest}>
        <GlobalNavElements scheme={scheme} />

        {children}
      </BlankLayout>
    );
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Category = mongoose.model('Category'),
	_ = require('lodash');

/**
 * Create a Category
 */
exports.create = function(req, res) {
	var category = new Category(req.body);
//	category.user = req.user;

	category.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(category);
		}
	});
};

/**
 * Show the current Category
 */
exports.read = function(req, res) {
	res.jsonp(req.category);
};

/**
 * Update a Category
 */
exports.update = function(req, res) {
	var category = req.category ;

	category = _.extend(category , req.body);

	category.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(category);
		}
	});
};

/**
 * Delete an Category
 */
exports.delete = function(req, res) {
	var category = req.category ;

	category.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(category);
		}
	});
};

/**
 * List of Categories
 */
exports.list = function(req, res) {
	Category.find().sort('-created').populate('user', 'displayName').exec(function(err, categories) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(categories);
		}
	});
};

/**
 * Category middleware
 */
exports.categoryByID = function(req, res, next, id) {
	Category.findById(id).populate('user', 'displayName').exec(function(err, category) {
		if (err) return next(err);
		if (! category) return next(new Error('Failed to load Category ' + id));
		req.category = category ;
		next();
	});
};

/**
 * Category authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.category.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<commit_msg>[create-pair] Sort categories by name on server side<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	Category = mongoose.model('Category'),
	_ = require('lodash');

/**
 * Create a Category
 */
exports.create = function(req, res) {
	var category = new Category(req.body);
//	category.user = req.user;

	category.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(category);
		}
	});
};

/**
 * Show the current Category
 */
exports.read = function(req, res) {
	res.jsonp(req.category);
};

/**
 * Update a Category
 */
exports.update = function(req, res) {
	var category = req.category ;

	category = _.extend(category , req.body);

	category.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(category);
		}
	});
};

/**
 * Delete an Category
 */
exports.delete = function(req, res) {
	var category = req.category ;

	category.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(category);
		}
	});
};

/**
 * List of Categories
 */
exports.list = function(req, res) {
	Category.find().sort('name').populate('user', 'displayName').exec(function(err, categories) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(categories);
		}
	});
};

/**
 * Category middleware
 */
exports.categoryByID = function(req, res, next, id) {
	Category.findById(id).populate('user', 'displayName').exec(function(err, category) {
		if (err) return next(err);
		if (! category) return next(new Error('Failed to load Category ' + id));
		req.category = category ;
		next();
	});
};

/**
 * Category authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.category.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import contains from 'dom-helpers/query/contains';
import Headline from '../../Headline';
import Icon from '../../Icon';
import css from '../Accordion.css';

const propTypes = {
  onToggle: PropTypes.func,
  label: PropTypes.oneOfType([PropTypes.element, PropTypes.string]).isRequired,
  open: PropTypes.bool,
  id: PropTypes.string,
  displayWhenOpen: PropTypes.element,
  displayWhenClosed: PropTypes.element,
  toggleRef: PropTypes.func,
};

const DefaultAccordionHeader = (props) => {
  let toggleElem = null;
  let labelElem = null;
  let containerElem = null;
  let iconElem = null;

  function handleHeaderClick(e) {
    if (contains(toggleElem, e.target) ||
      e.target === labelElem ||
      e.target === containerElem ||
      e.target === iconElem) {
      const { id, label } = props;
      props.onToggle({ id, label });
      e.stopPropagation();
    }
  }

  function handleKeyPress(e) {
    e.preventDefault();
    if (e.charCode === 13 || e.charCode === 32) { // enter key or space key...
      if (e.target === toggleElem || e.target === labelElem || e.target === containerElem) {
        const { id, label } = props;
        props.onToggle({ id, label });
      }
    }
  }

  const { label, open, displayWhenOpen, displayWhenClosed } = props;

  // Content in the right side of the header
  let headerRight = null;
  const headerRightContent = open ? displayWhenOpen : displayWhenClosed;
  if (headerRightContent) {
    headerRight =
{headerRightContent}
;
  }

  return (

 { containerElem = ref; }} >
      <div className={`${css.header} ${css.default}`}>
        <Headline size="medium" tag="h3">
          <button
            title={open ? 'collapse section' : 'expand section'}
            type="button"
            onClick={handleHeaderClick}
            onKeyPress={handleKeyPress}
            onKeyUp={e => e.preventDefault()}
            ref={(ref) => { props.toggleRef(ref); toggleElem = ref; }}
            className={css.defaultCollapseButton}
          >
            <Icon size="small" icon={props.open ? 'up-caret' : 'down-caret'} ref={(r) => { iconElem = r; }} />

 { labelElem = ref; }}>
              {label}

          </button>
        </Headline>

      { headerRight }

  );
};

DefaultAccordionHeader.propTypes = propTypes;

export default DefaultAccordionHeader;
<commit_msg>Larger icon on DefaultAccordionHeader<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import contains from 'dom-helpers/query/contains';
import Headline from '../../Headline';
import Icon from '../../Icon';
import css from '../Accordion.css';

const propTypes = {
  onToggle: PropTypes.func,
  label: PropTypes.oneOfType([PropTypes.element, PropTypes.string]).isRequired,
  open: PropTypes.bool,
  id: PropTypes.string,
  displayWhenOpen: PropTypes.element,
  displayWhenClosed: PropTypes.element,
  toggleRef: PropTypes.func,
};

const DefaultAccordionHeader = (props) => {
  let toggleElem = null;
  let labelElem = null;
  let containerElem = null;
  let iconElem = null;

  function handleHeaderClick(e) {
    if (contains(toggleElem, e.target) ||
      e.target === labelElem ||
      e.target === containerElem ||
      e.target === iconElem) {
      const { id, label } = props;
      props.onToggle({ id, label });
      e.stopPropagation();
    }
  }

  function handleKeyPress(e) {
    e.preventDefault();
    if (e.charCode === 13 || e.charCode === 32) { // enter key or space key...
      if (e.target === toggleElem || e.target === labelElem || e.target === containerElem) {
        const { id, label } = props;
        props.onToggle({ id, label });
      }
    }
  }

  const { label, open, displayWhenOpen, displayWhenClosed } = props;

  // Content in the right side of the header
  let headerRight = null;
  const headerRightContent = open ? displayWhenOpen : displayWhenClosed;
  if (headerRightContent) {
    headerRight =
{headerRightContent}
;
  }

  return (

 { containerElem = ref; }} >
      <div className={`${css.header} ${css.default}`}>
        <Headline size="medium" tag="h3">
          <button
            title={open ? 'collapse section' : 'expand section'}
            type="button"
            onClick={handleHeaderClick}
            onKeyPress={handleKeyPress}
            onKeyUp={e => e.preventDefault()}
            ref={(ref) => { props.toggleRef(ref); toggleElem = ref; }}
            className={css.defaultCollapseButton}
          >
            <Icon size="medium" icon={props.open ? 'up-caret' : 'down-caret'} ref={(r) => { iconElem = r; }} />

 { labelElem = ref; }}>
              {label}

          </button>
        </Headline>

      { headerRight }

  );
};

DefaultAccordionHeader.propTypes = propTypes;

export default DefaultAccordionHeader;
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  config = require('../../config/config'),
  async = require('async'),
  errorHandler = require('./errors.server.controller'),
  Pressbook = mongoose.model('Pressbook'),
  Pin = mongoose.model('Pin'),
  ImageModel = mongoose.model('Image'),
  pdf = require('html-pdf'),
  fs = require('fs'),
  NodeZip = new require('node-zip'),
  _ = require('lodash');

/**
 * Show the current pressbook
 */
exports.read = function(req, res) {
  res.json(req.pressbook);
};

var getImageLink = function (pressbook) {
  if(pressbook && pressbook.image) {
    return 'http://localhost:' + config.port + '/uploads/' + pressbook.image.filename;
  } else if(pressbook && pressbook.pin) {
    return pressbook.pin.imageLink.replace('237x', '736x');
  }
};
var getSourceUrl = function(pressbook) {
  if(pressbook && pressbook.pin) {
    return 'Source: ' + pressbook.pin.link;
  } else {
    return '';
  }
};

exports.generate = function(req, res) {
  var textTemplate = unescape(req.query.text) || '';

  Pressbook.find({user: req.user}).populate([{path:'image', select:'filename'}, {path:'pin', select:'imageLink link'}]).exec(function(err, pressbooks) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {

      var zip = new NodeZip();
      var html = fs.readFileSync('template.html', 'utf8');
      var options = {
        format: 'A4',
        quality: 100,
      };

      async.forEach(pressbooks, function(pressbook, callback) {
        var textTemplateWithContent = textTemplate
          .replace(/%%placeholder1%%/g, pressbook.placeholder1)
          .replace(/%%placeholder2%%/g, pressbook.placeholder2)
          .replace(/%%placeholder3%%/g, pressbook.placeholder3)
          .replace(/%%placeholder4%%/g, pressbook.placeholder4)
          .replace(/%%sourceUrl%%/g, getSourceUrl(pressbook))
          .trim()
          .replace(/\n|\r/g, '
');

        var htmlWithContent = html
          .replace(/%%imageLink%%/, getImageLink(pressbook))
          .replace(/%%text%%/, textTemplateWithContent);

        pdf.create(htmlWithContent, options).toBuffer(function(err, data) {
          if (err) return console.log(err);
          zip.file('template' + Math.floor(Math.random() * (1000 - 0)) + 0 + '.pdf', data);
          callback();
        });
      }, function(err) {
        var willSendthis = zip.generate({
          base64:false,
          compression:'DEFLATE'
        });

        res.set('Content-Type', 'application/zip');
        res.set('Content-Disposition', 'attachment; filename=pressbook.zip');
        res.set('Content-Length', willSendthis.length);
        res.end(willSendthis, 'binary');
      });
    }
  });
};

/**
 * Update a pressbook
 */
exports.update = function(req, res) {
  var pressbook = req.pressbook;

  pressbook = _.extend(pressbook, req.body);

  pressbook.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      if(pressbook.image) {
        pressbook.populate('image', 'filename', function(err, pressbook) {
          res.json(pressbook);
        });
      } else if (pressbook.pin) {
        pressbook.populate('pin', 'imageLink', function(err, pressbook) {
          res.json(pressbook);
        });
      }
    }
  });
};

/**
 * Delete an pressbook
 */
exports.delete = function(req, res) {
  var pressbook = req.pressbook;

  var relatedAsset = {};
  if(pressbook.image) {
    ImageModel.findById(pressbook.image, function(err, image) {
      relatedAsset = image;
      saveAsset();
    });
  } else if(pressbook.pin) {
    Pin.findById(pressbook.pin, function(err, pin) {
      relatedAsset = pin;
      saveAsset();
    });
  }

  var saveAsset = function() {
    relatedAsset.isInPressbook = false;
    relatedAsset.pressbookID = '';
    console.log('relatedAsset', relatedAsset);
    relatedAsset.save(function(err) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      }
      pressbook.remove(function(err) {
        if (err) {
          return res.status(400).send({
            message: errorHandler.getErrorMessage(err)
          });
        }
        res.json(pressbook);
      });
    });
  };
};

/**
 * List of Pressbooks
 */
exports.list = function(req, res) {
  Pressbook.find({user: req.user}).sort('-created').populate('image', 'filename').populate('pin', 'imageLink').exec(function(err, pressbooks) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(pressbooks);
    }
  });
};

/**
 * Pressbook middleware
 */
exports.pressbookByID = function(req, res, next, id) {
  Pressbook.findById(id).exec(function(err, pressbook) {
    if (err) return next(err);
    if (!pressbook) return next(new Error('Failed to load pressbook ' + id));
    req.pressbook = pressbook;
    next();
  });
};

/**
 * Pressbook authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
  if (req.pressbook.user.toString() !== req.user.id) {
    return res.status(403).send({
      message: 'User is not authorized'
    });
  }
  next();
};
<commit_msg>Fixes long generation time<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  config = require('../../config/config'),
  async = require('async'),
  errorHandler = require('./errors.server.controller'),
  Pressbook = mongoose.model('Pressbook'),
  Pin = mongoose.model('Pin'),
  ImageModel = mongoose.model('Image'),
  pdf = require('html-pdf'),
  fs = require('fs'),
  NodeZip = new require('node-zip'),
  _ = require('lodash');

/**
 * Show the current pressbook
 */
exports.read = function(req, res) {
  res.json(req.pressbook);
};

var getImageLink = function (pressbook) {
  if(pressbook && pressbook.image) {
    return 'http://localhost:' + config.port + '/uploads/' + pressbook.image.filename;
  } else if(pressbook && pressbook.pin) {
    return pressbook.pin.imageLink.replace('237x', '736x');
  }
};
var getSourceUrl = function(pressbook) {
  if(pressbook && pressbook.pin) {
    return 'Source: ' + pressbook.pin.link;
  } else {
    return '';
  }
};

exports.generate = function(req, res) {
  var textTemplate = unescape(req.query.text) || '';

  Pressbook.find({user: req.user}).populate([{path:'image', select:'filename'}, {path:'pin', select:'imageLink link'}]).exec(function(err, pressbooks) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {

      var zip = new NodeZip();
      var html = fs.readFileSync('template.html', 'utf8');
      var options = {
        format: 'A4',
        quality: 100,
        timeout: 300000
      };

      async.forEach(pressbooks, function(pressbook, callback) {
        var textTemplateWithContent = textTemplate
          .replace(/%%placeholder1%%/g, pressbook.placeholder1)
          .replace(/%%placeholder2%%/g, pressbook.placeholder2)
          .replace(/%%placeholder3%%/g, pressbook.placeholder3)
          .replace(/%%placeholder4%%/g, pressbook.placeholder4)
          .replace(/%%sourceUrl%%/g, getSourceUrl(pressbook))
          .trim()
          .replace(/\n|\r/g, '
');

        var htmlWithContent = html
          .replace(/%%imageLink%%/, getImageLink(pressbook))
          .replace(/%%text%%/, textTemplateWithContent);

        pdf.create(htmlWithContent, options).toBuffer(function(err, data) {
          if (err) return console.log(err);
          zip.file('template' + Math.floor(Math.random() * (1000 - 0)) + 0 + '.pdf', data);
          callback();
        });
      }, function(err) {
        var willSendthis = zip.generate({
          base64:false,
          compression:'DEFLATE'
        });

        res.set('Content-Type', 'application/zip');
        res.set('Content-Disposition', 'attachment; filename=pressbook.zip');
        res.set('Content-Length', willSendthis.length);
        res.end(willSendthis, 'binary');
      });
    }
  });
};

/**
 * Update a pressbook
 */
exports.update = function(req, res) {
  var pressbook = req.pressbook;

  pressbook = _.extend(pressbook, req.body);

  pressbook.save(function(err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      if(pressbook.image) {
        pressbook.populate('image', 'filename', function(err, pressbook) {
          res.json(pressbook);
        });
      } else if (pressbook.pin) {
        pressbook.populate('pin', 'imageLink', function(err, pressbook) {
          res.json(pressbook);
        });
      }
    }
  });
};

/**
 * Delete an pressbook
 */
exports.delete = function(req, res) {
  var pressbook = req.pressbook;

  var relatedAsset = {};
  if(pressbook.image) {
    ImageModel.findById(pressbook.image, function(err, image) {
      relatedAsset = image;
      saveAsset();
    });
  } else if(pressbook.pin) {
    Pin.findById(pressbook.pin, function(err, pin) {
      relatedAsset = pin;
      saveAsset();
    });
  }

  var saveAsset = function() {
    relatedAsset.isInPressbook = false;
    relatedAsset.pressbookID = '';
    console.log('relatedAsset', relatedAsset);
    relatedAsset.save(function(err) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      }
      pressbook.remove(function(err) {
        if (err) {
          return res.status(400).send({
            message: errorHandler.getErrorMessage(err)
          });
        }
        res.json(pressbook);
      });
    });
  };
};

/**
 * List of Pressbooks
 */
exports.list = function(req, res) {
  Pressbook.find({user: req.user}).sort('-created').populate('image', 'filename').populate('pin', 'imageLink').exec(function(err, pressbooks) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(pressbooks);
    }
  });
};

/**
 * Pressbook middleware
 */
exports.pressbookByID = function(req, res, next, id) {
  Pressbook.findById(id).exec(function(err, pressbook) {
    if (err) return next(err);
    if (!pressbook) return next(new Error('Failed to load pressbook ' + id));
    req.pressbook = pressbook;
    next();
  });
};

/**
 * Pressbook authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
  if (req.pressbook.user.toString() !== req.user.id) {
    return res.status(403).send({
      message: 'User is not authorized'
    });
  }
  next();
};
<|endoftext|>


<commit_before>function BaseDataSourceBuilder(){};

_.extend(BaseDataSourceBuilder.prototype, {
    build: function (builder, parent, metadata) {
        var dataSource = this.createDataSource(parent);
        dataSource.suspendUpdate();

        this.applyMetadata(builder, parent, metadata, dataSource);

        if(parent.onLoading){
            parent.onLoading(function () {
                dataSource.resumeUpdate();
            });
        }else{
            dataSource.resumeUpdate();
        }

        return dataSource;
    },

    applyMetadata: function(builder, parent, metadata, dataSource){
        var idProperty = metadata.IdProperty;
        if (idProperty) {
            dataSource.setIdProperty(idProperty);
        }

        dataSource.setName(metadata.Name);
        dataSource.setFillCreatedItem(metadata.FillCreatedItem);
        dataSource.setPageSize(metadata.PageSize || 15);
        dataSource.setPageNumber(metadata.PageNumber || null);

        dataSource.setErrorValidator(metadata.ValidationErrors);
        dataSource.setWarningValidator(metadata.ValidationWarnings);

        this.initScriptsHandlers(parent, metadata, dataSource);
    },

    createDataSource: function(parent){
        throw 'BaseDataSourceBuilder.createDataSource В потомке BaseDataSourceBuilder не переопределен метод createDataSource.';
    },

    initScriptsHandlers: function (parent, metadata, dataSource) {
        //Скриптовые обработчики на события
        if (parent && metadata.OnSelectedItemChanged) {
            dataSource.onSelectedItemChanged(function () {
                    new ScriptExecutor(parent).executeScript(metadata.OnSelectedItemChanged.Name);
            });
        }

        if (parent && metadata.OnItemsUpdated) {
            dataSource.onItemsUpdated(function () {
                new ScriptExecutor(parent).executeScript(metadata.OnItemsUpdated.Name);
            });
        }

        if (parent && metadata.OnSelectedItemModified) {
            dataSource.onSelectedItemModified(function () {
                new ScriptExecutor(parent).executeScript(metadata.OnSelectedItemModified.Name);
            });
        }

        if (parent && metadata.OnItemDeleted) {
            dataSource.onItemDeleted(function () {
                new ScriptExecutor(parent).executeScript(metadata.OnItemDeleted.Name);
            });
        }
    }
});<commit_msg>UI-1214: Изменить сигнатуру билдеров новых реализаций источников данных #resolved<commit_after>function BaseDataSourceBuilder(){};

_.extend(BaseDataSourceBuilder.prototype, {
    build: function (context, args) {
        var dataSource = this.createDataSource(args.view);
        dataSource.suspendUpdate();

        this.applyMetadata(args.builder, args.view, args.metadata, dataSource);

        if(args.view.onLoading){
            args.view.onLoading(function () {
                dataSource.resumeUpdate();
            });
        }else{
            dataSource.resumeUpdate();
        }

        return dataSource;
    },

    applyMetadata: function(builder, parent, metadata, dataSource){
        var idProperty = metadata.IdProperty;
        if (idProperty) {
            dataSource.setIdProperty(idProperty);
        }

        dataSource.setName(metadata.Name);
        dataSource.setFillCreatedItem(metadata.FillCreatedItem);
        dataSource.setPageSize(metadata.PageSize || 15);
        dataSource.setPageNumber(metadata.PageNumber || null);

        dataSource.setErrorValidator(metadata.ValidationErrors);
        dataSource.setWarningValidator(metadata.ValidationWarnings);

        this.initScriptsHandlers(parent, metadata, dataSource);
    },

    createDataSource: function(parent){
        throw 'BaseDataSourceBuilder.createDataSource В потомке BaseDataSourceBuilder не переопределен метод createDataSource.';
    },

    initScriptsHandlers: function (parent, metadata, dataSource) {
        //Скриптовые обработчики на события
        if (parent && metadata.OnSelectedItemChanged) {
            dataSource.onSelectedItemChanged(function () {
                    new ScriptExecutor(parent).executeScript(metadata.OnSelectedItemChanged.Name);
            });
        }

        if (parent && metadata.OnItemsUpdated) {
            dataSource.onItemsUpdated(function () {
                new ScriptExecutor(parent).executeScript(metadata.OnItemsUpdated.Name);
            });
        }

        if (parent && metadata.OnSelectedItemModified) {
            dataSource.onSelectedItemModified(function () {
                new ScriptExecutor(parent).executeScript(metadata.OnSelectedItemModified.Name);
            });
        }

        if (parent && metadata.OnItemDeleted) {
            dataSource.onItemDeleted(function () {
                new ScriptExecutor(parent).executeScript(metadata.OnItemDeleted.Name);
            });
        }
    }
});<|endoftext|>


<commit_before>module.exports = function(app) {
  app.controller('ResumeController', ['$scope', '$http', 'crudResource', 'currentResume', function($scope, $http, crudResource, currentResume){
    $scope.resumes = [];
    $scope.errors = [];
    $scope.resume = currentResume();
    // $scope.savedResume = {};
    //need to set default fields?
    $scope.adjustLayoutWidth = function() {
    if ($scope.formAndResume){
      $scope.layoutWidth = 'form-and-resume-layout';
    } else {
      $scope.layoutWidth = 'full-width-centered-layout';
    }
  }
    var defaults = {};
    $scope.newResume = angular.copy($scope.defaults);
    var resumeResource = crudResource('resumes');

    // displays all resumes in database
    $scope.getAll = function() {
      resumeResource.getAll(function (err, data) {
        if (err) return err;

        $scope.resumes = data;
      })
    };

    //adds new resume to database
    $scope.create = function(resumes) {
      resumeResource.create(resumes, function (err, data) {
        if (err) return err;

        console.log(resumes);
        $scope.resumes.push(data);
        $scope.newResume = angular.copy(defaults);
      });
    };

    //updates existing resume in database
    $scope.update = function(resumes) {
      resumes.editing = false;
      resumeResource.update(resumes, function (err, data) {
        if (err) return err;
      });
    };

    //removes existing resume from database
    $scope.remove = function(resumes) {
      $scope.resumes.splice($scope.resumes.indexOf(resumes), 1);
      resumeResource.remove(resumes, function (err, data) {
        if (err) return err;

        console.log('resumes has been removed');
      });
    };

    $scope.isEmpty = function(arrayOfObjects) {
      for(i = 0; i < arrayOfObjects.length; i++) {
        for(key in arrayOfObjects[i]){
          if (arrayOfObjects[i][key]) return false;
        }
      }
      return true;
    }

  }]);
};
<commit_msg>remove unused controller function<commit_after>module.exports = function(app) {
  app.controller('ResumeController', ['$scope', '$http', 'crudResource', 'currentResume', function($scope, $http, crudResource, currentResume){
    $scope.resumes = [];
    $scope.errors = [];
    $scope.resume = currentResume();
    // $scope.savedResume = {};
    //need to set default fields?
    $scope.adjustLayoutWidth = function() {
    if ($scope.formAndResume){
      $scope.layoutWidth = 'form-and-resume-layout';
    } else {
      $scope.layoutWidth = 'full-width-centered-layout';
    }
  }
    var defaults = {};
    $scope.newResume = angular.copy($scope.defaults);
    var resumeResource = crudResource('resumes');

    // displays all resumes in database
    $scope.getAll = function() {
      resumeResource.getAll(function (err, data) {
        if (err) return err;

        $scope.resumes = data;
      })
    };

    //adds new resume to database
    $scope.create = function(resumes) {
      resumeResource.create(resumes, function (err, data) {
        if (err) return err;

        console.log(resumes);
        $scope.resumes.push(data);
        $scope.newResume = angular.copy(defaults);
      });
    };

    //updates existing resume in database
    $scope.update = function(resumes) {
      resumes.editing = false;
      resumeResource.update(resumes, function (err, data) {
        if (err) return err;
      });
    };

    //removes existing resume from database
    $scope.remove = function(resumes) {
      $scope.resumes.splice($scope.resumes.indexOf(resumes), 1);
      resumeResource.remove(resumes, function (err, data) {
        if (err) return err;

        console.log('resumes has been removed');
      });
    };

  }]);
};
<|endoftext|>