<commit_before>/*
 * Copyright (C) 2019 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react'
import {act, render, wait, waitForElementToBeRemoved} from '@testing-library/react'

import Bridge from '../../../../bridge/Bridge'
import * as fakeSource from '../../../../sidebar/sources/fake'
import CanvasContentTray from '../CanvasContentTray'

describe.skip('RCE Plugins > CanvasContentTray', () => {
  let component
  let props

  function getProps(override={}) {
    props = {
      bridge: new Bridge(),
      containingContext: {type: 'course', contextId: '1201', userId: '17'},
      contextId: '1201',
      contextType: 'course',
      source: fakeSource,
      themeUrl: 'http://localhost/tinymce-theme.swf',
      ...override
    }
    return props
  }

  beforeEach(() => {
    jest.setTimeout(20000)
  })

  function renderComponent(trayprops) {
    component = render(<CanvasContentTray {...getProps(trayprops)} />)
  }

  function getTray() {
    const $tray = component.queryByRole('dialog')
    if ($tray) {
      return $tray
    }
    throw new Error('not mounted')
  }

    async function showTrayForPlugin(plugin) {
    act(() => {
      props.bridge.controller.showTrayForPlugin(plugin)
    })
    await wait(getTray, {timeout: 19500})
  }

  function getTrayLabel() {
    return getTray().getAttribute('aria-label')
  }

  describe('Tray Label', () => {
    beforeEach(() => {
      renderComponent()
    })

    it('is labeled with "Course Links" when using the "links" content type', async () => {
      await showTrayForPlugin('links')
      expect(getTrayLabel()).toEqual('Course Links')
    })

    // course
    it('is labeled with "Course Images" when using the "images" content type', async () => {
      await showTrayForPlugin('course_images')
      expect(getTrayLabel()).toEqual('Course Images')
    })

    it('is labeled with "Course Media" when using the "media" content type', async () => {
      await showTrayForPlugin('course_media')
      expect(getTrayLabel()).toEqual('Course Media')
    })

    it('is labeled with "Course Documents" when using the "course_documents" content type', async () => {
      await showTrayForPlugin('course_documents')
      expect(getTrayLabel()).toEqual('Course Documents')
    })

    // user
    it('is labeled with "User Images" when using the "user_images" content type', async () => {
      await showTrayForPlugin('user_images')
      expect(getTrayLabel()).toEqual('User Images')
    })

    it('is labeled with "User Media" when using the "user_media" content type', async () => {
      await showTrayForPlugin('user_media')
      expect(getTrayLabel()).toEqual('User Media')
    })

    it('is labeled with "User Documents" when using the "user_documents" content type', async () => {
      await showTrayForPlugin('user_documents')
      expect(getTrayLabel()).toEqual('User Documents')
    })
  })

  describe('content panel', () => {
    beforeEach(() => {
      renderComponent()
    })
    it('is the links panel for links content types', async () => {
      await showTrayForPlugin('links')
      expect(component.getByTestId('instructure_links-LinksPanel')).toBeInTheDocument()
    })

    it('is the documents panel for document content types', async () => {
      await showTrayForPlugin('course_documents')
      expect(component.getByTestId('instructure_links-DocumentsPanel')).toBeInTheDocument()
    })

    it('is the images panel for image content types', async () => {
      await showTrayForPlugin('images')
      expect(component.getByTestId('instructure_links-ImagesPanel')).toBeInTheDocument()
    })

    it('is the media panel for media content types', async () => {
      await showTrayForPlugin('course_media')
      expect(component.getByTestId('instructure_links-MediaPanel')).toBeInTheDocument()
    })
  })

  describe('focus', () => {
    beforeEach(() => {
      renderComponent()
    })

    it('is set on tinymce after tray closes', async () => {
      const mockFocus = jest.fn()
      props.bridge.focusActiveEditor = mockFocus

      await showTrayForPlugin('links')
      expect(component.getByTestId('CanvasContentTray')).toBeInTheDocument()

      const closeBtn = component.getByText('Close')
      closeBtn.click()
      // immediatly after being asked to close, INSTUI Tray removes role='dialog' and
      // adds aria-hidden='true', so the getTray() function above does not work
      await waitForElementToBeRemoved(() => component.queryByTestId('CanvasContentTray'))

      expect(mockFocus).toHaveBeenCalledWith(false)
    })
  })
})
<commit_msg>Remove it.only from test file<commit_after>/*
 * Copyright (C) 2019 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react'
import {act, render, wait, waitForElementToBeRemoved} from '@testing-library/react'

import Bridge from '../../../../bridge/Bridge'
import * as fakeSource from '../../../../sidebar/sources/fake'
import CanvasContentTray from '../CanvasContentTray'

describe('RCE Plugins > CanvasContentTray', () => {
  let component
  let props

  function getProps(override={}) {
    props = {
      bridge: new Bridge(),
      containingContext: {type: 'course', contextId: '1201', userId: '17'},
      contextId: '1201',
      contextType: 'course',
      source: fakeSource,
      themeUrl: 'http://localhost/tinymce-theme.swf',
      ...override
    }
    return props
  }

  beforeEach(() => {
    jest.setTimeout(20000)
  })

  function renderComponent(trayprops) {
    component = render(<CanvasContentTray {...getProps(trayprops)} />)
  }

  function getTray() {
    const $tray = component.queryByRole('dialog')
    if ($tray) {
      return $tray
    }
    throw new Error('not mounted')
  }

    async function showTrayForPlugin(plugin) {
    act(() => {
      props.bridge.controller.showTrayForPlugin(plugin)
    })
    await wait(getTray, {timeout: 19500})
  }

  function getTrayLabel() {
    return getTray().getAttribute('aria-label')
  }

  describe('Tray Label', () => {
    beforeEach(() => {
      renderComponent()
    })

    it('is labeled with "Course Links" when using the "links" content type', async () => {
      await showTrayForPlugin('links')
      expect(getTrayLabel()).toEqual('Course Links')
    })

    // course
    it('is labeled with "Course Images" when using the "images" content type', async () => {
      await showTrayForPlugin('course_images')
      expect(getTrayLabel()).toEqual('Course Images')
    })

    it('is labeled with "Course Media" when using the "media" content type', async () => {
      await showTrayForPlugin('course_media')
      expect(getTrayLabel()).toEqual('Course Media')
    })

    it('is labeled with "Course Documents" when using the "course_documents" content type', async () => {
      await showTrayForPlugin('course_documents')
      expect(getTrayLabel()).toEqual('Course Documents')
    })

    // user
    it('is labeled with "User Images" when using the "user_images" content type', async () => {
      await showTrayForPlugin('user_images')
      expect(getTrayLabel()).toEqual('User Images')
    })

    it('is labeled with "User Media" when using the "user_media" content type', async () => {
      await showTrayForPlugin('user_media')
      expect(getTrayLabel()).toEqual('User Media')
    })

    it('is labeled with "User Documents" when using the "user_documents" content type', async () => {
      await showTrayForPlugin('user_documents')
      expect(getTrayLabel()).toEqual('User Documents')
    })
  })

  describe('content panel', () => {
    beforeEach(() => {
      renderComponent()
    })
    it('is the links panel for links content types', async () => {
      await showTrayForPlugin('links')
      expect(component.getByTestId('instructure_links-LinksPanel')).toBeInTheDocument()
    })

    it('is the documents panel for document content types', async () => {
      await showTrayForPlugin('course_documents')
      expect(component.getByTestId('instructure_links-DocumentsPanel')).toBeInTheDocument()
    })

    it('is the images panel for image content types', async () => {
      await showTrayForPlugin('course_images')
      expect(component.getByTestId('instructure_links-ImagesPanel')).toBeInTheDocument()
    })

    it('is the media panel for media content types', async () => {
      await showTrayForPlugin('course_media')
      expect(component.getByTestId('instructure_links-MediaPanel')).toBeInTheDocument()
    })
  })

  describe('focus', () => {
    beforeEach(() => {
      renderComponent()
    })

    it('is set on tinymce after tray closes', async () => {
      const mockFocus = jest.fn()
      props.bridge.focusActiveEditor = mockFocus

      await showTrayForPlugin('links')
      expect(component.getByTestId('CanvasContentTray')).toBeInTheDocument()

      const closeBtn = component.getByText('Close')
      closeBtn.click()
      // immediatly after being asked to close, INSTUI Tray removes role='dialog' and
      // adds aria-hidden='true', so the getTray() function above does not work
      await waitForElementToBeRemoved(() => component.queryByTestId('CanvasContentTray'))

      expect(mockFocus).toHaveBeenCalledWith(false)
    })
  })
})
<|endoftext|>


<commit_before>var ldnode = require('../index');

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

var ns = require('../vocab/ns.js').ns;
var address = 'https://localhost:3456/test/';

var ldp = ldnode.createServer({
    mount: '/test',
    root: __dirname + '/resources',
    key: __dirname + '/keys/key.pem',
    cert: __dirname + '/keys/cert.pem',
    webid: true
});
ldp.listen(3457);
<commit_msg>Removed unnecessary debug file<commit_after><|endoftext|>


<commit_before>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

var version = require('util/version');
var http = require('services/http');

/**
 * List of enabled http endpoints
 */
var APPS = ['info', 'api', 'bundles', 'services', 'facts', 'health', 'instances'];

/**
 * Default http services root path
 */
var SERVICES_HTTP_ROOT = 'services/http/';

/**
 * Currently active API version
 */
var CURRENT_API_VERSION = '1.0';

/**
 * Headers which are added to every HTTP response.
 */
var BASE_HEADERS = { 'X-Cast-Agent-Version': version.toString(),
'X-Cast-API-Version': CURRENT_API_VERSION };

exports.BASE_HEADERS = BASE_HEADERS;
exports.APPS = APPS;
exports.SERVICES_HTTP_ROOT = SERVICES_HTTP_ROOT;
exports.CURRENT_API_VERSION = CURRENT_API_VERSION;
<commit_msg>Fix indent.<commit_after>/*
 * Licensed to Cloudkick, Inc ('Cloudkick') under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Cloudkick licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

var version = require('util/version');
var http = require('services/http');

/**
 * List of enabled http endpoints
 */
var APPS = ['info', 'api', 'bundles', 'services', 'facts', 'health', 'instances'];

/**
 * Default http services root path
 */
var SERVICES_HTTP_ROOT = 'services/http/';

/**
 * Currently active API version
 */
var CURRENT_API_VERSION = '1.0';

/**
 * Headers which are added to every HTTP response.
 */
var BASE_HEADERS = { 'X-Cast-Agent-Version': version.toString(),
                     'X-Cast-API-Version': CURRENT_API_VERSION };

