<commit_before>import path from 'path'
import xss from 'xss'
import pkg from '../../../package'

import {
  config,
  Page,
  cmsData,
  cmsEditor,
  cmsTemplates,
  coreUtils,
  abeExtend,
  Manager,
  User
} from '../../cli'

import locale from '../helpers/abe-locale'

function renderAbeAdmin(EditorVariables, obj, filePath) {
  var manager = {}

  manager.home = {
    files: [] //Manager.instance.getList()
  }

  manager.nbPosts = Manager.instance.getList().length
  manager.list = Manager.instance.getStructureAndTemplates()
  manager.editConfig = EditorVariables.express.req.app.get('config')
  manager.config = JSON.stringify(config)

  var _preview = filePath
    ? '/abe/page/' +
      EditorVariables.express.req.params[0] +
      `?filePath=${EditorVariables.express.req.query.filePath}`
    : false
  var _form = obj ? obj.form : false
  var _json = obj ? obj.json : false
  var _filePath = filePath ? filePath : false
  if (_filePath) {
    _filePath = '/' + _filePath.replace(/^\/+/, '')
  }

  var pageHtml = ''
  if (
    typeof _json !== 'undefined' &&
    _json !== null &&
    typeof _json.abe_meta !== 'undefined' &&
    _json.abe_meta !== null
  ) {
    var text = cmsTemplates.template.getTemplate(_json.abe_meta.template, _json)
    var page = new Page(text, _json, false)
    pageHtml = page.html
      .replace(/"/g, '"')
      .replace(/'/g, "'")
      .replace(/<!--/g, '<ABE!--')
      .replace(/-->/g, '--ABE>')
  }

  var editorWidth = '25%'
  EditorVariables.express.req.headers &&
    EditorVariables.express.req.headers.cookie &&
    EditorVariables.express.req.headers.cookie
      .split(';')
      .forEach(function(cookie) {
        var parts = cookie.match(/(.*?)=(.*)$/)
        if (
          typeof parts !== 'undefined' &&
          parts !== null &&
          parts.length > 2 &&
          parts[1] === 'editorWidth'
        )
          editorWidth = parts[2]
      })

  EditorVariables.pageHtml = pageHtml
  EditorVariables.test = JSON.stringify(locale)
  EditorVariables.text = locale
  EditorVariables.preview = _preview
  EditorVariables.form = _form
  EditorVariables.json = _json
  EditorVariables.manager = manager
  EditorVariables.editorWidth = editorWidth

  if (_json != null && _json.abe_meta) {
    EditorVariables.workflows = User.utils.getUserWorkflow(
      _json.abe_meta.status
    )
  }

  EditorVariables = abeExtend.hooks.instance.trigger(
    'afterVariables',
    EditorVariables
  )

  if (filePath != null && filePath.indexOf('.json') > -1) {
    EditorVariables.express.res.set('Content-Type', 'application/json')
    EditorVariables.express.res.send(JSON.stringify(_json))
  } else if (EditorVariables.pageHtml != '') {
    EditorVariables.express.res.render(config.abeEngine, EditorVariables)
  } else {
    EditorVariables.express.res.render(
      '../views/template-manager',
      EditorVariables
    )
  }
}

/**
 * This route returns the editor page as HTML
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
var route = function(req, res, next) {
  var filePath = req.originalUrl.replace('/abe/editor', '')
  if (filePath === '' || filePath === '/') {
    filePath = null
  }
  if(filePath != null && path.extname(filePath) != `.${config.files.templates.extension}`){
    next()
    return
  }
  if (filePath != null) {
    var testXSS = xss(filePath, {
      whiteList: [],
      stripIgnoreTag: true
    })
    if (testXSS !== filePath) {
      filePath = testXSS
    }
  }

  abeExtend.hooks.instance.trigger('beforeRoute', req, res, next)
  if (typeof res._header !== 'undefined' && res._header !== null) return

  var isHome = true
  var jsonPath = null
  var template = null
  var fileName = null
  var folderPath = null

  var EditorVariables = {
    user: res.user,
    slugs: Manager.instance.getSlugs(),
    express: {
      res: res,
      req: req
    },
    filename: fileName,
    folderPath: folderPath,
    abeUrl: '/abe/editor/',
    isHome: isHome,
    config: config,
    Locales: coreUtils.locales.instance.i18n,
    abeVersion: pkg.version
  }

  let p = new Promise(resolve => {
    if (filePath != null) {
      fileName = path.basename(filePath)
      folderPath = path.dirname(filePath)

      EditorVariables.isHome = false
      EditorVariables.isEditor = true
      var filePathTest = cmsData.revision.getDocumentRevision(filePath)
      if (typeof filePathTest !== 'undefined' && filePathTest !== null) {
        jsonPath = filePathTest.path
        template = filePathTest.abe_meta.template
      }

      if (jsonPath === null || !coreUtils.file.exist(jsonPath)) {
        res.redirect('/abe/editor')
        return
      }

      var json = {}
      if (coreUtils.file.exist(jsonPath)) {
        json = cmsData.file.get(jsonPath, 'utf8')
      }
      var text = cmsTemplates.template.getTemplate(template, json)
      cmsEditor.editor
        .create(text, json)
        .then(result => {
          resolve(result)
        })
        .catch(function(e) {
          console.error(e)
        })
    } else {
      resolve({
        json: {},
        manager: {}
      })
    }
  }).catch(function(e) {
    console.error(e) // "oh, no!"
  })

  p
    .then(obj => {
      var precontribs = Manager.instance.getPrecontribution()
      var promises = []
      EditorVariables.resultPrecontrib = []
      Array.prototype.forEach.call(precontribs, precontrib => {
        var p = cmsEditor.editor
          .create(precontrib, obj.json, true)
          .then(resultPrecontrib => {
            EditorVariables.resultPrecontrib.push(resultPrecontrib)
          })
          .catch(function(e) {
            console.error(e)
          })
        promises.push(p)
      })
      Promise.all(promises)
        .then(() => {
          renderAbeAdmin(EditorVariables, obj, filePath, isHome, template)
        })
        .catch(function(e) {
          console.error('get-main.js getDataList', e.stack)
        })
    })
    .catch(e => {
      console.log('error', e)
    })
}

export default route
<commit_msg>fix: Editor must be able to display the json version of the post<commit_after>import path from 'path'
import xss from 'xss'
import pkg from '../../../package'

import {
  config,
  Page,
  cmsData,
  cmsEditor,
  cmsTemplates,
  coreUtils,
  abeExtend,
  Manager,
  User
} from '../../cli'

import locale from '../helpers/abe-locale'

function renderAbeAdmin(EditorVariables, obj, filePath) {
  var manager = {}

  manager.home = {
    files: [] //Manager.instance.getList()
  }

  manager.nbPosts = Manager.instance.getList().length
  manager.list = Manager.instance.getStructureAndTemplates()
  manager.editConfig = EditorVariables.express.req.app.get('config')
  manager.config = JSON.stringify(config)

  var _preview = filePath
    ? '/abe/page/' +
      EditorVariables.express.req.params[0] +
      `?filePath=${EditorVariables.express.req.query.filePath}`
    : false
  var _form = obj ? obj.form : false
  var _json = obj ? obj.json : false
  var _filePath = filePath ? filePath : false
  if (_filePath) {
    _filePath = '/' + _filePath.replace(/^\/+/, '')
  }

  var pageHtml = ''
  if (
    typeof _json !== 'undefined' &&
    _json !== null &&
    typeof _json.abe_meta !== 'undefined' &&
    _json.abe_meta !== null
  ) {
    var text = cmsTemplates.template.getTemplate(_json.abe_meta.template, _json)
    var page = new Page(text, _json, false)
    pageHtml = page.html
      .replace(/"/g, '"')
      .replace(/'/g, "'")
      .replace(/<!--/g, '<ABE!--')
      .replace(/-->/g, '--ABE>')
  }

  var editorWidth = '25%'
  EditorVariables.express.req.headers &&
    EditorVariables.express.req.headers.cookie &&
    EditorVariables.express.req.headers.cookie
      .split(';')
      .forEach(function(cookie) {
        var parts = cookie.match(/(.*?)=(.*)$/)
        if (
          typeof parts !== 'undefined' &&
          parts !== null &&
          parts.length > 2 &&
          parts[1] === 'editorWidth'
        )
          editorWidth = parts[2]
      })

  EditorVariables.pageHtml = pageHtml
  EditorVariables.test = JSON.stringify(locale)
  EditorVariables.text = locale
  EditorVariables.preview = _preview
  EditorVariables.form = _form
  EditorVariables.json = _json
  EditorVariables.manager = manager
  EditorVariables.editorWidth = editorWidth

  if (_json != null && _json.abe_meta) {
    EditorVariables.workflows = User.utils.getUserWorkflow(
      _json.abe_meta.status
    )
  }

  EditorVariables = abeExtend.hooks.instance.trigger(
    'afterVariables',
    EditorVariables
  )

  if (filePath != null && filePath.indexOf('.json') > -1) {
    EditorVariables.express.res.set('Content-Type', 'application/json')
    EditorVariables.express.res.send(JSON.stringify(_json))
  } else if (EditorVariables.pageHtml != '') {
    EditorVariables.express.res.render(config.abeEngine, EditorVariables)
  } else {
    EditorVariables.express.res.render(
      '../views/template-manager',
      EditorVariables
    )
  }
}

/**
 * This route returns the editor page as HTML
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
var route = function(req, res, next) {
  var filePath = req.originalUrl.replace('/abe/editor', '')
  if (filePath === '' || filePath === '/') {
    filePath = null
  }
  if(filePath != null &&
    path.extname(filePath) != `.${config.files.templates.extension}` &&
    path.extname(filePath) != '.json'){
    next()
    return
  }
  if (filePath != null) {
    var testXSS = xss(filePath, {
      whiteList: [],
      stripIgnoreTag: true
    })
    if (testXSS !== filePath) {
      filePath = testXSS
    }
  }

  abeExtend.hooks.instance.trigger('beforeRoute', req, res, next)
  if (typeof res._header !== 'undefined' && res._header !== null) return

  var isHome = true
  var jsonPath = null
  var template = null
  var fileName = null
  var folderPath = null

  var EditorVariables = {
    user: res.user,
    slugs: Manager.instance.getSlugs(),
    express: {
      res: res,
      req: req
    },
    filename: fileName,
    folderPath: folderPath,
    abeUrl: '/abe/editor/',
    isHome: isHome,
    config: config,
    Locales: coreUtils.locales.instance.i18n,
    abeVersion: pkg.version
  }

  let p = new Promise(resolve => {
    if (filePath != null) {
      fileName = path.basename(filePath)
      folderPath = path.dirname(filePath)

      EditorVariables.isHome = false
      EditorVariables.isEditor = true
      var filePathTest = cmsData.revision.getDocumentRevision(filePath)
      if (typeof filePathTest !== 'undefined' && filePathTest !== null) {
        jsonPath = filePathTest.path
        template = filePathTest.abe_meta.template
      }

      if (jsonPath === null || !coreUtils.file.exist(jsonPath)) {
        res.redirect('/abe/editor')
        return
      }

      var json = {}
      if (coreUtils.file.exist(jsonPath)) {
        json = cmsData.file.get(jsonPath, 'utf8')
      }
      var text = cmsTemplates.template.getTemplate(template, json)
      cmsEditor.editor
        .create(text, json)
        .then(result => {
          resolve(result)
        })
        .catch(function(e) {
          console.error(e)
        })
    } else {
      resolve({
        json: {},
        manager: {}
      })
    }
  }).catch(function(e) {
    console.error(e) // "oh, no!"
  })

  p
    .then(obj => {
      var precontribs = Manager.instance.getPrecontribution()
      var promises = []
      EditorVariables.resultPrecontrib = []
      Array.prototype.forEach.call(precontribs, precontrib => {
        var p = cmsEditor.editor
          .create(precontrib, obj.json, true)
          .then(resultPrecontrib => {
            EditorVariables.resultPrecontrib.push(resultPrecontrib)
          })
          .catch(function(e) {
            console.error(e)
          })
        promises.push(p)
      })
      Promise.all(promises)
        .then(() => {
          renderAbeAdmin(EditorVariables, obj, filePath, isHome, template)
        })
        .catch(function(e) {
          console.error('get-main.js getDataList', e.stack)
        })
    })
    .catch(e => {
      console.log('error', e)
    })
}

export default route
<|endoftext|>


<commit_before>/* eslint unicorn/filename-case: "off", func-names: "off", camelcase: "off", no-unused-vars: "off" */

module.exports = function (iface) {
    const {mqttPub, mqttSub, mqttStatus, log, newAccessory, Service, Characteristic} = iface;

    /*
    // Required Characteristics
    this.addCharacteristic(Characteristic.SlatType);
    this.addCharacteristic(Characteristic.CurrentSlatState);

    // The value property of CurrentSlatState must be one of the following:
    Characteristic.CurrentSlatState.FIXED = 0;
    Characteristic.CurrentSlatState.JAMMED = 1;
    Characteristic.CurrentSlatState.SWINGING = 2;

    // Optional Characteristics
    this.addOptionalCharacteristic(Characteristic.Name);
    this.addOptionalCharacteristic(Characteristic.CurrentTiltAngle);
    this.addOptionalCharacteristic(Characteristic.TargetTiltAngle);
    this.addOptionalCharacteristic(Characteristic.SwingMode);

    // The value property of SwingMode must be one of the following:
    Characteristic.SwingMode.SWING_DISABLED = 0;
    Characteristic.SwingMode.SWING_ENABLED = 1;
     */

    return function createAccessory_Slat(settings) {
        const slat = newAccessory(settings);

        slat.addService(Service.Slat, settings.name)
            .getCharacteristic(Characteristic.CurrentSlatState)
            .on('set', (value, callback) => {
                log.debug('< hap set', settings.name, 'CurrentSlatState', value);
                log.debug('> mqtt', settings.topic.setActive, value);
                mqttPub(settings.topic.statusCurrentSlatState, value);
                callback();
            });

        const type = settings.config.SlatType || 0;
        log.debug('> hap set', settings.name, 'SlatType', type);
        slat.getService(Service.Slat)
            .setCharacteristic(Characteristic.SlatType, type);

        if (settings.topic.statusCurrentTiltAngle) {
            mqttSub(settings.topic.statusCurrentTiltAngle, val => {
                log.debug('< mqtt', settings.topic.statusCurrentTiltAngle, val);
                const angle = mqttStatus[settings.topic.statusCurrentTiltAngle];
                log.debug('> hap update', settings.name, 'CurrentTiltAngle', angle);
                slat.getService(Service.Valve)
                    .updateCharacteristic(Characteristic.CurrentTiltAngle, angle);
            });
        }

        if (settings.topic.statusTargetTiltAngle) {
            mqttSub(settings.topic.statusTargetTiltAngle, val => {
                log.debug('< mqtt', settings.topic.statusTargetTiltAngle, val);
                const angle = mqttStatus[settings.topic.statusTargetTiltAngle];
                log.debug('> hap update', settings.name, 'TargetTiltAngle', angle);
                slat.getService(Service.Valve)
                    .updateCharacteristic(Characteristic.TargetTiltAngle, angle);
            });
        }

        if (settings.topic.setTargetTiltAngle) {
            slat.addService(Service.Slat, settings.name)
                .getCharacteristic(Characteristic.TargetTiltAngle)
                .on('set', (value, callback) => {
                    log.debug('< hap set', settings.name, 'TargetTiltAngle', value);
                    log.debug('> mqtt', settings.topic.setTargetTiltAngle, value);
                    mqttPub(settings.topic.setTargetTiltAngle, value);
                    callback();
                });
        }

        if (settings.topic.statusSwingMode) {
            mqttSub(settings.topic.statusSwingMode, val => {
                log.debug('< mqtt', settings.topic.statusSwingMode, val);
                const angle = mqttStatus[settings.topic.statusSwingMode];
                log.debug('> hap update', settings.name, 'SwingMode', angle);
                slat.getService(Service.Valve)
                    .updateCharacteristic(Characteristic.SwingMode, angle);
            });
        }

        if (settings.topic.setSwingMode) {
            slat.addService(Service.Slat, settings.name)
                .getCharacteristic(Characteristic.SwingMode)
                .on('set', (value, callback) => {
                    log.debug('< hap set', settings.name, 'SwingMode', value);
                    log.debug('> mqtt', settings.topic.setSwingMode, value);
                    mqttPub(settings.topic.setSwingMode, value);
                    callback();
                });
        }
    };
};
<commit_msg>fix log output<commit_after>/* eslint unicorn/filename-case: "off", func-names: "off", camelcase: "off", no-unused-vars: "off" */

module.exports = function (iface) {
    const {mqttPub, mqttSub, mqttStatus, log, newAccessory, Service, Characteristic} = iface;

    /*
    // Required Characteristics
    this.addCharacteristic(Characteristic.SlatType);
    this.addCharacteristic(Characteristic.CurrentSlatState);

    // The value property of CurrentSlatState must be one of the following:
    Characteristic.CurrentSlatState.FIXED = 0;
    Characteristic.CurrentSlatState.JAMMED = 1;
    Characteristic.CurrentSlatState.SWINGING = 2;

    // Optional Characteristics
    this.addOptionalCharacteristic(Characteristic.Name);
    this.addOptionalCharacteristic(Characteristic.CurrentTiltAngle);
    this.addOptionalCharacteristic(Characteristic.TargetTiltAngle);
    this.addOptionalCharacteristic(Characteristic.SwingMode);

    // The value property of SwingMode must be one of the following:
    Characteristic.SwingMode.SWING_DISABLED = 0;
    Characteristic.SwingMode.SWING_ENABLED = 1;
     */

    return function createAccessory_Slat(settings) {
        const slat = newAccessory(settings);

        slat.addService(Service.Slat, settings.name)
            .getCharacteristic(Characteristic.CurrentSlatState)
            .on('set', (value, callback) => {
                log.debug('< hap set', settings.name, 'CurrentSlatState', value);
                log.debug('> mqtt', settings.topic.statusCurrentSlatState, value);
                mqttPub(settings.topic.statusCurrentSlatState, value);
                callback();
            });

        const type = settings.config.SlatType || 0;
        log.debug('> hap set', settings.name, 'SlatType', type);
        slat.getService(Service.Slat)
            .setCharacteristic(Characteristic.SlatType, type);

        if (settings.topic.statusCurrentTiltAngle) {
            mqttSub(settings.topic.statusCurrentTiltAngle, val => {
                log.debug('< mqtt', settings.topic.statusCurrentTiltAngle, val);
                const angle = mqttStatus[settings.topic.statusCurrentTiltAngle];
                log.debug('> hap update', settings.name, 'CurrentTiltAngle', angle);
                slat.getService(Service.Valve)
                    .updateCharacteristic(Characteristic.CurrentTiltAngle, angle);
            });
        }

        if (settings.topic.statusTargetTiltAngle) {
            mqttSub(settings.topic.statusTargetTiltAngle, val => {
                log.debug('< mqtt', settings.topic.statusTargetTiltAngle, val);
                const angle = mqttStatus[settings.topic.statusTargetTiltAngle];
                log.debug('> hap update', settings.name, 'TargetTiltAngle', angle);
                slat.getService(Service.Valve)
                    .updateCharacteristic(Characteristic.TargetTiltAngle, angle);
            });
        }

        if (settings.topic.setTargetTiltAngle) {
            slat.addService(Service.Slat, settings.name)
                .getCharacteristic(Characteristic.TargetTiltAngle)
                .on('set', (value, callback) => {
                    log.debug('< hap set', settings.name, 'TargetTiltAngle', value);
                    log.debug('> mqtt', settings.topic.setTargetTiltAngle, value);
                    mqttPub(settings.topic.setTargetTiltAngle, value);
                    callback();
                });
        }

        if (settings.topic.statusSwingMode) {
            mqttSub(settings.topic.statusSwingMode, val => {
                log.debug('< mqtt', settings.topic.statusSwingMode, val);
                const angle = mqttStatus[settings.topic.statusSwingMode];
                log.debug('> hap update', settings.name, 'SwingMode', angle);
                slat.getService(Service.Valve)
                    .updateCharacteristic(Characteristic.SwingMode, angle);
            });
        }

        if (settings.topic.setSwingMode) {
            slat.addService(Service.Slat, settings.name)
                .getCharacteristic(Characteristic.SwingMode)
                .on('set', (value, callback) => {
                    log.debug('< hap set', settings.name, 'SwingMode', value);
                    log.debug('> mqtt', settings.topic.setSwingMode, value);
                    mqttPub(settings.topic.setSwingMode, value);
                    callback();
                });
        }
    };
};
<|endoftext|>


<commit_before>(function () {

    angular.module('foodGenerator')
        .service('supermarkets', supermarketService);

    function supermarketService(BASEURL, $http) {

        this.getAll = getAll;

        ////////////////

        function getAll() {
            return $http.get(BASEURL + '/supermarkets');
        }

    }

})();
<commit_msg>updated supermarket service to use $resource class<commit_after>(function () {

    angular.module('foodGenerator')
        .factory('Supermarket', function(BASEURL, $resource) {
            return $resource(BASEURL + '/supermarkets/:id');
        });

})();
<|endoftext|>


<commit_before>define('app/models/machine', ['ember'],
    /**
     * Machine model
     *
     * Also check state mapping in config.py
     * @returns Class
     */
    function() {
        return Ember.Object.extend({
            id: null,

            imageId: null,

            image: null,
            name: null,
            backend: null,
            selected: false,
            hasKey: false,
            hasMonitoring: false,
            state: 'stopped',

            reboot: function(){
                log('Rebooting machine', this.name);

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=reboot',
                    success: function(data) {
                        that.set('state', 'rebooting');
                        info('Succesfully sent reboot to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending reboot to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending reboot to machine',
                                that.name);
                    }
                });
            },

            destroy: function(){
                log('Destroying machine', this.name);

                var that = this
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=destroy',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent destroy to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending destroy to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending destroy to machine',
                                that.name);
                    }
                });
            },

            start: function(){
                log('Starting machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=start',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent start to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending start to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending start to machine',
                                that.name);
                    }
                });
            },

            shutdown: function(){
                log('Stopping machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=stop',
                    success: function(data) {
                        that.set('state', 'stopped');
                        info('Successfully sent stop to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending stop to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending stop to machine',
                                that.name);
                    }
                });
            },

            shell: function(shell_command, callback){
                log('Sending', shell_command, 'to machine', this.name);

                var host;
                if (this.extra.dns_name) {
                    // it is an ec2 machine so it has dns_name
                    host = this.extra.dns_name;
                } else {
                    // if not in ec2, it should have a public ip
                    host = this.public_ips[0];
                }

                // In case of ec2, mist.io could have set this. Server can handle empty string.
                var ssh_user;
                try {
                    ssh_user = this.extra.tags.ssh_user;
                } catch (error) {
                    ssh_user = 'root';
                }

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                    type: 'POST',
                    data: {'host': host,
                           'ssh_user': ssh_user,
                           'command': shell_command},
                    success: function(data) {
                        if (data){
                            callback(data);
                        }
                        info('Successfully sent shell command', shell_command, 'to machine',
                                that.name, 'with result:\n', data);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error sending shell command ' +
                                shell_command + ' to machine ' + that.name);
                        error(textstate, errorThrown, 'when sending shell command',
                                shell_command, 'to machine', that.name);
                    }
                });

            },

            hasAlert : function(){
                //TODO when we have alerts
                return false;
            }.property('hasAlert'),

            startUptimeTimer: function() {
                var that = this;

                setInterval(function() {
                    if (that.get('state' == 'running') && that.get('uptimeFromServer') &&
                        that.get('uptimeChecked')) {

                        that.set('uptime', that.get('uptimeFromServer') + (Date.now()
                                           - that.get('uptimeChecked')));
                    } else {
                        return;
                    }
                }, 1000);
            },

            checkUptime: function(){
                if (this.state == 'running') {
                    var host;
                    if (this.extra.dns_name) {
                        // it is ec2 machine
                        host = this.extra.dns_name;
                    } else {
                        // if not ec2 it should have a public ip
                        host = this.public_ips[0];
                    }

                    // In case of ec2, mist.io could have set this. Server can handle empty string.
                    var ssh_user;
                    try {
                        ssh_user = this.extra.tags.ssh_user;
                    } catch (error) {
                        ssh_user = 'root';
                    }

                    var that = this;
                    $.ajax({
                        url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                        type: 'POST',
                        data: {'host': host,
                               'ssh_user': ssh_user,
                               'command': 'cat /proc/uptime'},
                        success: function(data) {
                            // also means in has a key
                            that.set('hasKey', true);
                            var resp = data.split(' ');
                            if (resp.length == 2) {
                                var uptime = parseFloat(resp[0]) * 1000;
                                that.set('uptimeChecked', Date.now());
                                that.set('uptimeFromServer', uptime);
                            }
                            info('Successfully got uptime', data, 'from machine', that.name);
                        },
                        error: function(jqXHR, textstate, errorThrown) {
                            that.set('hasKey', false);
                            Mist.notificationController.notify('Error getting uptime from machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'when getting uptime from machine',
                                    that.name);
                        }
                    });
                }
            },

            checkHasMonitoring: function(){
                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    success: function(data) {
                        log("machine has monitoring");
                        log(data);
                        if('monitoring' in data){
                            that.set('hasMonitoring', data.monitoring);
                        }
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                            Mist.notificationController.notify('Error checking monitoring of machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'while checking monitoring of machine',
                                    that.name);
                    }
                });
            },

            resetUptime: function() {
                if (this.state == 'running') {
                    this.startUptimeTimer();
                    this.checkUptime();
                } else {
                    this.set('uptime', 0);
                    this.uptimeTimer = false;
                }
            }.observes('state'),

            monitoringChanged: function(){
                var oldValue = !this.hasMonitoring;
                log("monitoring:  " + oldValue);

                var that = this;

                var host;
                if (this.extra.dns_name) {
                    // it is ec2 machine
                    host = this.extra.dns_name;
                } else {
                    // if not ec2 it should have a public ip
                    host = this.public_ips[0];
                }

                var payload = {
                   'monitoring': this.hasMonitoring,
                   'host': host,
                   'provider': this.backend.provider
                };

                $.ajax({
                    // TODO: this should point to https://mist.io/....
                    url: 'backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(payload),
                    dataType: 'json',
                    success: function(data) {

                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        that.set('hasMonitoring', oldValue);
                    }
                });
            }.observes('hasMonitoring'),

            init: function() {
                this._super();
                var that = this;
                this.backend.images.getImage(this.imageId, function(image) {
                    that.set('image', image);
                });
                this.startUptimeTimer();
                this.checkUptime();
                this.checkHasMonitoring();
            }

        });
    }
);
<commit_msg>Fix state checking before setting uptime value.<commit_after>define('app/models/machine', ['ember'],
    /**
     * Machine model
     *
     * Also check state mapping in config.py
     * @returns Class
     */
    function() {
        return Ember.Object.extend({
            id: null,

            imageId: null,

            image: null,
            name: null,
            backend: null,
            selected: false,
            hasKey: false,
            hasMonitoring: false,
            state: 'stopped',

            reboot: function(){
                log('Rebooting machine', this.name);

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=reboot',
                    success: function(data) {
                        that.set('state', 'rebooting');
                        info('Succesfully sent reboot to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending reboot to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending reboot to machine',
                                that.name);
                    }
                });
            },

            destroy: function(){
                log('Destroying machine', this.name);

                var that = this
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=destroy',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent destroy to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending destroy to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending destroy to machine',
                                that.name);
                    }
                });
            },

            start: function(){
                log('Starting machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=start',
                    success: function(data) {
                        that.set('state', 'pending');
                        info('Successfully sent start to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending start to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending start to machine',
                                that.name);
                    }
                });
            },

            shutdown: function(){
                log('Stopping machine', this.name);

                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id,
                    type: 'POST',
                    data: 'action=stop',
                    success: function(data) {
                        that.set('state', 'stopped');
                        info('Successfully sent stop to machine', that.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error when sending stop to machine ' +
                                that.name);
                        error(textstate, errorThrown, 'when sending stop to machine',
                                that.name);
                    }
                });
            },

            shell: function(shell_command, callback){
                log('Sending', shell_command, 'to machine', this.name);

                var host;
                if (this.extra.dns_name) {
                    // it is an ec2 machine so it has dns_name
                    host = this.extra.dns_name;
                } else {
                    // if not in ec2, it should have a public ip
                    host = this.public_ips[0];
                }

                // In case of ec2, mist.io could have set this. Server can handle empty string.
                var ssh_user;
                try {
                    ssh_user = this.extra.tags.ssh_user;
                } catch (error) {
                    ssh_user = 'root';
                }

                var that = this;
                $.ajax({
                    url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                    type: 'POST',
                    data: {'host': host,
                           'ssh_user': ssh_user,
                           'command': shell_command},
                    success: function(data) {
                        if (data){
                            callback(data);
                        }
                        info('Successfully sent shell command', shell_command, 'to machine',
                                that.name, 'with result:\n', data);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error sending shell command ' +
                                shell_command + ' to machine ' + that.name);
                        error(textstate, errorThrown, 'when sending shell command',
                                shell_command, 'to machine', that.name);
                    }
                });

            },

            hasAlert : function(){
                //TODO when we have alerts
                return false;
            }.property('hasAlert'),

            startUptimeTimer: function() {
                var that = this;

                setInterval(function() {
                    if (that.get('state') == 'running' && that.get('uptimeFromServer') &&
                        that.get('uptimeChecked')) {

                        that.set('uptime', that.get('uptimeFromServer') + (Date.now()
                                           - that.get('uptimeChecked')));
                    } else {
                        return;
                    }
                }, 1000);
            },

            checkUptime: function(){
                if (this.state == 'running') {
                    var host;
                    if (this.extra.dns_name) {
                        // it is ec2 machine
                        host = this.extra.dns_name;
                    } else {
                        // if not ec2 it should have a public ip
                        host = this.public_ips[0];
                    }

                    // In case of ec2, mist.io could have set this. Server can handle empty string.
                    var ssh_user;
                    try {
                        ssh_user = this.extra.tags.ssh_user;
                    } catch (error) {
                        ssh_user = 'root';
                    }

                    var that = this;
                    $.ajax({
                        url: '/backends/' + this.backend.index + '/machines/' + this.id + '/shell',
                        type: 'POST',
                        data: {'host': host,
                               'ssh_user': ssh_user,
                               'command': 'cat /proc/uptime'},
                        success: function(data) {
                            // also means in has a key
                            that.set('hasKey', true);
                            var resp = data.split(' ');
                            if (resp.length == 2) {
                                var uptime = parseFloat(resp[0]) * 1000;
                                that.set('uptimeChecked', Date.now());
                                that.set('uptimeFromServer', uptime);
                            }
                            info('Successfully got uptime', data, 'from machine', that.name);
                        },
                        error: function(jqXHR, textstate, errorThrown) {
                            that.set('hasKey', false);
                            error(textstate);
                            Mist.notificationController.notify('Error getting uptime from machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'when getting uptime from machine',
                                    that.name);
                        }
                    });
                }
            },

            checkHasMonitoring: function(){
                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    success: function(data) {
                        log("machine has monitoring");
                        log(data);
                        if('monitoring' in data){
                            that.set('hasMonitoring', data.monitoring);
                        }
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                            Mist.notificationController.notify('Error checking monitoring of machine ' +
                                    that.name);
                            error(textstate, errorThrown, 'while checking monitoring of machine',
                                    that.name);
                    }
                });
            },

            resetUptime: function() {
                if (this.get('state') == 'running') {
                    this.startUptimeTimer();
                    this.checkUptime();
                } else {
                    this.set('uptime', 0);
                    this.uptimeTimer = false;
                }
            }.observes('state'),

            monitoringChanged: function(){
                var oldValue = !this.hasMonitoring;
                log("monitoring:  " + oldValue);

                var that = this;

                var host;
                if (this.extra.dns_name) {
                    // it is ec2 machine
                    host = this.extra.dns_name;
                } else {
                    // if not ec2 it should have a public ip
                    host = this.public_ips[0];
                }

                var payload = {
                   'monitoring': this.hasMonitoring,
                   'host': host,
                   'provider': this.backend.provider
                };

                $.ajax({
                    // TODO: this should point to https://mist.io/....
                    url: 'backends/' + this.backend.index + '/machines/' + this.id + '/monitoring',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(payload),
                    dataType: 'json',
                    success: function(data) {

                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        that.set('hasMonitoring', oldValue);
                    }
                });
            }.observes('hasMonitoring'),

            init: function() {
                this._super();
                var that = this;
                this.backend.images.getImage(this.imageId, function(image) {
                    that.set('image', image);
                });
                this.startUptimeTimer();
                this.checkUptime();
                this.checkHasMonitoring();
            }

        });
    }
);
<|endoftext|>