exports.BASE_HEADERS = BASE_HEADERS;
exports.APPS = APPS;
exports.SERVICES_HTTP_ROOT = SERVICES_HTTP_ROOT;
exports.CURRENT_API_VERSION = CURRENT_API_VERSION;
<|endoftext|>


<commit_before>/* eslint-disable prefer-template */
/*!
 * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
 */

import {waitForValue, SparkPlugin} from '@ciscospark/spark-core';

import reportRequest from './report-request';

const Ediscovery = SparkPlugin.extend({
  namespace: 'Ediscovery',

  @waitForValue('@')
  createReport(userIds, keywords, spaceNames, spaceIds, range) {
    const body = reportRequest;
    body.userIds = userIds;
    body.keywords = keywords;
    body.spaceNames = spaceNames;
    body.spaceIds = spaceIds;
    body.range = range;

    return this.request({
      method: 'POST',
      service: 'ediscovery',
      resource: 'report',
      body
    }).then((res) => {
      console.log(res);
      this._processCreateReportSuccess(res);
    }).catch((reason) => {
      console.log(reason);
      return reason;
      // Normal behaviour
      //return Promise.reject(reason);
    });
  },

  _processCreateReportSuccess(res) {
    this.set(res.body);
    console.log('CreateReport response body set');
  },

  @waitForValue('@')
  getReports() {
    return this.request({
      method: 'GET',
      service: 'ediscovery',
      resource: 'reports'
    }).then((res) => {
      console.log(res);
      this._processGetReportsSuccess(res);
    }).catch((reason) => {
      console.log(reason);
      return reason;
      // Normal behaviour
      //return Promise.reject(reason);
    });
  },

  _processGetReportsSuccess(res) {
    this.set(res.body);
    console.log('GetReports response body set');
  }
});

export default Ediscovery;
<commit_msg>style(ediscovery): renaming export after pull<commit_after>/* eslint-disable prefer-template */
/*!
 * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
 */

import {waitForValue, SparkPlugin} from '@ciscospark/spark-core';

import reportRequest from './report-request';

const Ediscovery = SparkPlugin.extend({
  namespace: 'Ediscovery',

  @waitForValue('@')
  createReport(userIds, keywords, spaceNames, spaceIds, range) {
    const body = reportRequest;
    body.userIds = userIds;
    body.keywords = keywords;
    body.spaceNames = spaceNames;
    body.spaceIds = spaceIds;
    body.range = range;

    return this.request({
      method: 'POST',
      service: 'ediscovery',
      resource: 'reports',
      body
    }).then((res) => {
      console.log(res);
      return res;
    }).catch((reason) => {
      console.log(reason);
      return reason;
    });
  },

  @waitForValue('@')
  getReports() {
    return this.request({
      method: 'GET',
      service: 'ediscovery',
      resource: 'reports'
    }).then((res) => {
      console.log(res);
      return res;
    }).catch((reason) => {
      console.log(reason);
      return reason;
    });
  }
});

export default Ediscovery;
<|endoftext|>


<commit_before>//var Promise = require('promise');
var databaseAccessor = function() {
  var obj = {};
  /* Setter functions for various parts of the databaseAccessor
   */
  obj.setDb = function(db) {
    obj.ddb = db;
  };
  obj.setDbName = function(name) {
    obj.dbName = name;
  };
  obj.setKeyName = function(name) {
    obj.keyName = name;
  };
  obj.setValueName = function(name) {
    obj.valueName = name;
  };
  obj.setUser = function(user) {
    obj.user = user;
  };
  obj.setAuthenticator = function(authenticator) {
    obj.authenticator = authenticator();
  };
  obj.getAuthenticator = function(authenticator) {
    return obj.authenticator;
  };
  /*
   */
  obj.get = function(key) {
    console.log('Getting:', key);
    return new Promise(function(resolve,reject) {
      if(!obj.authenticator.authenticateRead(obj.user,key)) {
        console.error('Authentication failed!');
        reject('Access disallowed');
      }
      console.log('Accessing dynamo...');
      obj.ddb.getItem(obj.dbName,key, null, {}, function(err,res,cap) {
        console.log('Got result: ', res);
        if(err !== null) {
          console.log('Error in DynamoDB: ', err);
          reject(err);
        }else{
          if(typeof res === 'undefined') {
            console.log('Got undefined result in dynamo: ', res);
            resolve(null);
          }else{
            console.log('Returning from dynamo:', res[obj.valueName]);
            resolve(res[obj.valueName]);
          }
        }
      });
    });
  };
  obj.batchGet = function(keys) {
    console.log('Doing batch get for keys:', keys);
    return new Promise(function(resolve,reject) {
      for(var i = 0; i < keys.length; i++) {
        if(!obj.authenticator.authenticateRead(obj.user,keys[i])) {
          reject('Access disallowed');
        }
      }
      var req={};
      req[obj.dbName]={'keys':keys};
      obj.ddb.batchGetItem(req,function(err,res) {
        if(err) {
          reject(err);
        } else {
          if(!res) {
            resolve(null);
          }
          var vals = [];
          var dict = {};
          for(var i = 0; i<res.items.length; i++) {
            dict[res.items[i][obj.keyName]]=res.items[i][obj.valueName];
            //vals.push(res.items[i][obj.valueName]);
          }
          keys.forEach(function(element){
            vals.push(dict[element]);
          });
          resolve(vals);
        }
      });
    });
  };
  obj.getQuery = function(query) {
    return new Promise(function(resolve, reject) {
      obj.ddb.query(obj.dbName, query, {}, function(err, result) {
        if(err !== null) {
          reject(err);
        }
        console.log('Database got', result, 'from', query);
        resolve(result);
      });
    });
  };
  obj.set = function(key,value) {
    return new Promise(function(resolve,reject) {
      if(!obj.authenticator.authenticateWrite(obj.user,key)) {
        reject('Access disallowed');
      }
      var dbobj = {};
      dbobj[obj.valueName]={};
      dbobj[obj.valueName].value = value;
      obj.ddb.updateItem(obj.dbName,key, null, dbobj, {}, function(err,det,cap) {
        if(err !== null) {
          reject(err);
        }else{
          resolve(null);
        }
      });
    });
  };
  obj.batchSet = function(elements) {
    var groups = [];
    for(var i=0;i<elements.length;i+=25) {
      groups.push(elements.slice(i, i+25));
    }

    return new Promise(function(resolve,reject) {
      groups.forEach(function(items) {
        var dbobj={};
        dbobj[obj.dbName]=[];
        items.forEach(function(element) {
          var temp={};
          temp[obj.keyName]=element[0];
          temp[obj.valueName]=element[1];
          dbobj[obj.dbName].push(temp);
        });
        obj.ddb.batchWriteItem(dbobj,{},function(err,res,cap) {
          if(err !== null) {
            //reject(err);
          } else {
            resolve(null);
          }
        });
      });
    });
  };
  // Add key with empty value
  obj.addEmpty = function(key) {
    return new Promise(function(resolve, reject) {
      if(obj.authenticator.authenticateWrite(obj.user, key) === false) {
        reject('Access disallowed');
      }
      var dbobj = {};
      dbobj[obj.keyName] = key;
      console.log('Adding', dbobj, 'to database');
      obj.ddb.putItem(obj.dbName, dbobj, {}, function(err, det, cap) {
        if(err !== null) {
          reject(err);
        } else {
          resolve(null);
        }
      });
    });
  };
  // Insert new key-value
  obj.add = function(key, value) {
    if(value === undefined) {
      return obj.addEmpty(key);
    }
    return new Promise(function(resolve,reject) {
      if(!obj.authenticator.authenticateWrite(obj.user,key)) {
        reject('Access disallowed');
      }
      var dbobj = {};
      dbobj[obj.keyName] = key;
      dbobj[obj.valueName] = value;
      obj.ddb.putItem(obj.dbName, dbobj, {}, function(err,det,cap) {
        if(err !== null) {
          reject(err);
        } else {
          resolve(null);
        }
      });
    });
  };
  obj.allKeys = function() {
    return new Promise(function(resolve,reject) {
      var options = {attributesToGet: obj.keyName};
      obj.ddb.scan(obj.dbName, {}, function(err,res) {
        if(err!==null) {
          reject(err);
        } else {
          res = res.items.map(function(element) {
            return element[obj.keyName];
          });
          resolve(res);
        }
      });
    });
  };
  obj.deleteEntry = function(key){};

  return obj;
};
module.exports = databaseAccessor;
<commit_msg>Spaced out timing on writes<commit_after>//var Promise = require('promise');
var databaseAccessor = function() {
  var obj = {};
  /* Setter functions for various parts of the databaseAccessor
   */
  obj.setDb = function(db) {
    obj.ddb = db;
  };
  obj.setDbName = function(name) {
    obj.dbName = name;
  };
  obj.setKeyName = function(name) {
    obj.keyName = name;
  };
  obj.setValueName = function(name) {
    obj.valueName = name;
  };
  obj.setUser = function(user) {
    obj.user = user;
  };
  obj.setAuthenticator = function(authenticator) {
    obj.authenticator = authenticator();
  };
  obj.getAuthenticator = function(authenticator) {
    return obj.authenticator;
  };
  /*
   */
  obj.get = function(key) {
    console.log('Getting:', key);
    return new Promise(function(resolve,reject) {
      if(!obj.authenticator.authenticateRead(obj.user,key)) {
        console.error('Authentication failed!');
        reject('Access disallowed');
      }
      console.log('Accessing dynamo...');
      obj.ddb.getItem(obj.dbName,key, null, {}, function(err,res,cap) {
        console.log('Got result: ', res);
        if(err !== null) {
          console.log('Error in DynamoDB: ', err);
          reject(err);
        }else{
          if(typeof res === 'undefined') {
            console.log('Got undefined result in dynamo: ', res);
            resolve(null);
          }else{
            console.log('Returning from dynamo:', res[obj.valueName]);
            resolve(res[obj.valueName]);
          }
        }
      });
    });
  };
  obj.batchGet = function(keys) {
    console.log('Doing batch get for keys:', keys);
    return new Promise(function(resolve,reject) {
      for(var i = 0; i < keys.length; i++) {
        if(!obj.authenticator.authenticateRead(obj.user,keys[i])) {
          reject('Access disallowed');
        }
      }
      var req={};
      req[obj.dbName]={'keys':keys};
      obj.ddb.batchGetItem(req,function(err,res) {
        if(err) {
          reject(err);
        } else {
          if(!res) {
            resolve(null);
          }
          var vals = [];
          var dict = {};
          for(var i = 0; i<res.items.length; i++) {
            dict[res.items[i][obj.keyName]]=res.items[i][obj.valueName];
            //vals.push(res.items[i][obj.valueName]);
          }
          keys.forEach(function(element){
            vals.push(dict[element]);
          });
          resolve(vals);
        }
      });
    });
  };
  obj.getQuery = function(query) {
    return new Promise(function(resolve, reject) {
      obj.ddb.query(obj.dbName, query, {}, function(err, result) {
        if(err !== null) {
          reject(err);
        }
        console.log('Database got', result, 'from', query);
        resolve(result);
      });
    });
  };
  obj.set = function(key,value) {
    return new Promise(function(resolve,reject) {
      if(!obj.authenticator.authenticateWrite(obj.user,key)) {
        reject('Access disallowed');
      }
      var dbobj = {};
      dbobj[obj.valueName]={};
      dbobj[obj.valueName].value = value;
      obj.ddb.updateItem(obj.dbName,key, null, dbobj, {}, function(err,det,cap) {
        if(err !== null) {
          reject(err);
        }else{
          resolve(null);
        }
      });
    });
  };
  obj.batchSet = function(elements) {
    var groups = [];
    for(var i=0;i<elements.length;i+=25) {
      groups.push(elements.slice(i, i+25));
    }

    return new Promise(function(resolve,reject) {
      //groups.forEach(function(items) {
      var adds = function(items) {
        if(typeof(items) === 'undefined'){
          resolve(null);
          //return;
        } else {
          var dbobj={};
          dbobj[obj.dbName]=[];
          items.forEach(function(element) {
            var temp={};
            temp[obj.keyName]=element[0];
            temp[obj.valueName]=element[1];
            dbobj[obj.dbName].push(temp);
          });
          obj.ddb.batchWriteItem(dbobj,{},function(err,res,cap) {
            if(err !== null) {
              //reject(err);
            } else {
              //resolve(null);
              setTimeout(adds(groups.pop()),500);
            }
          });
        }
      };
      adds(groups.pop());
      //});
    });
  };
  // Add key with empty value
  obj.addEmpty = function(key) {
    return new Promise(function(resolve, reject) {
      if(obj.authenticator.authenticateWrite(obj.user, key) === false) {
        reject('Access disallowed');
      }
      var dbobj = {};
      dbobj[obj.keyName] = key;
      console.log('Adding', dbobj, 'to database');
      obj.ddb.putItem(obj.dbName, dbobj, {}, function(err, det, cap) {
        if(err !== null) {
          reject(err);
        } else {
          resolve(null);
        }
      });
    });
  };
  // Insert new key-value
  obj.add = function(key, value) {
    if(value === undefined) {
      return obj.addEmpty(key);
    }
    return new Promise(function(resolve,reject) {
      if(!obj.authenticator.authenticateWrite(obj.user,key)) {
        reject('Access disallowed');
      }
      var dbobj = {};
      dbobj[obj.keyName] = key;
      dbobj[obj.valueName] = value;
      obj.ddb.putItem(obj.dbName, dbobj, {}, function(err,det,cap) {
        if(err !== null) {
          reject(err);
        } else {
          resolve(null);
        }
      });
    });
  };
  obj.allKeys = function() {
    return new Promise(function(resolve,reject) {
      var options = {attributesToGet: obj.keyName};
      obj.ddb.scan(obj.dbName, {}, function(err,res) {
        if(err!==null) {
          reject(err);
        } else {
          res = res.items.map(function(element) {
            return element[obj.keyName];
          });
          resolve(res);
        }
      });
    });
  };
  obj.deleteEntry = function(key){};

  return obj;
};
module.exports = databaseAccessor;
<|endoftext|>


<commit_before>/*MIT License

Copyright (c) 2017 MTA SZTAKI

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/

var util = require('util');
var ape = require('../ape.js');
var moduleManager = require('../modules/module_manager/module_manager.js');
var express = moduleManager.requireNodeModule('express');
var app = express();
var async = moduleManager.requireNodeModule('async');
var utils = require('../modules/utils/utils.js');
var logger = require("../modules/log_manager/log_manager.js");
var resp = require('../modules/response_manager/response_manager.js');
var errorMap = require('../modules/utils/errors.js');
var path = moduleManager.requireNodeModule('path');
var formidable = moduleManager.requireNodeModule('formidable');
var fs = require('fs');

exports.moduleTag = 'ApeHTTPApiFileGeometry';

app.post('/filegeometries/', function(req, res){

    // create an incoming form object
    var form = new formidable.IncomingForm();

    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;

    // store all uploads in the /uploads directory
    form.uploadDir = path.join(moduleManager.apertusModulePath, 'uploads');
    var fullFilePath;

    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    form.on('file', function(field, file) {
      fullFilePath = path.join(form.uploadDir, file.name);
      fs.rename(file.path, fullFilePath);
    });

    // log any errors that occur
    form.on('error', function(err) {
      logger.error('An error has occured: \n' + err);
    });

    // once all the files have been uploaded, send a response to the client
    form.on('end', function() {
      res.end('success');
      logger.debug('file upload success: ', fullFilePath);
      var fileGeometry = ape.nbind.JsBindManager().createFileGeometry('robotFileGeometry');
      fileGeometry.setFileName(fullFilePath);
    });

    // parse the incoming request containing the form data
    form.parse(req);
});

module.exports = app;
<commit_msg>plugins: jsAPI: modified fileGeometry uploads path<commit_after>/*MIT License

Copyright (c) 2017 MTA SZTAKI

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/

var util = require('util');
var ape = require('../ape.js');
var moduleManager = require('../modules/module_manager/module_manager.js');
var express = moduleManager.requireNodeModule('express');
var app = express();
var async = moduleManager.requireNodeModule('async');
var utils = require('../modules/utils/utils.js');
var logger = require("../modules/log_manager/log_manager.js");
var resp = require('../modules/response_manager/response_manager.js');
var errorMap = require('../modules/utils/errors.js');
var path = moduleManager.requireNodeModule('path');
var formidable = moduleManager.requireNodeModule('formidable');
var fs = require('fs');

exports.moduleTag = 'ApeHTTPApiFileGeometry';

app.post('/filegeometries/', function(req, res){

    // create an incoming form object
    var form = new formidable.IncomingForm();

    // specify that we want to allow the user to upload multiple files in a single request
    form.multiples = true;

    // store all uploads in the /uploads directory
    form.uploadDir = path.join(moduleManager.configurationPath, 'uploads');
    var fullFilePath;

    // every time a file has been uploaded successfully,
    // rename it to it's orignal name
    form.on('file', function(field, file) {
      fullFilePath = path.join(form.uploadDir, file.name);
      fs.rename(file.path, fullFilePath);
    });

    // log any errors that occur
    form.on('error', function(err) {
      logger.error('An error has occured: \n' + err);
    });

    // once all the files have been uploaded, send a response to the client
    form.on('end', function() {
      res.end('success');
      logger.debug('file upload success: ', fullFilePath);
      var fileGeometry = ape.nbind.JsBindManager().createFileGeometry('robotFileGeometry');
      fileGeometry.setFileName(fullFilePath);
    });

    // parse the incoming request containing the form data
    form.parse(req);
});

module.exports = app;
<|endoftext|>


<commit_before>/* global by, element */

'use strict';

var authentication = require('../authentication/authentication');
var common = require('../common/common');
var topologyEditorCommon = require('../topology/topology_editor_common');
var topologyTemplates = require('../topology/topology_templates_common');
var applications = require('../applications/applications');

describe('Applications management :', function() {
  /* Before each spec in the tests suite */
  beforeEach(function() {
    common.before();
    authentication.login('applicationManager');
  });

  /* After each spec in the tests suite(s) */
  afterEach(function() {
    // Logout action
    common.after();
  });

  xit('should be able to go to application search page at ' + common.appSearchUrl + ' and create new application', function() {
    console.log('################# should be able to go to application search page at ' + common.appSearchUrl + ' and create new application');
    applications.createApplication('Alien', 'Great Application');
    // Go to the app details page
    expect(browser.element(by.binding('application.name')).getText()).toEqual('Alien');
    expect(browser.element(by.binding('application.description')).getText()).toEqual('Great Application');
  });

  xit('should create first a topology template with 3 node templates (COMPUTE, JAVA, TOMCATRPM) and an application based on this template', function() {
    console.log('################# should create first a topology template with 3 node templates (COMPUTE, JAVA, TOMCATRPM) and an application based on this template');
    // Login as architect to create a topology template
    authentication.reLogin('architect');

    // create a topology template with one Compute, 1 Java and 1 Tomcat RPM
    topologyTemplates.createTopologyTemplateWithNodesAndRelationships(topologyEditorCommon.topologyTemplates.template4);

    // create a new application with this template as model
    authentication.reLogin('applicationManager');
    // template at index 2 is the first and only one created (index 1 equals is the default, no template)
    applications.createApplication('JavaTomcatWarApplication', 'Simple application with one compute, one template and all that around java...', 2);

    // check the created topology application (count nodes, count relationship..)
    applications.goToApplicationDetailPage('JavaTomcatWarApplication', true);

    // check relationship count
    // check relationship count
    element(by.id('rect_JavaRPM')).click();
    browser.waitForAngular();
    var relationships = element.all(by.repeater('(relationshipName,relationshipDefinition) in selectedNodeTemplate.relationships'));
    expect(relationships.count()).toBe(2);
    element(by.id('rect_Compute_2')).click();
    browser.waitForAngular();
    relationships = element.all(by.repeater('(relationshipName,relationshipDefinition) in selectedNodeTemplate.relationships'));
    expect(relationships.count()).toBe(0);
    element(by.id('rect_Compute')).click();
    browser.waitForAngular();
    relationships = element.all(by.repeater('(relationshipName,relationshipDefinition) in selectedNodeTemplate.relationships'));
    expect(relationships.count()).toBe(0);
  });

  xit('should be able to delete an application from the search list and the application\'s detail page', function() {
    console.log('################# should be able to delete an application from the search list and the application\'s detail page');
    applications.createApplication('Alien_1', 'Great Application 1');
    applications.createApplication('Alien_2', 'Great Application 2');
    applications.createApplication('Alien_3', 'Great Application 3');
    applications.goToApplicationListPage('main', 'applications');
    // delete application from the search list
    var appElement = element(by.id('app_Alien_1'));
    common.ptor.actions().mouseMove(appElement).perform();
    browser.sleep(1000); // one second so the turn annimation ends.
    common.deleteWithConfirm('delete-app_Alien_1', true);
    expect(appElement.isPresent()).toBe(false);

    // cancel a delete action
    appElement = element(by.id('app_Alien_3'));
    common.ptor.actions().mouseMove(appElement).perform();
    browser.sleep(1000); // one second so the turn annimation ends.
    common.deleteWithConfirm('delete-app_Alien_3', false);
    expect(appElement.isPresent()).toBe(true);

    // delete application from it detail page
    appElement = element(by.id('app_Alien_2'));
    applications.goToApplicationDetailPage('Alien_2');
    common.deleteWithConfirm('btn-delete-app', true);
    expect(appElement.isPresent()).toBe(false);

  });

  it('should be able to edit an application', function() {
    console.log('################# should be able to rename an application');
    // Create an application
    applications.createApplication('MyNewApplication1', 'A brand new application...');
    applications.createApplication('MyNewApplication2', 'A rband new application...');
    applications.goToApplicationDetailPage('MyNewApplication1');

    // Rename the application with a non existing name
    common.sendValueToXEditable('app-name', 'NewNameForMyApp', false);
    expect(element(by.binding('application.name')).getText()).toEqual('NewNameForMyApp');
    common.expectNoErrors();

    // Change the application's description
    common.sendValueToXEditable('app-desc', 'Some Description', false, 'textarea');
    expect(element(by.binding('application.description')).getText()).toEqual('Some Description');
    common.expectNoErrors();

    // Rename with an existing application name
    common.sendValueToXEditable('app-name', 'MyNewApplication2', false);
    common.abortXEditable('app-name');
    common.expectTitleMessage('409'); // server 'AlreadyExist' exception error code
    common.dismissAlert();
  });

});
<commit_msg>ALIEN-500 : Rights management in Application view UI Test - correction<commit_after>/* global by, element */