<commit_before>(function() {
  angular.module('ncsaas')
    .controller('ProjectUsersTabController', [
      '$stateParams',
      'projectsService',
      'projectPermissionsService',
      'USERPROJECTROLE',
      'usersService',
      'baseControllerClass',
      'currentStateService',
      ProjectUsersTabController
    ]);

  function ProjectUsersTabController(
    $stateParams, projectsService, projectPermissionsService, USERPROJECTROLE, usersService, baseControllerClass,
    currentStateService) {
    var controllerScope = this;
    var Controller = baseControllerClass.extend({
      users: {}, // users with role in project
      usersListForAutoComplete: [],
      user: null,
      project: null,
      checkQuotas: 'user',

      init: function() {
        this.blockUIElement = 'tab-content';
        this._super();
        this.adminRole = USERPROJECTROLE.admin;
        this.managerRole = USERPROJECTROLE.manager;
        this.users[this.adminRole] = [];
        this.users[this.managerRole] = [];
        this.activate();
      },
      activate: function() {
        var vm = this;

        if ($stateParams.uuid) {
          projectsService.$get($stateParams.uuid).then(function(response) {
            vm.project = response;
            vm.getUsers();
          });
        } else {
          currentStateService.getProject().then(function(response) {
            vm.project = response;
            vm.getUsers();
          });
        }

        this.getUserListForAutoComplete();
      },
      getUsers: function() {
        this.getUsersForProject(this.adminRole);
        this.getUsersForProject(this.managerRole);
      },
      getUserListForAutoComplete: function(filter) {
        var vm = this;
        filter = filter || {};
        filter['DONTBLOCK'] = 1;
        usersService.getList(filter).then(function(response) {
          vm.usersListForAutoComplete = response;
        });
      },
      getUsersForProject: function(role) {
        var vm = this;
        var filter = {
          role: role,
          project: vm.project.uuid
        };
        projectPermissionsService.getList(filter).then(function(response) {
          vm.users[role] = response;
        });
      },
      userSearchInputChanged: function(searchText) {
        controllerScope.getUserListForAutoComplete({full_name: searchText});
      },
      selectedUsersCallback: function(selected) {
        if (selected) {
          controllerScope.user = selected.originalObject;
          controllerScope.addUser(this.id);
          controllerScope.getUserListForAutoComplete();
        }
      },
      addUser: function(role) {
        var vm = this;
        var instance = projectPermissionsService.$create();
        instance.user = vm.user.url;
        instance.project = vm.project.url;
        instance.role = role;
        instance.$save(
          function() {
            vm.getUsersForProject(role);
          },
          function(response) {
            alert(response.data.non_field_errors);
          }
        );
      },
      userProjectRemove: function(userProject) {
        var vm = this;
        var role = userProject.role;
        var index = vm.users[role].indexOf(userProject);
        var confirmDelete = confirm('Confirm user deletion?');
        if (confirmDelete) {
          projectPermissionsService.$delete(userProject.pk).then(
            function() {
              vm.users[role].splice(index, 1);
            },
            function(response) {
              alert(response.data.detail);
            }
          );
        } else {
          alert('User was not deleted.');
        }
      }
    });

    controllerScope.__proto__ = new Controller();
  }

})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectEventTabController', [
      '$stateParams',
      'projectsService',
      'baseEventListController',
      'currentStateService',
      ProjectEventTabController
    ]);

  function ProjectEventTabController($stateParams, projectsService, baseEventListController, currentStateService) {
    var controllerScope = this;
    var EventController = baseEventListController.extend({
      project: null,

      init: function() {
        this.controllerScope = controllerScope;
        this.blockUIElement = 'tab-content';
        this._super();
        this.getProject();
      },
      getList: function(filter) {
        if (this.project) {
          this.service.defaultFilter.scope = this.project.url;
          return this._super(filter);
        } else {
          return this.getProject();
        }
      },
      getProject: function() {
        var vm = this;
        if ($stateParams.uuid) {
          return projectsService.$get($stateParams.uuid).then(function(response) {
            vm.project = response;
            return vm.getList();
          });
        } else {
          return currentStateService.getProject().then(function(response) {
            vm.project = response;
            return vm.getList();
          });
        }
      }
    });

    controllerScope.__proto__ = new EventController();
  }

})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectAlertTabController', [
      'BaseAlertsListController',
      'currentStateService',
      ProjectAlertTabController
    ]);

  function ProjectAlertTabController(
    BaseAlertsListController,
    currentStateService
  ) {
    var controllerScope = this;
    var AlertController = BaseAlertsListController.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.blockUIElement = 'tab-content';
        this._super();
      },
      getList: function(filter) {
        var getList = this._super.bind(controllerScope),
          vm = this;
        this.service.defaultFilter.aggregate = 'project';
        this.service.defaultFilter.opened = true;
        return currentStateService.getProject().then(function(response) {
          vm.service.defaultFilter.uuid = response.uuid;
          return getList(filter);
        });
      }
    });

    controllerScope.__proto__ = new AlertController();
  }

})();