'use strict';

var authentication = require('../authentication/authentication');
var common = require('../common/common');
var topologyEditorCommon = require('../topology/topology_editor_common');
var topologyTemplates = require('../topology/topology_templates_common');
var applications = require('../applications/applications');

describe('Applications management :', function() {
  /* Before each spec in the tests suite */
  beforeEach(function() {
    common.before();
    authentication.login('applicationManager');
  });

  /* After each spec in the tests suite(s) */
  afterEach(function() {
    // Logout action
    common.after();
  });

  it('should be able to go to application search page at ' + common.appSearchUrl + ' and create new application', function() {
    console.log('################# should be able to go to application search page at ' + common.appSearchUrl + ' and create new application');
    applications.createApplication('Alien', 'Great Application');
    // Go to the app details page
    expect(browser.element(by.binding('application.name')).getText()).toEqual('Alien');
    expect(browser.element(by.binding('application.description')).getText()).toEqual('Great Application');
  });

  it('should create first a topology template with 3 node templates (COMPUTE, JAVA, TOMCATRPM) and an application based on this template', function() {
    console.log('################# should create first a topology template with 3 node templates (COMPUTE, JAVA, TOMCATRPM) and an application based on this template');
    // Login as architect to create a topology template
    authentication.reLogin('architect');

    // create a topology template with one Compute, 1 Java and 1 Tomcat RPM
    topologyTemplates.createTopologyTemplateWithNodesAndRelationships(topologyEditorCommon.topologyTemplates.template4);

    // create a new application with this template as model
    authentication.reLogin('applicationManager');
    // template at index 2 is the first and only one created (index 1 equals is the default, no template)
    applications.createApplication('JavaTomcatWarApplication', 'Simple application with one compute, one template and all that around java...', 2);

    // check the created topology application (count nodes, count relationship..)
    applications.goToApplicationDetailPage('JavaTomcatWarApplication', true);

    // check relationship count
    // check relationship count
    element(by.id('rect_JavaRPM')).click();
    browser.waitForAngular();
    var relationships = element.all(by.repeater('(relationshipName,relationshipDefinition) in selectedNodeTemplate.relationships'));
    expect(relationships.count()).toBe(2);
    element(by.id('rect_Compute_2')).click();
    browser.waitForAngular();
    relationships = element.all(by.repeater('(relationshipName,relationshipDefinition) in selectedNodeTemplate.relationships'));
    expect(relationships.count()).toBe(0);
    element(by.id('rect_Compute')).click();
    browser.waitForAngular();
    relationships = element.all(by.repeater('(relationshipName,relationshipDefinition) in selectedNodeTemplate.relationships'));
    expect(relationships.count()).toBe(0);
  });

  it('should be able to delete an application from the search list and the application\'s detail page', function() {
    console.log('################# should be able to delete an application from the search list and the application\'s detail page');
    applications.createApplication('Alien_1', 'Great Application 1');
    applications.createApplication('Alien_2', 'Great Application 2');
    applications.createApplication('Alien_3', 'Great Application 3');
    applications.goToApplicationListPage('main', 'applications');
    // delete application from the search list
    var appElement = element(by.id('app_Alien_1'));
    common.ptor.actions().mouseMove(appElement).perform();
    browser.sleep(1000); // one second so the turn annimation ends.
    common.deleteWithConfirm('delete-app_Alien_1', true);
    expect(appElement.isPresent()).toBe(false);

    // cancel a delete action
    appElement = element(by.id('app_Alien_3'));
    common.ptor.actions().mouseMove(appElement).perform();
    browser.sleep(1000); // one second so the turn annimation ends.
    common.deleteWithConfirm('delete-app_Alien_3', false);
    expect(appElement.isPresent()).toBe(true);

    // delete application from it detail page
    appElement = element(by.id('app_Alien_2'));
    applications.goToApplicationDetailPage('Alien_2');
    common.deleteWithConfirm('btn-delete-app', true);
    expect(appElement.isPresent()).toBe(false);

  });

  it('should be able to edit an application', function() {
    console.log('################# should be able to rename an application');
    // Create an application
    applications.createApplication('MyNewApplication1', 'A brand new application...');
    applications.createApplication('MyNewApplication2', 'A rband new application...');
    applications.goToApplicationDetailPage('MyNewApplication1');

    // Rename the application with a non existing name
    common.sendValueToXEditable('app-name', 'NewNameForMyApp', false);
    expect(element(by.binding('application.name')).getText()).toEqual('NewNameForMyApp');
    common.expectNoErrors();

    // Change the application's description
    common.sendValueToXEditable('app-desc', 'Some Description', false, 'textarea');
    expect(element(by.binding('application.description')).getText()).toEqual('Some Description');
    common.expectNoErrors();

    // Rename with an existing application name
    common.sendValueToXEditable('app-name', 'MyNewApplication2', false);
    common.abortXEditable('app-name');
    common.expectTitleMessage('409'); // server 'AlreadyExist' exception error code
    common.dismissAlert();
  });

});
<|endoftext|>


<commit_before>import angular from "angular";
import uiRouter from "angular-ui-router";
import storeDetailComponent from "./storeDetail.component";

let storeDetailModule = angular.module("storeDetail", [
  uiRouter
])

        .component("storeDetail", storeDetailComponent)

        .config(($stateProvider, hookProvider) => {
          "ngInject";
          $stateProvider
                  .state("storeDetail", {
                    url: "/store/:id",
                    component: "storeDetail",
                    resolve: {
                      storedata: (Store, $stateParams) => {
                        return Store.get({ "id": $stateParams.id });
                      }
                    }
                  });
          hookProvider.setup("storeDetail", { authenticated: true, anonymous: "login" });
        })

        .name;

export default storeDetailModule;
<commit_msg>changed formatting<commit_after>import angular from "angular";
import uiRouter from "angular-ui-router";
import storeDetailComponent from "./storeDetail.component";

let storeDetailModule = angular.module("storeDetail", [
  uiRouter
])

.component("storeDetail", storeDetailComponent)

.config(($stateProvider, hookProvider) => {
  "ngInject";
  $stateProvider
    .state("storeDetail", {
      url: "/store/:id",
      component: "storeDetail",
      resolve: {
        storedata: (Store, $stateParams) => {
          return Store.get({ "id": $stateParams.id });
        }
      }
    });
  hookProvider.setup("storeDetail", { authenticated: true, anonymous: "login" });
})

.name;

export default storeDetailModule;
<|endoftext|>


<commit_before>(function () {
  'use strict';
  /**
   * @ngdoc function
   * @name com.module.core.controller:MainCtrl
   * @description Login Controller
   * @requires $scope
   * @requires $state

   * @requires CoreService
   * @requires User
   * @requires gettextCatalog
   **/
  angular
    .module('com.module.core')
    .controller('MainCtrl', function ($scope, $rootScope, $state, LoopBackAuth, AppAuth, CoreService, User, gettextCatalog) {
      AppAuth.ensureHasCurrentUser(function (cu) {
        //This call also serves to redirect a user to the login screen, via the interceptor in users.auth.js, if they are not authenticated.
        $scope.currentUser = User.getCurrent();

      });

      $scope.menuoptions = [];

      User.roles({ id : LoopBackAuth.currentUserId//,filter: {where: {name: 'admin'}}
        }).$promise.then(function (data) {
          var menuoptions = [];
          //只展示有权限的菜单
          angular.forEach(data, function (role) {
            angular.forEach($rootScope.menu, function (menu) {
              var sd = $state.get(menu.sref).data;
              var nr = sd && sd.roles ? sd.roles : [];
              var hasRole = nr.length?false:true;
              angular.forEach(nr, function (ned) {
                if(role.name === ned) {hasRole = true;}
              });
              hasRole && this.push(menu);
            },menuoptions);
          });
          $scope.menuoptions = menuoptions;

        }, function () {
          // Error with request//$rootScope.r_deferred.reject();
        });

      $scope.logout = function () {
        AppAuth.logout(function () {
          CoreService.toastSuccess(gettextCatalog.getString('Logged out'),
            gettextCatalog.getString('You are logged out!'));
          $state.go('login');
        });
      };

    });

})();
<commit_msg>fix github user no roles no menu<commit_after>(function () {
  'use strict';
  /**
   * @ngdoc function
   * @name com.module.core.controller:MainCtrl
   * @description Login Controller
   * @requires $scope
   * @requires $state

   * @requires CoreService
   * @requires User
   * @requires gettextCatalog
   **/
  angular
    .module('com.module.core')
    .controller('MainCtrl', function ($scope, $rootScope, $state, LoopBackAuth, AppAuth, CoreService, User, gettextCatalog) {
      AppAuth.ensureHasCurrentUser(function (cu) {
        //This call also serves to redirect a user to the login screen, via the interceptor in users.auth.js, if they are not authenticated.
        $scope.currentUser = User.getCurrent();

      });

      $scope.menuoptions = [];

      User.roles({ id : LoopBackAuth.currentUserId//,filter: {where: {name: 'admin'}}
        }).$promise.then(function (data) {
          var menuoptions = [];
          //只展示有权限的菜单
          angular.forEach(data, function (role) {
            angular.forEach($rootScope.menu, function (menu) {
              var sd = $state.get(menu.sref).data;
              var nr = sd && sd.roles ? sd.roles : [];
              var hasRole = nr.length?false:true;
              angular.forEach(nr, function (ned) {
                if(role.name === ned) {hasRole = true;}
              });
              hasRole && this.push(menu);
            },menuoptions);
          });
          $scope.menuoptions = menuoptions;

        }, function () {
          // Error with request//$rootScope.r_deferred.reject();
          var menuoptions = [];
          //github user 没有roles,展示无rolse的菜单
          angular.forEach($rootScope.menu, function (menu) {
            var sd = $state.get(menu.sref).data;
            var nr = sd && sd.roles ? sd.roles : [];
            var hasRole = nr.length?false:true;
            hasRole && this.push(menu);
          },menuoptions);
          $scope.menuoptions = menuoptions;
        });

      $scope.logout = function () {
        AppAuth.logout(function () {
          CoreService.toastSuccess(gettextCatalog.getString('Logged out'),
            gettextCatalog.getString('You are logged out!'));
          $state.go('login');
        });
      };

    });

})();
<|endoftext|>


<commit_before>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */

import angular from 'angular';

blogService.$inject = ['api', '$q', '$rootScope', 'config'];

export default function blogService(api, $q, $rootScope, config) {
    function update(blog, updated) {
        return api.blogs.update(blog, updated);
    }

    function save(blog, data) {
        return api.blogs.save(blog, data);
    }

    function get(_id, param, cache) {
        return api.blogs.getById(_id, param, cache);
    }

    /**
    * Retrieve the public url of the given blog.
    * If not available, it will start to listen websocket publication notification
    * in order to update the blog with the fresh public url
    * @param {object} blog
    * @return {promise} public_url
    **/
    function getPublicUrl(blog) {
        var deferred = $q.defer();
        // for debug purpose
        if (!blog.public_url && config.debug) {
            deferred.resolve('http://localhost:5000/embed/' + blog._id);
        } else if (blog.public_url) {
            // if the blog contains the url, returns it
            deferred.resolve(blog.public_url.replace('http://', 'https://'));
        } else {
            // otherwise, listen for websocket notifications regarding publication
            var notif_listener = $rootScope.$on('blog', function updateBlogAndResolve(e, data) {
                if (data.blog_id === blog._id && data.published === 1) {
                    // update the blog property
                    blog.public_url = data.public_url;
                    // unbind the listener
                    notif_listener();
                    // return the url
                    // fix https issue
                    deferred.resolve(blog.public_url.replace('http://', 'https://'));
                }
            });
        }
        return deferred.promise;
    }

    return {
        get: get,
        update: update,
        save: save,
        getPublicUrl: getPublicUrl
    };
}
<commit_msg>fix: use server config in development.<commit_after>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */

import angular from 'angular';

blogService.$inject = ['api', '$q', '$rootScope', 'config'];

export default function blogService(api, $q, $rootScope, config) {
    function update(blog, updated) {
        return api.blogs.update(blog, updated);
    }

    function save(blog, data) {
        return api.blogs.save(blog, data);
    }

    function get(_id, param, cache) {
        return api.blogs.getById(_id, param, cache);
    }

    /**
    * Retrieve the public url of the given blog.
    * If not available, it will start to listen websocket publication notification
    * in order to update the blog with the fresh public url
    * @param {object} blog
    * @return {promise} public_url
    **/
    function getPublicUrl(blog) {
        var deferred = $q.defer();
        // for debug purpose
        if (!blog.public_url && config.debug) {
            deferred.resolve(config.server.url.replace('/api', `/embed/${blog._id}`));
        } else if (blog.public_url) {
            // if the blog contains the url, returns it
            deferred.resolve(config.debug ? blog.public_url : blog.public_url.replace('http://', 'https://'));
        } else {
            // otherwise, listen for websocket notifications regarding publication
            var notif_listener = $rootScope.$on('blog', function updateBlogAndResolve(e, data) {
                if (data.blog_id === blog._id && data.published === 1) {
                    // update the blog property
                    blog.public_url = data.public_url;
                    // unbind the listener
                    notif_listener();
                    // return the url
                    // fix https issue
                    deferred.resolve(config.debug ? blog.public_url : blog.public_url.replace('http://', 'https://'));
                }
            });
        }
        return deferred.promise;
    }

    return {
        get: get,
        update: update,
        save: save,
        getPublicUrl: getPublicUrl
    };
}
<|endoftext|>


<commit_before>/* @ flow */
'use strict'
const Vrt = require('../src/lib/vrt')
const GeoJSON = require('../src/lib/geojson')
const test = require('tape')
const fs = require('fs')
const Helper = require('./helper')
const _ = require('highland')

const output = `${__dirname}/output`

test('Set up', t => {
  Helper.before()
  t.end()
})

test('write a vrt', t => {
  t.plan(6)
  const vrtPath = `${output}/layer.vrt`
  fs.createReadStream(`${__dirname}/fixtures/fc.geojson`)
  .pipe(Vrt.createStream({ path: output, size: 33 }))
  .on('finish', () => {
    [0, 1, 2, 3].forEach(n => {
      const file = fs.readFileSync(`${output}/part.${n}.json`)
      try {
        JSON.parse(file)
        t.pass(`JSON part ${n + 1} of 4 parsed successfully`)
      } catch (e) {
        t.fail(`JSON part ${n + 1} of 4 could not be parsed`)
      }
    })
    t.ok(fs.statSync(vrtPath), 'VRT written')
    t.equal(fs.readFileSync(vrtPath).toString().length > 0, true, 'VRT has content')
  })
})

test('write a vrt from geojson that has a newline after the opening tags', t => {
  t.plan(6)
  const vrtPath = `${output}/layer.vrt`
  fs.createReadStream(`${__dirname}/fixtures/legacyFc.geojson`)
  .pipe(Vrt.createStream({ path: output, size: 33 }))
  .on('error', e => {
    t.fail('Failed while writing VRT')
    t.end()
  })
  .on('finish', () => {
    [0, 1, 2, 3].forEach(n => {
      const file = fs.readFileSync(`${output}/part.${n}.json`)
      try {
        JSON.parse(file)
        t.pass(`JSON part ${n + 1} of 4 parsed successfully`)
      } catch (e) {
        t.fail(`JSON part ${n + 1} of 4 could not be parsed`)
      }
    })
    t.ok(fs.statSync(vrtPath), 'VRT written')
    t.equal(fs.readFileSync(vrtPath).toString().length > 0, true, 'VRT has content')
  })
})

test('write a vrt using input from GeoJSON.createStream', t => {
  t.plan(6)
  fs.mkdirSync(`${output}/vrt2`)
  const outPath = `${output}/vrt2`
  const vrtPath = `${outPath}/layer.vrt`
  _(fs.createReadStream(`${__dirname}/fixtures/features.txt`))
  .split()
  .compact()
  .pipe(GeoJSON.createStream())
  .pipe(Vrt.createStream({ path: outPath, size: 33 }))
  .on('finish', () => {
    [0, 1, 2, 3].forEach(n => {
      const file = fs.readFileSync(`${outPath}/part.${n}.json`)
      try {
        JSON.parse(file)
        t.pass(`JSON part ${n + 1} of 4 parsed successfully`)
      } catch (e) {
        t.fail(`JSON part ${n + 1} of 4 could not be parsed`)
      }
    })
    t.ok(fs.statSync(vrtPath), 'VRT written')
    t.equal(fs.readFileSync(vrtPath).toString().length > 0, true, 'VRT has content')
  })
})

test('fail gracefully when geojson input is bad', t => {
  t.plan(3)
  fs.createReadStream(`${__dirname}/fixtures/bad.txt`)
  .pipe(Vrt.createStream({ path: output, size: 33 }))
  .on('error', e => {
    t.ok(e, 'Error emitted in expected place')
  })
  .on('finish', () => t.fail('Should not have finished'))
})

test('Teardown', t => {
  Helper.after()
  t.end()
})
<commit_msg>update test<commit_after>/* @ flow */
'use strict'
const Vrt = require('../src/lib/vrt')
const GeoJSON = require('../src/lib/geojson')
const test = require('tape')
const fs = require('fs')
const Helper = require('./helper')
const _ = require('highland')

const output = `${__dirname}/output`

test('Set up', t => {
  Helper.before()
  t.end()
})

test('write a vrt', t => {
  t.plan(6)
  const vrtPath = `${output}/layer.vrt`
  fs.createReadStream(`${__dirname}/fixtures/fc.geojson`)
  .pipe(Vrt.createStream({ path: output, size: 33 }))
  .on('finish', () => {
    [0, 1, 2, 3].forEach(n => {
      const file = fs.readFileSync(`${output}/part.${n}.json`)
      try {
        JSON.parse(file)
        t.pass(`JSON part ${n + 1} of 4 parsed successfully`)
      } catch (e) {
        t.fail(`JSON part ${n + 1} of 4 could not be parsed`)
      }
    })
    t.ok(fs.statSync(vrtPath), 'VRT written')
    t.equal(fs.readFileSync(vrtPath).toString().length > 0, true, 'VRT has content')
  })
})

test('write a vrt from geojson that has a newline after the opening tags', t => {
  t.plan(6)
  const vrtPath = `${output}/layer.vrt`
  fs.createReadStream(`${__dirname}/fixtures/legacyFc.geojson`)
  .pipe(Vrt.createStream({ path: output, size: 33 }))
  .on('error', e => {
    t.fail('Failed while writing VRT')
    t.end()
  })
  .on('finish', () => {
    [0, 1, 2, 3].forEach(n => {
      const file = fs.readFileSync(`${output}/part.${n}.json`)
      try {
        JSON.parse(file)
        t.pass(`JSON part ${n + 1} of 4 parsed successfully`)
      } catch (e) {
        t.fail(`JSON part ${n + 1} of 4 could not be parsed`)
      }
    })
    t.ok(fs.statSync(vrtPath), 'VRT written')
    t.equal(fs.readFileSync(vrtPath).toString().length > 0, true, 'VRT has content')
  })
})

test('write a vrt using input from GeoJSON.createStream', t => {
  t.plan(6)
  fs.mkdirSync(`${output}/vrt2`)
  const outPath = `${output}/vrt2`
  const vrtPath = `${outPath}/layer.vrt`
  _(fs.createReadStream(`${__dirname}/fixtures/features.txt`))
  .split()
  .compact()
  .pipe(GeoJSON.createStream())
  .pipe(Vrt.createStream({ path: outPath, size: 33 }))
  .on('finish', () => {
    [0, 1, 2, 3].forEach(n => {
      const file = fs.readFileSync(`${outPath}/part.${n}.json`)
      try {
        JSON.parse(file)
        t.pass(`JSON part ${n + 1} of 4 parsed successfully`)
      } catch (e) {
        t.fail(`JSON part ${n + 1} of 4 could not be parsed`)
      }
    })
    t.ok(fs.statSync(vrtPath), 'VRT written')
    t.equal(fs.readFileSync(vrtPath).toString().length > 0, true, 'VRT has content')
  })
})