(function() {
  angular.module('ncsaas')
    .service('BaseProjectResourcesTabController', [
      'baseResourceListController', 'currentStateService', BaseProjectResourcesTabController]);

  function BaseProjectResourcesTabController(baseResourceListController, currentStateService) {
    var controllerClass = baseResourceListController.extend({
      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        return currentStateService.getProject().then(function(project){
          vm.service.defaultFilter.project_uuid = project.uuid;
          return fn(filter);
        })
      }
    });
    return controllerClass;
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectResourcesTabController', [
      'BaseProjectResourcesTabController',
      'ENV',
      ProjectResourcesTabController
    ]);

  function ProjectResourcesTabController(BaseProjectResourcesTabController, ENV) {
    var controllerScope = this;
    var ResourceController = BaseProjectResourcesTabController.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.category = ENV.VirtualMachines;
        this._super();
        this.entityOptions.entityData.noMatchesText = 'No VMs found matching filter.';
      }
    });
    controllerScope.__proto__ = new ResourceController();
  }
})();

(function() {

  angular.module('ncsaas')
    .controller('ProjectApplicationsTabController', [
      'BaseProjectResourcesTabController', 'ENV',
      ProjectApplicationsTabController]);

  function ProjectApplicationsTabController(BaseProjectResourcesTabController, ENV) {
    var controllerScope = this;
    var ResourceController = BaseProjectResourcesTabController.extend({
      init:function() {
        this.controllerScope = controllerScope;
        this.category = ENV.Applications;
        this._super();

        this.entityOptions.entityData.noDataText = 'You have no applications yet';
        this.entityOptions.entityData.createLinkText = 'Create application';
        this.entityOptions.entityData.importLinkText = 'Import application';
        this.entityOptions.entityData.noMatchesText = 'No applications found matching filter.';
      }
    });
    controllerScope.__proto__ = new ResourceController();
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectServicesTabController',
    ['baseControllerListClass',
      'joinServiceProjectLinkService',
      'joinService',
      'currentStateService',
      'ENTITYLISTFIELDTYPES',
      '$rootScope',
      ProjectServicesTabController]);

  function ProjectServicesTabController(
    baseControllerListClass,
    joinServiceProjectLinkService,
    joinService,
    currentStateService,
    ENTITYLISTFIELDTYPES,
    $rootScope) {
    var controllerScope = this;
    var ServiceController = baseControllerListClass.extend({
      init: function() {
        this.service = joinService;
        this.service.defaultFilter.project_uuid = currentStateService.getProjectUuid();
        this.controllerScope = controllerScope;
        this.blockUIElement = 'tab-content';
        this._super();
        this.actionButtonsListItems = [
          {
            title: 'Remove',
            clickFunction: this.remove.bind(controllerScope),

            isDisabled: function(service) {
              return service.shared || service.resources_count > 0;
            }.bind(this.controllerScope),

            tooltip: function(service) {
              if (service.shared) {
                return 'You cannot remove shared provider';
              }
              if (service.resources_count) {
                return 'Provider has resources. Remove them first';
              }
            }.bind(this.controllerScope)
          }
        ];
        this.entityOptions = {
          entityData: {
            noDataText: 'No providers yet',
            createLink: 'services.create',
            createLinkText: 'Create provider',
            checkQuotas: 'service'
          },
          list: [
            {
              type: ENTITYLISTFIELDTYPES.statusCircle,
              className: 'statusCircle',
              propertyName: 'state',
              onlineStatus: 'In Sync'
            },
            {
              name: 'Name',
              propertyName: 'name',
              type: ENTITYLISTFIELDTYPES.name,
              link: 'organizations.details({uuid: "' + currentStateService.getCustomerUuid()
              + '", providerType: entity.service_type, providerUuid: entity.uuid, tab: "providers"})',
              className: 'name',
              showForMobile: true
            },
            {
              name: 'Type',
              propertyName: 'service_type',
              type: ENTITYLISTFIELDTYPES.noType
            },
            {
              name: 'Resources',
              propertyName: 'resources_count',
              emptyText: '0'
            }
          ]
        };
      },
      getList: function(filter) {
        return this._super(filter);
      },
      removeInstance: function(model) {
        return joinServiceProjectLinkService.$deleteByUrl(model.url);
      },
      afterInstanceRemove: function(instance) {
        $rootScope.$broadcast('refreshProjectList');
        this._super(instance);
      }
    });

    controllerScope.__proto__ = new ServiceController();
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectSupportTabController', [
      'baseControllerListClass',
      'premiumSupportContractsService',
      'premiumSupportPlansService',
      'currentStateService',
      'ENTITYLISTFIELDTYPES',
      'ENV',
      '$filter',
      '$stateParams',
      'ncUtils',
      ProjectSupportTabController
    ]);

  function ProjectSupportTabController(
    baseControllerListClass,
    premiumSupportContractsService,
    premiumSupportPlansService,
    currentStateService,
    ENTITYLISTFIELDTYPES,
    ENV,
    $filter,
    $stateParams,
    ncUtils
  ) {
    var controllerScope = this;
    var ResourceController = baseControllerListClass.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.service = premiumSupportContractsService;
        this.blockUIElement = 'tab-content';
        this._super();

        this.entityOptions = {
          entityData: {
            noDataText: 'You have no SLAs yet.',
            createLink: 'appstore.store({category: "support"})',
            createLinkText: 'Add SLA',
            expandable: true,
            hideActionButtons: true
          },
          list: [
            {
              name: 'Name',
              propertyName: 'plan_name',
              type: ENTITYLISTFIELDTYPES.none,
              showForMobile: ENTITYLISTFIELDTYPES.showForMobile
            },
            {
              name: 'State',
              propertyName: 'state',
              type: ENTITYLISTFIELDTYPES.none,
              showForMobile: ENTITYLISTFIELDTYPES.showForMobile
            }
          ]
        };
        this.expandableOptions = [
          {
            isList: false,
            addItemBlock: false,
            viewType: 'description',
            items: [
              {
                key: 'plan_description',
                label: 'Description'
              },
              {
                key: 'plan_base_rate',
                label: 'Base rate'
              },
              {
                key: 'plan_hour_rate',
                label: 'Hour rate'
              },
              {
                key: 'plan_terms',
                label: 'Terms'
              }
            ]
          }
        ];
      },
      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        if ($stateParams.uuid) {
          this.service.defaultFilter.project_uuid = $stateParams.uuid;
          return fn(filter);
        }
        return currentStateService.getProject().then(function(project) {
          vm.service.defaultFilter.project_uuid = project.uuid;
          return fn(filter);
        })
      },
      showMore: function(contract) {
        var promise = premiumSupportPlansService.$get(null, contract.plan).then(function(response) {
          contract.plan_description = response.description;
          contract.plan_terms = response.terms;
          contract.plan_base_rate = $filter('currency')(response.base_rate, ENV.currency);
          contract.plan_hour_rate = $filter('currency')(response.hour_rate, ENV.currency);
        });
        ncUtils.blockElement('block_'+contract.uuid, promise);
      }
    });

    controllerScope.__proto__ = new ResourceController();
  }

})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectDeleteTabController', [
      'baseControllerClass',
      'projectsService',
      'currentStateService',
      '$rootScope',
      '$state',
      '$window',
      ProjectDeleteTabController
    ]);

  function ProjectDeleteTabController(
    baseControllerClass,
    projectsService,
    currentStateService,
    $rootScope,
    $state,
    $window
  ) {
    var controllerScope = this;
    var DeleteController = baseControllerClass.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.service = projectsService;
        this._super();

        var vm = this;
        currentStateService.getProject().then(function(project) {
          vm.project = project;
        });
      },
      removeProject: function () {
        var confirmDelete = confirm('Confirm deletion?');
        if (confirmDelete) {
          this.project.$delete().then(function() {
            projectsService.clearAllCacheForCurrentEndpoint();
            return projectsService.getFirst().then(function(project) {
              currentStateService.setProject(project);
              $rootScope.$broadcast('refreshProjectList', {model: controllerScope.project, remove: true});
            });
          }).then(function() {
            currentStateService.getCustomer().then(function(customer) {
              $state.go('organizations.details', {uuid: customer.uuid, tab: 'projects'}, {notify: false});
              $window.location.reload();
            });
          });
        }
      }
    });

    controllerScope.__proto__ = new DeleteController();
  }

})();
<commit_msg>Add todo for optimizing the reload<commit_after>(function() {
  angular.module('ncsaas')
    .controller('ProjectUsersTabController', [
      '$stateParams',
      'projectsService',
      'projectPermissionsService',
      'USERPROJECTROLE',
      'usersService',
      'baseControllerClass',
      'currentStateService',
      ProjectUsersTabController
    ]);

  function ProjectUsersTabController(
    $stateParams, projectsService, projectPermissionsService, USERPROJECTROLE, usersService, baseControllerClass,
    currentStateService) {
    var controllerScope = this;
    var Controller = baseControllerClass.extend({
      users: {}, // users with role in project
      usersListForAutoComplete: [],
      user: null,
      project: null,
      checkQuotas: 'user',

      init: function() {
        this.blockUIElement = 'tab-content';
        this._super();
        this.adminRole = USERPROJECTROLE.admin;
        this.managerRole = USERPROJECTROLE.manager;
        this.users[this.adminRole] = [];
        this.users[this.managerRole] = [];
        this.activate();
      },
      activate: function() {
        var vm = this;

        if ($stateParams.uuid) {
          projectsService.$get($stateParams.uuid).then(function(response) {
            vm.project = response;
            vm.getUsers();
          });
        } else {
          currentStateService.getProject().then(function(response) {
            vm.project = response;
            vm.getUsers();
          });
        }

        this.getUserListForAutoComplete();
      },
      getUsers: function() {
        this.getUsersForProject(this.adminRole);
        this.getUsersForProject(this.managerRole);
      },
      getUserListForAutoComplete: function(filter) {
        var vm = this;
        filter = filter || {};
        filter['DONTBLOCK'] = 1;
        usersService.getList(filter).then(function(response) {
          vm.usersListForAutoComplete = response;
        });
      },
      getUsersForProject: function(role) {
        var vm = this;
        var filter = {
          role: role,
          project: vm.project.uuid
        };
        projectPermissionsService.getList(filter).then(function(response) {
          vm.users[role] = response;
        });
      },
      userSearchInputChanged: function(searchText) {
        controllerScope.getUserListForAutoComplete({full_name: searchText});
      },
      selectedUsersCallback: function(selected) {
        if (selected) {
          controllerScope.user = selected.originalObject;
          controllerScope.addUser(this.id);
          controllerScope.getUserListForAutoComplete();
        }
      },
      addUser: function(role) {
        var vm = this;
        var instance = projectPermissionsService.$create();
        instance.user = vm.user.url;
        instance.project = vm.project.url;
        instance.role = role;
        instance.$save(
          function() {
            vm.getUsersForProject(role);
          },
          function(response) {
            alert(response.data.non_field_errors);
          }
        );
      },
      userProjectRemove: function(userProject) {
        var vm = this;
        var role = userProject.role;
        var index = vm.users[role].indexOf(userProject);
        var confirmDelete = confirm('Confirm user deletion?');
        if (confirmDelete) {
          projectPermissionsService.$delete(userProject.pk).then(
            function() {
              vm.users[role].splice(index, 1);
            },
            function(response) {
              alert(response.data.detail);
            }
          );
        } else {
          alert('User was not deleted.');
        }
      }
    });

    controllerScope.__proto__ = new Controller();
  }

})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectEventTabController', [
      '$stateParams',
      'projectsService',
      'baseEventListController',
      'currentStateService',
      ProjectEventTabController
    ]);

  function ProjectEventTabController($stateParams, projectsService, baseEventListController, currentStateService) {
    var controllerScope = this;
    var EventController = baseEventListController.extend({
      project: null,

      init: function() {
        this.controllerScope = controllerScope;
        this.blockUIElement = 'tab-content';
        this._super();
        this.getProject();
      },
      getList: function(filter) {
        if (this.project) {
          this.service.defaultFilter.scope = this.project.url;
          return this._super(filter);
        } else {
          return this.getProject();
        }
      },
      getProject: function() {
        var vm = this;
        if ($stateParams.uuid) {
          return projectsService.$get($stateParams.uuid).then(function(response) {
            vm.project = response;
            return vm.getList();
          });
        } else {
          return currentStateService.getProject().then(function(response) {
            vm.project = response;
            return vm.getList();
          });
        }
      }
    });

    controllerScope.__proto__ = new EventController();
  }

})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectAlertTabController', [
      'BaseAlertsListController',
      'currentStateService',
      ProjectAlertTabController
    ]);

  function ProjectAlertTabController(
    BaseAlertsListController,
    currentStateService
  ) {
    var controllerScope = this;
    var AlertController = BaseAlertsListController.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.blockUIElement = 'tab-content';
        this._super();
      },
      getList: function(filter) {
        var getList = this._super.bind(controllerScope),
          vm = this;
        this.service.defaultFilter.aggregate = 'project';
        this.service.defaultFilter.opened = true;
        return currentStateService.getProject().then(function(response) {
          vm.service.defaultFilter.uuid = response.uuid;
          return getList(filter);
        });
      }
    });

    controllerScope.__proto__ = new AlertController();
  }

})();

(function() {
  angular.module('ncsaas')
    .service('BaseProjectResourcesTabController', [
      'baseResourceListController', 'currentStateService', BaseProjectResourcesTabController]);

  function BaseProjectResourcesTabController(baseResourceListController, currentStateService) {
    var controllerClass = baseResourceListController.extend({
      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        return currentStateService.getProject().then(function(project){
          vm.service.defaultFilter.project_uuid = project.uuid;
          return fn(filter);
        })
      }
    });
    return controllerClass;
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectResourcesTabController', [
      'BaseProjectResourcesTabController',
      'ENV',
      ProjectResourcesTabController
    ]);

  function ProjectResourcesTabController(BaseProjectResourcesTabController, ENV) {
    var controllerScope = this;
    var ResourceController = BaseProjectResourcesTabController.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.category = ENV.VirtualMachines;
        this._super();
        this.entityOptions.entityData.noMatchesText = 'No VMs found matching filter.';
      }
    });
    controllerScope.__proto__ = new ResourceController();
  }
})();

(function() {

  angular.module('ncsaas')
    .controller('ProjectApplicationsTabController', [
      'BaseProjectResourcesTabController', 'ENV',
      ProjectApplicationsTabController]);

  function ProjectApplicationsTabController(BaseProjectResourcesTabController, ENV) {
    var controllerScope = this;
    var ResourceController = BaseProjectResourcesTabController.extend({
      init:function() {
        this.controllerScope = controllerScope;
        this.category = ENV.Applications;
        this._super();

        this.entityOptions.entityData.noDataText = 'You have no applications yet';
        this.entityOptions.entityData.createLinkText = 'Create application';
        this.entityOptions.entityData.importLinkText = 'Import application';
        this.entityOptions.entityData.noMatchesText = 'No applications found matching filter.';
      }
    });
    controllerScope.__proto__ = new ResourceController();
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectServicesTabController',
    ['baseControllerListClass',
      'joinServiceProjectLinkService',
      'joinService',
      'currentStateService',
      'ENTITYLISTFIELDTYPES',
      '$rootScope',
      ProjectServicesTabController]);

  function ProjectServicesTabController(
    baseControllerListClass,
    joinServiceProjectLinkService,
    joinService,
    currentStateService,
    ENTITYLISTFIELDTYPES,
    $rootScope) {
    var controllerScope = this;
    var ServiceController = baseControllerListClass.extend({
      init: function() {
        this.service = joinService;
        this.service.defaultFilter.project_uuid = currentStateService.getProjectUuid();
        this.controllerScope = controllerScope;
        this.blockUIElement = 'tab-content';
        this._super();
        this.actionButtonsListItems = [
          {
            title: 'Remove',
            clickFunction: this.remove.bind(controllerScope),

            isDisabled: function(service) {
              return service.shared || service.resources_count > 0;
            }.bind(this.controllerScope),

            tooltip: function(service) {
              if (service.shared) {
                return 'You cannot remove shared provider';
              }
              if (service.resources_count) {
                return 'Provider has resources. Remove them first';
              }
            }.bind(this.controllerScope)
          }
        ];
        this.entityOptions = {
          entityData: {
            noDataText: 'No providers yet',
            createLink: 'services.create',
            createLinkText: 'Create provider',
            checkQuotas: 'service'
          },
          list: [
            {
              type: ENTITYLISTFIELDTYPES.statusCircle,
              className: 'statusCircle',
              propertyName: 'state',
              onlineStatus: 'In Sync'
            },
            {
              name: 'Name',
              propertyName: 'name',
              type: ENTITYLISTFIELDTYPES.name,
              link: 'organizations.details({uuid: "' + currentStateService.getCustomerUuid()
              + '", providerType: entity.service_type, providerUuid: entity.uuid, tab: "providers"})',
              className: 'name',
              showForMobile: true
            },
            {
              name: 'Type',
              propertyName: 'service_type',
              type: ENTITYLISTFIELDTYPES.noType
            },
            {
              name: 'Resources',
              propertyName: 'resources_count',
              emptyText: '0'
            }
          ]
        };
      },
      getList: function(filter) {
        return this._super(filter);
      },
      removeInstance: function(model) {
        return joinServiceProjectLinkService.$deleteByUrl(model.url);
      },
      afterInstanceRemove: function(instance) {
        $rootScope.$broadcast('refreshProjectList');
        this._super(instance);
      }
    });

    controllerScope.__proto__ = new ServiceController();
  }
})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectSupportTabController', [
      'baseControllerListClass',
      'premiumSupportContractsService',
      'premiumSupportPlansService',
      'currentStateService',
      'ENTITYLISTFIELDTYPES',
      'ENV',
      '$filter',
      '$stateParams',
      'ncUtils',
      ProjectSupportTabController
    ]);

  function ProjectSupportTabController(
    baseControllerListClass,
    premiumSupportContractsService,
    premiumSupportPlansService,
    currentStateService,
    ENTITYLISTFIELDTYPES,
    ENV,
    $filter,
    $stateParams,
    ncUtils
  ) {
    var controllerScope = this;
    var ResourceController = baseControllerListClass.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.service = premiumSupportContractsService;
        this.blockUIElement = 'tab-content';
        this._super();

        this.entityOptions = {
          entityData: {
            noDataText: 'You have no SLAs yet.',
            createLink: 'appstore.store({category: "support"})',
            createLinkText: 'Add SLA',
            expandable: true,
            hideActionButtons: true
          },
          list: [
            {
              name: 'Name',
              propertyName: 'plan_name',
              type: ENTITYLISTFIELDTYPES.none,
              showForMobile: ENTITYLISTFIELDTYPES.showForMobile
            },
            {
              name: 'State',
              propertyName: 'state',
              type: ENTITYLISTFIELDTYPES.none,
              showForMobile: ENTITYLISTFIELDTYPES.showForMobile
            }
          ]
        };
        this.expandableOptions = [
          {
            isList: false,
            addItemBlock: false,
            viewType: 'description',
            items: [
              {
                key: 'plan_description',
                label: 'Description'
              },
              {
                key: 'plan_base_rate',
                label: 'Base rate'
              },
              {
                key: 'plan_hour_rate',
                label: 'Hour rate'
              },
              {
                key: 'plan_terms',
                label: 'Terms'
              }
            ]
          }
        ];
      },
      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        if ($stateParams.uuid) {
          this.service.defaultFilter.project_uuid = $stateParams.uuid;
          return fn(filter);
        }
        return currentStateService.getProject().then(function(project) {
          vm.service.defaultFilter.project_uuid = project.uuid;
          return fn(filter);
        })
      },
      showMore: function(contract) {
        var promise = premiumSupportPlansService.$get(null, contract.plan).then(function(response) {
          contract.plan_description = response.description;
          contract.plan_terms = response.terms;
          contract.plan_base_rate = $filter('currency')(response.base_rate, ENV.currency);
          contract.plan_hour_rate = $filter('currency')(response.hour_rate, ENV.currency);
        });
        ncUtils.blockElement('block_'+contract.uuid, promise);
      }
    });

    controllerScope.__proto__ = new ResourceController();
  }

})();