test('fail gracefully when geojson input is bad', t => {
  t.plan(1)
  fs.createReadStream(`${__dirname}/fixtures/bad.txt`)
  .pipe(Vrt.createStream({ path: output, size: 33 }))
  .on('error', e => {
    t.ok(e, 'Error emitted in expected place')
  })
  .on('finish', () => t.fail('Should not have finished'))
})

test('Teardown', t => {
  Helper.after()
  t.end()
})
<|endoftext|>


<commit_before>// module EntryForm
//
// Features
// - use same form for entry creation and edit.
// - handles the API calls internally
// - is able to upload attachments
// - temporary store of content for interrupted creation or edit
//
var template = require('./template.ejs');
var AttachmentsView = require('./Attachments');
var MarkdownView = require('./Markdown');
var ErrorView = require('./Error');
var ui = require('tresdb-ui');
var emitter = require('component-emitter');
var account = tresdb.stores.account;
var entries = tresdb.stores.entries;

module.exports = function (location, entry) {
  // Entry form View.
  //
  // Parameters:
  //   location
  //     location object
  //   entry
  //     optional entry object. If not given, a blank entry form is shown.
  //
  if (!entry) {
    entry = {
      user: account.getName(),
      markdown: '',
      attachments: [],
      flags: [],
    };
  }

  var self = this;
  emitter(self);

  var $elems = {};
  var children = {};

  self.bind = function ($mount) {

    var isNew = !('_id' in entry);

    $mount.html(template({
      entry: entry,
      isNew: isNew,
    }));

    children.markdown = new MarkdownView(location, entry);
    children.markdown.bind($mount.find('.form-markdown-container'));

    children.attachments = new AttachmentsView(entry, entry.attachments);
    children.attachments.bind($mount.find('.form-attachments-container'));

    children.error = new ErrorView();
    children.error.bind($mount.find('.form-error-container'));

    $elems.saveBtn = $mount.find('.entry-form-save');
    $elems.saveBtn.click(function () {
      // Create new entry or update the existing

      var entryData = {
        markdown: children.markdown.getMarkdown().trim(),
        attachments: children.attachments.getAttachmentKeys(),
        flags: [], // TODO children.flags.getFlags(),
      };

      // Ensure non-empty content
      if (entryData.markdown.length + entryData.attachments.length === 0) {
        children.error.update('Empty posts are not allowed.');
        return;
      }

      if (isNew) {
        entries.create(location._id, entryData, function (err) {
          if (err) {
            // TODO show submit error
            return console.log(err);
          }
          self.emit('success');
        });
      } else {
        entries.change(location._id, entry._id, entryData, function (err) {
          if (err) {
            // TODO
            return console.log(err);
          }
          self.emit('success');
        });
      }
    });

    $elems.cancelBtn = $mount.find('.entry-form-cancel');
    $elems.cancelBtn.click(function () {
      self.emit('exit');
    });

    // Focus
    children.markdown.focus();
  };

  self.unbind = function () {
    ui.offAll($elems);
    ui.unbindAll(children);
  };
};
<commit_msg>Prevent double-click save and handle errors<commit_after>// module EntryForm
//
// Features
// - use same form for entry creation and edit.
// - handles the API calls internally
// - is able to upload attachments
// - temporary store of content for interrupted creation or edit
//
var template = require('./template.ejs');
var AttachmentsView = require('./Attachments');
var MarkdownView = require('./Markdown');
var ErrorView = require('./Error');
var ui = require('tresdb-ui');
var emitter = require('component-emitter');
var account = tresdb.stores.account;
var entries = tresdb.stores.entries;

module.exports = function (location, entry) {
  // Entry form View.
  //
  // Parameters:
  //   location
  //     location object
  //   entry
  //     optional entry object. If not given, a blank entry form is shown.
  //
  if (!entry) {
    entry = {
      user: account.getName(),
      markdown: '',
      attachments: [],
      flags: [],
    };
  }

  var self = this;
  emitter(self);

  var $elems = {};
  var children = {};

  self.bind = function ($mount) {

    var isNew = !('_id' in entry);

    $mount.html(template({
      entry: entry,
      isNew: isNew,
    }));

    children.markdown = new MarkdownView(location, entry);
    children.markdown.bind($mount.find('.form-markdown-container'));

    children.attachments = new AttachmentsView(entry, entry.attachments);
    children.attachments.bind($mount.find('.form-attachments-container'));

    children.error = new ErrorView();
    children.error.bind($mount.find('.form-error-container'));

    $elems.saveBtn = $mount.find('.entry-form-save');
    $elems.saveBtn.click(function () {
      // Create new entry or update the existing

      // Prevent double click
      $elems.saveBtn.attr('disabled', 'disabled');

      var entryData = {
        markdown: children.markdown.getMarkdown().trim(),
        attachments: children.attachments.getAttachmentKeys(),
        flags: [], // TODO children.flags.getFlags(),
      };

      var onError = function (msg) {
        // Show alert
        children.error.update(msg);
        // Enable save
        $elems.saveBtn.removeAttr('disabled');
      };

      var onSuccess = function () {
        self.emit('success');
      };

      // Ensure non-empty content
      if (entryData.markdown.length + entryData.attachments.length === 0) {
        return onError('Empty posts are not allowed.');
      }

      if (isNew) {
        entries.create(location._id, entryData, function (err) {
          if (err) {
            return onError(err.message);
          }
          onSuccess();
        });
      } else {
        entries.change(location._id, entry._id, entryData, function (err) {
          if (err) {
            return onError(err.message);
          }
          onSuccess();
        });
      }
    });

    $elems.cancelBtn = $mount.find('.entry-form-cancel');
    $elems.cancelBtn.click(function () {
      self.emit('exit');
    });

    // Focus
    children.markdown.focus();
  };

  self.unbind = function () {
    ui.offAll($elems);
    ui.unbindAll(children);
  };
};
<|endoftext|>


<commit_before>'use strict';
/* global google */

angular.module('fahrtenbuchApp')
  .factory('Directions', function Directions($q, Geocode) {

    return {

      /**
       * get route
       *
       * @param   {Function}  callback    - optional
       * @param   {Array}     coordinatesList
       * @param   {Array}     stays
       * @param   {Object}    map
       * @return  {Array}     routes
      */
      getRoute: function(callback, coordinatesList, stays, map) {

        var cb = callback || angular.noop;
        var deferred = $q.defer();

        if (google === undefined) {
          var err = new Error('No Connection to Google!');
          deferred.reject(err);
          return cb(err);
        }

        var marker;
        var origin;
        var destination;
        var waypts = [];

        var directionsService = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();

        google.maps.event.addDomListener(window, 'load', directionsDisplay.setMap(map));

        for (var i = 0; i < coordinatesList.length; i++) {
          if (i === 0) {
            origin = coordinatesList[i];
          }
          if (i === coordinatesList.length - 1) {
            destination = coordinatesList[i];
          } else {
            waypts.push({
              location: coordinatesList[i],
              stopover: true
            });
          }
        }

        var request = {
          origin: origin,
          destination: destination,
          waypoints: waypts,
          optimizeWaypoints: true,
          travelMode: google.maps.TravelMode.DRIVING
        };

        // directionsDisplay = new google.maps.DirectionsRenderer({
        //   suppressMarkers: true
        // });

        stays.forEach(function(stay) {
          new google.maps.Marker({
            position: new google.maps.LatLng(stay.destinationLat, stay.destinationLong),
            map: map,
            title: stay.destination
          });
        });

        var marker = new google.maps.Marker({
          position: origin,
          map: map,
          title: 'origin'
        });

        // var infowindow = new google.maps.InfoWindow({
        //   content: "There ones was a mayden from ..../span>"
        // });

        // google.maps.event.addListener(marker, 'click', function() {
        //   infowindow.open(map, marker);
        // });

        new google.maps.Marker({
          position: destination,
          map: map,
          title: 'destination'
        });

        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            deferred.resolve(response.routes[0]);
          } else {
            // var err = new Error('Route couldn\'t be calculated');
            var err = new Error(status);
            deferred.reject(err);
            return cb(err);
          }
        });

        return deferred.promise;
      },

      /**
       * draw route with polygons
       *
       * @param   {Function}  callback    - optional
       * @param   {Array}     coordinatesList
       * @param   {Object}    map
       * @return  {Array}     path
      */
      polygons: function(callback, coordinatesList , map) {

        //init
        console.log("coordinatesList:");
        console.log(coordinatesList);
        console.log(coordinatesList.length);
        // anderes Format?

        console.log("map:");
        console.log(map);

        var polyOptions = {
          strokeColor: '#000000',
          strokeOpacity: 1.0,
          strokeWeight: 3
        };

        console.log("polyOptions:");
        console.log(polyOptions);

        var poly = new google.maps.Polyline(polyOptions);

        console.log("poly:");
        console.log(poly);

        poly.setMap(map);
        // test: bis hier alles in trip.controller

        var path = poly.getPath();

        console.log("path:");
        console.log(path);

        coordinatesList.forEach(function(coord) {
          console.log(coord);

          path.push(new google.maps.LatLng(coord.coords.latitude, coord.coords.longitude));
          // path.push(coord);

          var marker = new google.maps.Marker({
            position: coord,
            // title: '#' + path.getLength(),
            map: map
          });
        });

      }
    };
  });<commit_msg>propably fixed polygons<commit_after>'use strict';
/* global google */