(function() {
  angular.module('ncsaas')
    .controller('ProjectDeleteTabController', [
      'baseControllerClass',
      'projectsService',
      'currentStateService',
      '$rootScope',
      '$state',
      '$window',
      ProjectDeleteTabController
    ]);

  function ProjectDeleteTabController(
    baseControllerClass,
    projectsService,
    currentStateService,
    $rootScope,
    $state,
    $window
  ) {
    var controllerScope = this;
    var DeleteController = baseControllerClass.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.service = projectsService;
        this._super();

        var vm = this;
        currentStateService.getProject().then(function(project) {
          vm.project = project;
        });
      },
      removeProject: function () {
        var confirmDelete = confirm('Confirm deletion?');
        if (confirmDelete) {
          this.project.$delete().then(function() {
            projectsService.clearAllCacheForCurrentEndpoint();
            return projectsService.getFirst().then(function(project) {
              currentStateService.setProject(project);
              $rootScope.$broadcast('refreshProjectList', {model: controllerScope.project, remove: true});
            });
          }).then(function() {
            currentStateService.getCustomer().then(function(customer) {
              $state.go('organizations.details', {uuid: customer.uuid, tab: 'projects'}, {notify: false});
              // TODO: consider not using a full reload here
              $window.location.reload();
            });
          });
        }
      }
    });

    controllerScope.__proto__ = new DeleteController();
  }

})();
<|endoftext|>