angular.module('fahrtenbuchApp')
  .factory('Directions', function Directions($q, Geocode) {

    return {

      /**
       * get route
       *
       * @param   {Function}  callback    - optional
       * @param   {Array}     coordinatesList
       * @param   {Array}     stays
       * @param   {Object}    map
       * @return  {Array}     routes
      */
      getRoute: function(callback, coordinatesList, stays, map) {

        var cb = callback || angular.noop;
        var deferred = $q.defer();

        if (google === undefined) {
          var err = new Error('No Connection to Google!');
          deferred.reject(err);
          return cb(err);
        }

        var marker;
        var origin;
        var destination;
        var waypts = [];

        var directionsService = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();

        google.maps.event.addDomListener(window, 'load', directionsDisplay.setMap(map));

        for (var i = 0; i < coordinatesList.length; i++) {
          if (i === 0) {
            origin = coordinatesList[i];
          }
          if (i === coordinatesList.length - 1) {
            destination = coordinatesList[i];
          } else {
            waypts.push({
              location: coordinatesList[i],
              stopover: true
            });
          }
        }

        var request = {
          origin: origin,
          destination: destination,
          waypoints: waypts,
          optimizeWaypoints: true,
          travelMode: google.maps.TravelMode.DRIVING
        };

        // directionsDisplay = new google.maps.DirectionsRenderer({
        //   suppressMarkers: true
        // });

        stays.forEach(function(stay) {
          new google.maps.Marker({
            position: new google.maps.LatLng(stay.destinationLat, stay.destinationLong),
            map: map,
            title: stay.destination
          });
        });

        var marker = new google.maps.Marker({
          position: origin,
          map: map,
          title: 'origin'
        });

        // var infowindow = new google.maps.InfoWindow({
        //   content: "There ones was a mayden from ..../span>"
        // });

        // google.maps.event.addListener(marker, 'click', function() {
        //   infowindow.open(map, marker);
        // });

        new google.maps.Marker({
          position: destination,
          map: map,
          title: 'destination'
        });

        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            deferred.resolve(response.routes[0]);
          } else {
            // var err = new Error('Route couldn\'t be calculated');
            var err = new Error(status);
            deferred.reject(err);
            return cb(err);
          }
        });

        return deferred.promise;
      },

      /**
       * draw route with polygons
       *
       * @param   {Function}  callback    - optional
       * @param   {Array}     coordinatesList
       * @param   {Object}    map
       * @return  {Array}     path
      */
      polygons: function(callback, coordinatesList , map) {

        //init
        console.log("coordinatesList:");
        console.log(coordinatesList);
        console.log(coordinatesList.length);
        // anderes Format?

        console.log("map:");
        console.log(map);

        var polyOptions = {
          strokeColor: '#000000',
          strokeOpacity: 1.0,
          strokeWeight: 3
        };

        console.log("polyOptions:");
        console.log(polyOptions);

        var poly = new google.maps.Polyline(polyOptions);

        console.log("poly:");
        console.log(poly);

        poly.setMap(map);
        // test: bis hier alles in trip.controller

        var path = poly.getPath();

        console.log("path:");
        console.log(path);

        // coordinatesList.forEach(function(coord) {
        for (var coord of coordinatesList) {
          console.log(coord);

          var lat = coord.coords.latitude;
          var lng = coord.coords.longitude;
          var element = new google.maps.LatLng(lat, lng);
          // var element = coord.coords.getPosition();

          // lat is no number?!!!!

          // var element = { lat: lat, lng: lng };
          console.log(element);

          path.push(element);
          // console.log(new google.maps.LatLng(coord.coords.latitude, coord.coords.longitude));
          // path.push(coord);

          var marker = new google.maps.Marker({
            position: element,
            // title: '#' + path.getLength(),
            map: map
          });
        } // );

      }
    };
  });<|endoftext|>


<commit_before>/** @jsx React.DOM */

"use strict";
"use babel";

const async = require("async");
const _ = require("lodash");
const React = require('react-atom-fork');
const open_url = require("open");
const floorc = require("../common/floorc");
const api = require("../common/api");
const constants = require("../common/constants");
const mixins = require("./mixins");

module.exports = React.createClass({
  mixins: [mixins.ReactUnwrapper, mixins.FormMixin],
  getInitialState: function () {
    return {
      error: "",
      name: "",
      create: true,
      hosts: {},
      host: "",
      disabled_hosts: {},
      owner: "",
      // perms
      view: true,
      edit: false,
      needsMonies: false
    };
  },
  componentWillMount: function () {
    if (!this.props.dir) {
      console.error("can't create a workspace without an open directory in atom");
      return this.destroy();
    }
    const state = this.state;
    state.name = this.props.dir.getBaseName();
    if (_.has(floorc.auth, constants.HOST)) {
      state.host = constants.HOST;
      state.owner = floorc.auth[constants.HOST].username;
    } else {
      state.host = _.keys(floorc.auth)[0];
      state.owner = floorc.auth[state.host].username;
    }

    _.each(floorc.auth, function (auth, host) {
      state.hosts[host] = [auth.username];
    });

    this.setState(state);

    const that = this;
    async.each(_.keys(floorc.auth), function (host, cb) {
      api.get_orgs_can_admin(host, function (err, res, body) {
        const hosts = that.state.hosts;
        if (err) {
          that.state.disabled_hosts[host] = true;
          that.setState(that.state);
          console.error(err);
        } else {
          _.each(body, function (org) {
            hosts[host].push(org.name);
          });
          that.setState(hosts);
        }
        return cb();
      });
    }, function (err) {
      if (err) {
        console.error(err);
      }

      const name = that.refs.name.getDOMNode();
      const length = name.value.length;
      name.setSelectionRange(length, length);
      name.focus();
    });
  },
  join: function (url, created) {
    const path = this.props.dir.getPath();
    process.nextTick(function () {
      require("../floobits").join_workspace_(path, url, created);
    });
    this.destroy();
  },
  onSubmit: function (event) {
    event.preventDefault();
    const create = this.refs.create ? this.refs.create.getDOMNode().checked : true;
    if (!create) {
      this.join(this.props.url);
      return;
    }
    const edit = this.refs.edit.getDOMNode().checked;
    const view = this.refs.view.getDOMNode().checked;
    const perms = [];
    if (edit) {
      perms.push("edit_room");
      perms.push("view_room");
    }
    if (view) {
      perms.push("view_room");
    }
    const name = this.refs.name.getDOMNode().value;
    const host = this.state.host;
    const owner = this.state.owner;
    const room_perms = {AnonymousUser: perms};
    api.create_workspace(host, name, owner, room_perms, function (err, res, body) {
      console.log(err, res, body);
      const code = res.statusCode;

      if (code < 400) {
        const workspace = `http://${host}/${owner}/${name}`;
        console.log("created workspace", workspace);
        this.join(workspace, true);
        return;
      }
      console.error('Unable to create workspace: ', code, body);

      switch (code) {
        case 400:
          this.setState({
            needsMonies: false,
            name: name.replace(/[^A-Za-z0-9_\-\.]/g, "-"),
            error: "Workspace names may only contain [A-Za-z0-9_\-\.]."
          });
          return;
        case 402:
          this.setState({needsMonies: true, error: false});
          return;
        case 409:
          this.setState({
            error: "A workspace with that name already exists.",
            needsMonies: false,
            name: this.state.name + "1"}
          );
          return;
        default:
          this.setState({
            needsMonies: false,
            error: `Could not create workspace ${code}: ${body}`
          });
          return;
      }
    }.bind(this));
  },
  toggleCreate: function (event) {
    this.setState({create: event.target.checked});
  },
  onNameChange: function (event) {
    this.setState({name: event.target.value});
  },
  onSelectAuth: function (event) {
    this.setState({host: event.target.value});
  },
  render_auth: function () {
    const auths = _.keys(this.state.hosts);
    if (auths.length <= 1) {
      return;
    }
    auths.sort(function (a, b) {
      if (a === constants.HOST) {
        return -1;
      }
      if (b === constants.HOST) {
        return 1;
      }
      if (a === b) {
        return 0;
      } else if (a < b) {
        return -1;
      }
      return 1;
    });
    const that = this;
    return (

        Host

          {auths.map(function (host) {
            const disabled = that.state.disabled_hosts[host];
            return (

                <input onChange={that.onSelectAuth} type="radio" name="host" value={host} tabIndex="3"
                  disabled={disabled} checked={host === that.state.host} className="native-key-bindings" /> {host}

            );
          })}

    );
  },
  onChangedOwner: function (event) {
    this.setState({owner: event.target.value});
  },
  onChangeView: function (event) {
    const state = {view: event.target.checked};
    if (!state.view) {
      state.edit = false;
    }
    this.setState(state);
  },
  onChangeEdit: function (event) {
    const state = {edit: event.target.checked};
    if (state.edit) {
      state.view = true;
    }
    this.setState(state);
  },
  render_create: function () {
    const owners = this.state.hosts[this.state.host];

    let username = floorc.auth[this.state.host];
    username = username && username.username;

    owners.sort(function (a, b) {
      if (a === username) {
        return -1;
      }
      if (b === username) {
        return 1;
      }
      if (a === b) {
        return 0;
      } else if (a < b) {
        return -1;
      }
      return 1;
    });
    const that = this;
    const labels = owners.map(function (o) {
      return (

          <input type="radio" onChange={that.onChangedOwner} name="owner" tabIndex="5"
            value={o} className="native-key-bindings" checked={o === that.state.owner}/> {o}

      );
    });
    return (

        {this.render_auth()}

          Owner

            {labels}

          Name

            <input tabIndex="7" id="floobits-name" ref="name" className="native-key-bindings form-control" type="text" value={this.state.name} onChange={this.onNameChange}/>

          Description

            <textarea tabIndex="9" id="floobits-description" ref="description" className="native-key-bindings form-control" type="text" rows="3" />

          Global Permissions

              <input tabIndex="11" checked={this.state.view} onChange={this.onChangeView} type="checkbox" ref="view" value="view" className="native-key-bindings" /> Viewable

              <input tabIndex="13" checked={this.state.edit} type="checkbox" ref="edit" value="edit" onChange={this.onChangeEdit} className="native-key-bindings" /> Editable

    );
  },
  render_create_new_workspace_option: function () {
    const url = this.props.url;
    if (!url) {
      return;
    }
    return (

              The workspace {url} already exists.  Do you want to create a new workspace?

                <input id="floobits-create" ref="create" type="checkbox" tabIndex="1"
                  onChange={this.toggleCreate} checked={this.state.create} className="native-key-bindings" /> Create New Workspace

    );
  },
  openBilling: function (event) {
    event.preventDefault();
    open_url(`https://${this.state.host}/${this.state.owner}/settings#billing`);
  },
  render: function () {
    return (

Create Workspace

          <form id="join-workspace" className="form-horizontal native-key-bindings" onSubmit={this.onSubmit}>
            {this.render_create_new_workspace_option()}
            {this.state.create && this.render_create()}
            {!this.state.error ? "" :

                {this.state.error}

            }
            {!this.state.needsMonies ? "" :

                You reached the limit for workspaces for {this.state.host}/{this.state.owner}.

            }

              <input tabIndex="14" type="submit" value={this.state.create ? "Create Workspace" : "Join Workspace"} className="floobits-submit" />
              <input tabIndex="15" type="submit" value="Cancel" className="floobits-submit" onClick={this.destroy} />

          </form>

    );
  }
});<commit_msg>fixes #85 - handle error condition on http api<commit_after>/** @jsx React.DOM */

"use strict";
"use babel";

const async = require("async");
const _ = require("lodash");
const React = require('react-atom-fork');
const open_url = require("open");
const floorc = require("../common/floorc");
const api = require("../common/api");
const constants = require("../common/constants");
const mixins = require("./mixins");

module.exports = React.createClass({
  mixins: [mixins.ReactUnwrapper, mixins.FormMixin],
  getInitialState: function () {
    return {
      error: "",
      name: "",
      create: true,
      hosts: {},
      host: "",
      disabled_hosts: {},
      owner: "",
      // perms
      view: true,
      edit: false,
      needsMonies: false
    };
  },
  componentWillMount: function () {
    if (!this.props.dir) {
      console.error("can't create a workspace without an open directory in atom");
      return this.destroy();
    }
    const state = this.state;
    state.name = this.props.dir.getBaseName();
    if (_.has(floorc.auth, constants.HOST)) {
      state.host = constants.HOST;
      state.owner = floorc.auth[constants.HOST].username;
    } else {
      state.host = _.keys(floorc.auth)[0];
      state.owner = floorc.auth[state.host].username;
    }

    _.each(floorc.auth, function (auth, host) {
      state.hosts[host] = [auth.username];
    });

    this.setState(state);

    const that = this;
    async.each(_.keys(floorc.auth), function (host, cb) {
      api.get_orgs_can_admin(host, function (err, res, body) {
        const hosts = that.state.hosts;
        if (err) {
          that.state.disabled_hosts[host] = true;
          that.setState(that.state);
          console.error(err);
        } else {
          _.each(body, function (org) {
            hosts[host].push(org.name);
          });
          that.setState(hosts);
        }
        return cb();
      });
    }, function (err) {
      if (err) {
        console.error(err);
      }

      const name = that.refs.name.getDOMNode();
      const length = name.value.length;
      name.setSelectionRange(length, length);
      name.focus();
    });
  },
  join: function (url, created) {
    const path = this.props.dir.getPath();
    process.nextTick(function () {
      require("../floobits").join_workspace_(path, url, created);
    });
    this.destroy();
  },
  onSubmit: function (event) {
    event.preventDefault();
    const create = this.refs.create ? this.refs.create.getDOMNode().checked : true;
    if (!create) {
      this.join(this.props.url);
      return;
    }
    const edit = this.refs.edit.getDOMNode().checked;
    const view = this.refs.view.getDOMNode().checked;
    const perms = [];
    if (edit) {
      perms.push("edit_room");
      perms.push("view_room");
    }
    if (view) {
      perms.push("view_room");
    }
    const name = this.refs.name.getDOMNode().value;
    const host = this.state.host;
    const owner = this.state.owner;
    const room_perms = {AnonymousUser: perms};
    api.create_workspace(host, name, owner, room_perms, function (err, res, body) {
      if (err) {
        atom.confirm({
          message: "Could not Create Workspace",
          detailedMessage: err.toString(),
          buttons: {"OK": function () {}}
        });
        console.error(err, res, body);
        return;
      }

      console.log(err, res, body);
      const code = res.statusCode;

      if (code < 400) {
        const workspace = `http://${host}/${owner}/${name}`;
        console.log("created workspace", workspace);
        this.join(workspace, true);
        return;
      }
      console.error('Unable to create workspace: ', code, body);

      switch (code) {
        case 400:
          this.setState({
            needsMonies: false,
            name: name.replace(/[^A-Za-z0-9_\-\.]/g, "-"),
            error: "Workspace names may only contain [A-Za-z0-9_\-\.]."
          });
          return;
        case 402:
          this.setState({needsMonies: true, error: false});
          return;
        case 409:
          this.setState({
            error: "A workspace with that name already exists.",
            needsMonies: false,
            name: this.state.name + "1"}
          );
          return;
        default:
          this.setState({
            needsMonies: false,
            error: `Could not create workspace ${code}: ${body}`
          });
          return;
      }
    }.bind(this));
  },
  toggleCreate: function (event) {
    this.setState({create: event.target.checked});
  },
  onNameChange: function (event) {
    this.setState({name: event.target.value});
  },
  onSelectAuth: function (event) {
    this.setState({host: event.target.value});
  },
  render_auth: function () {
    const auths = _.keys(this.state.hosts);
    if (auths.length <= 1) {
      return;
    }
    auths.sort(function (a, b) {
      if (a === constants.HOST) {
        return -1;
      }
      if (b === constants.HOST) {
        return 1;
      }
      if (a === b) {
        return 0;
      } else if (a < b) {
        return -1;
      }
      return 1;
    });
    const that = this;
    return (

        Host

          {auths.map(function (host) {
            const disabled = that.state.disabled_hosts[host];
            return (

                <input onChange={that.onSelectAuth} type="radio" name="host" value={host} tabIndex="3"
                  disabled={disabled} checked={host === that.state.host} className="native-key-bindings" /> {host}

            );
          })}

    );
  },
  onChangedOwner: function (event) {
    this.setState({owner: event.target.value});
  },
  onChangeView: function (event) {
    const state = {view: event.target.checked};
    if (!state.view) {
      state.edit = false;
    }
    this.setState(state);
  },
  onChangeEdit: function (event) {
    const state = {edit: event.target.checked};
    if (state.edit) {
      state.view = true;
    }
    this.setState(state);
  },
  render_create: function () {
    const owners = this.state.hosts[this.state.host];

    let username = floorc.auth[this.state.host];
    username = username && username.username;

    owners.sort(function (a, b) {
      if (a === username) {
        return -1;
      }
      if (b === username) {
        return 1;
      }
      if (a === b) {
        return 0;
      } else if (a < b) {
        return -1;
      }
      return 1;
    });
    const that = this;
    const labels = owners.map(function (o) {
      return (

          <input type="radio" onChange={that.onChangedOwner} name="owner" tabIndex="5"
            value={o} className="native-key-bindings" checked={o === that.state.owner}/> {o}

      );
    });
    return (

        {this.render_auth()}

          Owner

            {labels}

          Name

            <input tabIndex="7" id="floobits-name" ref="name" className="native-key-bindings form-control" type="text" value={this.state.name} onChange={this.onNameChange}/>

          Description

            <textarea tabIndex="9" id="floobits-description" ref="description" className="native-key-bindings form-control" type="text" rows="3" />

          Global Permissions

              <input tabIndex="11" checked={this.state.view} onChange={this.onChangeView} type="checkbox" ref="view" value="view" className="native-key-bindings" /> Viewable

              <input tabIndex="13" checked={this.state.edit} type="checkbox" ref="edit" value="edit" onChange={this.onChangeEdit} className="native-key-bindings" /> Editable

    );
  },
  render_create_new_workspace_option: function () {
    const url = this.props.url;
    if (!url) {
      return;
    }
    return (

              The workspace {url} already exists.  Do you want to create a new workspace?

                <input id="floobits-create" ref="create" type="checkbox" tabIndex="1"
                  onChange={this.toggleCreate} checked={this.state.create} className="native-key-bindings" /> Create New Workspace

    );
  },
  openBilling: function (event) {
    event.preventDefault();
    open_url(`https://${this.state.host}/${this.state.owner}/settings#billing`);
  },
  render: function () {
    return (

Create Workspace

          <form id="join-workspace" className="form-horizontal native-key-bindings" onSubmit={this.onSubmit}>
            {this.render_create_new_workspace_option()}
            {this.state.create && this.render_create()}
            {!this.state.error ? "" :

                {this.state.error}

            }
            {!this.state.needsMonies ? "" :

                You reached the limit for workspaces for {this.state.host}/{this.state.owner}.

            }

              <input tabIndex="14" type="submit" value={this.state.create ? "Create Workspace" : "Join Workspace"} className="floobits-submit" />
              <input tabIndex="15" type="submit" value="Cancel" className="floobits-submit" onClick={this.destroy} />

          </form>

    );
  }
});<|endoftext|>


<commit_before>define(['views/getview',
		'modules/samples/views/list',
        'modules/samples/views/view',

        'modules/types/gen/samples/views/list',
        'modules/types/gen/samples/views/view',

        'modules/samples/views/proteinlist',
        'modules/samples/views/proteinview',
        'modules/samples/views/proteinadd',

        'modules/types/gen/samples/views/componentlist',
        'modules/types/gen/samples/views/componentadd',
        'modules/types/gen/samples/views/componentview',
], function(GetView,
	SampleList, SampleView,
	GenSampleList, GenSampleView,

	ProteinList, ProteinView, AddProteinView,
	GenComponentList, GenComponentAdd, GenComponentView
	){

	return {

		SampleList: new GetView({
			views: {
 				mx: SampleList,
              	gen: GenSampleList,
			},
			default: GenSampleList,
		}),

		SampleView: new GetView({
        	views: {
        		mx: SampleView,
                gen: GenSampleView,
        	},
        	default: GenSampleView,
        }),

		ProteinList: new GetView({
			views: {
				mx: ProteinList,
            	gen: GenComponentList,
            },
            default: GenComponentList,
        }),

        ProteinAdd: new GetView({
        	views: {
        		mx: AddProteinView,
            	gen: GenComponentAdd,
        	},
        	default: GenComponentAdd
        }),

        ProteinView: new GetView({
        	views: {
        		mx: ProteinView,
                gen: GenComponentView,
        	},
        	default: GenComponentView,
        })

	}

})<commit_msg>saxs uses mx protein / sample views<commit_after>define(['views/getview',
		'modules/samples/views/list',
        'modules/samples/views/view',

        'modules/types/gen/samples/views/list',
        'modules/types/gen/samples/views/view',

        'modules/samples/views/proteinlist',
        'modules/samples/views/proteinview',
        'modules/samples/views/proteinadd',

        'modules/types/gen/samples/views/componentlist',
        'modules/types/gen/samples/views/componentadd',
        'modules/types/gen/samples/views/componentview',
], function(GetView,
	SampleList, SampleView,
	GenSampleList, GenSampleView,

	ProteinList, ProteinView, AddProteinView,
	GenComponentList, GenComponentAdd, GenComponentView
	){

	return {

		SampleList: new GetView({
			views: {
                mx: SampleList,
 				saxs: SampleList,
              	gen: GenSampleList,
			},
			default: GenSampleList,
		}),

		SampleView: new GetView({
        	views: {
                mx: SampleView,
        		saxs: SampleView,
                gen: GenSampleView,
        	},
        	default: GenSampleView,
        }),

		ProteinList: new GetView({
			views: {
                mx: ProteinList,
				saxs: ProteinList,
            	gen: GenComponentList,
            },
            default: GenComponentList,
        }),

        ProteinAdd: new GetView({
        	views: {
                mx: AddProteinView,
        		saxs: AddProteinView,
            	gen: GenComponentAdd,
        	},
        	default: GenComponentAdd
        }),

        ProteinView: new GetView({
        	views: {
                mx: ProteinView,
        		saxs: ProteinView,
                gen: GenComponentView,
        	},
        	default: GenComponentView,
        })

	}

})<|endoftext|>