<commit_before>var fs = require('fs');
var postcss = require('postcss');
var prefixer = require('postcss-prefix-selector');

var css = fs.readFileSync('node_modules/bootstrap/dist/css/bootstrap.css', 'utf8').toString();

var out = postcss()
    .use(prefixer({
        prefix: '.bsi'
    }))
    .process(css).then(function (result) {
        fs.writeFileSync('node_modules/bootstrap/dist/css/bootstrap.isolated.css', result.css);
        console.log('bootstrap.isolated.css file created in node_modules/bootstrap/dist/css directory');
    })

<commit_msg>Fix warning when isolating bootstrap<commit_after>const fs = require('fs');
const postcss = require('postcss');
const prefixer = require('postcss-prefix-selector');

const css = fs
  .readFileSync('node_modules/bootstrap/dist/css/bootstrap.css', 'utf8')
  .toString();

const out = postcss()
  .use(
    prefixer({
      prefix: '.bsi',
    })
  )
  .process(css, {from: undefined})
  .then((result) => {
    fs.writeFileSync(
      'node_modules/bootstrap/dist/css/bootstrap.isolated.css',
      result.css
    );
    console.log(
      'bootstrap.isolated.css file created in node_modules/bootstrap/dist/css directory'
    );
  });
<|endoftext|>