entities listlengths 1 8.61k | max_stars_repo_path stringlengths 7 172 | max_stars_repo_name stringlengths 5 89 | max_stars_count int64 0 82k | content stringlengths 14 1.05M | id stringlengths 2 6 | new_content stringlengths 15 1.05M | modified bool 1 class | references stringlengths 29 1.05M |
|---|---|---|---|---|---|---|---|---|
[
{
"context": "it 'should have a key/secret pair', ->\n k = 'abcdefghijklmnopqrstuvwxyz123456'\n s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'\n ",
"end": 462,
"score": 0.9995545744895935,
"start": 430,
"tag": "KEY",
"value": "abcdefghijklmnopqrstuvwxyz123456"
},
{
"context": "re... | test/auth_keysecret.coffee | buttercoin/buttercoinsdk-node | 2 | should = require('should')
KeySecretAuthorizer = require('../src/auth/keysecret.coffee')
RequestBuilder = require('../src/request_builder')
describe 'Buttercoin key/secret authorizer', ->
it 'should export a single class', ->
KeySecretAuthorizer.should.be.type 'function'
KeySecretAuthorizer.name.should.equal 'KeySecretAuthorizer'
describe 'initialization', ->
it 'should have a key/secret pair', ->
k = 'abcdefghijklmnopqrstuvwxyz123456'
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth = new KeySecretAuthorizer(k, s)
auth.key.should.equal(k)
auth.secret.should.equal(s)
it 'should reject a null or undefined key', ->
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Key parameter must be specified and be of length 32 characters')
k = null
(-> new KeySecretAuthorizer(k, s)).should.throw('API Key parameter must be specified and be of length 32 characters')
it 'should reject a short key', ->
k = 'too_short'
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Key parameter must be specified and be of length 32 characters')
it 'should reject a null or undefined secret', ->
k = 'abcdefghijklmnopqrstuvwxyz123456'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Secret parameter must be specified and be of length 32 characters')
s = null
(-> new KeySecretAuthorizer(k, s)).should.throw('API Secret parameter must be specified and be of length 32 characters')
it 'should reject a short secret', ->
k = 'abcdefghijklmnopqrstuvwxyz123456'
s = 'too_short'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Secret parameter must be specified and be of length 32 characters')
k = 'abcdefghijklmnopqrstuvwxyz123456'
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth = new KeySecretAuthorizer(k, s)
builder = new RequestBuilder()
describe 'signing', ->
it 'should produce expected signatures for known values', ->
signature = auth.sign(
'1403558182457https://api.buttercoin.com/v1/key',
'abcdefghijklmnopqrstuvwxyz123456')
signature.should.equal 'amakcIy40XLCUaSz6urhl+687F2pIexux+TJ2bl+66I='
it 'should produce signing strings w/ params for GET requests', ->
req = builder.buildRequest('GET', 'account/balances', qs: {foo: 'bar', x: 1})
auth.stringToSign(req).should.equal(
'https://sandbox.buttercoin.com/v1/account/balances?foo=bar&x=1')
it 'should produce signing strings w/ body for POST requests', ->
req = builder.buildRequest('POST', 'orders', body: {foo: 'bar', x: 3})
auth.stringToSign(req).should.equal(
'https://sandbox.buttercoin.com/v1/orders{"foo":"bar","x":3}')
describe 'authenticated requests', ->
it 'should add signing headers to an authenticated request', ->
timestamp = 1423078156750
req =
method: 'GET'
url: 'https://sandbox.buttercoin.com/v1/account/balances'
_auth: true
expected = auth.sign(timestamp + req.url, s)
req = auth.authorize(req, timestamp: timestamp)
req.headers['X-Buttercoin-Access-Key'].should.equal k
req.headers['X-Buttercoin-Signature'].should.equal expected
req.headers['X-Buttercoin-Date'].should.equal timestamp
it 'should calculate a timestamp if one is not provided', ->
early = (new Date).getTime()
req = auth.authorize(builder.buildRequest('GET', '/'))
req.headers['X-Buttercoin-Date'].should.be.type 'number'
req.headers['X-Buttercoin-Date'].should.be.greaterThan (early - 1)
it 'should not add signing headers to an unauthenticated request', ->
req = auth.authorize({_auth: false})
should.not.exist(req.headers?['X-Buttercoin-Access-Key'])
should.not.exist(req.headers?['X-Buttercoin-Signature'])
should.not.exist(req.headers?['X-Buttercoin-Date'])
| 42486 | should = require('should')
KeySecretAuthorizer = require('../src/auth/keysecret.coffee')
RequestBuilder = require('../src/request_builder')
describe 'Buttercoin key/secret authorizer', ->
it 'should export a single class', ->
KeySecretAuthorizer.should.be.type 'function'
KeySecretAuthorizer.name.should.equal 'KeySecretAuthorizer'
describe 'initialization', ->
it 'should have a key/secret pair', ->
k = '<KEY>'
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth = new KeySecretAuthorizer(k, s)
auth.key.should.equal(k)
auth.secret.should.equal(s)
it 'should reject a null or undefined key', ->
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Key parameter must be specified and be of length 32 characters')
k = null
(-> new KeySecretAuthorizer(k, s)).should.throw('API Key parameter must be specified and be of length 32 characters')
it 'should reject a short key', ->
k = 'too_short'
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Key parameter must be specified and be of length 32 characters')
it 'should reject a null or undefined secret', ->
k = '<KEY>'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Secret parameter must be specified and be of length 32 characters')
s = null
(-> new KeySecretAuthorizer(k, s)).should.throw('API Secret parameter must be specified and be of length 32 characters')
it 'should reject a short secret', ->
k = '<KEY>'
s = 'too_short'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Secret parameter must be specified and be of length 32 characters')
k = '<KEY>'
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth = new KeySecretAuthorizer(k, s)
builder = new RequestBuilder()
describe 'signing', ->
it 'should produce expected signatures for known values', ->
signature = auth.sign(
'1403558182457https://api.buttercoin.com/v1/key',
'abcdefghijklmnopqrstuvwxyz<KEY>2<KEY>')
signature.should.equal 'amakcIy40XLCUaSz6urhl+687F2pIexux+TJ2bl+66I='
it 'should produce signing strings w/ params for GET requests', ->
req = builder.buildRequest('GET', 'account/balances', qs: {foo: 'bar', x: 1})
auth.stringToSign(req).should.equal(
'https://sandbox.buttercoin.com/v1/account/balances?foo=bar&x=1')
it 'should produce signing strings w/ body for POST requests', ->
req = builder.buildRequest('POST', 'orders', body: {foo: 'bar', x: 3})
auth.stringToSign(req).should.equal(
'https://sandbox.buttercoin.com/v1/orders{"foo":"bar","x":3}')
describe 'authenticated requests', ->
it 'should add signing headers to an authenticated request', ->
timestamp = 1423078156750
req =
method: 'GET'
url: 'https://sandbox.buttercoin.com/v1/account/balances'
_auth: true
expected = auth.sign(timestamp + req.url, s)
req = auth.authorize(req, timestamp: timestamp)
req.headers['X-Buttercoin-Access-Key'].should.equal k
req.headers['X-Buttercoin-Signature'].should.equal expected
req.headers['X-Buttercoin-Date'].should.equal timestamp
it 'should calculate a timestamp if one is not provided', ->
early = (new Date).getTime()
req = auth.authorize(builder.buildRequest('GET', '/'))
req.headers['X-Buttercoin-Date'].should.be.type 'number'
req.headers['X-Buttercoin-Date'].should.be.greaterThan (early - 1)
it 'should not add signing headers to an unauthenticated request', ->
req = auth.authorize({_auth: false})
should.not.exist(req.headers?['X-Buttercoin-Access-Key'])
should.not.exist(req.headers?['X-Buttercoin-Signature'])
should.not.exist(req.headers?['X-Buttercoin-Date'])
| true | should = require('should')
KeySecretAuthorizer = require('../src/auth/keysecret.coffee')
RequestBuilder = require('../src/request_builder')
describe 'Buttercoin key/secret authorizer', ->
it 'should export a single class', ->
KeySecretAuthorizer.should.be.type 'function'
KeySecretAuthorizer.name.should.equal 'KeySecretAuthorizer'
describe 'initialization', ->
it 'should have a key/secret pair', ->
k = 'PI:KEY:<KEY>END_PI'
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth = new KeySecretAuthorizer(k, s)
auth.key.should.equal(k)
auth.secret.should.equal(s)
it 'should reject a null or undefined key', ->
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Key parameter must be specified and be of length 32 characters')
k = null
(-> new KeySecretAuthorizer(k, s)).should.throw('API Key parameter must be specified and be of length 32 characters')
it 'should reject a short key', ->
k = 'too_short'
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Key parameter must be specified and be of length 32 characters')
it 'should reject a null or undefined secret', ->
k = 'PI:KEY:<KEY>END_PI'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Secret parameter must be specified and be of length 32 characters')
s = null
(-> new KeySecretAuthorizer(k, s)).should.throw('API Secret parameter must be specified and be of length 32 characters')
it 'should reject a short secret', ->
k = 'PI:KEY:<KEY>END_PI'
s = 'too_short'
(-> new KeySecretAuthorizer(k, s)).should.throw('API Secret parameter must be specified and be of length 32 characters')
k = 'PI:KEY:<KEY>END_PI'
s = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth = new KeySecretAuthorizer(k, s)
builder = new RequestBuilder()
describe 'signing', ->
it 'should produce expected signatures for known values', ->
signature = auth.sign(
'1403558182457https://api.buttercoin.com/v1/key',
'abcdefghijklmnopqrstuvwxyzPI:KEY:<KEY>END_PI2PI:KEY:<KEY>END_PI')
signature.should.equal 'amakcIy40XLCUaSz6urhl+687F2pIexux+TJ2bl+66I='
it 'should produce signing strings w/ params for GET requests', ->
req = builder.buildRequest('GET', 'account/balances', qs: {foo: 'bar', x: 1})
auth.stringToSign(req).should.equal(
'https://sandbox.buttercoin.com/v1/account/balances?foo=bar&x=1')
it 'should produce signing strings w/ body for POST requests', ->
req = builder.buildRequest('POST', 'orders', body: {foo: 'bar', x: 3})
auth.stringToSign(req).should.equal(
'https://sandbox.buttercoin.com/v1/orders{"foo":"bar","x":3}')
describe 'authenticated requests', ->
it 'should add signing headers to an authenticated request', ->
timestamp = 1423078156750
req =
method: 'GET'
url: 'https://sandbox.buttercoin.com/v1/account/balances'
_auth: true
expected = auth.sign(timestamp + req.url, s)
req = auth.authorize(req, timestamp: timestamp)
req.headers['X-Buttercoin-Access-Key'].should.equal k
req.headers['X-Buttercoin-Signature'].should.equal expected
req.headers['X-Buttercoin-Date'].should.equal timestamp
it 'should calculate a timestamp if one is not provided', ->
early = (new Date).getTime()
req = auth.authorize(builder.buildRequest('GET', '/'))
req.headers['X-Buttercoin-Date'].should.be.type 'number'
req.headers['X-Buttercoin-Date'].should.be.greaterThan (early - 1)
it 'should not add signing headers to an unauthenticated request', ->
req = auth.authorize({_auth: false})
should.not.exist(req.headers?['X-Buttercoin-Access-Key'])
should.not.exist(req.headers?['X-Buttercoin-Signature'])
should.not.exist(req.headers?['X-Buttercoin-Date'])
|
[
{
"context": "exports.DB_USER = 'root'\n exports.DB_PASS = 'root'\n\n when \"testing\"\n exports.DEBUG_LOG = tr",
"end": 488,
"score": 0.9917677640914917,
"start": 484,
"tag": "PASSWORD",
"value": "root"
}
] | src/config/index.coffee | Whoaa512/express-coffee | 115 | #### Config file
# Sets application config parameters depending on `env` name
exports.setEnvironment = (env) ->
console.log "set app environment: #{env}"
switch(env)
when "development"
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
exports.DB_HOST = 'localhost'
exports.DB_PORT = "3306"
exports.DB_NAME = 'mvc_example'
exports.DB_USER = 'root'
exports.DB_PASS = 'root'
when "testing"
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
when "production"
exports.DEBUG_LOG = false
exports.DEBUG_WARN = false
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = false
else
console.log "environment #{env} not found"
| 142321 | #### Config file
# Sets application config parameters depending on `env` name
exports.setEnvironment = (env) ->
console.log "set app environment: #{env}"
switch(env)
when "development"
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
exports.DB_HOST = 'localhost'
exports.DB_PORT = "3306"
exports.DB_NAME = 'mvc_example'
exports.DB_USER = 'root'
exports.DB_PASS = '<PASSWORD>'
when "testing"
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
when "production"
exports.DEBUG_LOG = false
exports.DEBUG_WARN = false
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = false
else
console.log "environment #{env} not found"
| true | #### Config file
# Sets application config parameters depending on `env` name
exports.setEnvironment = (env) ->
console.log "set app environment: #{env}"
switch(env)
when "development"
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
exports.DB_HOST = 'localhost'
exports.DB_PORT = "3306"
exports.DB_NAME = 'mvc_example'
exports.DB_USER = 'root'
exports.DB_PASS = 'PI:PASSWORD:<PASSWORD>END_PI'
when "testing"
exports.DEBUG_LOG = true
exports.DEBUG_WARN = true
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = true
when "production"
exports.DEBUG_LOG = false
exports.DEBUG_WARN = false
exports.DEBUG_ERROR = true
exports.DEBUG_CLIENT = false
else
console.log "environment #{env} not found"
|
[
{
"context": "login : auth.login\n resetPassword : auth.resetPassword\n confirmEmail : auth.confirmEmail\n li",
"end": 1597,
"score": 0.9988672733306885,
"start": 1579,
"tag": "PASSWORD",
"value": "auth.resetPassword"
},
{
"context": "ed by Hull main file a... | src/client/index.coffee | fossabot/hull-js | 25 | _ = require '../utils/lodash'
clone = require '../utils/clone'
EventBus = require '../utils/eventbus'
Entity = require '../utils/entity'
findUrl = require '../utils/find-url'
logger = require '../utils/logger'
Api = require './api'
Auth = require './auth'
Flag = require './flag/index'
Tracker = require './track/index'
Traits = require './traits/index'
Sharer = require './sharer/index'
QueryString = require './querystring/index'
utils = require '../utils/utils'
class Client
constructor: (channel, currentUser, currentConfig)->
@currentConfig = currentConfig
api = new Api(channel, currentUser, currentConfig)
alias = (id) -> api.message({ path: "/me/alias" }, "post", { anonymous_id: id })
auth = new Auth(api, currentUser, currentConfig)
tracker = new Tracker(api)
sharer = new Sharer(currentConfig);
flag = new Flag(api)
traits = new Traits(api)
qs = new QueryString(traits, tracker.track, alias)
if @currentConfig.get('debug.enabled')
EventBus.on 'hull.**', (args...)->
logger.log("--HULL EVENT--[#{@event}]--", args...);
# Creating the complete hull object we'll send back to the API
@hull =
config : @currentConfig.get
utils : utils
api : api.message
currentUser : currentUser.get
entity : Entity
signup : auth.signup
logout : auth.logout
login : auth.login
resetPassword : auth.resetPassword
confirmEmail : auth.confirmEmail
linkIdentity : auth.linkIdentity
unlinkIdentity : auth.unlinkIdentity
track : tracker.track
trackForm : tracker.trackForm
alias : alias
flag : flag
identify : traits
traits : traits
trait : traits
share : sharer.share
findUrl : findUrl
parseQueryString : qs.parse
# Return an object that will be digested by Hull main file and
# has everything
@hull
module.exports = Client
| 224455 | _ = require '../utils/lodash'
clone = require '../utils/clone'
EventBus = require '../utils/eventbus'
Entity = require '../utils/entity'
findUrl = require '../utils/find-url'
logger = require '../utils/logger'
Api = require './api'
Auth = require './auth'
Flag = require './flag/index'
Tracker = require './track/index'
Traits = require './traits/index'
Sharer = require './sharer/index'
QueryString = require './querystring/index'
utils = require '../utils/utils'
class Client
constructor: (channel, currentUser, currentConfig)->
@currentConfig = currentConfig
api = new Api(channel, currentUser, currentConfig)
alias = (id) -> api.message({ path: "/me/alias" }, "post", { anonymous_id: id })
auth = new Auth(api, currentUser, currentConfig)
tracker = new Tracker(api)
sharer = new Sharer(currentConfig);
flag = new Flag(api)
traits = new Traits(api)
qs = new QueryString(traits, tracker.track, alias)
if @currentConfig.get('debug.enabled')
EventBus.on 'hull.**', (args...)->
logger.log("--HULL EVENT--[#{@event}]--", args...);
# Creating the complete hull object we'll send back to the API
@hull =
config : @currentConfig.get
utils : utils
api : api.message
currentUser : currentUser.get
entity : Entity
signup : auth.signup
logout : auth.logout
login : auth.login
resetPassword : <PASSWORD>
confirmEmail : auth.confirmEmail
linkIdentity : auth.linkIdentity
unlinkIdentity : auth.unlinkIdentity
track : tracker.track
trackForm : tracker.trackForm
alias : alias
flag : flag
identify : traits
traits : traits
trait : traits
share : sharer.share
findUrl : findUrl
parseQueryString : qs.parse
# Return an object that will be digested by Hull main file and
# has everything
@hull
module.exports = Client
| true | _ = require '../utils/lodash'
clone = require '../utils/clone'
EventBus = require '../utils/eventbus'
Entity = require '../utils/entity'
findUrl = require '../utils/find-url'
logger = require '../utils/logger'
Api = require './api'
Auth = require './auth'
Flag = require './flag/index'
Tracker = require './track/index'
Traits = require './traits/index'
Sharer = require './sharer/index'
QueryString = require './querystring/index'
utils = require '../utils/utils'
class Client
constructor: (channel, currentUser, currentConfig)->
@currentConfig = currentConfig
api = new Api(channel, currentUser, currentConfig)
alias = (id) -> api.message({ path: "/me/alias" }, "post", { anonymous_id: id })
auth = new Auth(api, currentUser, currentConfig)
tracker = new Tracker(api)
sharer = new Sharer(currentConfig);
flag = new Flag(api)
traits = new Traits(api)
qs = new QueryString(traits, tracker.track, alias)
if @currentConfig.get('debug.enabled')
EventBus.on 'hull.**', (args...)->
logger.log("--HULL EVENT--[#{@event}]--", args...);
# Creating the complete hull object we'll send back to the API
@hull =
config : @currentConfig.get
utils : utils
api : api.message
currentUser : currentUser.get
entity : Entity
signup : auth.signup
logout : auth.logout
login : auth.login
resetPassword : PI:PASSWORD:<PASSWORD>END_PI
confirmEmail : auth.confirmEmail
linkIdentity : auth.linkIdentity
unlinkIdentity : auth.unlinkIdentity
track : tracker.track
trackForm : tracker.trackForm
alias : alias
flag : flag
identify : traits
traits : traits
trait : traits
share : sharer.share
findUrl : findUrl
parseQueryString : qs.parse
# Return an object that will be digested by Hull main file and
# has everything
@hull
module.exports = Client
|
[
{
"context": "nfirmation\n else\n confirmation_key = key + \"_confirmation\"\n\n value = record.get(key)\n con",
"end": 368,
"score": 0.5301233530044556,
"start": 366,
"tag": "KEY",
"value": "\"_"
}
] | src/model/validations/confirmation_validator.coffee | davidcornu/batman | 0 | #= require ./validators
class Batman.ConfirmationValidator extends Batman.Validator
@triggers 'confirmation'
validateEach: (errors, record, key, callback) ->
options = @options
return if !options.confirmation
if Batman.typeOf(@options.confirmation) == "String"
confirmation_key = @options.confirmation
else
confirmation_key = key + "_confirmation"
value = record.get(key)
confirmation_value = record.get(confirmation_key)
if value != confirmation_value
errors.add key, 'and confirmation do not match'
callback()
Batman.Validators.push Batman.ConfirmationValidator
| 195078 | #= require ./validators
class Batman.ConfirmationValidator extends Batman.Validator
@triggers 'confirmation'
validateEach: (errors, record, key, callback) ->
options = @options
return if !options.confirmation
if Batman.typeOf(@options.confirmation) == "String"
confirmation_key = @options.confirmation
else
confirmation_key = key + <KEY>confirmation"
value = record.get(key)
confirmation_value = record.get(confirmation_key)
if value != confirmation_value
errors.add key, 'and confirmation do not match'
callback()
Batman.Validators.push Batman.ConfirmationValidator
| true | #= require ./validators
class Batman.ConfirmationValidator extends Batman.Validator
@triggers 'confirmation'
validateEach: (errors, record, key, callback) ->
options = @options
return if !options.confirmation
if Batman.typeOf(@options.confirmation) == "String"
confirmation_key = @options.confirmation
else
confirmation_key = key + PI:KEY:<KEY>END_PIconfirmation"
value = record.get(key)
confirmation_value = record.get(confirmation_key)
if value != confirmation_value
errors.add key, 'and confirmation do not match'
callback()
Batman.Validators.push Batman.ConfirmationValidator
|
[
{
"context": ">\n $scope.wizard =\n firstName: 'some name'\n lastName: ''\n email: ''\n ",
"end": 175,
"score": 0.8227055668830872,
"start": 166,
"tag": "NAME",
"value": "some name"
}
] | rainbow-v1.2/rainbow/client/scripts/Form/FormValidation.coffee | DigitalWant/K11 | 2 | 'use strict'
angular.module('app.form.validation', [])
.controller('wizardFormCtrl', [
'$scope'
($scope) ->
$scope.wizard =
firstName: 'some name'
lastName: ''
email: ''
password: ''
age: ''
address: ''
$scope.isValidateStep1 = ->
console.log $scope.wizard_step1
console.log $scope.wizard.firstName isnt ''
console.log $scope.wizard.lastName is ''
console.log $scope.wizard.firstName isnt '' && $scope.wizard.lastName isnt ''
# console.log $scope.wizard_step1.$valid
$scope.finishedWizard = ->
console.log 'yoo'
])
.controller('formConstraintsCtrl', [
'$scope'
($scope) ->
$scope.form =
required: ''
minlength: ''
maxlength: ''
length_rage: ''
type_something: ''
confirm_type: ''
foo: ''
email: ''
url: ''
num: ''
minVal: ''
maxVal: ''
valRange: ''
pattern: ''
original = angular.copy($scope.form)
$scope.revert = ->
$scope.form = angular.copy(original)
$scope.form_constraints.$setPristine()
$scope.canRevert = ->
return !angular.equals($scope.form, original) || !$scope.form_constraints.$pristine
$scope.canSubmit = ->
return $scope.form_constraints.$valid && !angular.equals($scope.form, original)
])
.controller('signinCtrl', [
'$scope'
($scope) ->
$scope.user =
email: ''
password: ''
$scope.showInfoOnSubmit = false
original = angular.copy($scope.user)
$scope.revert = ->
$scope.user = angular.copy(original)
$scope.form_signin.$setPristine()
$scope.canRevert = ->
return !angular.equals($scope.user, original) || !$scope.form_signin.$pristine
$scope.canSubmit = ->
return $scope.form_signin.$valid && !angular.equals($scope.user, original)
$scope.submitForm = ->
$scope.showInfoOnSubmit = true
$scope.revert()
])
.controller('signupCtrl', [
'$scope'
($scope) ->
$scope.user =
name: ''
email: ''
password: ''
confirmPassword: ''
age: ''
$scope.showInfoOnSubmit = false
original = angular.copy($scope.user)
$scope.revert = ->
$scope.user = angular.copy(original)
$scope.form_signup.$setPristine()
$scope.form_signup.confirmPassword.$setPristine()
$scope.canRevert = ->
return !angular.equals($scope.user, original) || !$scope.form_signup.$pristine
$scope.canSubmit = ->
return $scope.form_signup.$valid && !angular.equals($scope.user, original)
$scope.submitForm = ->
$scope.showInfoOnSubmit = true
$scope.revert()
])
# used for confirm password
# Note: if you modify the "confirm" input box, and then update the target input box to match it, it'll still show invalid style though the values are the same now
# Note2: also remember to use " ng-trim='false' " to disable the trim
.directive('validateEquals', [ () ->
return {
require: 'ngModel'
link: (scope, ele, attrs, ngModelCtrl) ->
validateEqual = (value) ->
valid = ( value is scope.$eval(attrs.validateEquals) )
ngModelCtrl.$setValidity('equal', valid)
return valid? value : undefined
ngModelCtrl.$parsers.push(validateEqual)
ngModelCtrl.$formatters.push(validateEqual)
scope.$watch(attrs.validateEquals, (newValue, oldValue) ->
if newValue isnt oldValue # so that watch only fire after change, otherwise watch will fire on load and add invalid style to "confirm" input box
ngModelCtrl.$setViewValue(ngModelCtrl.$ViewValue)
)
}
])
# Comment out, use AngularJS built in directive instead.
# unique string, use on unique username, blacklist etc.
# angularjs already support it, yet you get the picture
# validate number value, jquery free, only number >=x, <= y are valid, e.g. 1~100, >= 0, <= -1...
# use with AngularJS built in type="number"
# .directive('minvalue', [ ->
# return {
# restrict: 'A'
# require: 'ngModel'
# link: (scope, ele, attrs, ngModelCtrl) ->
# minVal = attrs.minvalue
# validateVal = (value) ->
# valid = if value >= minVal then true else false
# ngModelCtrl.$setValidity('minVal', valid)
# scope.$watch(attrs.ngModel, validateVal)
# }
# ])
# .directive('maxvalue', [ ->
# return {
# restrict: 'A'
# require: 'ngModel'
# link: (scope, ele, attrs, ngModelCtrl) ->
# maxVal = attrs.maxvalue
# validateVal = (value) ->
# valid = if value <= maxVal then true else false
# ngModelCtrl.$setValidity('maxVal', valid)
# scope.$watch(attrs.ngModel, validateVal)
# }
# ]) | 203607 | 'use strict'
angular.module('app.form.validation', [])
.controller('wizardFormCtrl', [
'$scope'
($scope) ->
$scope.wizard =
firstName: '<NAME>'
lastName: ''
email: ''
password: ''
age: ''
address: ''
$scope.isValidateStep1 = ->
console.log $scope.wizard_step1
console.log $scope.wizard.firstName isnt ''
console.log $scope.wizard.lastName is ''
console.log $scope.wizard.firstName isnt '' && $scope.wizard.lastName isnt ''
# console.log $scope.wizard_step1.$valid
$scope.finishedWizard = ->
console.log 'yoo'
])
.controller('formConstraintsCtrl', [
'$scope'
($scope) ->
$scope.form =
required: ''
minlength: ''
maxlength: ''
length_rage: ''
type_something: ''
confirm_type: ''
foo: ''
email: ''
url: ''
num: ''
minVal: ''
maxVal: ''
valRange: ''
pattern: ''
original = angular.copy($scope.form)
$scope.revert = ->
$scope.form = angular.copy(original)
$scope.form_constraints.$setPristine()
$scope.canRevert = ->
return !angular.equals($scope.form, original) || !$scope.form_constraints.$pristine
$scope.canSubmit = ->
return $scope.form_constraints.$valid && !angular.equals($scope.form, original)
])
.controller('signinCtrl', [
'$scope'
($scope) ->
$scope.user =
email: ''
password: ''
$scope.showInfoOnSubmit = false
original = angular.copy($scope.user)
$scope.revert = ->
$scope.user = angular.copy(original)
$scope.form_signin.$setPristine()
$scope.canRevert = ->
return !angular.equals($scope.user, original) || !$scope.form_signin.$pristine
$scope.canSubmit = ->
return $scope.form_signin.$valid && !angular.equals($scope.user, original)
$scope.submitForm = ->
$scope.showInfoOnSubmit = true
$scope.revert()
])
.controller('signupCtrl', [
'$scope'
($scope) ->
$scope.user =
name: ''
email: ''
password: ''
confirmPassword: ''
age: ''
$scope.showInfoOnSubmit = false
original = angular.copy($scope.user)
$scope.revert = ->
$scope.user = angular.copy(original)
$scope.form_signup.$setPristine()
$scope.form_signup.confirmPassword.$setPristine()
$scope.canRevert = ->
return !angular.equals($scope.user, original) || !$scope.form_signup.$pristine
$scope.canSubmit = ->
return $scope.form_signup.$valid && !angular.equals($scope.user, original)
$scope.submitForm = ->
$scope.showInfoOnSubmit = true
$scope.revert()
])
# used for confirm password
# Note: if you modify the "confirm" input box, and then update the target input box to match it, it'll still show invalid style though the values are the same now
# Note2: also remember to use " ng-trim='false' " to disable the trim
.directive('validateEquals', [ () ->
return {
require: 'ngModel'
link: (scope, ele, attrs, ngModelCtrl) ->
validateEqual = (value) ->
valid = ( value is scope.$eval(attrs.validateEquals) )
ngModelCtrl.$setValidity('equal', valid)
return valid? value : undefined
ngModelCtrl.$parsers.push(validateEqual)
ngModelCtrl.$formatters.push(validateEqual)
scope.$watch(attrs.validateEquals, (newValue, oldValue) ->
if newValue isnt oldValue # so that watch only fire after change, otherwise watch will fire on load and add invalid style to "confirm" input box
ngModelCtrl.$setViewValue(ngModelCtrl.$ViewValue)
)
}
])
# Comment out, use AngularJS built in directive instead.
# unique string, use on unique username, blacklist etc.
# angularjs already support it, yet you get the picture
# validate number value, jquery free, only number >=x, <= y are valid, e.g. 1~100, >= 0, <= -1...
# use with AngularJS built in type="number"
# .directive('minvalue', [ ->
# return {
# restrict: 'A'
# require: 'ngModel'
# link: (scope, ele, attrs, ngModelCtrl) ->
# minVal = attrs.minvalue
# validateVal = (value) ->
# valid = if value >= minVal then true else false
# ngModelCtrl.$setValidity('minVal', valid)
# scope.$watch(attrs.ngModel, validateVal)
# }
# ])
# .directive('maxvalue', [ ->
# return {
# restrict: 'A'
# require: 'ngModel'
# link: (scope, ele, attrs, ngModelCtrl) ->
# maxVal = attrs.maxvalue
# validateVal = (value) ->
# valid = if value <= maxVal then true else false
# ngModelCtrl.$setValidity('maxVal', valid)
# scope.$watch(attrs.ngModel, validateVal)
# }
# ]) | true | 'use strict'
angular.module('app.form.validation', [])
.controller('wizardFormCtrl', [
'$scope'
($scope) ->
$scope.wizard =
firstName: 'PI:NAME:<NAME>END_PI'
lastName: ''
email: ''
password: ''
age: ''
address: ''
$scope.isValidateStep1 = ->
console.log $scope.wizard_step1
console.log $scope.wizard.firstName isnt ''
console.log $scope.wizard.lastName is ''
console.log $scope.wizard.firstName isnt '' && $scope.wizard.lastName isnt ''
# console.log $scope.wizard_step1.$valid
$scope.finishedWizard = ->
console.log 'yoo'
])
.controller('formConstraintsCtrl', [
'$scope'
($scope) ->
$scope.form =
required: ''
minlength: ''
maxlength: ''
length_rage: ''
type_something: ''
confirm_type: ''
foo: ''
email: ''
url: ''
num: ''
minVal: ''
maxVal: ''
valRange: ''
pattern: ''
original = angular.copy($scope.form)
$scope.revert = ->
$scope.form = angular.copy(original)
$scope.form_constraints.$setPristine()
$scope.canRevert = ->
return !angular.equals($scope.form, original) || !$scope.form_constraints.$pristine
$scope.canSubmit = ->
return $scope.form_constraints.$valid && !angular.equals($scope.form, original)
])
.controller('signinCtrl', [
'$scope'
($scope) ->
$scope.user =
email: ''
password: ''
$scope.showInfoOnSubmit = false
original = angular.copy($scope.user)
$scope.revert = ->
$scope.user = angular.copy(original)
$scope.form_signin.$setPristine()
$scope.canRevert = ->
return !angular.equals($scope.user, original) || !$scope.form_signin.$pristine
$scope.canSubmit = ->
return $scope.form_signin.$valid && !angular.equals($scope.user, original)
$scope.submitForm = ->
$scope.showInfoOnSubmit = true
$scope.revert()
])
.controller('signupCtrl', [
'$scope'
($scope) ->
$scope.user =
name: ''
email: ''
password: ''
confirmPassword: ''
age: ''
$scope.showInfoOnSubmit = false
original = angular.copy($scope.user)
$scope.revert = ->
$scope.user = angular.copy(original)
$scope.form_signup.$setPristine()
$scope.form_signup.confirmPassword.$setPristine()
$scope.canRevert = ->
return !angular.equals($scope.user, original) || !$scope.form_signup.$pristine
$scope.canSubmit = ->
return $scope.form_signup.$valid && !angular.equals($scope.user, original)
$scope.submitForm = ->
$scope.showInfoOnSubmit = true
$scope.revert()
])
# used for confirm password
# Note: if you modify the "confirm" input box, and then update the target input box to match it, it'll still show invalid style though the values are the same now
# Note2: also remember to use " ng-trim='false' " to disable the trim
.directive('validateEquals', [ () ->
return {
require: 'ngModel'
link: (scope, ele, attrs, ngModelCtrl) ->
validateEqual = (value) ->
valid = ( value is scope.$eval(attrs.validateEquals) )
ngModelCtrl.$setValidity('equal', valid)
return valid? value : undefined
ngModelCtrl.$parsers.push(validateEqual)
ngModelCtrl.$formatters.push(validateEqual)
scope.$watch(attrs.validateEquals, (newValue, oldValue) ->
if newValue isnt oldValue # so that watch only fire after change, otherwise watch will fire on load and add invalid style to "confirm" input box
ngModelCtrl.$setViewValue(ngModelCtrl.$ViewValue)
)
}
])
# Comment out, use AngularJS built in directive instead.
# unique string, use on unique username, blacklist etc.
# angularjs already support it, yet you get the picture
# validate number value, jquery free, only number >=x, <= y are valid, e.g. 1~100, >= 0, <= -1...
# use with AngularJS built in type="number"
# .directive('minvalue', [ ->
# return {
# restrict: 'A'
# require: 'ngModel'
# link: (scope, ele, attrs, ngModelCtrl) ->
# minVal = attrs.minvalue
# validateVal = (value) ->
# valid = if value >= minVal then true else false
# ngModelCtrl.$setValidity('minVal', valid)
# scope.$watch(attrs.ngModel, validateVal)
# }
# ])
# .directive('maxvalue', [ ->
# return {
# restrict: 'A'
# require: 'ngModel'
# link: (scope, ele, attrs, ngModelCtrl) ->
# maxVal = attrs.maxvalue
# validateVal = (value) ->
# valid = if value <= maxVal then true else false
# ngModelCtrl.$setValidity('maxVal', valid)
# scope.$watch(attrs.ngModel, validateVal)
# }
# ]) |
[
{
"context": "https://js.stripe.com/v2/'\n\nstripeRequestKeys = ['number', 'cvc', 'name', 'exp_month', 'exp_year']\n\n\nexports.ensureClient = ensureClient = (publisha",
"end": 311,
"score": 0.9330476522445679,
"start": 263,
"tag": "KEY",
"value": "number', 'cvc', 'name', 'exp_month', 'exp_y... | client/app/lib/redux/services/stripe.coffee | lionheart1022/koding | 0 | appendHeadElement = require 'app/util/appendHeadElement'
{ isEmail } = require 'validator'
cardValidator = require 'card-validator'
stripeFixtures = require 'app/redux/services/fixtures/stripe'
STRIPE_API_URL = 'https://js.stripe.com/v2/'
stripeRequestKeys = ['number', 'cvc', 'name', 'exp_month', 'exp_year']
exports.ensureClient = ensureClient = (publishableKey) -> new Promise (resolve, reject) ->
return resolve(global.Stripe) if global.Stripe
# if there there is no global.Stripe or publishableKey there is something
# wrong going on, let's reject.
unless publishableKey
return reject(new Error 'stripe.service: publishableKey is not set')
appendHeadElement { type: 'script', url: STRIPE_API_URL }, (err) ->
return reject(err) if err
global.Stripe.setPublishableKey publishableKey
resolve(global.Stripe)
exports.createToken = createToken = (options) ->
errors = validateOptions options
if errors.length
return Promise.reject(errors)
# stripe returns Bad request error if we send more request parameter then it
# accepts, make sure we are not sending more than enough.
options = _.pick options, stripeRequestKeys
success = (client) -> new Promise (resolve, reject) ->
client.card.createToken options, (stat, { error, id }) ->
if error then reject(error) else resolve(id)
return ensureClient().then(success)
validateErrorResponses =
number: stripeFixtures.createTokenError.number
cvc: stripeFixtures.createTokenError.cvc
exp_year: stripeFixtures.createTokenError.year
exp_month: stripeFixtures.createTokenError.month
email: stripeFixtures.createTokenError.email
pickBy = (obj, fn) ->
Object.keys(obj)
.filter (key) -> fn(obj[key], key)
.reduce (res, key) ->
res[key] = obj[key]
return res
, {}
validateOptions = (options) ->
isAmex = cardValidator.number(options.number).card?.isAmex
validators = makeValidators isAmex
# for each validator use the corresponding data from options
# if return falsy there is an error for that key
# if return truthy there is no error for that key
# pick keys where result is falsy
notValidMap = pickBy validators, (validator, key) -> not validator options[key]
# return a list with an item of { param: key } where key is one of the keys
# with errors.
return _.map notValidMap, (error, key) -> validateErrorResponses[key]
makeValidators = (isAmex) ->
fieldValidator = (field, rest...) -> (value) ->
value = value.toString()
cardValidator[field](value, rest...).isValid
return {
number: fieldValidator 'number'
cvc: fieldValidator 'cvv', if isAmex then 4 else 3
exp_month: fieldValidator 'expirationMonth'
exp_year: fieldValidator 'expirationYear'
email: isEmail
}
| 83632 | appendHeadElement = require 'app/util/appendHeadElement'
{ isEmail } = require 'validator'
cardValidator = require 'card-validator'
stripeFixtures = require 'app/redux/services/fixtures/stripe'
STRIPE_API_URL = 'https://js.stripe.com/v2/'
stripeRequestKeys = ['<KEY>
exports.ensureClient = ensureClient = (publishableKey) -> new Promise (resolve, reject) ->
return resolve(global.Stripe) if global.Stripe
# if there there is no global.Stripe or publishableKey there is something
# wrong going on, let's reject.
unless publishableKey
return reject(new Error 'stripe.service: publishableKey is not set')
appendHeadElement { type: 'script', url: STRIPE_API_URL }, (err) ->
return reject(err) if err
global.Stripe.setPublishableKey publishableKey
resolve(global.Stripe)
exports.createToken = createToken = (options) ->
errors = validateOptions options
if errors.length
return Promise.reject(errors)
# stripe returns Bad request error if we send more request parameter then it
# accepts, make sure we are not sending more than enough.
options = _.pick options, stripeRequestKeys
success = (client) -> new Promise (resolve, reject) ->
client.card.createToken options, (stat, { error, id }) ->
if error then reject(error) else resolve(id)
return ensureClient().then(success)
validateErrorResponses =
number: stripeFixtures.createTokenError.number
cvc: stripeFixtures.createTokenError.cvc
exp_year: stripeFixtures.createTokenError.year
exp_month: stripeFixtures.createTokenError.month
email: stripeFixtures.createTokenError.email
pickBy = (obj, fn) ->
Object.keys(obj)
.filter (key) -> fn(obj[key], key)
.reduce (res, key) ->
res[key] = obj[key]
return res
, {}
validateOptions = (options) ->
isAmex = cardValidator.number(options.number).card?.isAmex
validators = makeValidators isAmex
# for each validator use the corresponding data from options
# if return falsy there is an error for that key
# if return truthy there is no error for that key
# pick keys where result is falsy
notValidMap = pickBy validators, (validator, key) -> not validator options[key]
# return a list with an item of { param: key } where key is one of the keys
# with errors.
return _.map notValidMap, (error, key) -> validateErrorResponses[key]
makeValidators = (isAmex) ->
fieldValidator = (field, rest...) -> (value) ->
value = value.toString()
cardValidator[field](value, rest...).isValid
return {
number: fieldValidator 'number'
cvc: fieldValidator 'cvv', if isAmex then 4 else 3
exp_month: fieldValidator 'expirationMonth'
exp_year: fieldValidator 'expirationYear'
email: isEmail
}
| true | appendHeadElement = require 'app/util/appendHeadElement'
{ isEmail } = require 'validator'
cardValidator = require 'card-validator'
stripeFixtures = require 'app/redux/services/fixtures/stripe'
STRIPE_API_URL = 'https://js.stripe.com/v2/'
stripeRequestKeys = ['PI:KEY:<KEY>END_PI
exports.ensureClient = ensureClient = (publishableKey) -> new Promise (resolve, reject) ->
return resolve(global.Stripe) if global.Stripe
# if there there is no global.Stripe or publishableKey there is something
# wrong going on, let's reject.
unless publishableKey
return reject(new Error 'stripe.service: publishableKey is not set')
appendHeadElement { type: 'script', url: STRIPE_API_URL }, (err) ->
return reject(err) if err
global.Stripe.setPublishableKey publishableKey
resolve(global.Stripe)
exports.createToken = createToken = (options) ->
errors = validateOptions options
if errors.length
return Promise.reject(errors)
# stripe returns Bad request error if we send more request parameter then it
# accepts, make sure we are not sending more than enough.
options = _.pick options, stripeRequestKeys
success = (client) -> new Promise (resolve, reject) ->
client.card.createToken options, (stat, { error, id }) ->
if error then reject(error) else resolve(id)
return ensureClient().then(success)
validateErrorResponses =
number: stripeFixtures.createTokenError.number
cvc: stripeFixtures.createTokenError.cvc
exp_year: stripeFixtures.createTokenError.year
exp_month: stripeFixtures.createTokenError.month
email: stripeFixtures.createTokenError.email
pickBy = (obj, fn) ->
Object.keys(obj)
.filter (key) -> fn(obj[key], key)
.reduce (res, key) ->
res[key] = obj[key]
return res
, {}
validateOptions = (options) ->
isAmex = cardValidator.number(options.number).card?.isAmex
validators = makeValidators isAmex
# for each validator use the corresponding data from options
# if return falsy there is an error for that key
# if return truthy there is no error for that key
# pick keys where result is falsy
notValidMap = pickBy validators, (validator, key) -> not validator options[key]
# return a list with an item of { param: key } where key is one of the keys
# with errors.
return _.map notValidMap, (error, key) -> validateErrorResponses[key]
makeValidators = (isAmex) ->
fieldValidator = (field, rest...) -> (value) ->
value = value.toString()
cardValidator[field](value, rest...).isValid
return {
number: fieldValidator 'number'
cvc: fieldValidator 'cvv', if isAmex then 4 else 3
exp_month: fieldValidator 'expirationMonth'
exp_year: fieldValidator 'expirationYear'
email: isEmail
}
|
[
{
"context": "t a person by name', () -> \n expect(greet 'howard').to.be.eql 'hello, howard'\n it 'should greet ",
"end": 193,
"score": 0.9968931674957275,
"start": 187,
"tag": "NAME",
"value": "howard"
},
{
"context": " \n expect(greet 'howard').to.be.eql 'hello, ho... | test/greet_spec.coffee | yqnetwork/besike-node-greet | 0 | greet = require('greet')
describe 'greet', () ->
it 'is a dummy sucess case', () ->
expect(1).to.eql 1
it 'should greet a person by name', () ->
expect(greet 'howard').to.be.eql 'hello, howard'
it 'should greet a person flirtatiously if drunk', () ->
expect(greet 'howard', true).to.eql 'hello, howard, you look sexy today'
| 174524 | greet = require('greet')
describe 'greet', () ->
it 'is a dummy sucess case', () ->
expect(1).to.eql 1
it 'should greet a person by name', () ->
expect(greet '<NAME>').to.be.eql 'hello, <NAME>'
it 'should greet a person flirtatiously if drunk', () ->
expect(greet '<NAME>', true).to.eql 'hello, <NAME>, you look sexy today'
| true | greet = require('greet')
describe 'greet', () ->
it 'is a dummy sucess case', () ->
expect(1).to.eql 1
it 'should greet a person by name', () ->
expect(greet 'PI:NAME:<NAME>END_PI').to.be.eql 'hello, PI:NAME:<NAME>END_PI'
it 'should greet a person flirtatiously if drunk', () ->
expect(greet 'PI:NAME:<NAME>END_PI', true).to.eql 'hello, PI:NAME:<NAME>END_PI, you look sexy today'
|
[
{
"context": "Horizontal: false\n\n\n#Change Title here\n(title = [\"Bobby Drake\", \"Scott Summers\",\"Jean Grey\", \"Warren Worthingto",
"end": 318,
"score": 0.9998922348022461,
"start": 307,
"tag": "NAME",
"value": "Bobby Drake"
},
{
"context": "se\n\n\n#Change Title here\n(title ... | Android-Components/Cards/Cards.coffee | iamkeeler/UXTOOLTIME-Framer | 4 | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#Cards
# Create the draggable layer
scrollpanel = new ScrollComponent
width: Screen.width
height: Screen.height - 80
x: Align.center
y: Align.bottom
backgroundColor: "#F2F2F2"
scrollHorizontal: false
#Change Title here
(title = ["Bobby Drake", "Scott Summers","Jean Grey", "Warren Worthington III", "Hank McCoy", "Kurt Wagner", "Lorna Dane", "Kevin Sydney", "Armando Muñoz"])
#Change content text here
(content = ["123 Oak Street
Lutherville-Timonium, MD",
"345 Elm Street
Lutherville-Timonium, MD",
"456 Spruce Street
Lutherville-Timonium, MD",
"567 Pine Avenue
Lutherville-Timonium, MD"
"678 Birch Street
Lutherville-Timonium, MD"
"789 Sycamore Road
Lutherville-Timonium, MD"
"123 Maple Court
Lutherville-Timonium, MD"
"345 Willow Court
Lutherville-Timonium, MD"
"678 Cedar Street
Lutherville-Timonium, MD"])
#Change Subright text here
(subright = ["2", "10", "3", "1", "0", "0", "12", "5", "4"])
for i in [0...8]
CardItem = new Layer
height: 83
width: Screen.width-16
backgroundColor: "#fff"
y: i *90 + 10
#y: Align.top 80
x: Align.center
z: 1
borderRadius: 4
shadow: 4
name: [i]
shadowSpread: 1
shadowColor: "rgba(156,156,156,0.5)"
shadowBlur: 4
shadowY: 2
shadowX: 0
parent: scrollpanel.content
Title = new TextLayer
text: title[i]
fontFamily: "Roboto"
fontSize: 16
fontWeight: 500
color: "#2F2F2F"
x: 64
y: 16
parent: CardItem
Content = new TextLayer
text: content[i]
fontFamily: "Roboto"
fontSize: 14
fontWeight: 500
truncate: true
color: "#000000"
opacity: 0.54
x: 64
y: 36
lineHeight: 1.0
parent: CardItem
Icon = new SVGLayer
image: ""
size: 32
x: 16
y: Align.center
parent: CardItem
Icon.states.selected =
image:""
Subright = new TextLayer
text: subright[i]
fontFamily: "Roboto"
fontSize: 14
fontWeight: 500
color: "#626161"
y: Align.top 16
x: Align.right
padding: right: 20
parent: CardItem
# </fold>
"""
| 220336 | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#Cards
# Create the draggable layer
scrollpanel = new ScrollComponent
width: Screen.width
height: Screen.height - 80
x: Align.center
y: Align.bottom
backgroundColor: "#F2F2F2"
scrollHorizontal: false
#Change Title here
(title = ["<NAME>", "<NAME>","<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"])
#Change content text here
(content = ["123 Oak Street
Lutherville-Timonium, MD",
"345 Elm Street
Lutherville-Timonium, MD",
"456 Spruce Street
Lutherville-Timonium, MD",
"567 Pine Avenue
Lutherville-Timonium, MD"
"678 Birch Street
Lutherville-Timonium, MD"
"789 Sycamore Road
Lutherville-Timonium, MD"
"123 Maple Court
Lutherville-Timonium, MD"
"345 Willow Court
Lutherville-Timonium, MD"
"678 Cedar Street
Lutherville-Timonium, MD"])
#Change Subright text here
(subright = ["2", "10", "3", "1", "0", "0", "12", "5", "4"])
for i in [0...8]
CardItem = new Layer
height: 83
width: Screen.width-16
backgroundColor: "#fff"
y: i *90 + 10
#y: Align.top 80
x: Align.center
z: 1
borderRadius: 4
shadow: 4
name: [i]
shadowSpread: 1
shadowColor: "rgba(156,156,156,0.5)"
shadowBlur: 4
shadowY: 2
shadowX: 0
parent: scrollpanel.content
Title = new TextLayer
text: title[i]
fontFamily: "Roboto"
fontSize: 16
fontWeight: 500
color: "#2F2F2F"
x: 64
y: 16
parent: CardItem
Content = new TextLayer
text: content[i]
fontFamily: "Roboto"
fontSize: 14
fontWeight: 500
truncate: true
color: "#000000"
opacity: 0.54
x: 64
y: 36
lineHeight: 1.0
parent: CardItem
Icon = new SVGLayer
image: ""
size: 32
x: 16
y: Align.center
parent: CardItem
Icon.states.selected =
image:""
Subright = new TextLayer
text: subright[i]
fontFamily: "Roboto"
fontSize: 14
fontWeight: 500
color: "#626161"
y: Align.top 16
x: Align.right
padding: right: 20
parent: CardItem
# </fold>
"""
| true | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#Cards
# Create the draggable layer
scrollpanel = new ScrollComponent
width: Screen.width
height: Screen.height - 80
x: Align.center
y: Align.bottom
backgroundColor: "#F2F2F2"
scrollHorizontal: false
#Change Title here
(title = ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"])
#Change content text here
(content = ["123 Oak Street
Lutherville-Timonium, MD",
"345 Elm Street
Lutherville-Timonium, MD",
"456 Spruce Street
Lutherville-Timonium, MD",
"567 Pine Avenue
Lutherville-Timonium, MD"
"678 Birch Street
Lutherville-Timonium, MD"
"789 Sycamore Road
Lutherville-Timonium, MD"
"123 Maple Court
Lutherville-Timonium, MD"
"345 Willow Court
Lutherville-Timonium, MD"
"678 Cedar Street
Lutherville-Timonium, MD"])
#Change Subright text here
(subright = ["2", "10", "3", "1", "0", "0", "12", "5", "4"])
for i in [0...8]
CardItem = new Layer
height: 83
width: Screen.width-16
backgroundColor: "#fff"
y: i *90 + 10
#y: Align.top 80
x: Align.center
z: 1
borderRadius: 4
shadow: 4
name: [i]
shadowSpread: 1
shadowColor: "rgba(156,156,156,0.5)"
shadowBlur: 4
shadowY: 2
shadowX: 0
parent: scrollpanel.content
Title = new TextLayer
text: title[i]
fontFamily: "Roboto"
fontSize: 16
fontWeight: 500
color: "#2F2F2F"
x: 64
y: 16
parent: CardItem
Content = new TextLayer
text: content[i]
fontFamily: "Roboto"
fontSize: 14
fontWeight: 500
truncate: true
color: "#000000"
opacity: 0.54
x: 64
y: 36
lineHeight: 1.0
parent: CardItem
Icon = new SVGLayer
image: ""
size: 32
x: 16
y: Align.center
parent: CardItem
Icon.states.selected =
image:""
Subright = new TextLayer
text: subright[i]
fontFamily: "Roboto"
fontSize: 14
fontWeight: 500
color: "#626161"
y: Align.top 16
x: Align.right
padding: right: 20
parent: CardItem
# </fold>
"""
|
[
{
"context": "ormalized hide address bar for iOS & Android\n (c) Scott Jehl, scottjehl.com\n MIT License\n ###\n \n # If we s",
"end": 264,
"score": 0.9996917247772217,
"start": 254,
"tag": "NAME",
"value": "Scott Jehl"
},
{
"context": "de address bar for iOS & Android\n (c) Sc... | app/templates/source/scripts/helper.coffee | codemeasandwich/generator-codesandwich | 0 | ###
MBP - Mobile boilerplate helper functions
###
((document) ->
###
Fix for iPhone viewport scale bug
http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/
###
###
Normalized hide address bar for iOS & Android
(c) Scott Jehl, scottjehl.com
MIT License
###
# If we split this up into two functions we can reuse
# this function if we aren't doing full page reloads.
# If we cache this we don't need to re-calibrate everytime we call
# the hide url bar
# So we don't redefine this function everytime we
# we call hideUrlBar
# It should be up to the mobile
# if there is a hash, or MBP.BODY_SCROLL_TOP hasn't been set yet, wait till that happens
# If there's a hash, or addEventListener is undefined, stop here
# scroll to 1
# reset to 0 on bodyready, if needed
# at load, if user hasn't scrolled more than 20 or so...
# reset to hide addr bar at onload
###
Fast Buttons - read wiki below before using
https://github.com/h5bp/mobile-boilerplate/wiki/JavaScript-Helper
###
# styling of .pressed is defined in the project's CSS files
# This is a bit of fun for Android 2.3...
# If you change window.location via fastButton, a click event will fire
# on the new page, as if the events are continuing from the previous page.
# We pick that event up here, but MBP.coords is empty, because it's a new page,
# so we don't prevent it. Here's we're assuming that click events on touch devices
# that occur without a preceding touchStart are to be ignored.
# This bug only affects touch Android 2.3 devices, but a simple ontouchstart test creates a false positive on
# some Blackberry devices. https://github.com/Modernizr/Modernizr/issues/372
# The browser sniffing is to avoid the Blackberry case. Bah
# fn arg can be an object or a function, thanks to handleEvent
# read more about the explanation at: http://www.thecssninja.com/javascript/handleevent
addEvt = (el, evt, fn, bubble) ->
if "addEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.addEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.addEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
return
), bubble
else
throw e
else if "attachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.attachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
return
else
el.attachEvent "on" + evt, fn
return
rmEvt = (el, evt, fn, bubble) ->
if "removeEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.removeEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.removeEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
return
), bubble
else
throw e
else if "detachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.detachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
return
else
el.detachEvent "on" + evt, fn
return
window.MBP = window.MBP or {}
MBP.viewportmeta = document.querySelector and document.querySelector("meta[name=\"viewport\"]")
MBP.ua = navigator.userAgent
MBP.scaleFix = ->
if MBP.viewportmeta and /iPhone|iPad|iPod/.test(MBP.ua) and not /Opera Mini/.test(MBP.ua)
MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0"
document.addEventListener "gesturestart", MBP.gestureStart, false
return
MBP.gestureStart = ->
MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6"
return
MBP.BODY_SCROLL_TOP = false
MBP.getScrollTop = ->
win = window
doc = document
win.pageYOffset or doc.compatMode is "CSS1Compat" and doc.documentElement.scrollTop or doc.body.scrollTop or 0
MBP.hideUrlBar = ->
win = window
win.scrollTo 0, (if MBP.BODY_SCROLL_TOP is 1 then 0 else 1) if not location.hash and MBP.BODY_SCROLL_TOP isnt false
return
MBP.hideUrlBarOnLoad = ->
win = window
doc = win.document
bodycheck = undefined
if not win.navigator.standalone and not location.hash and win.addEventListener
window.scrollTo 0, 1
MBP.BODY_SCROLL_TOP = 1
bodycheck = setInterval(->
if doc.body
clearInterval bodycheck
MBP.BODY_SCROLL_TOP = MBP.getScrollTop()
MBP.hideUrlBar()
return
, 15)
win.addEventListener "load", (->
setTimeout (->
MBP.hideUrlBar() if MBP.getScrollTop() < 20
return
), 0
return
), false
return
MBP.fastButton = (element, handler, pressedClass) ->
@handler = handler
@pressedClass = (if typeof pressedClass is "undefined" then "pressed" else pressedClass)
MBP.listenForGhostClicks()
if element.length and element.length > 1
for singleElIdx of element
@addClickEvent element[singleElIdx]
else
@addClickEvent element
return
MBP.fastButton::handleEvent = (event) ->
event = event or window.event
switch event.type
when "touchstart"
@onTouchStart event
when "touchmove"
@onTouchMove event
when "touchend"
@onClick event
when "click"
@onClick event
MBP.fastButton::onTouchStart = (event) ->
element = event.target or event.srcElement
event.stopPropagation()
element.addEventListener "touchend", this, false
document.body.addEventListener "touchmove", this, false
@startX = event.touches[0].clientX
@startY = event.touches[0].clientY
element.className += " " + @pressedClass
return
MBP.fastButton::onTouchMove = (event) ->
@reset event if Math.abs(event.touches[0].clientX - @startX) > 10 or Math.abs(event.touches[0].clientY - @startY) > 10
return
MBP.fastButton::onClick = (event) ->
event = event or window.event
element = event.target or event.srcElement
event.stopPropagation() if event.stopPropagation
@reset event
@handler.apply event.currentTarget, [event]
MBP.preventGhostClick @startX, @startY if event.type is "touchend"
pattern = new RegExp(" ?" + @pressedClass, "gi")
element.className = element.className.replace(pattern, "")
return
MBP.fastButton::reset = (event) ->
element = event.target or event.srcElement
rmEvt element, "touchend", this, false
rmEvt document.body, "touchmove", this, false
pattern = new RegExp(" ?" + @pressedClass, "gi")
element.className = element.className.replace(pattern, "")
return
MBP.fastButton::addClickEvent = (element) ->
addEvt element, "touchstart", this, false
addEvt element, "click", this, false
return
MBP.preventGhostClick = (x, y) ->
MBP.coords.push x, y
window.setTimeout (->
MBP.coords.splice 0, 2
return
), 2500
return
MBP.ghostClickHandler = (event) ->
if not MBP.hadTouchEvent and MBP.dodgyAndroid
event.stopPropagation()
event.preventDefault()
return
i = 0
len = MBP.coords.length
while i < len
x = MBP.coords[i]
y = MBP.coords[i + 1]
if Math.abs(event.clientX - x) < 25 and Math.abs(event.clientY - y) < 25
event.stopPropagation()
event.preventDefault()
i += 2
return
MBP.dodgyAndroid = ("ontouchstart" of window) and (navigator.userAgent.indexOf("Android 2.3") isnt -1)
MBP.listenForGhostClicks = (->
alreadyRan = false
->
return if alreadyRan
document.addEventListener "click", MBP.ghostClickHandler, true if document.addEventListener
addEvt document.documentElement, "touchstart", (->
MBP.hadTouchEvent = true
return
), false
alreadyRan = true
return
)()
MBP.coords = []
###
Autogrow
http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series.html
###
MBP.autogrow = (element, lh) ->
handler = (e) ->
newHeight = @scrollHeight
currentHeight = @clientHeight
@style.height = newHeight + 3 * textLineHeight + "px" if newHeight > currentHeight
return
setLineHeight = (if (lh) then lh else 12)
textLineHeight = (if element.currentStyle then element.currentStyle.lineHeight else getComputedStyle(element, null).lineHeight)
textLineHeight = (if (textLineHeight.indexOf("px") is -1) then setLineHeight else parseInt(textLineHeight, 10))
element.style.overflow = "hidden"
(if element.addEventListener then element.addEventListener("input", handler, false) else element.attachEvent("onpropertychange", handler))
return
###
Enable CSS active pseudo styles in Mobile Safari
http://alxgbsn.co.uk/2011/10/17/enable-css-active-pseudo-styles-in-mobile-safari/
###
MBP.enableActive = ->
document.addEventListener "touchstart", (->
), false
return
###
Prevent default scrolling on document window
###
MBP.preventScrolling = ->
document.addEventListener "touchmove", ((e) ->
return if e.target.type is "range"
e.preventDefault()
return
), false
return
###
Prevent iOS from zooming onfocus
https://github.com/h5bp/mobile-boilerplate/pull/108
Adapted from original jQuery code here: http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/
###
MBP.preventZoom = ->
if MBP.viewportmeta and navigator.platform.match(/iPad|iPhone|iPod/i)
formFields = document.querySelectorAll("input, select, textarea")
contentString = "width=device-width,initial-scale=1,maximum-scale="
i = 0
fieldLength = formFields.length
setViewportOnFocus = ->
MBP.viewportmeta.content = contentString + "1"
return
setViewportOnBlur = ->
MBP.viewportmeta.content = contentString + "10"
return
while i < fieldLength
formFields[i].onfocus = setViewportOnFocus
formFields[i].onblur = setViewportOnBlur
i++
return
###
iOS Startup Image helper
###
MBP.startupImage = ->
portrait = undefined
landscape = undefined
pixelRatio = undefined
head = undefined
link1 = undefined
link2 = undefined
pixelRatio = window.devicePixelRatio
head = document.getElementsByTagName("head")[0]
if navigator.platform is "iPad"
portrait = (if pixelRatio is 2 then "img/startup/startup-tablet-portrait-retina.png" else "img/startup/startup-tablet-portrait.png")
landscape = (if pixelRatio is 2 then "img/startup/startup-tablet-landscape-retina.png" else "img/startup/startup-tablet-landscape.png")
link1 = document.createElement("link")
link1.setAttribute "rel", "apple-touch-startup-image"
link1.setAttribute "media", "screen and (orientation: portrait)"
link1.setAttribute "href", portrait
head.appendChild link1
link2 = document.createElement("link")
link2.setAttribute "rel", "apple-touch-startup-image"
link2.setAttribute "media", "screen and (orientation: landscape)"
link2.setAttribute "href", landscape
head.appendChild link2
else
portrait = (if pixelRatio is 2 then "img/startup/startup-retina.png" else "img/startup/startup.png")
portrait = (if screen.height is 568 then "img/startup/startup-retina-4in.png" else portrait)
link1 = document.createElement("link")
link1.setAttribute "rel", "apple-touch-startup-image"
link1.setAttribute "href", portrait
head.appendChild link1
#hack to fix letterboxed full screen web apps on 4" iPhone / iPod with iOS 6
MBP.viewportmeta.content = MBP.viewportmeta.content.replace(/\bwidth\s*=\s*320\b/, "width=320.1").replace(/\bwidth\s*=\s*device-width\b/, "") if MBP.viewportmeta if navigator.platform.match(/iPhone|iPod/i) and (screen.height is 568) and navigator.userAgent.match(/\bOS 6_/)
return
return
) document | 1450 | ###
MBP - Mobile boilerplate helper functions
###
((document) ->
###
Fix for iPhone viewport scale bug
http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/
###
###
Normalized hide address bar for iOS & Android
(c) <NAME>, <EMAIL>
MIT License
###
# If we split this up into two functions we can reuse
# this function if we aren't doing full page reloads.
# If we cache this we don't need to re-calibrate everytime we call
# the hide url bar
# So we don't redefine this function everytime we
# we call hideUrlBar
# It should be up to the mobile
# if there is a hash, or MBP.BODY_SCROLL_TOP hasn't been set yet, wait till that happens
# If there's a hash, or addEventListener is undefined, stop here
# scroll to 1
# reset to 0 on bodyready, if needed
# at load, if user hasn't scrolled more than 20 or so...
# reset to hide addr bar at onload
###
Fast Buttons - read wiki below before using
https://github.com/h5bp/mobile-boilerplate/wiki/JavaScript-Helper
###
# styling of .pressed is defined in the project's CSS files
# This is a bit of fun for Android 2.3...
# If you change window.location via fastButton, a click event will fire
# on the new page, as if the events are continuing from the previous page.
# We pick that event up here, but MBP.coords is empty, because it's a new page,
# so we don't prevent it. Here's we're assuming that click events on touch devices
# that occur without a preceding touchStart are to be ignored.
# This bug only affects touch Android 2.3 devices, but a simple ontouchstart test creates a false positive on
# some Blackberry devices. https://github.com/Modernizr/Modernizr/issues/372
# The browser sniffing is to avoid the Blackberry case. Bah
# fn arg can be an object or a function, thanks to handleEvent
# read more about the explanation at: http://www.thecssninja.com/javascript/handleevent
addEvt = (el, evt, fn, bubble) ->
if "addEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.addEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.addEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
return
), bubble
else
throw e
else if "attachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.attachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
return
else
el.attachEvent "on" + evt, fn
return
rmEvt = (el, evt, fn, bubble) ->
if "removeEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.removeEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.removeEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
return
), bubble
else
throw e
else if "detachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.detachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
return
else
el.detachEvent "on" + evt, fn
return
window.MBP = window.MBP or {}
MBP.viewportmeta = document.querySelector and document.querySelector("meta[name=\"viewport\"]")
MBP.ua = navigator.userAgent
MBP.scaleFix = ->
if MBP.viewportmeta and /iPhone|iPad|iPod/.test(MBP.ua) and not /Opera Mini/.test(MBP.ua)
MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0"
document.addEventListener "gesturestart", MBP.gestureStart, false
return
MBP.gestureStart = ->
MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6"
return
MBP.BODY_SCROLL_TOP = false
MBP.getScrollTop = ->
win = window
doc = document
win.pageYOffset or doc.compatMode is "CSS1Compat" and doc.documentElement.scrollTop or doc.body.scrollTop or 0
MBP.hideUrlBar = ->
win = window
win.scrollTo 0, (if MBP.BODY_SCROLL_TOP is 1 then 0 else 1) if not location.hash and MBP.BODY_SCROLL_TOP isnt false
return
MBP.hideUrlBarOnLoad = ->
win = window
doc = win.document
bodycheck = undefined
if not win.navigator.standalone and not location.hash and win.addEventListener
window.scrollTo 0, 1
MBP.BODY_SCROLL_TOP = 1
bodycheck = setInterval(->
if doc.body
clearInterval bodycheck
MBP.BODY_SCROLL_TOP = MBP.getScrollTop()
MBP.hideUrlBar()
return
, 15)
win.addEventListener "load", (->
setTimeout (->
MBP.hideUrlBar() if MBP.getScrollTop() < 20
return
), 0
return
), false
return
MBP.fastButton = (element, handler, pressedClass) ->
@handler = handler
@pressedClass = (if typeof pressedClass is "undefined" then "pressed" else pressedClass)
MBP.listenForGhostClicks()
if element.length and element.length > 1
for singleElIdx of element
@addClickEvent element[singleElIdx]
else
@addClickEvent element
return
MBP.fastButton::handleEvent = (event) ->
event = event or window.event
switch event.type
when "touchstart"
@onTouchStart event
when "touchmove"
@onTouchMove event
when "touchend"
@onClick event
when "click"
@onClick event
MBP.fastButton::onTouchStart = (event) ->
element = event.target or event.srcElement
event.stopPropagation()
element.addEventListener "touchend", this, false
document.body.addEventListener "touchmove", this, false
@startX = event.touches[0].clientX
@startY = event.touches[0].clientY
element.className += " " + @pressedClass
return
MBP.fastButton::onTouchMove = (event) ->
@reset event if Math.abs(event.touches[0].clientX - @startX) > 10 or Math.abs(event.touches[0].clientY - @startY) > 10
return
MBP.fastButton::onClick = (event) ->
event = event or window.event
element = event.target or event.srcElement
event.stopPropagation() if event.stopPropagation
@reset event
@handler.apply event.currentTarget, [event]
MBP.preventGhostClick @startX, @startY if event.type is "touchend"
pattern = new RegExp(" ?" + @pressedClass, "gi")
element.className = element.className.replace(pattern, "")
return
MBP.fastButton::reset = (event) ->
element = event.target or event.srcElement
rmEvt element, "touchend", this, false
rmEvt document.body, "touchmove", this, false
pattern = new RegExp(" ?" + @pressedClass, "gi")
element.className = element.className.replace(pattern, "")
return
MBP.fastButton::addClickEvent = (element) ->
addEvt element, "touchstart", this, false
addEvt element, "click", this, false
return
MBP.preventGhostClick = (x, y) ->
MBP.coords.push x, y
window.setTimeout (->
MBP.coords.splice 0, 2
return
), 2500
return
MBP.ghostClickHandler = (event) ->
if not MBP.hadTouchEvent and MBP.dodgyAndroid
event.stopPropagation()
event.preventDefault()
return
i = 0
len = MBP.coords.length
while i < len
x = MBP.coords[i]
y = MBP.coords[i + 1]
if Math.abs(event.clientX - x) < 25 and Math.abs(event.clientY - y) < 25
event.stopPropagation()
event.preventDefault()
i += 2
return
MBP.dodgyAndroid = ("ontouchstart" of window) and (navigator.userAgent.indexOf("Android 2.3") isnt -1)
MBP.listenForGhostClicks = (->
alreadyRan = false
->
return if alreadyRan
document.addEventListener "click", MBP.ghostClickHandler, true if document.addEventListener
addEvt document.documentElement, "touchstart", (->
MBP.hadTouchEvent = true
return
), false
alreadyRan = true
return
)()
MBP.coords = []
###
Autogrow
http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series.html
###
MBP.autogrow = (element, lh) ->
handler = (e) ->
newHeight = @scrollHeight
currentHeight = @clientHeight
@style.height = newHeight + 3 * textLineHeight + "px" if newHeight > currentHeight
return
setLineHeight = (if (lh) then lh else 12)
textLineHeight = (if element.currentStyle then element.currentStyle.lineHeight else getComputedStyle(element, null).lineHeight)
textLineHeight = (if (textLineHeight.indexOf("px") is -1) then setLineHeight else parseInt(textLineHeight, 10))
element.style.overflow = "hidden"
(if element.addEventListener then element.addEventListener("input", handler, false) else element.attachEvent("onpropertychange", handler))
return
###
Enable CSS active pseudo styles in Mobile Safari
http://alxgbsn.co.uk/2011/10/17/enable-css-active-pseudo-styles-in-mobile-safari/
###
MBP.enableActive = ->
document.addEventListener "touchstart", (->
), false
return
###
Prevent default scrolling on document window
###
MBP.preventScrolling = ->
document.addEventListener "touchmove", ((e) ->
return if e.target.type is "range"
e.preventDefault()
return
), false
return
###
Prevent iOS from zooming onfocus
https://github.com/h5bp/mobile-boilerplate/pull/108
Adapted from original jQuery code here: http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/
###
MBP.preventZoom = ->
if MBP.viewportmeta and navigator.platform.match(/iPad|iPhone|iPod/i)
formFields = document.querySelectorAll("input, select, textarea")
contentString = "width=device-width,initial-scale=1,maximum-scale="
i = 0
fieldLength = formFields.length
setViewportOnFocus = ->
MBP.viewportmeta.content = contentString + "1"
return
setViewportOnBlur = ->
MBP.viewportmeta.content = contentString + "10"
return
while i < fieldLength
formFields[i].onfocus = setViewportOnFocus
formFields[i].onblur = setViewportOnBlur
i++
return
###
iOS Startup Image helper
###
MBP.startupImage = ->
portrait = undefined
landscape = undefined
pixelRatio = undefined
head = undefined
link1 = undefined
link2 = undefined
pixelRatio = window.devicePixelRatio
head = document.getElementsByTagName("head")[0]
if navigator.platform is "iPad"
portrait = (if pixelRatio is 2 then "img/startup/startup-tablet-portrait-retina.png" else "img/startup/startup-tablet-portrait.png")
landscape = (if pixelRatio is 2 then "img/startup/startup-tablet-landscape-retina.png" else "img/startup/startup-tablet-landscape.png")
link1 = document.createElement("link")
link1.setAttribute "rel", "apple-touch-startup-image"
link1.setAttribute "media", "screen and (orientation: portrait)"
link1.setAttribute "href", portrait
head.appendChild link1
link2 = document.createElement("link")
link2.setAttribute "rel", "apple-touch-startup-image"
link2.setAttribute "media", "screen and (orientation: landscape)"
link2.setAttribute "href", landscape
head.appendChild link2
else
portrait = (if pixelRatio is 2 then "img/startup/startup-retina.png" else "img/startup/startup.png")
portrait = (if screen.height is 568 then "img/startup/startup-retina-4in.png" else portrait)
link1 = document.createElement("link")
link1.setAttribute "rel", "apple-touch-startup-image"
link1.setAttribute "href", portrait
head.appendChild link1
#hack to fix letterboxed full screen web apps on 4" iPhone / iPod with iOS 6
MBP.viewportmeta.content = MBP.viewportmeta.content.replace(/\bwidth\s*=\s*320\b/, "width=320.1").replace(/\bwidth\s*=\s*device-width\b/, "") if MBP.viewportmeta if navigator.platform.match(/iPhone|iPod/i) and (screen.height is 568) and navigator.userAgent.match(/\bOS 6_/)
return
return
) document | true | ###
MBP - Mobile boilerplate helper functions
###
((document) ->
###
Fix for iPhone viewport scale bug
http://www.blog.highub.com/mobile-2/a-fix-for-iphone-viewport-scale-bug/
###
###
Normalized hide address bar for iOS & Android
(c) PI:NAME:<NAME>END_PI, PI:EMAIL:<EMAIL>END_PI
MIT License
###
# If we split this up into two functions we can reuse
# this function if we aren't doing full page reloads.
# If we cache this we don't need to re-calibrate everytime we call
# the hide url bar
# So we don't redefine this function everytime we
# we call hideUrlBar
# It should be up to the mobile
# if there is a hash, or MBP.BODY_SCROLL_TOP hasn't been set yet, wait till that happens
# If there's a hash, or addEventListener is undefined, stop here
# scroll to 1
# reset to 0 on bodyready, if needed
# at load, if user hasn't scrolled more than 20 or so...
# reset to hide addr bar at onload
###
Fast Buttons - read wiki below before using
https://github.com/h5bp/mobile-boilerplate/wiki/JavaScript-Helper
###
# styling of .pressed is defined in the project's CSS files
# This is a bit of fun for Android 2.3...
# If you change window.location via fastButton, a click event will fire
# on the new page, as if the events are continuing from the previous page.
# We pick that event up here, but MBP.coords is empty, because it's a new page,
# so we don't prevent it. Here's we're assuming that click events on touch devices
# that occur without a preceding touchStart are to be ignored.
# This bug only affects touch Android 2.3 devices, but a simple ontouchstart test creates a false positive on
# some Blackberry devices. https://github.com/Modernizr/Modernizr/issues/372
# The browser sniffing is to avoid the Blackberry case. Bah
# fn arg can be an object or a function, thanks to handleEvent
# read more about the explanation at: http://www.thecssninja.com/javascript/handleevent
addEvt = (el, evt, fn, bubble) ->
if "addEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.addEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.addEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
return
), bubble
else
throw e
else if "attachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.attachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
return
else
el.attachEvent "on" + evt, fn
return
rmEvt = (el, evt, fn, bubble) ->
if "removeEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.removeEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.removeEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
return
), bubble
else
throw e
else if "detachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.detachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
return
else
el.detachEvent "on" + evt, fn
return
window.MBP = window.MBP or {}
MBP.viewportmeta = document.querySelector and document.querySelector("meta[name=\"viewport\"]")
MBP.ua = navigator.userAgent
MBP.scaleFix = ->
if MBP.viewportmeta and /iPhone|iPad|iPod/.test(MBP.ua) and not /Opera Mini/.test(MBP.ua)
MBP.viewportmeta.content = "width=device-width, minimum-scale=1.0, maximum-scale=1.0"
document.addEventListener "gesturestart", MBP.gestureStart, false
return
MBP.gestureStart = ->
MBP.viewportmeta.content = "width=device-width, minimum-scale=0.25, maximum-scale=1.6"
return
MBP.BODY_SCROLL_TOP = false
MBP.getScrollTop = ->
win = window
doc = document
win.pageYOffset or doc.compatMode is "CSS1Compat" and doc.documentElement.scrollTop or doc.body.scrollTop or 0
MBP.hideUrlBar = ->
win = window
win.scrollTo 0, (if MBP.BODY_SCROLL_TOP is 1 then 0 else 1) if not location.hash and MBP.BODY_SCROLL_TOP isnt false
return
MBP.hideUrlBarOnLoad = ->
win = window
doc = win.document
bodycheck = undefined
if not win.navigator.standalone and not location.hash and win.addEventListener
window.scrollTo 0, 1
MBP.BODY_SCROLL_TOP = 1
bodycheck = setInterval(->
if doc.body
clearInterval bodycheck
MBP.BODY_SCROLL_TOP = MBP.getScrollTop()
MBP.hideUrlBar()
return
, 15)
win.addEventListener "load", (->
setTimeout (->
MBP.hideUrlBar() if MBP.getScrollTop() < 20
return
), 0
return
), false
return
MBP.fastButton = (element, handler, pressedClass) ->
@handler = handler
@pressedClass = (if typeof pressedClass is "undefined" then "pressed" else pressedClass)
MBP.listenForGhostClicks()
if element.length and element.length > 1
for singleElIdx of element
@addClickEvent element[singleElIdx]
else
@addClickEvent element
return
MBP.fastButton::handleEvent = (event) ->
event = event or window.event
switch event.type
when "touchstart"
@onTouchStart event
when "touchmove"
@onTouchMove event
when "touchend"
@onClick event
when "click"
@onClick event
MBP.fastButton::onTouchStart = (event) ->
element = event.target or event.srcElement
event.stopPropagation()
element.addEventListener "touchend", this, false
document.body.addEventListener "touchmove", this, false
@startX = event.touches[0].clientX
@startY = event.touches[0].clientY
element.className += " " + @pressedClass
return
MBP.fastButton::onTouchMove = (event) ->
@reset event if Math.abs(event.touches[0].clientX - @startX) > 10 or Math.abs(event.touches[0].clientY - @startY) > 10
return
MBP.fastButton::onClick = (event) ->
event = event or window.event
element = event.target or event.srcElement
event.stopPropagation() if event.stopPropagation
@reset event
@handler.apply event.currentTarget, [event]
MBP.preventGhostClick @startX, @startY if event.type is "touchend"
pattern = new RegExp(" ?" + @pressedClass, "gi")
element.className = element.className.replace(pattern, "")
return
MBP.fastButton::reset = (event) ->
element = event.target or event.srcElement
rmEvt element, "touchend", this, false
rmEvt document.body, "touchmove", this, false
pattern = new RegExp(" ?" + @pressedClass, "gi")
element.className = element.className.replace(pattern, "")
return
MBP.fastButton::addClickEvent = (element) ->
addEvt element, "touchstart", this, false
addEvt element, "click", this, false
return
MBP.preventGhostClick = (x, y) ->
MBP.coords.push x, y
window.setTimeout (->
MBP.coords.splice 0, 2
return
), 2500
return
MBP.ghostClickHandler = (event) ->
if not MBP.hadTouchEvent and MBP.dodgyAndroid
event.stopPropagation()
event.preventDefault()
return
i = 0
len = MBP.coords.length
while i < len
x = MBP.coords[i]
y = MBP.coords[i + 1]
if Math.abs(event.clientX - x) < 25 and Math.abs(event.clientY - y) < 25
event.stopPropagation()
event.preventDefault()
i += 2
return
MBP.dodgyAndroid = ("ontouchstart" of window) and (navigator.userAgent.indexOf("Android 2.3") isnt -1)
MBP.listenForGhostClicks = (->
alreadyRan = false
->
return if alreadyRan
document.addEventListener "click", MBP.ghostClickHandler, true if document.addEventListener
addEvt document.documentElement, "touchstart", (->
MBP.hadTouchEvent = true
return
), false
alreadyRan = true
return
)()
MBP.coords = []
###
Autogrow
http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series.html
###
MBP.autogrow = (element, lh) ->
handler = (e) ->
newHeight = @scrollHeight
currentHeight = @clientHeight
@style.height = newHeight + 3 * textLineHeight + "px" if newHeight > currentHeight
return
setLineHeight = (if (lh) then lh else 12)
textLineHeight = (if element.currentStyle then element.currentStyle.lineHeight else getComputedStyle(element, null).lineHeight)
textLineHeight = (if (textLineHeight.indexOf("px") is -1) then setLineHeight else parseInt(textLineHeight, 10))
element.style.overflow = "hidden"
(if element.addEventListener then element.addEventListener("input", handler, false) else element.attachEvent("onpropertychange", handler))
return
###
Enable CSS active pseudo styles in Mobile Safari
http://alxgbsn.co.uk/2011/10/17/enable-css-active-pseudo-styles-in-mobile-safari/
###
MBP.enableActive = ->
document.addEventListener "touchstart", (->
), false
return
###
Prevent default scrolling on document window
###
MBP.preventScrolling = ->
document.addEventListener "touchmove", ((e) ->
return if e.target.type is "range"
e.preventDefault()
return
), false
return
###
Prevent iOS from zooming onfocus
https://github.com/h5bp/mobile-boilerplate/pull/108
Adapted from original jQuery code here: http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/
###
MBP.preventZoom = ->
if MBP.viewportmeta and navigator.platform.match(/iPad|iPhone|iPod/i)
formFields = document.querySelectorAll("input, select, textarea")
contentString = "width=device-width,initial-scale=1,maximum-scale="
i = 0
fieldLength = formFields.length
setViewportOnFocus = ->
MBP.viewportmeta.content = contentString + "1"
return
setViewportOnBlur = ->
MBP.viewportmeta.content = contentString + "10"
return
while i < fieldLength
formFields[i].onfocus = setViewportOnFocus
formFields[i].onblur = setViewportOnBlur
i++
return
###
iOS Startup Image helper
###
MBP.startupImage = ->
portrait = undefined
landscape = undefined
pixelRatio = undefined
head = undefined
link1 = undefined
link2 = undefined
pixelRatio = window.devicePixelRatio
head = document.getElementsByTagName("head")[0]
if navigator.platform is "iPad"
portrait = (if pixelRatio is 2 then "img/startup/startup-tablet-portrait-retina.png" else "img/startup/startup-tablet-portrait.png")
landscape = (if pixelRatio is 2 then "img/startup/startup-tablet-landscape-retina.png" else "img/startup/startup-tablet-landscape.png")
link1 = document.createElement("link")
link1.setAttribute "rel", "apple-touch-startup-image"
link1.setAttribute "media", "screen and (orientation: portrait)"
link1.setAttribute "href", portrait
head.appendChild link1
link2 = document.createElement("link")
link2.setAttribute "rel", "apple-touch-startup-image"
link2.setAttribute "media", "screen and (orientation: landscape)"
link2.setAttribute "href", landscape
head.appendChild link2
else
portrait = (if pixelRatio is 2 then "img/startup/startup-retina.png" else "img/startup/startup.png")
portrait = (if screen.height is 568 then "img/startup/startup-retina-4in.png" else portrait)
link1 = document.createElement("link")
link1.setAttribute "rel", "apple-touch-startup-image"
link1.setAttribute "href", portrait
head.appendChild link1
#hack to fix letterboxed full screen web apps on 4" iPhone / iPod with iOS 6
MBP.viewportmeta.content = MBP.viewportmeta.content.replace(/\bwidth\s*=\s*320\b/, "width=320.1").replace(/\bwidth\s*=\s*device-width\b/, "") if MBP.viewportmeta if navigator.platform.match(/iPhone|iPod/i) and (screen.height is 568) and navigator.userAgent.match(/\bOS 6_/)
return
return
) document |
[
{
"context": "lback = (error, recentlyCompiled) ->) ->\n\t\tkey = \"compile:#{project_id}:#{user_id}\"\n\t\trclient.set key, true, \"EX\", @COMPILE_DELAY, \"N",
"end": 3414,
"score": 0.9506658911705017,
"start": 3381,
"tag": "KEY",
"value": "compile:#{project_id}:#{user_id}\""
}
] | app/coffee/Features/Compile/CompileManager.coffee | HasanSanli/web-sharelatex | 0 | Settings = require('settings-sharelatex')
RedisWrapper = require("../../infrastructure/RedisWrapper")
rclient = RedisWrapper.client("clsi_recently_compiled")
Project = require("../../models/Project").Project
ProjectRootDocManager = require "../Project/ProjectRootDocManager"
UserGetter = require "../User/UserGetter"
ClsiManager = require "./ClsiManager"
Metrics = require('metrics-sharelatex')
logger = require("logger-sharelatex")
rateLimiter = require("../../infrastructure/RateLimiter")
module.exports = CompileManager =
compile: (project_id, user_id, options = {}, _callback = (error) ->) ->
timer = new Metrics.Timer("editor.compile")
callback = (args...) ->
timer.done()
_callback(args...)
@_checkIfAutoCompileLimitHasBeenHit options.isAutoCompile, "everyone", (err, canCompile)->
if !canCompile
return callback null, "autocompile-backoff", []
logger.log project_id: project_id, user_id: user_id, "compiling project"
CompileManager._checkIfRecentlyCompiled project_id, user_id, (error, recentlyCompiled) ->
return callback(error) if error?
if recentlyCompiled
logger.warn {project_id, user_id}, "project was recently compiled so not continuing"
return callback null, "too-recently-compiled", []
CompileManager._ensureRootDocumentIsSet project_id, (error) ->
return callback(error) if error?
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
for key, value of limits
options[key] = value
# Put a lower limit on autocompiles for free users, based on compileGroup
CompileManager._checkCompileGroupAutoCompileLimit options.isAutoCompile, limits.compileGroup, (err, canCompile)->
if !canCompile
return callback null, "autocompile-backoff", []
# only pass user_id down to clsi if this is a per-user compile
compileAsUser = if Settings.disablePerUserCompiles then undefined else user_id
ClsiManager.sendRequest project_id, compileAsUser, options, (error, status, outputFiles, clsiServerId, validationProblems) ->
return callback(error) if error?
logger.log files: outputFiles, "output files"
callback(null, status, outputFiles, clsiServerId, limits, validationProblems)
stopCompile: (project_id, user_id, callback = (error) ->) ->
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
ClsiManager.stopCompile project_id, user_id, limits, callback
deleteAuxFiles: (project_id, user_id, callback = (error) ->) ->
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
ClsiManager.deleteAuxFiles project_id, user_id, limits, callback
getProjectCompileLimits: (project_id, callback = (error, limits) ->) ->
Project.findById project_id, {owner_ref: 1}, (error, project) ->
return callback(error) if error?
UserGetter.getUser project.owner_ref, {"features":1}, (err, owner)->
return callback(error) if error?
callback null, {
timeout: owner.features?.compileTimeout || Settings.defaultFeatures.compileTimeout
compileGroup: owner.features?.compileGroup || Settings.defaultFeatures.compileGroup
}
COMPILE_DELAY: 1 # seconds
_checkIfRecentlyCompiled: (project_id, user_id, callback = (error, recentlyCompiled) ->) ->
key = "compile:#{project_id}:#{user_id}"
rclient.set key, true, "EX", @COMPILE_DELAY, "NX", (error, ok) ->
return callback(error) if error?
if ok == "OK"
return callback null, false
else
return callback null, true
_checkCompileGroupAutoCompileLimit: (isAutoCompile, compileGroup, callback = (err, canCompile)->)->
if !isAutoCompile
return callback(null, true)
if compileGroup is "standard"
# apply extra limits to the standard compile group
CompileManager._checkIfAutoCompileLimitHasBeenHit isAutoCompile, compileGroup, callback
else
Metrics.inc "auto-compile-#{compileGroup}"
return callback(null, true) # always allow priority group users to compile
_checkIfAutoCompileLimitHasBeenHit: (isAutoCompile, compileGroup, callback = (err, canCompile)->)->
if !isAutoCompile
return callback(null, true)
Metrics.inc "auto-compile-#{compileGroup}"
opts =
endpointName:"auto_compile"
timeInterval:20
subjectName:compileGroup
throttle: Settings?.rateLimit?.autoCompile?[compileGroup] || 25
rateLimiter.addCount opts, (err, canCompile)->
if err?
canCompile = false
if !canCompile
Metrics.inc "auto-compile-#{compileGroup}-limited"
callback err, canCompile
_ensureRootDocumentIsSet: (project_id, callback = (error) ->) ->
Project.findById project_id, 'rootDoc_id', (error, project)=>
return callback(error) if error?
if !project?
return callback new Error("project not found")
if project.rootDoc_id?
callback()
else
ProjectRootDocManager.setRootDocAutomatically project_id, callback
wordCount: (project_id, user_id, file, callback = (error) ->) ->
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
ClsiManager.wordCount project_id, user_id, file, limits, callback
| 40992 | Settings = require('settings-sharelatex')
RedisWrapper = require("../../infrastructure/RedisWrapper")
rclient = RedisWrapper.client("clsi_recently_compiled")
Project = require("../../models/Project").Project
ProjectRootDocManager = require "../Project/ProjectRootDocManager"
UserGetter = require "../User/UserGetter"
ClsiManager = require "./ClsiManager"
Metrics = require('metrics-sharelatex')
logger = require("logger-sharelatex")
rateLimiter = require("../../infrastructure/RateLimiter")
module.exports = CompileManager =
compile: (project_id, user_id, options = {}, _callback = (error) ->) ->
timer = new Metrics.Timer("editor.compile")
callback = (args...) ->
timer.done()
_callback(args...)
@_checkIfAutoCompileLimitHasBeenHit options.isAutoCompile, "everyone", (err, canCompile)->
if !canCompile
return callback null, "autocompile-backoff", []
logger.log project_id: project_id, user_id: user_id, "compiling project"
CompileManager._checkIfRecentlyCompiled project_id, user_id, (error, recentlyCompiled) ->
return callback(error) if error?
if recentlyCompiled
logger.warn {project_id, user_id}, "project was recently compiled so not continuing"
return callback null, "too-recently-compiled", []
CompileManager._ensureRootDocumentIsSet project_id, (error) ->
return callback(error) if error?
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
for key, value of limits
options[key] = value
# Put a lower limit on autocompiles for free users, based on compileGroup
CompileManager._checkCompileGroupAutoCompileLimit options.isAutoCompile, limits.compileGroup, (err, canCompile)->
if !canCompile
return callback null, "autocompile-backoff", []
# only pass user_id down to clsi if this is a per-user compile
compileAsUser = if Settings.disablePerUserCompiles then undefined else user_id
ClsiManager.sendRequest project_id, compileAsUser, options, (error, status, outputFiles, clsiServerId, validationProblems) ->
return callback(error) if error?
logger.log files: outputFiles, "output files"
callback(null, status, outputFiles, clsiServerId, limits, validationProblems)
stopCompile: (project_id, user_id, callback = (error) ->) ->
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
ClsiManager.stopCompile project_id, user_id, limits, callback
deleteAuxFiles: (project_id, user_id, callback = (error) ->) ->
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
ClsiManager.deleteAuxFiles project_id, user_id, limits, callback
getProjectCompileLimits: (project_id, callback = (error, limits) ->) ->
Project.findById project_id, {owner_ref: 1}, (error, project) ->
return callback(error) if error?
UserGetter.getUser project.owner_ref, {"features":1}, (err, owner)->
return callback(error) if error?
callback null, {
timeout: owner.features?.compileTimeout || Settings.defaultFeatures.compileTimeout
compileGroup: owner.features?.compileGroup || Settings.defaultFeatures.compileGroup
}
COMPILE_DELAY: 1 # seconds
_checkIfRecentlyCompiled: (project_id, user_id, callback = (error, recentlyCompiled) ->) ->
key = "<KEY>
rclient.set key, true, "EX", @COMPILE_DELAY, "NX", (error, ok) ->
return callback(error) if error?
if ok == "OK"
return callback null, false
else
return callback null, true
_checkCompileGroupAutoCompileLimit: (isAutoCompile, compileGroup, callback = (err, canCompile)->)->
if !isAutoCompile
return callback(null, true)
if compileGroup is "standard"
# apply extra limits to the standard compile group
CompileManager._checkIfAutoCompileLimitHasBeenHit isAutoCompile, compileGroup, callback
else
Metrics.inc "auto-compile-#{compileGroup}"
return callback(null, true) # always allow priority group users to compile
_checkIfAutoCompileLimitHasBeenHit: (isAutoCompile, compileGroup, callback = (err, canCompile)->)->
if !isAutoCompile
return callback(null, true)
Metrics.inc "auto-compile-#{compileGroup}"
opts =
endpointName:"auto_compile"
timeInterval:20
subjectName:compileGroup
throttle: Settings?.rateLimit?.autoCompile?[compileGroup] || 25
rateLimiter.addCount opts, (err, canCompile)->
if err?
canCompile = false
if !canCompile
Metrics.inc "auto-compile-#{compileGroup}-limited"
callback err, canCompile
_ensureRootDocumentIsSet: (project_id, callback = (error) ->) ->
Project.findById project_id, 'rootDoc_id', (error, project)=>
return callback(error) if error?
if !project?
return callback new Error("project not found")
if project.rootDoc_id?
callback()
else
ProjectRootDocManager.setRootDocAutomatically project_id, callback
wordCount: (project_id, user_id, file, callback = (error) ->) ->
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
ClsiManager.wordCount project_id, user_id, file, limits, callback
| true | Settings = require('settings-sharelatex')
RedisWrapper = require("../../infrastructure/RedisWrapper")
rclient = RedisWrapper.client("clsi_recently_compiled")
Project = require("../../models/Project").Project
ProjectRootDocManager = require "../Project/ProjectRootDocManager"
UserGetter = require "../User/UserGetter"
ClsiManager = require "./ClsiManager"
Metrics = require('metrics-sharelatex')
logger = require("logger-sharelatex")
rateLimiter = require("../../infrastructure/RateLimiter")
module.exports = CompileManager =
compile: (project_id, user_id, options = {}, _callback = (error) ->) ->
timer = new Metrics.Timer("editor.compile")
callback = (args...) ->
timer.done()
_callback(args...)
@_checkIfAutoCompileLimitHasBeenHit options.isAutoCompile, "everyone", (err, canCompile)->
if !canCompile
return callback null, "autocompile-backoff", []
logger.log project_id: project_id, user_id: user_id, "compiling project"
CompileManager._checkIfRecentlyCompiled project_id, user_id, (error, recentlyCompiled) ->
return callback(error) if error?
if recentlyCompiled
logger.warn {project_id, user_id}, "project was recently compiled so not continuing"
return callback null, "too-recently-compiled", []
CompileManager._ensureRootDocumentIsSet project_id, (error) ->
return callback(error) if error?
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
for key, value of limits
options[key] = value
# Put a lower limit on autocompiles for free users, based on compileGroup
CompileManager._checkCompileGroupAutoCompileLimit options.isAutoCompile, limits.compileGroup, (err, canCompile)->
if !canCompile
return callback null, "autocompile-backoff", []
# only pass user_id down to clsi if this is a per-user compile
compileAsUser = if Settings.disablePerUserCompiles then undefined else user_id
ClsiManager.sendRequest project_id, compileAsUser, options, (error, status, outputFiles, clsiServerId, validationProblems) ->
return callback(error) if error?
logger.log files: outputFiles, "output files"
callback(null, status, outputFiles, clsiServerId, limits, validationProblems)
stopCompile: (project_id, user_id, callback = (error) ->) ->
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
ClsiManager.stopCompile project_id, user_id, limits, callback
deleteAuxFiles: (project_id, user_id, callback = (error) ->) ->
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
ClsiManager.deleteAuxFiles project_id, user_id, limits, callback
getProjectCompileLimits: (project_id, callback = (error, limits) ->) ->
Project.findById project_id, {owner_ref: 1}, (error, project) ->
return callback(error) if error?
UserGetter.getUser project.owner_ref, {"features":1}, (err, owner)->
return callback(error) if error?
callback null, {
timeout: owner.features?.compileTimeout || Settings.defaultFeatures.compileTimeout
compileGroup: owner.features?.compileGroup || Settings.defaultFeatures.compileGroup
}
COMPILE_DELAY: 1 # seconds
_checkIfRecentlyCompiled: (project_id, user_id, callback = (error, recentlyCompiled) ->) ->
key = "PI:KEY:<KEY>END_PI
rclient.set key, true, "EX", @COMPILE_DELAY, "NX", (error, ok) ->
return callback(error) if error?
if ok == "OK"
return callback null, false
else
return callback null, true
_checkCompileGroupAutoCompileLimit: (isAutoCompile, compileGroup, callback = (err, canCompile)->)->
if !isAutoCompile
return callback(null, true)
if compileGroup is "standard"
# apply extra limits to the standard compile group
CompileManager._checkIfAutoCompileLimitHasBeenHit isAutoCompile, compileGroup, callback
else
Metrics.inc "auto-compile-#{compileGroup}"
return callback(null, true) # always allow priority group users to compile
_checkIfAutoCompileLimitHasBeenHit: (isAutoCompile, compileGroup, callback = (err, canCompile)->)->
if !isAutoCompile
return callback(null, true)
Metrics.inc "auto-compile-#{compileGroup}"
opts =
endpointName:"auto_compile"
timeInterval:20
subjectName:compileGroup
throttle: Settings?.rateLimit?.autoCompile?[compileGroup] || 25
rateLimiter.addCount opts, (err, canCompile)->
if err?
canCompile = false
if !canCompile
Metrics.inc "auto-compile-#{compileGroup}-limited"
callback err, canCompile
_ensureRootDocumentIsSet: (project_id, callback = (error) ->) ->
Project.findById project_id, 'rootDoc_id', (error, project)=>
return callback(error) if error?
if !project?
return callback new Error("project not found")
if project.rootDoc_id?
callback()
else
ProjectRootDocManager.setRootDocAutomatically project_id, callback
wordCount: (project_id, user_id, file, callback = (error) ->) ->
CompileManager.getProjectCompileLimits project_id, (error, limits) ->
return callback(error) if error?
ClsiManager.wordCount project_id, user_id, file, limits, callback
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GN",
"end": 17,
"score": 0.6060669422149658,
"start": 16,
"tag": "USERNAME",
"value": "p"
},
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero G",
"end": 27,
... | resources/assets/coffee/_classes/timeout.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @Timeout
@clear: (id) ->
clearTimeout id
@set: (delay, func) ->
setTimeout func, delay
| 184346 | # Copyright (c) ppy <NAME> <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @Timeout
@clear: (id) ->
clearTimeout id
@set: (delay, func) ->
setTimeout func, delay
| true | # Copyright (c) ppy PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @Timeout
@clear: (id) ->
clearTimeout id
@set: (delay, func) ->
setTimeout func, delay
|
[
{
"context": "########\n# Title: Collection Base Class\n# Author: kevin@wintr.us @ WINTR\n#########################################",
"end": 115,
"score": 0.9999097585678101,
"start": 101,
"tag": "EMAIL",
"value": "kevin@wintr.us"
}
] | source/javascripts/models/supers/Collection.coffee | WikiEducationFoundation/WikiEduWizard | 1 |
#########################################################
# Title: Collection Base Class
# Author: kevin@wintr.us @ WINTR
#########################################################
module.exports = class Collection extends Backbone.Collection
| 104776 |
#########################################################
# Title: Collection Base Class
# Author: <EMAIL> @ WINTR
#########################################################
module.exports = class Collection extends Backbone.Collection
| true |
#########################################################
# Title: Collection Base Class
# Author: PI:EMAIL:<EMAIL>END_PI @ WINTR
#########################################################
module.exports = class Collection extends Backbone.Collection
|
[
{
"context": "og text\n algorithm = 'aes-256-ctr'\n password = 'd6F3Efeqd6F3Efeqd6F3Efeqd6F3Efeq'\n iv = '1234567890123456'\n decipher = crypto.cr",
"end": 240,
"score": 0.999420166015625,
"start": 208,
"tag": "PASSWORD",
"value": "d6F3Efeqd6F3Efeqd6F3Efeqd6F3Efeq"
}
] | server/methods/decryptParams.coffee | usmanasif/Rocket.chat | 0 | Meteor.methods
decryptParams: (text) ->
crypto = Npm.require('crypto')
find = ' '
re = new RegExp(find, 'g')
text = text.replace(re, '+')
console.log text
algorithm = 'aes-256-ctr'
password = 'd6F3Efeqd6F3Efeqd6F3Efeqd6F3Efeq'
iv = '1234567890123456'
decipher = crypto.createDecipheriv(algorithm, password , iv)
dec = decipher.update(text, 'base64', 'utf8')
dec += decipher.final('utf8')
console.log dec
dec
| 96019 | Meteor.methods
decryptParams: (text) ->
crypto = Npm.require('crypto')
find = ' '
re = new RegExp(find, 'g')
text = text.replace(re, '+')
console.log text
algorithm = 'aes-256-ctr'
password = '<PASSWORD>'
iv = '1234567890123456'
decipher = crypto.createDecipheriv(algorithm, password , iv)
dec = decipher.update(text, 'base64', 'utf8')
dec += decipher.final('utf8')
console.log dec
dec
| true | Meteor.methods
decryptParams: (text) ->
crypto = Npm.require('crypto')
find = ' '
re = new RegExp(find, 'g')
text = text.replace(re, '+')
console.log text
algorithm = 'aes-256-ctr'
password = 'PI:PASSWORD:<PASSWORD>END_PI'
iv = '1234567890123456'
decipher = crypto.createDecipheriv(algorithm, password , iv)
dec = decipher.update(text, 'base64', 'utf8')
dec += decipher.final('utf8')
console.log dec
dec
|
[
{
"context": "s = ld.defaults {}, options, {\n host: '127.0.0.1'\n port: 6379\n keyPrefix: 'l",
"end": 184,
"score": 0.9996340870857239,
"start": 175,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "1'\n port: 6379\n k... | src/cache/redisCache.coffee | jwalton/lol-js | 30 | ld = require 'lodash'
redis = require 'redis'
module.exports = class RedisCache
constructor: (options) ->
options = ld.defaults {}, options, {
host: '127.0.0.1'
port: 6379
keyPrefix: 'loljs-'
}
@keyPrefix = options.keyPrefix
@client = redis.createClient(options.port, options.host)
get: (params, done) ->
@client.get "#{@keyPrefix}-#{params.key}", (err, answer) ->
return done err if err?
answer = JSON.parse answer
done null, answer
set: (params, value) ->
key = "#{@keyPrefix}-#{params.key}"
@client.set key, JSON.stringify(value)
if params.ttl? then @client.expire key, params.ttl
destroy: ->
@client.quit()
| 193449 | ld = require 'lodash'
redis = require 'redis'
module.exports = class RedisCache
constructor: (options) ->
options = ld.defaults {}, options, {
host: '127.0.0.1'
port: 6379
keyPrefix: '<KEY>
}
@keyPrefix = options.keyPrefix
@client = redis.createClient(options.port, options.host)
get: (params, done) ->
@client.get "#{@keyPrefix}-#{params.key}", (err, answer) ->
return done err if err?
answer = JSON.parse answer
done null, answer
set: (params, value) ->
key = "#{@key<KEY>params.key}"
@client.set key, JSON.stringify(value)
if params.ttl? then @client.expire key, params.ttl
destroy: ->
@client.quit()
| true | ld = require 'lodash'
redis = require 'redis'
module.exports = class RedisCache
constructor: (options) ->
options = ld.defaults {}, options, {
host: '127.0.0.1'
port: 6379
keyPrefix: 'PI:KEY:<KEY>END_PI
}
@keyPrefix = options.keyPrefix
@client = redis.createClient(options.port, options.host)
get: (params, done) ->
@client.get "#{@keyPrefix}-#{params.key}", (err, answer) ->
return done err if err?
answer = JSON.parse answer
done null, answer
set: (params, value) ->
key = "#{@keyPI:KEY:<KEY>END_PIparams.key}"
@client.set key, JSON.stringify(value)
if params.ttl? then @client.expire key, params.ttl
destroy: ->
@client.quit()
|
[
{
"context": "m1: [Factory('Celebi')]\n team2: [Factory('Gyarados')]\n shared.biasRNG.call(this, 'randInt',",
"end": 1357,
"score": 0.6340147256851196,
"start": 1354,
"tag": "NAME",
"value": "yar"
},
{
"context": " @p2.currentHP = 1\n @controller.makeMove(@id1, 'P... | test/bw/battle_engine.coffee | sarenji/pokebattle-sim | 5 | require '../helpers'
{Battle} = require('../../server/bw/battle')
{Pokemon} = require('../../server/bw/pokemon')
{Status, Attachment} = require('../../server/bw/attachment')
{Conditions} = require '../../shared/conditions'
{Factory} = require '../factory'
should = require 'should'
shared = require '../shared'
{Protocol} = require '../../shared/protocol'
describe 'Mechanics', ->
describe 'an attack missing', ->
it 'deals no damage', ->
shared.create.call this,
team1: [Factory('Celebi')]
team2: [Factory('Magikarp')]
shared.biasRNG.call(this, 'randInt', 'miss', 100)
move = @battle.getMove('Leaf Storm')
originalHP = @p2.currentHP
@battle.performMove(@p1, @battle.getMove('Leaf Storm'))
@p2.currentHP.should.equal(originalHP)
it 'triggers effects dependent on the move missing', ->
shared.create.call this,
team1: [Factory('Hitmonlee')]
team2: [Factory('Magikarp')]
shared.biasRNG.call(this, 'randInt', 'miss', 100)
hiJumpKick = @battle.getMove('Hi Jump Kick')
mock = @sandbox.mock(hiJumpKick).expects('afterMiss').once()
@battle.performMove(@p1, hiJumpKick)
mock.verify()
it 'does not trigger effects dependent on the move hitting', ->
shared.create.call this,
team1: [Factory('Celebi')]
team2: [Factory('Gyarados')]
shared.biasRNG.call(this, 'randInt', 'miss', 100)
hiJumpKick = @battle.getMove('Hi Jump Kick')
mock = @sandbox.mock(hiJumpKick).expects('afterSuccessfulHit').never()
@battle.performMove(@p1, hiJumpKick)
mock.verify()
describe 'fainting', ->
it 'forces a new pokemon to be picked', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
spy = @sandbox.spy(@battle, 'tellPlayer')
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
spy.calledWith(@id2, Protocol.REQUEST_ACTIONS).should.be.true
it 'does not increment the turn count', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
turn = @battle.turn
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
@battle.turn.should.not.equal turn + 1
it 'removes the fainted pokemon from the action priority queue', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
@p1.currentHP = 1
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
@p1.currentHP.should.be.below 1
@p2.currentHP.should.equal 1
action = @battle.getAction(@p1)
should.not.exist(action)
it 'lets the player switch in a new pokemon', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
@controller.makeSwitch(@id2, 1)
@team2.first().species.should.equal 'Heracross'
it "occurs when a pokemon faints from passive damage", ->
shared.create.call(this)
@p2.currentHP = 1
@battle.performMove(@p1, @battle.getMove("Leech Seed"))
spy = @sandbox.spy(@p2, 'faint')
@battle.endTurn()
spy.calledOnce.should.be.true
it "occurs when a pokemon faints normally", ->
shared.create.call(this)
@p2.currentHP = 1
spy = @sandbox.spy(@p2, 'faint')
@battle.performMove(@p1, @battle.getMove("Tackle"))
spy.calledOnce.should.be.true
describe 'secondary effect attacks', ->
it 'can inflict effect on successful hit', ->
shared.create.call this,
team1: [Factory('Porygon-Z')]
team2: [Factory('Porygon-Z')]
shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance
@battle.performMove(@p1, @battle.getMove('Flamethrower'))
@p2.has(Status.Burn).should.be.true
describe 'the fang attacks', ->
it 'can inflict two effects at the same time', ->
shared.create.call this,
team1: [Factory('Gyarados')]
team2: [Factory('Gyarados')]
shared.biasRNG.call(this, "randInt", "secondary effect", 0) # 100% chance
shared.biasRNG.call(this, "randInt", "flinch", 0)
@battle.performMove(@p1, @battle.getMove("Ice Fang"))
@p2.has(Attachment.Flinch).should.be.true
@p2.has(Status.Freeze).should.be.true
describe 'a pokemon with technician', ->
it "doesn't increase damage if the move has bp > 60", ->
shared.create.call this,
team1: [Factory('Hitmontop')]
team2: [Factory('Mew')]
icePunch = @battle.getMove('Ice Punch')
icePunch.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "increases damage if the move has bp <= 60", ->
shared.create.call this,
team1: [Factory('Hitmontop')]
team2: [Factory('Shaymin')]
bulletPunch = @battle.getMove('Bullet Punch')
bulletPunch.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
describe 'STAB', ->
it "gets applied if the move and user share a type", ->
shared.create.call this,
team1: [Factory('Heracross')]
team2: [Factory('Regirock')]
megahorn = @battle.getMove("Megahorn")
megahorn.stabModifier(@battle, @p1, @p2).should.equal(0x1800)
it "doesn't get applied if the move and user are of different types", ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Mew')]
icePunch = @battle.getMove("Ice Punch")
icePunch.stabModifier(@battle, @p1, @p2).should.equal(0x1000)
describe 'turn order', ->
it 'randomly decides winner if pokemon have the same speed and priority', ->
shared.create.call this,
team1: [Factory('Mew')]
team2: [Factory('Mew')]
spy = @sandbox.spy(@battle, 'determineTurnOrder')
shared.biasRNG.call(this, "next", "turn order", .6)
@battle.recordMove(@id1, @battle.getMove('Psychic'))
@battle.recordMove(@id2, @battle.getMove('Psychic'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ]
@battle.pokemonActions = []
shared.biasRNG.call(this, "next", "turn order", .4)
@battle.recordMove(@id1, @battle.getMove('Psychic'))
@battle.recordMove(@id2, @battle.getMove('Psychic'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p1, @p2 ]
it 'decides winner by highest priority move', ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Hitmonchan')]
spy = @sandbox.spy(@battle, 'determineTurnOrder')
@battle.recordMove(@id1, @battle.getMove('Mach Punch'))
@battle.recordMove(@id2, @battle.getMove('Psychic'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p1, @p2 ]
@battle.pokemonActions = []
@battle.recordMove(@id1, @battle.getMove('Psychic'))
@battle.recordMove(@id2, @battle.getMove('Mach Punch'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ]
it 'decides winner by speed if priority is equal', ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Hitmonchan', evs: { speed: 4 })]
@battle.recordMove(@id1, @battle.getMove('ThunderPunch'))
@battle.recordMove(@id2, @battle.getMove('ThunderPunch'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ]
describe 'fainting all the opposing pokemon', ->
it "doesn't request any more actions from players", ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Mew')]
@p2.currentHP = 1
@controller.makeMove(@id1, 'Mach Punch')
@controller.makeMove(@id2, 'Psychic')
@battle.requests.should.not.have.property @id1.id
@battle.requests.should.not.have.property @id2.id
it 'ends the battle', ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Mew')]
@p2.currentHP = 1
mock = @sandbox.mock(@battle)
mock.expects('endBattle').once()
@controller.makeMove(@id1, 'Mach Punch')
@controller.makeMove(@id2, 'Psychic')
mock.verify()
describe 'a pokemon with a type immunity', ->
it 'cannot be damaged by a move of that type', ->
shared.create.call this,
team1: [Factory('Camerupt')]
team2: [Factory('Gyarados')]
@controller.makeMove(@id1, 'Earthquake')
@controller.makeMove(@id2, 'Dragon Dance')
@p2.currentHP.should.equal @p2.stat('hp')
describe 'a confused pokemon', ->
it "has a 50% chance of hurting itself", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'confusion turns', 1) # always 1 turn
@p1.attach(Attachment.Confusion, {@battle})
shared.biasRNG.call(this, "next", 'confusion', 0) # always hits
mock = @sandbox.mock(@battle.getMove('Tackle'))
mock.expects('execute').never()
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Splash')
mock.verify()
@p1.currentHP.should.be.lessThan @p1.stat('hp')
@p2.currentHP.should.equal @p2.stat('hp')
it "deals a minimum of 1 damage", ->
shared.create.call(this, team1: [Factory("Shuckle", level: 1)])
shared.biasRNG.call(this, "randInt", 'confusion turns', 1) # always 1 turn
@p1.attach(Attachment.Confusion, {@battle})
shared.biasRNG.call(this, "next", 'confusion', 0) # always hits
@sandbox.stub(@battle.confusionMove, 'calculateDamage', -> 0)
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.currentHP.should.equal(@p1.stat('hp') - 1)
it "snaps out of confusion after a predetermined number of turns", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'confusion turns', 1) # always 1 turn
@p1.attach(Attachment.Confusion)
@controller.makeMove(@id1, 'Splash')
@controller.makeMove(@id2, 'Splash')
@controller.makeMove(@id1, 'Splash')
@controller.makeMove(@id2, 'Splash')
@p1.has(Attachment.Confusion).should.be.false
it "will not crit the confusion recoil", ->
shared.create.call(this)
@p1.attach(Attachment.Confusion)
shared.biasRNG.call(this, "next", 'confusion', 0) # always recoils
shared.biasRNG.call(this, 'next', 'ch', 0) # always crits
spy = @sandbox.spy(@battle.confusionMove, 'isCriticalHit')
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Tackle')
spy.returned(false).should.be.true
it "will not error for not having unusual move properties", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Iron Fist")])
@p1.attach(Attachment.Confusion)
shared.biasRNG.call(this, "next", 'confusion', 0) # always recoils
(=>
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Tackle')
).should.not.throw()
describe 'a frozen pokemon', ->
it "will not execute moves", ->
shared.create.call(this)
@p1.attach(Status.Freeze)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
mock = @sandbox.mock(@battle.getMove('Tackle'))
mock.expects('execute').never()
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Splash')
mock.verify()
it "has a 20% chance of unfreezing", ->
shared.create.call(this)
@p1.attach(Status.Freeze)
shared.biasRNG.call(this, "next", 'unfreeze chance', 0) # always unfreezes
@controller.makeMove(@id1, 'Splash')
@controller.makeMove(@id2, 'Splash')
@p1.has(Status.Freeze).should.be.false
it "unfreezes if hit by a fire move", ->
shared.create.call(this)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
@p1.attach(Status.Freeze)
@battle.performMove(@p2, @battle.getMove('Flamethrower'))
@p1.has(Status.Freeze).should.be.false
it "does not unfreeze if hit by a non-damaging move", ->
shared.create.call(this)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
@p1.attach(Status.Freeze)
@battle.performMove(@p2, @battle.getMove('Will-O-Wisp'))
@p1.has(Status.Freeze).should.be.true
for moveName in ["Sacred Fire", "Flare Blitz", "Flame Wheel", "Fusion Flare", "Scald"]
it "automatically unfreezes if using #{moveName}", ->
shared.create.call(this)
@p1.attach(Status.Freeze)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
@battle.performMove(@p1, @battle.getMove(moveName))
@p1.has(Status.Freeze).should.be.false
describe "a paralyzed pokemon", ->
it "has a 25% chance of being fully paralyzed", ->
shared.create.call(this)
@p1.attach(Status.Paralyze)
shared.biasRNG.call(this, "next", 'paralyze chance', 0) # always stays frozen
mock = @sandbox.mock(@battle.getMove('Tackle'))
mock.expects('execute').never()
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Splash')
mock.verify()
it "has its speed quartered", ->
shared.create.call(this)
speed = @p1.stat('speed')
@p1.attach(Status.Paralyze)
@p1.stat('speed').should.equal Math.floor(speed / 4)
describe "a burned pokemon", ->
it "loses 1/8 of its HP each turn", ->
shared.create.call(this)
@p1.attach(Status.Burn)
hp = @p1.currentHP
eighth = Math.floor(hp / 8)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(eighth)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(2 * eighth)
it "loses 1 minimum HP", ->
shared.create.call(this, team1: [Factory("Shedinja")])
@p1.attach(Status.Burn)
@p1.currentHP.should.equal(1)
@battle.endTurn()
@p1.currentHP.should.equal(0)
describe "a sleeping pokemon", ->
it "sleeps for 1-3 turns", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'sleep turns', 3)
@p1.attach(Status.Sleep)
tackle = @battle.getMove('Tackle')
for i in [0...3]
@battle.performMove(@p1, tackle)
@p1.has(Status.Sleep).should.be.true
@battle.performMove(@p1, tackle)
@p1.has(Status.Sleep).should.be.false
it "cannot move while asleep", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'sleep turns', 3)
@p1.attach(Status.Sleep)
tackle = @battle.getMove('Tackle')
mock = @sandbox.mock(tackle).expects('execute').never()
for i in [0...3]
@battle.performMove(@p1, tackle)
mock.verify()
tackle.execute.restore()
mock = @sandbox.mock(tackle).expects('execute').once()
@battle.performMove(@p1, tackle)
mock.verify()
it "resets its counter when switching out", ->
shared.create.call this,
team1: [ Factory("Magikarp"), Factory("Magikarp") ]
shared.biasRNG.call(this, "randInt", 'sleep turns', 1)
@p1.attach(Status.Sleep)
tackle = @battle.getMove('Tackle')
@battle.performMove(@p1, tackle)
@battle.performSwitch(@team1.first(), 1)
@battle.performSwitch(@team1.first(), 1)
@battle.performMove(@team1.first(), tackle)
@p1.has(Status.Sleep).should.be.true
describe "a poisoned pokemon", ->
it "loses 1/8 of its HP each turn", ->
shared.create.call(this)
@p1.attach(Status.Poison)
hp = @p1.currentHP
eighth = Math.floor(hp / 8)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(eighth)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(2 * eighth)
it "loses 1 minimum HP", ->
shared.create.call(this, team1: [Factory("Shedinja")])
@p1.attach(Status.Poison)
@p1.currentHP.should.equal(1)
@battle.endTurn()
@p1.currentHP.should.equal(0)
describe "a badly poisoned pokemon", ->
it "loses 1/16 of its HP the first turn", ->
shared.create.call(this)
@p1.attach(Status.Toxic)
hp = @p1.currentHP
@battle.endTurn()
(hp - @p1.currentHP).should.equal(hp >> 4)
it "loses 1/16 of its max HP, rounded down, times x where x is the number of turns up to 15", ->
shared.create.call(this)
@p1.attach(Status.Toxic)
hp = @p1.currentHP
fraction = (hp >> 4)
for i in [1..16]
@battle.endTurn()
hpFraction = Math.min(fraction * i, fraction * 15)
(hp - @p1.currentHP).should.equal(hpFraction)
@p1.currentHP = hp
it "still increases the counter with poison heal", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Poison Heal")])
@p1.attach(Status.Toxic)
hp = @p1.currentHP
fraction = (hp >> 4)
turns = 3
for i in [1...turns]
@battle.endTurn()
@p1.copyAbility(null)
@battle.endTurn()
hpFraction = Math.min(fraction * turns, fraction * 15)
(hp - @p1.currentHP).should.equal(hpFraction)
it "loses 1 minimum HP", ->
shared.create.call(this, team1: [Factory("Shedinja")])
@p1.attach(Status.Toxic)
@p1.currentHP.should.equal(1)
@battle.endTurn()
@p1.currentHP.should.equal(0)
it "resets its counter when switching out", ->
shared.create.call this,
team1: [ Factory("Magikarp"), Factory("Magikarp") ]
@p1.attach(Status.Toxic)
hp = @p1.currentHP
@battle.endTurn()
@battle.performSwitch(@team1.first(), 1)
@p1.currentHP = hp
@battle.performSwitch(@team1.first(), 1)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(hp >> 4)
describe "Pokemon#turnsActive", ->
it "is 1 on start of battle", ->
shared.create.call(this)
@p1.turnsActive.should.equal 1
it "is set to 0 when switching", ->
shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2]))
@p1.turnsActive = 4
@team1.switch(@p1, 0)
@team1.first().turnsActive.should.equal 0
it "increases by 1 when a turn ends", ->
shared.create.call(this)
@p1.turnsActive.should.equal 1
@battle.endTurn()
@p1.turnsActive.should.equal 2
describe "A move with 0 PP", ->
it "will not execute", ->
shared.create.call(this)
move = @p1.moves[0]
@p1.setPP(move, 0)
@sandbox.mock(move).expects('execute').never()
@sandbox.mock(@p1).expects('beforeMove').never()
@battle.performMove(@p1, move)
describe "A pokemon with no available moves", ->
it "can struggle", ->
shared.create.call(this)
@battle.removeRequest(@id1)
# Next turn, @p1 will have no available moves.
for move in @p1.moves
@p1.blockMove(move)
@p1.resetBlocks = ->
@p1.validMoves().should.be.empty
@battle.beginTurn()
request = @battle.requestFor(@p1)
should.exist(request)
request.should.have.property('moves')
request.moves.should.eql(["Struggle"])
describe "Ability activation at the beginning of a battle", ->
it "considers Abilities that are always active", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Clear Body")]
team2: [Factory("Magikarp", ability: "Intimidate")]
@p1.stages.should.containEql(attack: 0)
xit "works the same way regardless of the entry order", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Intimidate")]
team2: [Factory("Magikarp", ability: "Clear Body")]
@p2.stages.should.containEql(attack: 0)
| 20564 | require '../helpers'
{Battle} = require('../../server/bw/battle')
{Pokemon} = require('../../server/bw/pokemon')
{Status, Attachment} = require('../../server/bw/attachment')
{Conditions} = require '../../shared/conditions'
{Factory} = require '../factory'
should = require 'should'
shared = require '../shared'
{Protocol} = require '../../shared/protocol'
describe 'Mechanics', ->
describe 'an attack missing', ->
it 'deals no damage', ->
shared.create.call this,
team1: [Factory('Celebi')]
team2: [Factory('Magikarp')]
shared.biasRNG.call(this, 'randInt', 'miss', 100)
move = @battle.getMove('Leaf Storm')
originalHP = @p2.currentHP
@battle.performMove(@p1, @battle.getMove('Leaf Storm'))
@p2.currentHP.should.equal(originalHP)
it 'triggers effects dependent on the move missing', ->
shared.create.call this,
team1: [Factory('Hitmonlee')]
team2: [Factory('Magikarp')]
shared.biasRNG.call(this, 'randInt', 'miss', 100)
hiJumpKick = @battle.getMove('Hi Jump Kick')
mock = @sandbox.mock(hiJumpKick).expects('afterMiss').once()
@battle.performMove(@p1, hiJumpKick)
mock.verify()
it 'does not trigger effects dependent on the move hitting', ->
shared.create.call this,
team1: [Factory('Celebi')]
team2: [Factory('G<NAME>ados')]
shared.biasRNG.call(this, 'randInt', 'miss', 100)
hiJumpKick = @battle.getMove('Hi Jump Kick')
mock = @sandbox.mock(hiJumpKick).expects('afterSuccessfulHit').never()
@battle.performMove(@p1, hiJumpKick)
mock.verify()
describe 'fainting', ->
it 'forces a new pokemon to be picked', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
spy = @sandbox.spy(@battle, 'tellPlayer')
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
spy.calledWith(@id2, Protocol.REQUEST_ACTIONS).should.be.true
it 'does not increment the turn count', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
turn = @battle.turn
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
@battle.turn.should.not.equal turn + 1
it 'removes the fainted pokemon from the action priority queue', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
@p1.currentHP = 1
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
@p1.currentHP.should.be.below 1
@p2.currentHP.should.equal 1
action = @battle.getAction(@p1)
should.not.exist(action)
it 'lets the player switch in a new pokemon', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
@controller.makeSwitch(@id2, 1)
@team2.first().species.should.equal 'Heracross'
it "occurs when a pokemon faints from passive damage", ->
shared.create.call(this)
@p2.currentHP = 1
@battle.performMove(@p1, @battle.getMove("Leech Seed"))
spy = @sandbox.spy(@p2, 'faint')
@battle.endTurn()
spy.calledOnce.should.be.true
it "occurs when a pokemon faints normally", ->
shared.create.call(this)
@p2.currentHP = 1
spy = @sandbox.spy(@p2, 'faint')
@battle.performMove(@p1, @battle.getMove("Tackle"))
spy.calledOnce.should.be.true
describe 'secondary effect attacks', ->
it 'can inflict effect on successful hit', ->
shared.create.call this,
team1: [Factory('Porygon-Z')]
team2: [Factory('Porygon-Z')]
shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance
@battle.performMove(@p1, @battle.getMove('Flamethrower'))
@p2.has(Status.Burn).should.be.true
describe 'the fang attacks', ->
it 'can inflict two effects at the same time', ->
shared.create.call this,
team1: [Factory('Gyarados')]
team2: [Factory('Gyarados')]
shared.biasRNG.call(this, "randInt", "secondary effect", 0) # 100% chance
shared.biasRNG.call(this, "randInt", "flinch", 0)
@battle.performMove(@p1, @battle.getMove("Ice Fang"))
@p2.has(Attachment.Flinch).should.be.true
@p2.has(Status.Freeze).should.be.true
describe 'a pokemon with technician', ->
it "doesn't increase damage if the move has bp > 60", ->
shared.create.call this,
team1: [Factory('Hitmontop')]
team2: [Factory('Mew')]
icePunch = @battle.getMove('Ice Punch')
icePunch.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "increases damage if the move has bp <= 60", ->
shared.create.call this,
team1: [Factory('Hitmontop')]
team2: [Factory('<NAME>')]
bulletPunch = @battle.getMove('Bullet Punch')
bulletPunch.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
describe 'STAB', ->
it "gets applied if the move and user share a type", ->
shared.create.call this,
team1: [Factory('Heracross')]
team2: [Factory('<NAME>')]
megahorn = @battle.getMove("Megahorn")
megahorn.stabModifier(@battle, @p1, @p2).should.equal(0x1800)
it "doesn't get applied if the move and user are of different types", ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Mew')]
icePunch = @battle.getMove("Ice Punch")
icePunch.stabModifier(@battle, @p1, @p2).should.equal(0x1000)
describe 'turn order', ->
it 'randomly decides winner if pokemon have the same speed and priority', ->
shared.create.call this,
team1: [Factory('Mew')]
team2: [Factory('Mew')]
spy = @sandbox.spy(@battle, 'determineTurnOrder')
shared.biasRNG.call(this, "next", "turn order", .6)
@battle.recordMove(@id1, @battle.getMove('Psychic'))
@battle.recordMove(@id2, @battle.getMove('Psychic'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ]
@battle.pokemonActions = []
shared.biasRNG.call(this, "next", "turn order", .4)
@battle.recordMove(@id1, @battle.getMove('Psychic'))
@battle.recordMove(@id2, @battle.getMove('Psychic'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p1, @p2 ]
it 'decides winner by highest priority move', ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Hitmonchan')]
spy = @sandbox.spy(@battle, 'determineTurnOrder')
@battle.recordMove(@id1, @battle.getMove('Mach Punch'))
@battle.recordMove(@id2, @battle.getMove('Psychic'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p1, @p2 ]
@battle.pokemonActions = []
@battle.recordMove(@id1, @battle.getMove('Psychic'))
@battle.recordMove(@id2, @battle.getMove('Mach Punch'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ]
it 'decides winner by speed if priority is equal', ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Hitmonchan', evs: { speed: 4 })]
@battle.recordMove(@id1, @battle.getMove('ThunderPunch'))
@battle.recordMove(@id2, @battle.getMove('ThunderPunch'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ]
describe 'fainting all the opposing pokemon', ->
it "doesn't request any more actions from players", ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Mew')]
@p2.currentHP = 1
@controller.makeMove(@id1, 'Mach Punch')
@controller.makeMove(@id2, 'Psychic')
@battle.requests.should.not.have.property @id1.id
@battle.requests.should.not.have.property @id2.id
it 'ends the battle', ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Mew')]
@p2.currentHP = 1
mock = @sandbox.mock(@battle)
mock.expects('endBattle').once()
@controller.makeMove(@id1, 'Mach Punch')
@controller.makeMove(@id2, 'Psychic')
mock.verify()
describe 'a pokemon with a type immunity', ->
it 'cannot be damaged by a move of that type', ->
shared.create.call this,
team1: [Factory('Camerupt')]
team2: [Factory('Gyarados')]
@controller.makeMove(@id1, 'Earthquake')
@controller.makeMove(@id2, 'Dragon Dance')
@p2.currentHP.should.equal @p2.stat('hp')
describe 'a confused pokemon', ->
it "has a 50% chance of hurting itself", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'confusion turns', 1) # always 1 turn
@p1.attach(Attachment.Confusion, {@battle})
shared.biasRNG.call(this, "next", 'confusion', 0) # always hits
mock = @sandbox.mock(@battle.getMove('Tackle'))
mock.expects('execute').never()
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Splash')
mock.verify()
@p1.currentHP.should.be.lessThan @p1.stat('hp')
@p2.currentHP.should.equal @p2.stat('hp')
it "deals a minimum of 1 damage", ->
shared.create.call(this, team1: [Factory("Shuckle", level: 1)])
shared.biasRNG.call(this, "randInt", 'confusion turns', 1) # always 1 turn
@p1.attach(Attachment.Confusion, {@battle})
shared.biasRNG.call(this, "next", 'confusion', 0) # always hits
@sandbox.stub(@battle.confusionMove, 'calculateDamage', -> 0)
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.currentHP.should.equal(@p1.stat('hp') - 1)
it "snaps out of confusion after a predetermined number of turns", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'confusion turns', 1) # always 1 turn
@p1.attach(Attachment.Confusion)
@controller.makeMove(@id1, 'Splash')
@controller.makeMove(@id2, 'Splash')
@controller.makeMove(@id1, 'Splash')
@controller.makeMove(@id2, 'Splash')
@p1.has(Attachment.Confusion).should.be.false
it "will not crit the confusion recoil", ->
shared.create.call(this)
@p1.attach(Attachment.Confusion)
shared.biasRNG.call(this, "next", 'confusion', 0) # always recoils
shared.biasRNG.call(this, 'next', 'ch', 0) # always crits
spy = @sandbox.spy(@battle.confusionMove, 'isCriticalHit')
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Tackle')
spy.returned(false).should.be.true
it "will not error for not having unusual move properties", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Iron Fist")])
@p1.attach(Attachment.Confusion)
shared.biasRNG.call(this, "next", 'confusion', 0) # always recoils
(=>
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Tackle')
).should.not.throw()
describe 'a frozen pokemon', ->
it "will not execute moves", ->
shared.create.call(this)
@p1.attach(Status.Freeze)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
mock = @sandbox.mock(@battle.getMove('Tackle'))
mock.expects('execute').never()
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Splash')
mock.verify()
it "has a 20% chance of unfreezing", ->
shared.create.call(this)
@p1.attach(Status.Freeze)
shared.biasRNG.call(this, "next", 'unfreeze chance', 0) # always unfreezes
@controller.makeMove(@id1, 'Splash')
@controller.makeMove(@id2, 'Splash')
@p1.has(Status.Freeze).should.be.false
it "unfreezes if hit by a fire move", ->
shared.create.call(this)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
@p1.attach(Status.Freeze)
@battle.performMove(@p2, @battle.getMove('Flamethrower'))
@p1.has(Status.Freeze).should.be.false
it "does not unfreeze if hit by a non-damaging move", ->
shared.create.call(this)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
@p1.attach(Status.Freeze)
@battle.performMove(@p2, @battle.getMove('Will-O-Wisp'))
@p1.has(Status.Freeze).should.be.true
for moveName in ["Sacred Fire", "Flare Blitz", "Flame Wheel", "Fusion Flare", "Scald"]
it "automatically unfreezes if using #{moveName}", ->
shared.create.call(this)
@p1.attach(Status.Freeze)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
@battle.performMove(@p1, @battle.getMove(moveName))
@p1.has(Status.Freeze).should.be.false
describe "a paralyzed pokemon", ->
it "has a 25% chance of being fully paralyzed", ->
shared.create.call(this)
@p1.attach(Status.Paralyze)
shared.biasRNG.call(this, "next", 'paralyze chance', 0) # always stays frozen
mock = @sandbox.mock(@battle.getMove('Tackle'))
mock.expects('execute').never()
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Splash')
mock.verify()
it "has its speed quartered", ->
shared.create.call(this)
speed = @p1.stat('speed')
@p1.attach(Status.Paralyze)
@p1.stat('speed').should.equal Math.floor(speed / 4)
describe "a burned pokemon", ->
it "loses 1/8 of its HP each turn", ->
shared.create.call(this)
@p1.attach(Status.Burn)
hp = @p1.currentHP
eighth = Math.floor(hp / 8)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(eighth)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(2 * eighth)
it "loses 1 minimum HP", ->
shared.create.call(this, team1: [Factory("Shedinja")])
@p1.attach(Status.Burn)
@p1.currentHP.should.equal(1)
@battle.endTurn()
@p1.currentHP.should.equal(0)
describe "a sleeping pokemon", ->
it "sleeps for 1-3 turns", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'sleep turns', 3)
@p1.attach(Status.Sleep)
tackle = @battle.getMove('Tackle')
for i in [0...3]
@battle.performMove(@p1, tackle)
@p1.has(Status.Sleep).should.be.true
@battle.performMove(@p1, tackle)
@p1.has(Status.Sleep).should.be.false
it "cannot move while asleep", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'sleep turns', 3)
@p1.attach(Status.Sleep)
tackle = @battle.getMove('Tackle')
mock = @sandbox.mock(tackle).expects('execute').never()
for i in [0...3]
@battle.performMove(@p1, tackle)
mock.verify()
tackle.execute.restore()
mock = @sandbox.mock(tackle).expects('execute').once()
@battle.performMove(@p1, tackle)
mock.verify()
it "resets its counter when switching out", ->
shared.create.call this,
team1: [ Factory("Magikarp"), Factory("Magikarp") ]
shared.biasRNG.call(this, "randInt", 'sleep turns', 1)
@p1.attach(Status.Sleep)
tackle = @battle.getMove('Tackle')
@battle.performMove(@p1, tackle)
@battle.performSwitch(@team1.first(), 1)
@battle.performSwitch(@team1.first(), 1)
@battle.performMove(@team1.first(), tackle)
@p1.has(Status.Sleep).should.be.true
describe "a poisoned pokemon", ->
it "loses 1/8 of its HP each turn", ->
shared.create.call(this)
@p1.attach(Status.Poison)
hp = @p1.currentHP
eighth = Math.floor(hp / 8)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(eighth)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(2 * eighth)
it "loses 1 minimum HP", ->
shared.create.call(this, team1: [Factory("Shedinja")])
@p1.attach(Status.Poison)
@p1.currentHP.should.equal(1)
@battle.endTurn()
@p1.currentHP.should.equal(0)
describe "a badly poisoned pokemon", ->
it "loses 1/16 of its HP the first turn", ->
shared.create.call(this)
@p1.attach(Status.Toxic)
hp = @p1.currentHP
@battle.endTurn()
(hp - @p1.currentHP).should.equal(hp >> 4)
it "loses 1/16 of its max HP, rounded down, times x where x is the number of turns up to 15", ->
shared.create.call(this)
@p1.attach(Status.Toxic)
hp = @p1.currentHP
fraction = (hp >> 4)
for i in [1..16]
@battle.endTurn()
hpFraction = Math.min(fraction * i, fraction * 15)
(hp - @p1.currentHP).should.equal(hpFraction)
@p1.currentHP = hp
it "still increases the counter with poison heal", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Poison Heal")])
@p1.attach(Status.Toxic)
hp = @p1.currentHP
fraction = (hp >> 4)
turns = 3
for i in [1...turns]
@battle.endTurn()
@p1.copyAbility(null)
@battle.endTurn()
hpFraction = Math.min(fraction * turns, fraction * 15)
(hp - @p1.currentHP).should.equal(hpFraction)
it "loses 1 minimum HP", ->
shared.create.call(this, team1: [Factory("Shedinja")])
@p1.attach(Status.Toxic)
@p1.currentHP.should.equal(1)
@battle.endTurn()
@p1.currentHP.should.equal(0)
it "resets its counter when switching out", ->
shared.create.call this,
team1: [ Factory("Magikarp"), Factory("<NAME>") ]
@p1.attach(Status.Toxic)
hp = @p1.currentHP
@battle.endTurn()
@battle.performSwitch(@team1.first(), 1)
@p1.currentHP = hp
@battle.performSwitch(@team1.first(), 1)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(hp >> 4)
describe "Pokemon#turnsActive", ->
it "is 1 on start of battle", ->
shared.create.call(this)
@p1.turnsActive.should.equal 1
it "is set to 0 when switching", ->
shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2]))
@p1.turnsActive = 4
@team1.switch(@p1, 0)
@team1.first().turnsActive.should.equal 0
it "increases by 1 when a turn ends", ->
shared.create.call(this)
@p1.turnsActive.should.equal 1
@battle.endTurn()
@p1.turnsActive.should.equal 2
describe "A move with 0 PP", ->
it "will not execute", ->
shared.create.call(this)
move = @p1.moves[0]
@p1.setPP(move, 0)
@sandbox.mock(move).expects('execute').never()
@sandbox.mock(@p1).expects('beforeMove').never()
@battle.performMove(@p1, move)
describe "A pokemon with no available moves", ->
it "can struggle", ->
shared.create.call(this)
@battle.removeRequest(@id1)
# Next turn, @p1 will have no available moves.
for move in @p1.moves
@p1.blockMove(move)
@p1.resetBlocks = ->
@p1.validMoves().should.be.empty
@battle.beginTurn()
request = @battle.requestFor(@p1)
should.exist(request)
request.should.have.property('moves')
request.moves.should.eql(["Struggle"])
describe "Ability activation at the beginning of a battle", ->
it "considers Abilities that are always active", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Clear Body")]
team2: [Factory("Magikarp", ability: "Intimidate")]
@p1.stages.should.containEql(attack: 0)
xit "works the same way regardless of the entry order", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Intimidate")]
team2: [Factory("Magikarp", ability: "Clear Body")]
@p2.stages.should.containEql(attack: 0)
| true | require '../helpers'
{Battle} = require('../../server/bw/battle')
{Pokemon} = require('../../server/bw/pokemon')
{Status, Attachment} = require('../../server/bw/attachment')
{Conditions} = require '../../shared/conditions'
{Factory} = require '../factory'
should = require 'should'
shared = require '../shared'
{Protocol} = require '../../shared/protocol'
describe 'Mechanics', ->
describe 'an attack missing', ->
it 'deals no damage', ->
shared.create.call this,
team1: [Factory('Celebi')]
team2: [Factory('Magikarp')]
shared.biasRNG.call(this, 'randInt', 'miss', 100)
move = @battle.getMove('Leaf Storm')
originalHP = @p2.currentHP
@battle.performMove(@p1, @battle.getMove('Leaf Storm'))
@p2.currentHP.should.equal(originalHP)
it 'triggers effects dependent on the move missing', ->
shared.create.call this,
team1: [Factory('Hitmonlee')]
team2: [Factory('Magikarp')]
shared.biasRNG.call(this, 'randInt', 'miss', 100)
hiJumpKick = @battle.getMove('Hi Jump Kick')
mock = @sandbox.mock(hiJumpKick).expects('afterMiss').once()
@battle.performMove(@p1, hiJumpKick)
mock.verify()
it 'does not trigger effects dependent on the move hitting', ->
shared.create.call this,
team1: [Factory('Celebi')]
team2: [Factory('GPI:NAME:<NAME>END_PIados')]
shared.biasRNG.call(this, 'randInt', 'miss', 100)
hiJumpKick = @battle.getMove('Hi Jump Kick')
mock = @sandbox.mock(hiJumpKick).expects('afterSuccessfulHit').never()
@battle.performMove(@p1, hiJumpKick)
mock.verify()
describe 'fainting', ->
it 'forces a new pokemon to be picked', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
spy = @sandbox.spy(@battle, 'tellPlayer')
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
spy.calledWith(@id2, Protocol.REQUEST_ACTIONS).should.be.true
it 'does not increment the turn count', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
turn = @battle.turn
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
@battle.turn.should.not.equal turn + 1
it 'removes the fainted pokemon from the action priority queue', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
@p1.currentHP = 1
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
@p1.currentHP.should.be.below 1
@p2.currentHP.should.equal 1
action = @battle.getAction(@p1)
should.not.exist(action)
it 'lets the player switch in a new pokemon', ->
shared.create.call this,
team1: [Factory('Mew'), Factory('Heracross')]
team2: [Factory('Hitmonchan'), Factory('Heracross')]
@p2.currentHP = 1
@controller.makeMove(@id1, 'Psychic')
@controller.makeMove(@id2, 'Mach Punch')
@controller.makeSwitch(@id2, 1)
@team2.first().species.should.equal 'Heracross'
it "occurs when a pokemon faints from passive damage", ->
shared.create.call(this)
@p2.currentHP = 1
@battle.performMove(@p1, @battle.getMove("Leech Seed"))
spy = @sandbox.spy(@p2, 'faint')
@battle.endTurn()
spy.calledOnce.should.be.true
it "occurs when a pokemon faints normally", ->
shared.create.call(this)
@p2.currentHP = 1
spy = @sandbox.spy(@p2, 'faint')
@battle.performMove(@p1, @battle.getMove("Tackle"))
spy.calledOnce.should.be.true
describe 'secondary effect attacks', ->
it 'can inflict effect on successful hit', ->
shared.create.call this,
team1: [Factory('Porygon-Z')]
team2: [Factory('Porygon-Z')]
shared.biasRNG.call(this, "next", 'secondary effect', 0) # 100% chance
@battle.performMove(@p1, @battle.getMove('Flamethrower'))
@p2.has(Status.Burn).should.be.true
describe 'the fang attacks', ->
it 'can inflict two effects at the same time', ->
shared.create.call this,
team1: [Factory('Gyarados')]
team2: [Factory('Gyarados')]
shared.biasRNG.call(this, "randInt", "secondary effect", 0) # 100% chance
shared.biasRNG.call(this, "randInt", "flinch", 0)
@battle.performMove(@p1, @battle.getMove("Ice Fang"))
@p2.has(Attachment.Flinch).should.be.true
@p2.has(Status.Freeze).should.be.true
describe 'a pokemon with technician', ->
it "doesn't increase damage if the move has bp > 60", ->
shared.create.call this,
team1: [Factory('Hitmontop')]
team2: [Factory('Mew')]
icePunch = @battle.getMove('Ice Punch')
icePunch.modifyBasePower(@battle, @p1, @p2).should.equal(0x1000)
it "increases damage if the move has bp <= 60", ->
shared.create.call this,
team1: [Factory('Hitmontop')]
team2: [Factory('PI:NAME:<NAME>END_PI')]
bulletPunch = @battle.getMove('Bullet Punch')
bulletPunch.modifyBasePower(@battle, @p1, @p2).should.equal(0x1800)
describe 'STAB', ->
it "gets applied if the move and user share a type", ->
shared.create.call this,
team1: [Factory('Heracross')]
team2: [Factory('PI:NAME:<NAME>END_PI')]
megahorn = @battle.getMove("Megahorn")
megahorn.stabModifier(@battle, @p1, @p2).should.equal(0x1800)
it "doesn't get applied if the move and user are of different types", ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Mew')]
icePunch = @battle.getMove("Ice Punch")
icePunch.stabModifier(@battle, @p1, @p2).should.equal(0x1000)
describe 'turn order', ->
it 'randomly decides winner if pokemon have the same speed and priority', ->
shared.create.call this,
team1: [Factory('Mew')]
team2: [Factory('Mew')]
spy = @sandbox.spy(@battle, 'determineTurnOrder')
shared.biasRNG.call(this, "next", "turn order", .6)
@battle.recordMove(@id1, @battle.getMove('Psychic'))
@battle.recordMove(@id2, @battle.getMove('Psychic'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ]
@battle.pokemonActions = []
shared.biasRNG.call(this, "next", "turn order", .4)
@battle.recordMove(@id1, @battle.getMove('Psychic'))
@battle.recordMove(@id2, @battle.getMove('Psychic'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p1, @p2 ]
it 'decides winner by highest priority move', ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Hitmonchan')]
spy = @sandbox.spy(@battle, 'determineTurnOrder')
@battle.recordMove(@id1, @battle.getMove('Mach Punch'))
@battle.recordMove(@id2, @battle.getMove('Psychic'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p1, @p2 ]
@battle.pokemonActions = []
@battle.recordMove(@id1, @battle.getMove('Psychic'))
@battle.recordMove(@id2, @battle.getMove('Mach Punch'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ]
it 'decides winner by speed if priority is equal', ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Hitmonchan', evs: { speed: 4 })]
@battle.recordMove(@id1, @battle.getMove('ThunderPunch'))
@battle.recordMove(@id2, @battle.getMove('ThunderPunch'))
@battle.determineTurnOrder().map((o) -> o.pokemon).should.eql [ @p2, @p1 ]
describe 'fainting all the opposing pokemon', ->
it "doesn't request any more actions from players", ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Mew')]
@p2.currentHP = 1
@controller.makeMove(@id1, 'Mach Punch')
@controller.makeMove(@id2, 'Psychic')
@battle.requests.should.not.have.property @id1.id
@battle.requests.should.not.have.property @id2.id
it 'ends the battle', ->
shared.create.call this,
team1: [Factory('Hitmonchan')]
team2: [Factory('Mew')]
@p2.currentHP = 1
mock = @sandbox.mock(@battle)
mock.expects('endBattle').once()
@controller.makeMove(@id1, 'Mach Punch')
@controller.makeMove(@id2, 'Psychic')
mock.verify()
describe 'a pokemon with a type immunity', ->
it 'cannot be damaged by a move of that type', ->
shared.create.call this,
team1: [Factory('Camerupt')]
team2: [Factory('Gyarados')]
@controller.makeMove(@id1, 'Earthquake')
@controller.makeMove(@id2, 'Dragon Dance')
@p2.currentHP.should.equal @p2.stat('hp')
describe 'a confused pokemon', ->
it "has a 50% chance of hurting itself", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'confusion turns', 1) # always 1 turn
@p1.attach(Attachment.Confusion, {@battle})
shared.biasRNG.call(this, "next", 'confusion', 0) # always hits
mock = @sandbox.mock(@battle.getMove('Tackle'))
mock.expects('execute').never()
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Splash')
mock.verify()
@p1.currentHP.should.be.lessThan @p1.stat('hp')
@p2.currentHP.should.equal @p2.stat('hp')
it "deals a minimum of 1 damage", ->
shared.create.call(this, team1: [Factory("Shuckle", level: 1)])
shared.biasRNG.call(this, "randInt", 'confusion turns', 1) # always 1 turn
@p1.attach(Attachment.Confusion, {@battle})
shared.biasRNG.call(this, "next", 'confusion', 0) # always hits
@sandbox.stub(@battle.confusionMove, 'calculateDamage', -> 0)
@battle.performMove(@p1, @battle.getMove('Tackle'))
@p1.currentHP.should.equal(@p1.stat('hp') - 1)
it "snaps out of confusion after a predetermined number of turns", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'confusion turns', 1) # always 1 turn
@p1.attach(Attachment.Confusion)
@controller.makeMove(@id1, 'Splash')
@controller.makeMove(@id2, 'Splash')
@controller.makeMove(@id1, 'Splash')
@controller.makeMove(@id2, 'Splash')
@p1.has(Attachment.Confusion).should.be.false
it "will not crit the confusion recoil", ->
shared.create.call(this)
@p1.attach(Attachment.Confusion)
shared.biasRNG.call(this, "next", 'confusion', 0) # always recoils
shared.biasRNG.call(this, 'next', 'ch', 0) # always crits
spy = @sandbox.spy(@battle.confusionMove, 'isCriticalHit')
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Tackle')
spy.returned(false).should.be.true
it "will not error for not having unusual move properties", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Iron Fist")])
@p1.attach(Attachment.Confusion)
shared.biasRNG.call(this, "next", 'confusion', 0) # always recoils
(=>
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Tackle')
).should.not.throw()
describe 'a frozen pokemon', ->
it "will not execute moves", ->
shared.create.call(this)
@p1.attach(Status.Freeze)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
mock = @sandbox.mock(@battle.getMove('Tackle'))
mock.expects('execute').never()
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Splash')
mock.verify()
it "has a 20% chance of unfreezing", ->
shared.create.call(this)
@p1.attach(Status.Freeze)
shared.biasRNG.call(this, "next", 'unfreeze chance', 0) # always unfreezes
@controller.makeMove(@id1, 'Splash')
@controller.makeMove(@id2, 'Splash')
@p1.has(Status.Freeze).should.be.false
it "unfreezes if hit by a fire move", ->
shared.create.call(this)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
@p1.attach(Status.Freeze)
@battle.performMove(@p2, @battle.getMove('Flamethrower'))
@p1.has(Status.Freeze).should.be.false
it "does not unfreeze if hit by a non-damaging move", ->
shared.create.call(this)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
@p1.attach(Status.Freeze)
@battle.performMove(@p2, @battle.getMove('Will-O-Wisp'))
@p1.has(Status.Freeze).should.be.true
for moveName in ["Sacred Fire", "Flare Blitz", "Flame Wheel", "Fusion Flare", "Scald"]
it "automatically unfreezes if using #{moveName}", ->
shared.create.call(this)
@p1.attach(Status.Freeze)
shared.biasRNG.call(this, "next", 'unfreeze chance', 1) # always stays frozen
@battle.performMove(@p1, @battle.getMove(moveName))
@p1.has(Status.Freeze).should.be.false
describe "a paralyzed pokemon", ->
it "has a 25% chance of being fully paralyzed", ->
shared.create.call(this)
@p1.attach(Status.Paralyze)
shared.biasRNG.call(this, "next", 'paralyze chance', 0) # always stays frozen
mock = @sandbox.mock(@battle.getMove('Tackle'))
mock.expects('execute').never()
@controller.makeMove(@id1, 'Tackle')
@controller.makeMove(@id2, 'Splash')
mock.verify()
it "has its speed quartered", ->
shared.create.call(this)
speed = @p1.stat('speed')
@p1.attach(Status.Paralyze)
@p1.stat('speed').should.equal Math.floor(speed / 4)
describe "a burned pokemon", ->
it "loses 1/8 of its HP each turn", ->
shared.create.call(this)
@p1.attach(Status.Burn)
hp = @p1.currentHP
eighth = Math.floor(hp / 8)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(eighth)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(2 * eighth)
it "loses 1 minimum HP", ->
shared.create.call(this, team1: [Factory("Shedinja")])
@p1.attach(Status.Burn)
@p1.currentHP.should.equal(1)
@battle.endTurn()
@p1.currentHP.should.equal(0)
describe "a sleeping pokemon", ->
it "sleeps for 1-3 turns", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'sleep turns', 3)
@p1.attach(Status.Sleep)
tackle = @battle.getMove('Tackle')
for i in [0...3]
@battle.performMove(@p1, tackle)
@p1.has(Status.Sleep).should.be.true
@battle.performMove(@p1, tackle)
@p1.has(Status.Sleep).should.be.false
it "cannot move while asleep", ->
shared.create.call(this)
shared.biasRNG.call(this, "randInt", 'sleep turns', 3)
@p1.attach(Status.Sleep)
tackle = @battle.getMove('Tackle')
mock = @sandbox.mock(tackle).expects('execute').never()
for i in [0...3]
@battle.performMove(@p1, tackle)
mock.verify()
tackle.execute.restore()
mock = @sandbox.mock(tackle).expects('execute').once()
@battle.performMove(@p1, tackle)
mock.verify()
it "resets its counter when switching out", ->
shared.create.call this,
team1: [ Factory("Magikarp"), Factory("Magikarp") ]
shared.biasRNG.call(this, "randInt", 'sleep turns', 1)
@p1.attach(Status.Sleep)
tackle = @battle.getMove('Tackle')
@battle.performMove(@p1, tackle)
@battle.performSwitch(@team1.first(), 1)
@battle.performSwitch(@team1.first(), 1)
@battle.performMove(@team1.first(), tackle)
@p1.has(Status.Sleep).should.be.true
describe "a poisoned pokemon", ->
it "loses 1/8 of its HP each turn", ->
shared.create.call(this)
@p1.attach(Status.Poison)
hp = @p1.currentHP
eighth = Math.floor(hp / 8)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(eighth)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(2 * eighth)
it "loses 1 minimum HP", ->
shared.create.call(this, team1: [Factory("Shedinja")])
@p1.attach(Status.Poison)
@p1.currentHP.should.equal(1)
@battle.endTurn()
@p1.currentHP.should.equal(0)
describe "a badly poisoned pokemon", ->
it "loses 1/16 of its HP the first turn", ->
shared.create.call(this)
@p1.attach(Status.Toxic)
hp = @p1.currentHP
@battle.endTurn()
(hp - @p1.currentHP).should.equal(hp >> 4)
it "loses 1/16 of its max HP, rounded down, times x where x is the number of turns up to 15", ->
shared.create.call(this)
@p1.attach(Status.Toxic)
hp = @p1.currentHP
fraction = (hp >> 4)
for i in [1..16]
@battle.endTurn()
hpFraction = Math.min(fraction * i, fraction * 15)
(hp - @p1.currentHP).should.equal(hpFraction)
@p1.currentHP = hp
it "still increases the counter with poison heal", ->
shared.create.call(this, team1: [Factory("Magikarp", ability: "Poison Heal")])
@p1.attach(Status.Toxic)
hp = @p1.currentHP
fraction = (hp >> 4)
turns = 3
for i in [1...turns]
@battle.endTurn()
@p1.copyAbility(null)
@battle.endTurn()
hpFraction = Math.min(fraction * turns, fraction * 15)
(hp - @p1.currentHP).should.equal(hpFraction)
it "loses 1 minimum HP", ->
shared.create.call(this, team1: [Factory("Shedinja")])
@p1.attach(Status.Toxic)
@p1.currentHP.should.equal(1)
@battle.endTurn()
@p1.currentHP.should.equal(0)
it "resets its counter when switching out", ->
shared.create.call this,
team1: [ Factory("Magikarp"), Factory("PI:NAME:<NAME>END_PI") ]
@p1.attach(Status.Toxic)
hp = @p1.currentHP
@battle.endTurn()
@battle.performSwitch(@team1.first(), 1)
@p1.currentHP = hp
@battle.performSwitch(@team1.first(), 1)
@battle.endTurn()
(hp - @p1.currentHP).should.equal(hp >> 4)
describe "Pokemon#turnsActive", ->
it "is 1 on start of battle", ->
shared.create.call(this)
@p1.turnsActive.should.equal 1
it "is set to 0 when switching", ->
shared.create.call(this, team1: (Factory("Magikarp") for x in [1..2]))
@p1.turnsActive = 4
@team1.switch(@p1, 0)
@team1.first().turnsActive.should.equal 0
it "increases by 1 when a turn ends", ->
shared.create.call(this)
@p1.turnsActive.should.equal 1
@battle.endTurn()
@p1.turnsActive.should.equal 2
describe "A move with 0 PP", ->
it "will not execute", ->
shared.create.call(this)
move = @p1.moves[0]
@p1.setPP(move, 0)
@sandbox.mock(move).expects('execute').never()
@sandbox.mock(@p1).expects('beforeMove').never()
@battle.performMove(@p1, move)
describe "A pokemon with no available moves", ->
it "can struggle", ->
shared.create.call(this)
@battle.removeRequest(@id1)
# Next turn, @p1 will have no available moves.
for move in @p1.moves
@p1.blockMove(move)
@p1.resetBlocks = ->
@p1.validMoves().should.be.empty
@battle.beginTurn()
request = @battle.requestFor(@p1)
should.exist(request)
request.should.have.property('moves')
request.moves.should.eql(["Struggle"])
describe "Ability activation at the beginning of a battle", ->
it "considers Abilities that are always active", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Clear Body")]
team2: [Factory("Magikarp", ability: "Intimidate")]
@p1.stages.should.containEql(attack: 0)
xit "works the same way regardless of the entry order", ->
shared.create.call this,
team1: [Factory("Magikarp", ability: "Intimidate")]
team2: [Factory("Magikarp", ability: "Clear Body")]
@p2.stages.should.containEql(attack: 0)
|
[
{
"context": " getForm: (resources) =>\n form = [\n key: 'subschema'\n title: 'Action'\n titleMap: @getSubsch",
"end": 204,
"score": 0.8585065603256226,
"start": 195,
"tag": "KEY",
"value": "subschema"
},
{
"context": " (resource) =>\n form = [\n key: \"#{re... | channel-to-form.coffee | octoblu/parse-channel-to-json | 0 | _ = require 'lodash'
class ChannelToForm
transform: (channel) =>
return [] unless channel?
@getForm channel?.application?.resources
getForm: (resources) =>
form = [
key: 'subschema'
title: 'Action'
titleMap: @getSubschemaTitleMap resources
]
resourceForms = _.flatten( _.map resources, @getFormFromResource )
form.concat resourceForms
getFormFromResource: (resource) =>
form = [
key: "#{resource.action}"
notitle: true
type: 'hidden'
]
_.each resource.params, (param) =>
form.push(@getFormFromParam resource.action, param)
form
getFormFromParam: (action, param) =>
formParam =
key: "#{action}.#{@sanitizeParam param.name}"
title: param.displayName
condition: "model.subschema === '#{action}'"
required: param.required
if param.hidden?
formParam.type = 'hidden'
formParam.notitle = true
formParam
getSubschemaTitleMap: (resources) =>
_.map resources, (resource) =>
value: resource.action, name: resource.displayName
convertFormParam: (param, url, method) =>
formParam =
key: "#{@sanitizeParam param.name}"
title: param.displayName
condition: "model.url === '#{url}' && model.method === '#{method}'"
if param.hidden?
formParam.type = 'hidden'
formParam.notitle = true
formParam
sanitizeParam: (param) =>
param.replace(/^:/, '')
module.exports = ChannelToForm
| 188802 | _ = require 'lodash'
class ChannelToForm
transform: (channel) =>
return [] unless channel?
@getForm channel?.application?.resources
getForm: (resources) =>
form = [
key: '<KEY>'
title: 'Action'
titleMap: @getSubschemaTitleMap resources
]
resourceForms = _.flatten( _.map resources, @getFormFromResource )
form.concat resourceForms
getFormFromResource: (resource) =>
form = [
key: "#{resource.<KEY>
notitle: true
type: 'hidden'
]
_.each resource.params, (param) =>
form.push(@getFormFromParam resource.action, param)
form
getFormFromParam: (action, param) =>
formParam =
key: "#{<KEY>#{@sanitizeParam param.name}"
title: param.displayName
condition: "model.subschema === '#{action}'"
required: param.required
if param.hidden?
formParam.type = 'hidden'
formParam.notitle = true
formParam
getSubschemaTitleMap: (resources) =>
_.map resources, (resource) =>
value: resource.action, name: resource.displayName
convertFormParam: (param, url, method) =>
formParam =
key: "#{@sanitizeParam param.name}"
title: param.displayName
condition: "model.url === '#{url}' && model.method === '#{method}'"
if param.hidden?
formParam.type = 'hidden'
formParam.notitle = true
formParam
sanitizeParam: (param) =>
param.replace(/^:/, '')
module.exports = ChannelToForm
| true | _ = require 'lodash'
class ChannelToForm
transform: (channel) =>
return [] unless channel?
@getForm channel?.application?.resources
getForm: (resources) =>
form = [
key: 'PI:KEY:<KEY>END_PI'
title: 'Action'
titleMap: @getSubschemaTitleMap resources
]
resourceForms = _.flatten( _.map resources, @getFormFromResource )
form.concat resourceForms
getFormFromResource: (resource) =>
form = [
key: "#{resource.PI:KEY:<KEY>END_PI
notitle: true
type: 'hidden'
]
_.each resource.params, (param) =>
form.push(@getFormFromParam resource.action, param)
form
getFormFromParam: (action, param) =>
formParam =
key: "#{PI:KEY:<KEY>END_PI#{@sanitizeParam param.name}"
title: param.displayName
condition: "model.subschema === '#{action}'"
required: param.required
if param.hidden?
formParam.type = 'hidden'
formParam.notitle = true
formParam
getSubschemaTitleMap: (resources) =>
_.map resources, (resource) =>
value: resource.action, name: resource.displayName
convertFormParam: (param, url, method) =>
formParam =
key: "#{@sanitizeParam param.name}"
title: param.displayName
condition: "model.url === '#{url}' && model.method === '#{method}'"
if param.hidden?
formParam.type = 'hidden'
formParam.notitle = true
formParam
sanitizeParam: (param) =>
param.replace(/^:/, '')
module.exports = ChannelToForm
|
[
{
"context": " This guild base is located in Maeles.\n *\n * @name Maeles\n * @category Bases\n * @package Guild\n * @cost {mo",
"end": 100,
"score": 0.7551264762878418,
"start": 94,
"tag": "NAME",
"value": "Maeles"
}
] | src/map/guild-bases/Maeles.coffee | jawsome/IdleLands | 3 | GuildBase = require "../GuildBase"
`/**
* This guild base is located in Maeles.
*
* @name Maeles
* @category Bases
* @package Guild
* @cost {move-in} 100000
* @cost {build-sm} 60000
* @cost {build-md} 75000
* @cost {build-lg} 100000
* @buildings {sm} 3
* @buildings {md} 2
* @buildings {lg} 3
*/`
class MaelesGuildHall extends GuildBase
constructor: (game, guild) ->
super "Maeles", game, guild
@costs = MaelesGuildHall::costs =
moveIn: 100000
build:
sm: 60000
md: 75000
lg: 100000
baseTile: 7
startLoc: [10, 16]
buildings:
## Small buildings
sm: [
{
startCoords: [30, 11]
signpostLoc: [29, 11]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
{
startCoords: [30, 16]
signpostLoc: [29, 16]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
{
startCoords: [30, 21]
signpostLoc: [29, 21]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
]
## Medium Buildings
md: [
{
startCoords: [5, 3]
signpostLoc: [6, 8]
tiles: [
3, 3, 3, 3, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 3, 0, 3, 3
]
}
{
startCoords: [5, 27]
signpostLoc: [6, 26]
tiles: [
3, 3, 0, 3, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 3, 3, 3, 3
]
}
]
## Large Buildings
lg: [
{
startCoords: [14, 2]
signpostLoc: [16, 9]
tiles: [
3, 3, 3, 3, 3, 3, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3
3, 3, 3, 0, 3, 3, 3
]
}
{
startCoords: [18, 14]
signpostLoc: [17, 17]
tiles: [
3, 3, 3, 0, 3, 3, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3
3, 3, 3, 0, 3, 3, 3
]
}
{
startCoords: [14, 26]
signpostLoc: [16, 25]
tiles: [
3, 3, 3, 0, 3, 3, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3
3, 3, 3, 3, 3, 3, 3
]
}
]
module.exports = exports = MaelesGuildHall | 28905 | GuildBase = require "../GuildBase"
`/**
* This guild base is located in Maeles.
*
* @name <NAME>
* @category Bases
* @package Guild
* @cost {move-in} 100000
* @cost {build-sm} 60000
* @cost {build-md} 75000
* @cost {build-lg} 100000
* @buildings {sm} 3
* @buildings {md} 2
* @buildings {lg} 3
*/`
class MaelesGuildHall extends GuildBase
constructor: (game, guild) ->
super "Maeles", game, guild
@costs = MaelesGuildHall::costs =
moveIn: 100000
build:
sm: 60000
md: 75000
lg: 100000
baseTile: 7
startLoc: [10, 16]
buildings:
## Small buildings
sm: [
{
startCoords: [30, 11]
signpostLoc: [29, 11]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
{
startCoords: [30, 16]
signpostLoc: [29, 16]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
{
startCoords: [30, 21]
signpostLoc: [29, 21]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
]
## Medium Buildings
md: [
{
startCoords: [5, 3]
signpostLoc: [6, 8]
tiles: [
3, 3, 3, 3, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 3, 0, 3, 3
]
}
{
startCoords: [5, 27]
signpostLoc: [6, 26]
tiles: [
3, 3, 0, 3, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 3, 3, 3, 3
]
}
]
## Large Buildings
lg: [
{
startCoords: [14, 2]
signpostLoc: [16, 9]
tiles: [
3, 3, 3, 3, 3, 3, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3
3, 3, 3, 0, 3, 3, 3
]
}
{
startCoords: [18, 14]
signpostLoc: [17, 17]
tiles: [
3, 3, 3, 0, 3, 3, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3
3, 3, 3, 0, 3, 3, 3
]
}
{
startCoords: [14, 26]
signpostLoc: [16, 25]
tiles: [
3, 3, 3, 0, 3, 3, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3
3, 3, 3, 3, 3, 3, 3
]
}
]
module.exports = exports = MaelesGuildHall | true | GuildBase = require "../GuildBase"
`/**
* This guild base is located in Maeles.
*
* @name PI:NAME:<NAME>END_PI
* @category Bases
* @package Guild
* @cost {move-in} 100000
* @cost {build-sm} 60000
* @cost {build-md} 75000
* @cost {build-lg} 100000
* @buildings {sm} 3
* @buildings {md} 2
* @buildings {lg} 3
*/`
class MaelesGuildHall extends GuildBase
constructor: (game, guild) ->
super "Maeles", game, guild
@costs = MaelesGuildHall::costs =
moveIn: 100000
build:
sm: 60000
md: 75000
lg: 100000
baseTile: 7
startLoc: [10, 16]
buildings:
## Small buildings
sm: [
{
startCoords: [30, 11]
signpostLoc: [29, 11]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
{
startCoords: [30, 16]
signpostLoc: [29, 16]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
{
startCoords: [30, 21]
signpostLoc: [29, 21]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
]
## Medium Buildings
md: [
{
startCoords: [5, 3]
signpostLoc: [6, 8]
tiles: [
3, 3, 3, 3, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 3, 0, 3, 3
]
}
{
startCoords: [5, 27]
signpostLoc: [6, 26]
tiles: [
3, 3, 0, 3, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 0, 0, 0, 3,
3, 3, 3, 3, 3
]
}
]
## Large Buildings
lg: [
{
startCoords: [14, 2]
signpostLoc: [16, 9]
tiles: [
3, 3, 3, 3, 3, 3, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3
3, 3, 3, 0, 3, 3, 3
]
}
{
startCoords: [18, 14]
signpostLoc: [17, 17]
tiles: [
3, 3, 3, 0, 3, 3, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3
3, 3, 3, 0, 3, 3, 3
]
}
{
startCoords: [14, 26]
signpostLoc: [16, 25]
tiles: [
3, 3, 3, 0, 3, 3, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3,
3, 0, 0, 0, 0, 0, 3
3, 3, 3, 3, 3, 3, 3
]
}
]
module.exports = exports = MaelesGuildHall |
[
{
"context": "lias clear - Clear the alias table\n#\n# Author:\n# dtaniwaki\n#\n\"use strict\"\n\nALIAS_TABLE_KEY = 'hubot-alias-ta",
"end": 224,
"score": 0.9997020959854126,
"start": 215,
"tag": "USERNAME",
"value": "dtaniwaki"
},
{
"context": "\n# dtaniwaki\n#\n\"use strict\"\n... | node_modules/hubot-alias/src/scripts/alias.coffee | Viper702/riley-reid | 17 | # Description:
# Action alias for hubot
#
# Commands:
# hubot alias xxx=yyy - Make alias xxx for yyy
# hubot alias xxx= - Remove alias xxx for yyy
# hubot alias clear - Clear the alias table
#
# Author:
# dtaniwaki
#
"use strict"
ALIAS_TABLE_KEY = 'hubot-alias-table'
loadArgumentsInAction = (args, action) ->
args = args.trim()
if args
argItems = args.split(' ')
for val, i in argItems
if action.indexOf('$'+(i+1)) > -1 then action = action.replace('$'+(i+1), val) else action += " #{val}"
action = action.replace(/\$\d+/g, "")
action.trim()
module.exports = (robot) ->
receiveOrg = robot.receive
robot.receive = (msg)->
table = robot.brain.get(ALIAS_TABLE_KEY) || {}
orgText = msg.text?.trim()
if new RegExp("(^[@]?(?:#{robot.name}|#{robot.alias})[:,]?)(\\s+)(.*)$").test orgText
name = RegExp.$1
sp = RegExp.$2
action = RegExp.$3
if action && action.indexOf('alias') != 0
rest = ''
for k in Object.keys(table).sort().reverse()
v = table[k]
if new RegExp("^#{k}\\b").test(action)
rest = action.slice(k.length)
action = v
break
msg.text = "#{name}#{sp}"
msg.text += loadArgumentsInAction(rest, action)
robot.logger.info "Replace \"#{orgText}\" as \"#{msg.text}\"" if orgText != msg.text
receiveOrg.bind(robot)(msg)
robot.respond /alias(.*)$/i, (msg)->
text = msg.match[1].trim()
table = robot.brain.get(ALIAS_TABLE_KEY) || {}
if text.toLowerCase() == 'clear'
robot.brain.set ALIAS_TABLE_KEY, {}
msg.send "I cleared the alias table."
else if !text
s = []
for k, v of table
s.push "#{k} : #{v}"
msg.send "Here you go.\n#{s.join("\n")}"
else
match = text.match /([^=]*)=(.*)?$/
alias = match[1]
action = match[2]
if action?
table[alias] = action
robot.brain.set ALIAS_TABLE_KEY, table
msg.send "I made an alias #{alias} for \"#{action}\"."
else
delete table[alias]
robot.brain.set ALIAS_TABLE_KEY, table
msg.send "I removed the alias #{alias}."
| 38970 | # Description:
# Action alias for hubot
#
# Commands:
# hubot alias xxx=yyy - Make alias xxx for yyy
# hubot alias xxx= - Remove alias xxx for yyy
# hubot alias clear - Clear the alias table
#
# Author:
# dtaniwaki
#
"use strict"
ALIAS_TABLE_KEY = '<KEY>'
loadArgumentsInAction = (args, action) ->
args = args.trim()
if args
argItems = args.split(' ')
for val, i in argItems
if action.indexOf('$'+(i+1)) > -1 then action = action.replace('$'+(i+1), val) else action += " #{val}"
action = action.replace(/\$\d+/g, "")
action.trim()
module.exports = (robot) ->
receiveOrg = robot.receive
robot.receive = (msg)->
table = robot.brain.get(ALIAS_TABLE_KEY) || {}
orgText = msg.text?.trim()
if new RegExp("(^[@]?(?:#{robot.name}|#{robot.alias})[:,]?)(\\s+)(.*)$").test orgText
name = RegExp.$1
sp = RegExp.$2
action = RegExp.$3
if action && action.indexOf('alias') != 0
rest = ''
for k in Object.keys(table).sort().reverse()
v = table[k]
if new RegExp("^#{k}\\b").test(action)
rest = action.slice(k.length)
action = v
break
msg.text = "#{name}#{sp}"
msg.text += loadArgumentsInAction(rest, action)
robot.logger.info "Replace \"#{orgText}\" as \"#{msg.text}\"" if orgText != msg.text
receiveOrg.bind(robot)(msg)
robot.respond /alias(.*)$/i, (msg)->
text = msg.match[1].trim()
table = robot.brain.get(ALIAS_TABLE_KEY) || {}
if text.toLowerCase() == 'clear'
robot.brain.set ALIAS_TABLE_KEY, {}
msg.send "I cleared the alias table."
else if !text
s = []
for k, v of table
s.push "#{k} : #{v}"
msg.send "Here you go.\n#{s.join("\n")}"
else
match = text.match /([^=]*)=(.*)?$/
alias = match[1]
action = match[2]
if action?
table[alias] = action
robot.brain.set ALIAS_TABLE_KEY, table
msg.send "I made an alias #{alias} for \"#{action}\"."
else
delete table[alias]
robot.brain.set ALIAS_TABLE_KEY, table
msg.send "I removed the alias #{alias}."
| true | # Description:
# Action alias for hubot
#
# Commands:
# hubot alias xxx=yyy - Make alias xxx for yyy
# hubot alias xxx= - Remove alias xxx for yyy
# hubot alias clear - Clear the alias table
#
# Author:
# dtaniwaki
#
"use strict"
ALIAS_TABLE_KEY = 'PI:KEY:<KEY>END_PI'
loadArgumentsInAction = (args, action) ->
args = args.trim()
if args
argItems = args.split(' ')
for val, i in argItems
if action.indexOf('$'+(i+1)) > -1 then action = action.replace('$'+(i+1), val) else action += " #{val}"
action = action.replace(/\$\d+/g, "")
action.trim()
module.exports = (robot) ->
receiveOrg = robot.receive
robot.receive = (msg)->
table = robot.brain.get(ALIAS_TABLE_KEY) || {}
orgText = msg.text?.trim()
if new RegExp("(^[@]?(?:#{robot.name}|#{robot.alias})[:,]?)(\\s+)(.*)$").test orgText
name = RegExp.$1
sp = RegExp.$2
action = RegExp.$3
if action && action.indexOf('alias') != 0
rest = ''
for k in Object.keys(table).sort().reverse()
v = table[k]
if new RegExp("^#{k}\\b").test(action)
rest = action.slice(k.length)
action = v
break
msg.text = "#{name}#{sp}"
msg.text += loadArgumentsInAction(rest, action)
robot.logger.info "Replace \"#{orgText}\" as \"#{msg.text}\"" if orgText != msg.text
receiveOrg.bind(robot)(msg)
robot.respond /alias(.*)$/i, (msg)->
text = msg.match[1].trim()
table = robot.brain.get(ALIAS_TABLE_KEY) || {}
if text.toLowerCase() == 'clear'
robot.brain.set ALIAS_TABLE_KEY, {}
msg.send "I cleared the alias table."
else if !text
s = []
for k, v of table
s.push "#{k} : #{v}"
msg.send "Here you go.\n#{s.join("\n")}"
else
match = text.match /([^=]*)=(.*)?$/
alias = match[1]
action = match[2]
if action?
table[alias] = action
robot.brain.set ALIAS_TABLE_KEY, table
msg.send "I made an alias #{alias} for \"#{action}\"."
else
delete table[alias]
robot.brain.set ALIAS_TABLE_KEY, table
msg.send "I removed the alias #{alias}."
|
[
{
"context": " # db.getAll bucket, { where: { name: 'Testing 2', other: undefined } }, @callback\n # ",
"end": 4586,
"score": 0.6966456174850464,
"start": 4579,
"tag": "NAME",
"value": "Testing"
}
] | spec/batch_http.coffee | geeklist/riak-js-geeklist | 1 | assert = require 'assert'
bucket = 'riakjs_http'
fs = require 'fs'
module.exports =
bucket: bucket
data:
riakjs_http:
'test1': [{name: 'Testing 1'}]
'test2': [{name: 'Testing 2'}]
'test3': [{name: 'Testing 3'}]
batches: (db) -> [
{
'bucket properties':
topic: ->
db.getProps bucket, @callback
'have allow_mult disabled': (response) ->
assert.equal response.allow_mult, false
'bucket count request':
topic: ->
db.count bucket, @callback
'returns several elements': (count) ->
assert.equal count, 3
'head request':
topic: ->
db.head bucket, 'test1', @callback
'data is undefined': (err, data, meta) ->
assert.isUndefined data
'meta is present': (err, data, meta) ->
assert.ok meta
'exists request (1)':
topic: ->
db.exists bucket, 'test1', @callback
'document exists': (exists) ->
assert.isTrue exists
'exists request (2)':
topic: ->
db.exists bucket, 'test-3739192843943-b', @callback
'document does not exist': (exists) ->
assert.isFalse exists
'keys request':
topic: ->
db.keys bucket, @callback
'keys are returned (unsorted)': (keys) ->
assert.deepEqual ['test1', 'test2', 'test3'], keys.sort()
'getAll request':
topic: ->
db.getAll bucket, @callback
'documents are returned in {data, meta} pairs': (err, elems, meta) ->
assert.equal elems.length, 3
# get first
[{ meta: { key: key }, data: { name: name }}] = elems
assert.ok key.match /^test/
assert.ok name.match /^Testing/
'a Buffer':
topic: ->
db.save bucket, 'test-buffer', new Buffer('hello'), { contentType: 'application/x-play', responseEncoding: 'binary', returnbody: true }, @callback
'remains a Buffer when requested with responseEncoding=binary': (data) ->
assert.ok data instanceof Buffer
assert.equal 'hello', data.toString()
'when removed':
topic: ->
db.remove bucket, 'test-buffer', @callback
'succeeds': ->
'another Buffer':
topic: ->
image = new Buffer('&Sttt ïÁÕõßæøq„Fï*UÓ‹Ωk¥Ÿåf≥…bypÛfÙΩ{F/¸ò6≠9', 'binary')
db.save bucket, 'test-another-buffer', image, { contentType: 'image/png', returnbody: true }, @callback
'remains a Buffer if content-type is image (responseEncoding is automatic with known content types)': (data) ->
assert.ok data instanceof Buffer
'when removed':
topic: ->
db.remove bucket, 'test-another-buffer', @callback
'succeeds': ->
}
# allow_mult=true
{
'bucket properties update':
topic: ->
db.updateProps bucket, { n_val: 8, allow_mult: true }, @callback
'when fetched':
topic: ->
db.getProps bucket, @callback
'n_val is updated': (response) ->
assert.equal response.n_val, 8
'allow_mult is updated': (response) ->
assert.ok response.allow_mult
}
# {
#
# 'a document':
# topic: ->
# db.save bucket, 'test1', { name: 'Testing conflicting' }, { returnbody: true }, @callback
#
# 'when allow_mult=true, returns conflicting versions': (err, data, meta) ->
# assert.equal data.length, 2
#
# 'when solving the conflict':
# # we now select the document with name 'Testing conflicting'
# # and save (meta passes the correct vclock along)
# topic: (data) ->
# assert.instanceOf data, Array
# [resolved] = data.filter (e) -> e.data.name is 'Testing conflicting'
# resolved.meta.returnbody = true
# db.save bucket, 'test1', resolved.data, resolved.meta, @callback
#
# 'gives back one document again': (data) ->
# # we now get the object with name 'Testing conflicting'
# assert.equal !!data.length, false
# assert.equal data.name, 'Testing conflicting'
#
# 'when requesting a different document':
# topic: ->
# db.getAll bucket, { where: { name: 'Testing 2', other: undefined } }, @callback
#
# 'does not give a conflict': (err, elems, meta) ->
# assert.equal elems.length, 1
# assert.notEqual 300, meta.statusCode
#
# }
# luwak
{
'trying to save a non-buffer':
topic: ->
db.saveLarge 'lowcost-pilot', "String data, no Buffer", @callback
'gives back an error': (err, data) ->
assert.instanceOf err, Error
'getting a non-existent file':
topic: ->
db.getLarge '90230230230dff3j0f3', @callback
'gives back a 404': (err, data) ->
assert.equal err?.statusCode, 404
# TODO test range get - once we can list keys in luwak, to be able to remove the test doc later
'getting a file stored in luwak':
topic: ->
done = @callback
fs.readFile "#{__dirname}/fixtures/lowcost-pilot.jpg", (err, data) =>
@length = data.length
db.saveLarge 'lowcost-pilot', data, { contentType: 'jpeg' }, (err) ->
setTimeout -> # let's wait for Riak for 80ms
db.getLarge 'lowcost-pilot', done
, 80
'returns a Buffer of the same length as the original': (data) ->
assert.instanceOf data, Buffer
assert.equal @length, data.length
'and when removing the file':
topic: ->
db.removeLarge 'lowcost-pilot', @callback
'is complete': (err, data) ->
assert.ok not err
}
# remove allow_mult
{
'updating allow_mult':
topic: ->
db.updateProps bucket, { allow_mult: false }, @callback
'is complete': ->
}
] | 107055 | assert = require 'assert'
bucket = 'riakjs_http'
fs = require 'fs'
module.exports =
bucket: bucket
data:
riakjs_http:
'test1': [{name: 'Testing 1'}]
'test2': [{name: 'Testing 2'}]
'test3': [{name: 'Testing 3'}]
batches: (db) -> [
{
'bucket properties':
topic: ->
db.getProps bucket, @callback
'have allow_mult disabled': (response) ->
assert.equal response.allow_mult, false
'bucket count request':
topic: ->
db.count bucket, @callback
'returns several elements': (count) ->
assert.equal count, 3
'head request':
topic: ->
db.head bucket, 'test1', @callback
'data is undefined': (err, data, meta) ->
assert.isUndefined data
'meta is present': (err, data, meta) ->
assert.ok meta
'exists request (1)':
topic: ->
db.exists bucket, 'test1', @callback
'document exists': (exists) ->
assert.isTrue exists
'exists request (2)':
topic: ->
db.exists bucket, 'test-3739192843943-b', @callback
'document does not exist': (exists) ->
assert.isFalse exists
'keys request':
topic: ->
db.keys bucket, @callback
'keys are returned (unsorted)': (keys) ->
assert.deepEqual ['test1', 'test2', 'test3'], keys.sort()
'getAll request':
topic: ->
db.getAll bucket, @callback
'documents are returned in {data, meta} pairs': (err, elems, meta) ->
assert.equal elems.length, 3
# get first
[{ meta: { key: key }, data: { name: name }}] = elems
assert.ok key.match /^test/
assert.ok name.match /^Testing/
'a Buffer':
topic: ->
db.save bucket, 'test-buffer', new Buffer('hello'), { contentType: 'application/x-play', responseEncoding: 'binary', returnbody: true }, @callback
'remains a Buffer when requested with responseEncoding=binary': (data) ->
assert.ok data instanceof Buffer
assert.equal 'hello', data.toString()
'when removed':
topic: ->
db.remove bucket, 'test-buffer', @callback
'succeeds': ->
'another Buffer':
topic: ->
image = new Buffer('&Sttt ïÁÕõßæøq„Fï*UÓ‹Ωk¥Ÿåf≥…bypÛfÙΩ{F/¸ò6≠9', 'binary')
db.save bucket, 'test-another-buffer', image, { contentType: 'image/png', returnbody: true }, @callback
'remains a Buffer if content-type is image (responseEncoding is automatic with known content types)': (data) ->
assert.ok data instanceof Buffer
'when removed':
topic: ->
db.remove bucket, 'test-another-buffer', @callback
'succeeds': ->
}
# allow_mult=true
{
'bucket properties update':
topic: ->
db.updateProps bucket, { n_val: 8, allow_mult: true }, @callback
'when fetched':
topic: ->
db.getProps bucket, @callback
'n_val is updated': (response) ->
assert.equal response.n_val, 8
'allow_mult is updated': (response) ->
assert.ok response.allow_mult
}
# {
#
# 'a document':
# topic: ->
# db.save bucket, 'test1', { name: 'Testing conflicting' }, { returnbody: true }, @callback
#
# 'when allow_mult=true, returns conflicting versions': (err, data, meta) ->
# assert.equal data.length, 2
#
# 'when solving the conflict':
# # we now select the document with name 'Testing conflicting'
# # and save (meta passes the correct vclock along)
# topic: (data) ->
# assert.instanceOf data, Array
# [resolved] = data.filter (e) -> e.data.name is 'Testing conflicting'
# resolved.meta.returnbody = true
# db.save bucket, 'test1', resolved.data, resolved.meta, @callback
#
# 'gives back one document again': (data) ->
# # we now get the object with name 'Testing conflicting'
# assert.equal !!data.length, false
# assert.equal data.name, 'Testing conflicting'
#
# 'when requesting a different document':
# topic: ->
# db.getAll bucket, { where: { name: '<NAME> 2', other: undefined } }, @callback
#
# 'does not give a conflict': (err, elems, meta) ->
# assert.equal elems.length, 1
# assert.notEqual 300, meta.statusCode
#
# }
# luwak
{
'trying to save a non-buffer':
topic: ->
db.saveLarge 'lowcost-pilot', "String data, no Buffer", @callback
'gives back an error': (err, data) ->
assert.instanceOf err, Error
'getting a non-existent file':
topic: ->
db.getLarge '90230230230dff3j0f3', @callback
'gives back a 404': (err, data) ->
assert.equal err?.statusCode, 404
# TODO test range get - once we can list keys in luwak, to be able to remove the test doc later
'getting a file stored in luwak':
topic: ->
done = @callback
fs.readFile "#{__dirname}/fixtures/lowcost-pilot.jpg", (err, data) =>
@length = data.length
db.saveLarge 'lowcost-pilot', data, { contentType: 'jpeg' }, (err) ->
setTimeout -> # let's wait for Riak for 80ms
db.getLarge 'lowcost-pilot', done
, 80
'returns a Buffer of the same length as the original': (data) ->
assert.instanceOf data, Buffer
assert.equal @length, data.length
'and when removing the file':
topic: ->
db.removeLarge 'lowcost-pilot', @callback
'is complete': (err, data) ->
assert.ok not err
}
# remove allow_mult
{
'updating allow_mult':
topic: ->
db.updateProps bucket, { allow_mult: false }, @callback
'is complete': ->
}
] | true | assert = require 'assert'
bucket = 'riakjs_http'
fs = require 'fs'
module.exports =
bucket: bucket
data:
riakjs_http:
'test1': [{name: 'Testing 1'}]
'test2': [{name: 'Testing 2'}]
'test3': [{name: 'Testing 3'}]
batches: (db) -> [
{
'bucket properties':
topic: ->
db.getProps bucket, @callback
'have allow_mult disabled': (response) ->
assert.equal response.allow_mult, false
'bucket count request':
topic: ->
db.count bucket, @callback
'returns several elements': (count) ->
assert.equal count, 3
'head request':
topic: ->
db.head bucket, 'test1', @callback
'data is undefined': (err, data, meta) ->
assert.isUndefined data
'meta is present': (err, data, meta) ->
assert.ok meta
'exists request (1)':
topic: ->
db.exists bucket, 'test1', @callback
'document exists': (exists) ->
assert.isTrue exists
'exists request (2)':
topic: ->
db.exists bucket, 'test-3739192843943-b', @callback
'document does not exist': (exists) ->
assert.isFalse exists
'keys request':
topic: ->
db.keys bucket, @callback
'keys are returned (unsorted)': (keys) ->
assert.deepEqual ['test1', 'test2', 'test3'], keys.sort()
'getAll request':
topic: ->
db.getAll bucket, @callback
'documents are returned in {data, meta} pairs': (err, elems, meta) ->
assert.equal elems.length, 3
# get first
[{ meta: { key: key }, data: { name: name }}] = elems
assert.ok key.match /^test/
assert.ok name.match /^Testing/
'a Buffer':
topic: ->
db.save bucket, 'test-buffer', new Buffer('hello'), { contentType: 'application/x-play', responseEncoding: 'binary', returnbody: true }, @callback
'remains a Buffer when requested with responseEncoding=binary': (data) ->
assert.ok data instanceof Buffer
assert.equal 'hello', data.toString()
'when removed':
topic: ->
db.remove bucket, 'test-buffer', @callback
'succeeds': ->
'another Buffer':
topic: ->
image = new Buffer('&Sttt ïÁÕõßæøq„Fï*UÓ‹Ωk¥Ÿåf≥…bypÛfÙΩ{F/¸ò6≠9', 'binary')
db.save bucket, 'test-another-buffer', image, { contentType: 'image/png', returnbody: true }, @callback
'remains a Buffer if content-type is image (responseEncoding is automatic with known content types)': (data) ->
assert.ok data instanceof Buffer
'when removed':
topic: ->
db.remove bucket, 'test-another-buffer', @callback
'succeeds': ->
}
# allow_mult=true
{
'bucket properties update':
topic: ->
db.updateProps bucket, { n_val: 8, allow_mult: true }, @callback
'when fetched':
topic: ->
db.getProps bucket, @callback
'n_val is updated': (response) ->
assert.equal response.n_val, 8
'allow_mult is updated': (response) ->
assert.ok response.allow_mult
}
# {
#
# 'a document':
# topic: ->
# db.save bucket, 'test1', { name: 'Testing conflicting' }, { returnbody: true }, @callback
#
# 'when allow_mult=true, returns conflicting versions': (err, data, meta) ->
# assert.equal data.length, 2
#
# 'when solving the conflict':
# # we now select the document with name 'Testing conflicting'
# # and save (meta passes the correct vclock along)
# topic: (data) ->
# assert.instanceOf data, Array
# [resolved] = data.filter (e) -> e.data.name is 'Testing conflicting'
# resolved.meta.returnbody = true
# db.save bucket, 'test1', resolved.data, resolved.meta, @callback
#
# 'gives back one document again': (data) ->
# # we now get the object with name 'Testing conflicting'
# assert.equal !!data.length, false
# assert.equal data.name, 'Testing conflicting'
#
# 'when requesting a different document':
# topic: ->
# db.getAll bucket, { where: { name: 'PI:NAME:<NAME>END_PI 2', other: undefined } }, @callback
#
# 'does not give a conflict': (err, elems, meta) ->
# assert.equal elems.length, 1
# assert.notEqual 300, meta.statusCode
#
# }
# luwak
{
'trying to save a non-buffer':
topic: ->
db.saveLarge 'lowcost-pilot', "String data, no Buffer", @callback
'gives back an error': (err, data) ->
assert.instanceOf err, Error
'getting a non-existent file':
topic: ->
db.getLarge '90230230230dff3j0f3', @callback
'gives back a 404': (err, data) ->
assert.equal err?.statusCode, 404
# TODO test range get - once we can list keys in luwak, to be able to remove the test doc later
'getting a file stored in luwak':
topic: ->
done = @callback
fs.readFile "#{__dirname}/fixtures/lowcost-pilot.jpg", (err, data) =>
@length = data.length
db.saveLarge 'lowcost-pilot', data, { contentType: 'jpeg' }, (err) ->
setTimeout -> # let's wait for Riak for 80ms
db.getLarge 'lowcost-pilot', done
, 80
'returns a Buffer of the same length as the original': (data) ->
assert.instanceOf data, Buffer
assert.equal @length, data.length
'and when removing the file':
topic: ->
db.removeLarge 'lowcost-pilot', @callback
'is complete': (err, data) ->
assert.ok not err
}
# remove allow_mult
{
'updating allow_mult':
topic: ->
db.updateProps bucket, { allow_mult: false }, @callback
'is complete': ->
}
] |
[
{
"context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http",
"end": 63,
"score": 0.5529676079750061,
"start": 62,
"tag": "NAME",
"value": "H"
}
] | src/spec/SpecContentEditLayerExportable.coffee | heartyoh/infopik | 0 | # ==========================================
# Copyright 2014 Hatio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'../command/CommandPropertyChange'
'../command/CommandMove'
], (
CommandPropertyChange
CommandMove
) ->
_move = (appcontext, to) ->
view = appcontext.selectionManager.focus()
return if not view
appcontext.execute new CommandMove
to: to
view: view
model: appcontext.getAttachedModel(view)
moveForward = (appcontext) ->
_move appcontext, 'FORWARD'
moveBackward = (appcontext) ->
_move appcontext, 'BACKWARD'
moveToFront = (appcontext) ->
_move appcontext, 'FRONT'
moveToBack = (appcontext) ->
_move appcontext, 'BACK'
cut = (appcontext) ->
appcontext.clipboard.cut appcontext.selectionManager.get()
copy = (appcontext) ->
appcontext.clipboard.copy appcontext.selectionManager.get()
paste = (appcontext) ->
components = appcontext.clipboard.paste()
nodes = (appcontext.getAttachedModel(component) for component in components)
appcontext.selectionManager.select(nodes)
moveDelta = (appcontext, component, delta) ->
nodes = appcontext.selectionManager.get()
changes = []
for node in nodes
comp = appcontext.getAttachedModel(node)
before = {}
after = {}
for attr of delta
before[attr] = comp.get(attr)
after[attr] = comp.get(attr) + delta[attr]
changes.push
component : comp
before : before
after : after
appcontext.commandManager.execute(new CommandPropertyChange {
changes : changes
})
offset = (appcontext, component, position) ->
layer = component.getViews()[0]
layer.offset position
layer.fire('change-offset', layer.offset(), false);
layer.batchDraw()
(appcontext, component) ->
exportableFunctions =
moveDelta: (delta) -> moveDelta(appcontext, component, delta)
moveForward: -> moveForward(appcontext, component)
moveBackward: -> moveBackward(appcontext, component)
moveToFront: -> moveToFront(appcontext, component)
moveToBack: -> moveToBack(appcontext, component)
offset: (position) -> offset(appcontext, component, position)
cut: -> cut(appcontext, component)
copy: -> copy(appcontext, component)
paste: -> paste(appcontext, component)
appcontext[name] = func for name, func of exportableFunctions
| 175455 | # ==========================================
# Copyright 2014 <NAME>atio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'../command/CommandPropertyChange'
'../command/CommandMove'
], (
CommandPropertyChange
CommandMove
) ->
_move = (appcontext, to) ->
view = appcontext.selectionManager.focus()
return if not view
appcontext.execute new CommandMove
to: to
view: view
model: appcontext.getAttachedModel(view)
moveForward = (appcontext) ->
_move appcontext, 'FORWARD'
moveBackward = (appcontext) ->
_move appcontext, 'BACKWARD'
moveToFront = (appcontext) ->
_move appcontext, 'FRONT'
moveToBack = (appcontext) ->
_move appcontext, 'BACK'
cut = (appcontext) ->
appcontext.clipboard.cut appcontext.selectionManager.get()
copy = (appcontext) ->
appcontext.clipboard.copy appcontext.selectionManager.get()
paste = (appcontext) ->
components = appcontext.clipboard.paste()
nodes = (appcontext.getAttachedModel(component) for component in components)
appcontext.selectionManager.select(nodes)
moveDelta = (appcontext, component, delta) ->
nodes = appcontext.selectionManager.get()
changes = []
for node in nodes
comp = appcontext.getAttachedModel(node)
before = {}
after = {}
for attr of delta
before[attr] = comp.get(attr)
after[attr] = comp.get(attr) + delta[attr]
changes.push
component : comp
before : before
after : after
appcontext.commandManager.execute(new CommandPropertyChange {
changes : changes
})
offset = (appcontext, component, position) ->
layer = component.getViews()[0]
layer.offset position
layer.fire('change-offset', layer.offset(), false);
layer.batchDraw()
(appcontext, component) ->
exportableFunctions =
moveDelta: (delta) -> moveDelta(appcontext, component, delta)
moveForward: -> moveForward(appcontext, component)
moveBackward: -> moveBackward(appcontext, component)
moveToFront: -> moveToFront(appcontext, component)
moveToBack: -> moveToBack(appcontext, component)
offset: (position) -> offset(appcontext, component, position)
cut: -> cut(appcontext, component)
copy: -> copy(appcontext, component)
paste: -> paste(appcontext, component)
appcontext[name] = func for name, func of exportableFunctions
| true | # ==========================================
# Copyright 2014 PI:NAME:<NAME>END_PIatio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'../command/CommandPropertyChange'
'../command/CommandMove'
], (
CommandPropertyChange
CommandMove
) ->
_move = (appcontext, to) ->
view = appcontext.selectionManager.focus()
return if not view
appcontext.execute new CommandMove
to: to
view: view
model: appcontext.getAttachedModel(view)
moveForward = (appcontext) ->
_move appcontext, 'FORWARD'
moveBackward = (appcontext) ->
_move appcontext, 'BACKWARD'
moveToFront = (appcontext) ->
_move appcontext, 'FRONT'
moveToBack = (appcontext) ->
_move appcontext, 'BACK'
cut = (appcontext) ->
appcontext.clipboard.cut appcontext.selectionManager.get()
copy = (appcontext) ->
appcontext.clipboard.copy appcontext.selectionManager.get()
paste = (appcontext) ->
components = appcontext.clipboard.paste()
nodes = (appcontext.getAttachedModel(component) for component in components)
appcontext.selectionManager.select(nodes)
moveDelta = (appcontext, component, delta) ->
nodes = appcontext.selectionManager.get()
changes = []
for node in nodes
comp = appcontext.getAttachedModel(node)
before = {}
after = {}
for attr of delta
before[attr] = comp.get(attr)
after[attr] = comp.get(attr) + delta[attr]
changes.push
component : comp
before : before
after : after
appcontext.commandManager.execute(new CommandPropertyChange {
changes : changes
})
offset = (appcontext, component, position) ->
layer = component.getViews()[0]
layer.offset position
layer.fire('change-offset', layer.offset(), false);
layer.batchDraw()
(appcontext, component) ->
exportableFunctions =
moveDelta: (delta) -> moveDelta(appcontext, component, delta)
moveForward: -> moveForward(appcontext, component)
moveBackward: -> moveBackward(appcontext, component)
moveToFront: -> moveToFront(appcontext, component)
moveToBack: -> moveToBack(appcontext, component)
offset: (position) -> offset(appcontext, component, position)
cut: -> cut(appcontext, component)
copy: -> copy(appcontext, component)
paste: -> paste(appcontext, component)
appcontext[name] = func for name, func of exportableFunctions
|
[
{
"context": "ect(options.series[0]).to.be.eql {\n name: \"Показы\"\n pointStart: '2014-01-01'\n pointIn",
"end": 1925,
"score": 0.9768993854522705,
"start": 1919,
"tag": "NAME",
"value": "Показы"
},
{
"context": "ect(options.series[1]).to.be.eql {\n name:... | src/Vifeed/FrontendBundle/Tests/unit/analytics/services/chart-configurator.spec.coffee | bzis/zomba | 0 | describe 'ChartConfigurator', ->
'use strict'
beforeEach( -> module 'analytics' )
describe 'Service', ->
config = {}
expect = chai.expect
beforeEach(inject (ChartConfigurator) -> config = ChartConfigurator)
it 'should throw an error when period structure is not set', ->
fn = -> config.getConfig({})
expect(fn).to.throw /The property "period" is not set/
it 'should throw an error when zoomLevel option is not set', ->
fn = -> config.getConfig {
period: startDate: '2014-01-01', endDate: '2014-01-10'
}
expect(fn).to.throw /The property "zoomLevel" is not set/
it 'should throw an error when records option is not set', ->
fn = -> config.getConfig {
period: startDate: '2014-01-01', endDate: '2014-01-10'
zoomLevel: 1
}
expect(fn).to.throw /The property "records" is not set/
it 'should throw an error when records option is not an array', ->
fn = -> config.getConfig {
period: startDate: '2014-01-01', endDate: '2014-01-10'
zoomLevel: 1
records: {}
}
expect(fn).to.throw /The property "records" must be an array/
it 'should return config structure when valid period in days is set', ->
options = config.getConfig {
period:
startDate: '2014-01-01', endDate: '2014-01-03'
zoomLevel: 1
records: [
{"views":"3291","paid_views":"2749","date":"2014-01-01"},
{"views":"1020","paid_views":"858","date":"2014-01-02"},
{"views":"128","paid_views":"107","date":"2014-01-03"}
]
}
expect(options).to.be.instanceof Object
expect(options).to.have.ownProperty 'options'
expect(options).to.have.ownProperty 'series'
expect(options.series).to.be.instanceof Array
expect(options.series).to.have.length 2
expect(options.series[0]).to.be.eql {
name: "Показы"
pointStart: '2014-01-01'
pointInterval: 24 * 3600000
data: [['January 1, 2014', 3291], ['January 2, 2014', 1020], ['January 3, 2014', 128]]
}
expect(options.series[1]).to.be.eql {
name: "Просмотры"
pointStart: '2014-01-01'
pointInterval: 24 * 3600000
data: [['January 1, 2014', 2749], ['January 2, 2014', 858], ['January 3, 2014', 107]]
}
expect(options).to.have.ownProperty 'title'
expect(options).to.have.ownProperty 'credits'
expect(options).to.have.ownProperty 'loading'
it 'should return config structure when valid period in hours is set', ->
options = config.getConfig {
hourly: true
period:
startDate: '2014-01-01', endDate: '2014-01-01'
zoomLevel: 1
records: [
{"views":"3291","paid_views":"2749","hour":"1"},
{"views":"1020","paid_views":"858","hour":"5"},
{"views":"128","paid_views":"107","hour":"10"}
]
}
expect(options).to.be.instanceof Object
expect(options).to.have.ownProperty 'options'
expect(options).to.have.ownProperty 'series'
expect(options.series).to.be.instanceof Array
expect(options.series).to.have.length 2
expect(options.series[0]).to.be.eql {
name: "Показы"
pointStart: '2014-01-01'
pointInterval: 3600000
data: [
['00:00', 0], ['01:00', 3291], ['02:00', 0]
['03:00', 0], ['04:00', 0], ['05:00', 1020]
['06:00', 0], ['07:00', 0], ['08:00', 0]
['09:00', 0], ['10:00', 128], ['11:00', 0]
['12:00', 0], ['13:00', 0], ['14:00', 0]
['15:00', 0], ['16:00', 0], ['17:00', 0]
['18:00', 0], ['19:00', 0], ['20:00', 0]
['21:00', 0], ['22:00', 0], ['23:00', 0]
]
}
expect(options.series[1]).to.be.eql {
name: "Просмотры"
pointStart: '2014-01-01'
pointInterval: 3600000
data: [
['00:00', 0], ['01:00', 2749], ['02:00', 0]
['03:00', 0], ['04:00', 0], ['05:00', 858]
['06:00', 0], ['07:00', 0], ['08:00', 0]
['09:00', 0], ['10:00', 107], ['11:00', 0]
['12:00', 0], ['13:00', 0], ['14:00', 0]
['15:00', 0], ['16:00', 0], ['17:00', 0]
['18:00', 0], ['19:00', 0], ['20:00', 0]
['21:00', 0], ['22:00', 0], ['23:00', 0]
]
}
expect(options).to.have.ownProperty 'title'
expect(options).to.have.ownProperty 'credits'
expect(options).to.have.ownProperty 'loading'
| 45974 | describe 'ChartConfigurator', ->
'use strict'
beforeEach( -> module 'analytics' )
describe 'Service', ->
config = {}
expect = chai.expect
beforeEach(inject (ChartConfigurator) -> config = ChartConfigurator)
it 'should throw an error when period structure is not set', ->
fn = -> config.getConfig({})
expect(fn).to.throw /The property "period" is not set/
it 'should throw an error when zoomLevel option is not set', ->
fn = -> config.getConfig {
period: startDate: '2014-01-01', endDate: '2014-01-10'
}
expect(fn).to.throw /The property "zoomLevel" is not set/
it 'should throw an error when records option is not set', ->
fn = -> config.getConfig {
period: startDate: '2014-01-01', endDate: '2014-01-10'
zoomLevel: 1
}
expect(fn).to.throw /The property "records" is not set/
it 'should throw an error when records option is not an array', ->
fn = -> config.getConfig {
period: startDate: '2014-01-01', endDate: '2014-01-10'
zoomLevel: 1
records: {}
}
expect(fn).to.throw /The property "records" must be an array/
it 'should return config structure when valid period in days is set', ->
options = config.getConfig {
period:
startDate: '2014-01-01', endDate: '2014-01-03'
zoomLevel: 1
records: [
{"views":"3291","paid_views":"2749","date":"2014-01-01"},
{"views":"1020","paid_views":"858","date":"2014-01-02"},
{"views":"128","paid_views":"107","date":"2014-01-03"}
]
}
expect(options).to.be.instanceof Object
expect(options).to.have.ownProperty 'options'
expect(options).to.have.ownProperty 'series'
expect(options.series).to.be.instanceof Array
expect(options.series).to.have.length 2
expect(options.series[0]).to.be.eql {
name: "<NAME>"
pointStart: '2014-01-01'
pointInterval: 24 * 3600000
data: [['January 1, 2014', 3291], ['January 2, 2014', 1020], ['January 3, 2014', 128]]
}
expect(options.series[1]).to.be.eql {
name: "<NAME>"
pointStart: '2014-01-01'
pointInterval: 24 * 3600000
data: [['January 1, 2014', 2749], ['January 2, 2014', 858], ['January 3, 2014', 107]]
}
expect(options).to.have.ownProperty 'title'
expect(options).to.have.ownProperty 'credits'
expect(options).to.have.ownProperty 'loading'
it 'should return config structure when valid period in hours is set', ->
options = config.getConfig {
hourly: true
period:
startDate: '2014-01-01', endDate: '2014-01-01'
zoomLevel: 1
records: [
{"views":"3291","paid_views":"2749","hour":"1"},
{"views":"1020","paid_views":"858","hour":"5"},
{"views":"128","paid_views":"107","hour":"10"}
]
}
expect(options).to.be.instanceof Object
expect(options).to.have.ownProperty 'options'
expect(options).to.have.ownProperty 'series'
expect(options.series).to.be.instanceof Array
expect(options.series).to.have.length 2
expect(options.series[0]).to.be.eql {
name: "<NAME>"
pointStart: '2014-01-01'
pointInterval: 3600000
data: [
['00:00', 0], ['01:00', 3291], ['02:00', 0]
['03:00', 0], ['04:00', 0], ['05:00', 1020]
['06:00', 0], ['07:00', 0], ['08:00', 0]
['09:00', 0], ['10:00', 128], ['11:00', 0]
['12:00', 0], ['13:00', 0], ['14:00', 0]
['15:00', 0], ['16:00', 0], ['17:00', 0]
['18:00', 0], ['19:00', 0], ['20:00', 0]
['21:00', 0], ['22:00', 0], ['23:00', 0]
]
}
expect(options.series[1]).to.be.eql {
name: "<NAME>"
pointStart: '2014-01-01'
pointInterval: 3600000
data: [
['00:00', 0], ['01:00', 2749], ['02:00', 0]
['03:00', 0], ['04:00', 0], ['05:00', 858]
['06:00', 0], ['07:00', 0], ['08:00', 0]
['09:00', 0], ['10:00', 107], ['11:00', 0]
['12:00', 0], ['13:00', 0], ['14:00', 0]
['15:00', 0], ['16:00', 0], ['17:00', 0]
['18:00', 0], ['19:00', 0], ['20:00', 0]
['21:00', 0], ['22:00', 0], ['23:00', 0]
]
}
expect(options).to.have.ownProperty 'title'
expect(options).to.have.ownProperty 'credits'
expect(options).to.have.ownProperty 'loading'
| true | describe 'ChartConfigurator', ->
'use strict'
beforeEach( -> module 'analytics' )
describe 'Service', ->
config = {}
expect = chai.expect
beforeEach(inject (ChartConfigurator) -> config = ChartConfigurator)
it 'should throw an error when period structure is not set', ->
fn = -> config.getConfig({})
expect(fn).to.throw /The property "period" is not set/
it 'should throw an error when zoomLevel option is not set', ->
fn = -> config.getConfig {
period: startDate: '2014-01-01', endDate: '2014-01-10'
}
expect(fn).to.throw /The property "zoomLevel" is not set/
it 'should throw an error when records option is not set', ->
fn = -> config.getConfig {
period: startDate: '2014-01-01', endDate: '2014-01-10'
zoomLevel: 1
}
expect(fn).to.throw /The property "records" is not set/
it 'should throw an error when records option is not an array', ->
fn = -> config.getConfig {
period: startDate: '2014-01-01', endDate: '2014-01-10'
zoomLevel: 1
records: {}
}
expect(fn).to.throw /The property "records" must be an array/
it 'should return config structure when valid period in days is set', ->
options = config.getConfig {
period:
startDate: '2014-01-01', endDate: '2014-01-03'
zoomLevel: 1
records: [
{"views":"3291","paid_views":"2749","date":"2014-01-01"},
{"views":"1020","paid_views":"858","date":"2014-01-02"},
{"views":"128","paid_views":"107","date":"2014-01-03"}
]
}
expect(options).to.be.instanceof Object
expect(options).to.have.ownProperty 'options'
expect(options).to.have.ownProperty 'series'
expect(options.series).to.be.instanceof Array
expect(options.series).to.have.length 2
expect(options.series[0]).to.be.eql {
name: "PI:NAME:<NAME>END_PI"
pointStart: '2014-01-01'
pointInterval: 24 * 3600000
data: [['January 1, 2014', 3291], ['January 2, 2014', 1020], ['January 3, 2014', 128]]
}
expect(options.series[1]).to.be.eql {
name: "PI:NAME:<NAME>END_PI"
pointStart: '2014-01-01'
pointInterval: 24 * 3600000
data: [['January 1, 2014', 2749], ['January 2, 2014', 858], ['January 3, 2014', 107]]
}
expect(options).to.have.ownProperty 'title'
expect(options).to.have.ownProperty 'credits'
expect(options).to.have.ownProperty 'loading'
it 'should return config structure when valid period in hours is set', ->
options = config.getConfig {
hourly: true
period:
startDate: '2014-01-01', endDate: '2014-01-01'
zoomLevel: 1
records: [
{"views":"3291","paid_views":"2749","hour":"1"},
{"views":"1020","paid_views":"858","hour":"5"},
{"views":"128","paid_views":"107","hour":"10"}
]
}
expect(options).to.be.instanceof Object
expect(options).to.have.ownProperty 'options'
expect(options).to.have.ownProperty 'series'
expect(options.series).to.be.instanceof Array
expect(options.series).to.have.length 2
expect(options.series[0]).to.be.eql {
name: "PI:NAME:<NAME>END_PI"
pointStart: '2014-01-01'
pointInterval: 3600000
data: [
['00:00', 0], ['01:00', 3291], ['02:00', 0]
['03:00', 0], ['04:00', 0], ['05:00', 1020]
['06:00', 0], ['07:00', 0], ['08:00', 0]
['09:00', 0], ['10:00', 128], ['11:00', 0]
['12:00', 0], ['13:00', 0], ['14:00', 0]
['15:00', 0], ['16:00', 0], ['17:00', 0]
['18:00', 0], ['19:00', 0], ['20:00', 0]
['21:00', 0], ['22:00', 0], ['23:00', 0]
]
}
expect(options.series[1]).to.be.eql {
name: "PI:NAME:<NAME>END_PI"
pointStart: '2014-01-01'
pointInterval: 3600000
data: [
['00:00', 0], ['01:00', 2749], ['02:00', 0]
['03:00', 0], ['04:00', 0], ['05:00', 858]
['06:00', 0], ['07:00', 0], ['08:00', 0]
['09:00', 0], ['10:00', 107], ['11:00', 0]
['12:00', 0], ['13:00', 0], ['14:00', 0]
['15:00', 0], ['16:00', 0], ['17:00', 0]
['18:00', 0], ['19:00', 0], ['20:00', 0]
['21:00', 0], ['22:00', 0], ['23:00', 0]
]
}
expect(options).to.have.ownProperty 'title'
expect(options).to.have.ownProperty 'credits'
expect(options).to.have.ownProperty 'loading'
|
[
{
"context": "lize(\"publisher\")\n\t\t@getId = -> id\n\t\t@getName = -> name\n\t\t@startWeek = undefined\n\t\t@retireWeek = undefine",
"end": 658,
"score": 0.6281317472457886,
"start": 654,
"tag": "NAME",
"value": "name"
},
{
"context": "(id)\n\t\t@getId = -> id\n\t\t{\n\t\t\tid: @g... | coffee/api/objects/publisher.coffee | Spartan322/Spartan-Dev-Project | 1 | SDP.GDT.__notUniquePublisher = (id) ->
item = {id: id}
not Checks.checkUniqueness(item, 'id', ProjectContracts.getAllPublishers())
class SDP.GDT.Publisher
topicOverride: []
platformOverride: []
genreWeightings: SDP.GDT.Weight.Default()
audWeightings: SDP.GDT.Weight.Default(false)
constructor: (name, id = name) ->
if SDP.GDT.Company? and name instanceof SDP.GDT.Company
@getCompany = -> name
id = name.getId()
name = name.getName()
else if name? and typeof name is 'object'
name.isPrimitive = true
@getCompany = -> name
id = name.id
name = name.name
name = name.localize("publisher")
@getId = -> id
@getName = -> name
@startWeek = undefined
@retireWeek = undefined
addTopicOverride: (id, weight) =>
@topicOverride.push {id: id, weight: weight.clamp(0,1)} if Topics.topics.findIndex((val) -> val.id is id) isnt -1
addPlatformOverride: (id, weight) =>
@platformOverride.push {id: id, weight: weight.clamp(0,1)} if Platforms.allPlatforms.findIndex((val) -> val.id is id) isnt -1
setWeight: (weight) =>
@genreWeightings = weight if weight.isGenre()
@audWeightings = weight if weight.isAudience()
toString: => @getName()
getAudience: (random) =>
auds = SDP.Enum.Audience.toArray()
auds.forEach (val, i, arr) -> arr.push(val, val)
for a in SDP.Enum.Audience.toArray()
v = Math.floor(General.getAudienceWeighting(@audWeightings.get(), a)*10)-8
continue if Math.abs(v) > 2
while v > 0
auds.push(a)
v--
while v < 0
auds.splice(auds.findIndex((val) -> val is a), 1)
v++
auds.pickRandom(random)
getGenre: (random) =>
defGenres = SDP.Enum.Genre.toArray()
genres = SDP.Enum.Genre.toArray()
genres.forEach (val, i, arr) -> arr.push(val, val)
for g in defGenres
v = Math.floor(General.getGenreWeighting(@genreWeightings.get(), g)*10)-8
continue if Math.abs(v) > 2
while v > 0
genres.push(g)
v--
while v < 0
genres.splice(genres.findIndex((val) -> val is g), 1)
v++
genres.pickRandom(random)
getPlatform: (random, defPlats) =>
defPlats = defPlats.filter (p) -> @platformOverride.findIndex((v) -> v.id is p.id) isnt -1
return unless defPlats
platforms = defPlats.splice()
platforms.forEach (val, i, arr) -> arr.push(val, val)
for p in defPlats
v = Math.floor(@platformOverride.find((val) -> val.id is p.id).weight*10)-8
continue if Math.abs(v) > 2
while v > 0
platforms.push(p)
v--
while v < 0
platforms.splice(platforms.findIndex((val) -> val is g), 1)
v++
platforms.pickRandom(random)
getTopic: (random, defTopics) =>
defTopics = defTopics.filter (t) -> @topicOverride.findIndex((v) -> v.id is t.id) isnt -1
return unless defPlats
topics = defTopics.map (val) -> val
topics.forEach (val, i, arr) -> arr.push(val, val)
for p in defTopics
v = Math.floor(@topicOverride.find((val) -> val.id is p.id).weight*10)-8
continue if Math.abs(v) > 2
while v > 0
topics.push(p)
v--
while v < 0
topics.splice(topics.findIndex((val) -> val is g), 1)
v++
topics.pickRandom(random)
toInput: =>
id = @getId()
id += '_' while SDP.GDT.__notUniquePlatform(id)
@getId = -> id
{
id: @getId()
name: @getName()
isCompany: @getCompany()?
company: @getCompany()
getGenre: @getGenre
getAudience: @getAudience
getTopic: @getTopic
getPlatform: @getPlatform
} | 104164 | SDP.GDT.__notUniquePublisher = (id) ->
item = {id: id}
not Checks.checkUniqueness(item, 'id', ProjectContracts.getAllPublishers())
class SDP.GDT.Publisher
topicOverride: []
platformOverride: []
genreWeightings: SDP.GDT.Weight.Default()
audWeightings: SDP.GDT.Weight.Default(false)
constructor: (name, id = name) ->
if SDP.GDT.Company? and name instanceof SDP.GDT.Company
@getCompany = -> name
id = name.getId()
name = name.getName()
else if name? and typeof name is 'object'
name.isPrimitive = true
@getCompany = -> name
id = name.id
name = name.name
name = name.localize("publisher")
@getId = -> id
@getName = -> <NAME>
@startWeek = undefined
@retireWeek = undefined
addTopicOverride: (id, weight) =>
@topicOverride.push {id: id, weight: weight.clamp(0,1)} if Topics.topics.findIndex((val) -> val.id is id) isnt -1
addPlatformOverride: (id, weight) =>
@platformOverride.push {id: id, weight: weight.clamp(0,1)} if Platforms.allPlatforms.findIndex((val) -> val.id is id) isnt -1
setWeight: (weight) =>
@genreWeightings = weight if weight.isGenre()
@audWeightings = weight if weight.isAudience()
toString: => @getName()
getAudience: (random) =>
auds = SDP.Enum.Audience.toArray()
auds.forEach (val, i, arr) -> arr.push(val, val)
for a in SDP.Enum.Audience.toArray()
v = Math.floor(General.getAudienceWeighting(@audWeightings.get(), a)*10)-8
continue if Math.abs(v) > 2
while v > 0
auds.push(a)
v--
while v < 0
auds.splice(auds.findIndex((val) -> val is a), 1)
v++
auds.pickRandom(random)
getGenre: (random) =>
defGenres = SDP.Enum.Genre.toArray()
genres = SDP.Enum.Genre.toArray()
genres.forEach (val, i, arr) -> arr.push(val, val)
for g in defGenres
v = Math.floor(General.getGenreWeighting(@genreWeightings.get(), g)*10)-8
continue if Math.abs(v) > 2
while v > 0
genres.push(g)
v--
while v < 0
genres.splice(genres.findIndex((val) -> val is g), 1)
v++
genres.pickRandom(random)
getPlatform: (random, defPlats) =>
defPlats = defPlats.filter (p) -> @platformOverride.findIndex((v) -> v.id is p.id) isnt -1
return unless defPlats
platforms = defPlats.splice()
platforms.forEach (val, i, arr) -> arr.push(val, val)
for p in defPlats
v = Math.floor(@platformOverride.find((val) -> val.id is p.id).weight*10)-8
continue if Math.abs(v) > 2
while v > 0
platforms.push(p)
v--
while v < 0
platforms.splice(platforms.findIndex((val) -> val is g), 1)
v++
platforms.pickRandom(random)
getTopic: (random, defTopics) =>
defTopics = defTopics.filter (t) -> @topicOverride.findIndex((v) -> v.id is t.id) isnt -1
return unless defPlats
topics = defTopics.map (val) -> val
topics.forEach (val, i, arr) -> arr.push(val, val)
for p in defTopics
v = Math.floor(@topicOverride.find((val) -> val.id is p.id).weight*10)-8
continue if Math.abs(v) > 2
while v > 0
topics.push(p)
v--
while v < 0
topics.splice(topics.findIndex((val) -> val is g), 1)
v++
topics.pickRandom(random)
toInput: =>
id = @getId()
id += '_' while SDP.GDT.__notUniquePlatform(id)
@getId = -> id
{
id: @getId()
name:<NAME> @getName()
isCompany: @getCompany()?
company: @getCompany()
getGenre: @getGenre
getAudience: @getAudience
getTopic: @getTopic
getPlatform: @getPlatform
} | true | SDP.GDT.__notUniquePublisher = (id) ->
item = {id: id}
not Checks.checkUniqueness(item, 'id', ProjectContracts.getAllPublishers())
class SDP.GDT.Publisher
topicOverride: []
platformOverride: []
genreWeightings: SDP.GDT.Weight.Default()
audWeightings: SDP.GDT.Weight.Default(false)
constructor: (name, id = name) ->
if SDP.GDT.Company? and name instanceof SDP.GDT.Company
@getCompany = -> name
id = name.getId()
name = name.getName()
else if name? and typeof name is 'object'
name.isPrimitive = true
@getCompany = -> name
id = name.id
name = name.name
name = name.localize("publisher")
@getId = -> id
@getName = -> PI:NAME:<NAME>END_PI
@startWeek = undefined
@retireWeek = undefined
addTopicOverride: (id, weight) =>
@topicOverride.push {id: id, weight: weight.clamp(0,1)} if Topics.topics.findIndex((val) -> val.id is id) isnt -1
addPlatformOverride: (id, weight) =>
@platformOverride.push {id: id, weight: weight.clamp(0,1)} if Platforms.allPlatforms.findIndex((val) -> val.id is id) isnt -1
setWeight: (weight) =>
@genreWeightings = weight if weight.isGenre()
@audWeightings = weight if weight.isAudience()
toString: => @getName()
getAudience: (random) =>
auds = SDP.Enum.Audience.toArray()
auds.forEach (val, i, arr) -> arr.push(val, val)
for a in SDP.Enum.Audience.toArray()
v = Math.floor(General.getAudienceWeighting(@audWeightings.get(), a)*10)-8
continue if Math.abs(v) > 2
while v > 0
auds.push(a)
v--
while v < 0
auds.splice(auds.findIndex((val) -> val is a), 1)
v++
auds.pickRandom(random)
getGenre: (random) =>
defGenres = SDP.Enum.Genre.toArray()
genres = SDP.Enum.Genre.toArray()
genres.forEach (val, i, arr) -> arr.push(val, val)
for g in defGenres
v = Math.floor(General.getGenreWeighting(@genreWeightings.get(), g)*10)-8
continue if Math.abs(v) > 2
while v > 0
genres.push(g)
v--
while v < 0
genres.splice(genres.findIndex((val) -> val is g), 1)
v++
genres.pickRandom(random)
getPlatform: (random, defPlats) =>
defPlats = defPlats.filter (p) -> @platformOverride.findIndex((v) -> v.id is p.id) isnt -1
return unless defPlats
platforms = defPlats.splice()
platforms.forEach (val, i, arr) -> arr.push(val, val)
for p in defPlats
v = Math.floor(@platformOverride.find((val) -> val.id is p.id).weight*10)-8
continue if Math.abs(v) > 2
while v > 0
platforms.push(p)
v--
while v < 0
platforms.splice(platforms.findIndex((val) -> val is g), 1)
v++
platforms.pickRandom(random)
getTopic: (random, defTopics) =>
defTopics = defTopics.filter (t) -> @topicOverride.findIndex((v) -> v.id is t.id) isnt -1
return unless defPlats
topics = defTopics.map (val) -> val
topics.forEach (val, i, arr) -> arr.push(val, val)
for p in defTopics
v = Math.floor(@topicOverride.find((val) -> val.id is p.id).weight*10)-8
continue if Math.abs(v) > 2
while v > 0
topics.push(p)
v--
while v < 0
topics.splice(topics.findIndex((val) -> val is g), 1)
v++
topics.pickRandom(random)
toInput: =>
id = @getId()
id += '_' while SDP.GDT.__notUniquePlatform(id)
@getId = -> id
{
id: @getId()
name:PI:NAME:<NAME>END_PI @getName()
isCompany: @getCompany()?
company: @getCompany()
getGenre: @getGenre
getAudience: @getAudience
getTopic: @getTopic
getPlatform: @getPlatform
} |
[
{
"context": " protocol in protocols\n\n # check an ip addr. eg. 102.33.22.1\n ipReg = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]",
"end": 382,
"score": 0.9996681213378906,
"start": 371,
"tag": "IP_ADDRESS",
"value": "102.33.22.1"
}
] | common/coffee/utils.coffee | evecalm/MyWebrequest | 15 | ((root, factory)->
if typeof define is 'function' and (define.amd or define.cmd)
define ->
factory root
else if typeof exports is 'object'
module.exports = factory root
else
root.utils = factory root
return
)(this, (root) ->
protocols = [ '*', 'https', 'http']
isProtocol = (protocol)->
protocol in protocols
# check an ip addr. eg. 102.33.22.1
ipReg = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$/
isIp = (ip)->
ipReg.test ip
# check a host. eg. google.com, dev.fb.com, etc.
# top level domain's length extend to 10
# for there are so many new TLDs have long names, like .software
hostReg = /^(\*((\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,4})?|([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,10})$/
isHost = (host)->
hostReg.test host
# check a path. eg. path/subpath/file.html?querystring
pathReg = /^[a-z0-9-_\+=&%@!\.,\*\?\|~\/]+$/i
isPath = (path)->
pathReg.test path
# reg to match protocol, host, path, query
urlComponentReg = /^(\*|\w+):\/\/([^/]+)\/([^?]*)(\?(.*))?$/
isUrl = (url)->
matches = urlComponentReg.exec url
return false unless matches
return false unless isProtocol matches[1]
return false unless isHost( matches[2] ) or isIp( matches[2] )
path = matches[3] + matches[4]
return false unless isPath path
return true
###*
* get i18n text
* @param {String} msgid text label id
* @return {String}
###
i18n = (msgid)->
chrome.i18n.getMessage msgid
###*
* get object's values into an array
* @param {Object} o
* @return {Array}
###
getObjVals = (o)->
res = []
for own k, v of o
res.push v
res
# return undefined if valid or a error message
isRegValid = (reg)->
try
new RegExp reg
return
catch e
return e.message
###*
* GET url info url the clipboard, returns {protocol, host, path, search}
* @param {Event} e paste event
* @return {Object}
###
getUrlFromClipboard = (e)->
result = {}
url = e.originalEvent.clipboardData.getData 'text/plain'
return result unless url
# trim hash(search) in url
url = url.replace /#.*$/, ''
i = url.indexOf '://'
url = '*://' + url if i is -1
return result unless url.match urlComponentReg
# extract regexp results right now or things changed
result.protocol = RegExp.$1.toLowerCase()
result.host = RegExp.$2.toLowerCase()
result.path = RegExp.$3
result.search = RegExp.$4
result.raw = url
result
###*
* is rule coverring subRule
* like: *://*.g.com covers http://ad.g.com or http://*.g.com
* exmaple: to detect if a custom rule is conflicted with a block rule
###
isSubRule = (rule, subRule)->
matches = urlComponentReg.exec rule
prtl1 = matches[1]
url1 = matches[2] + matches[3]
matches = urlComponentReg.exec subRule
prtl2 = matches[1]
url2 = matches[2] + matches[3]
return false if prtl1 isnt '*' and prtl1 isnt prtl2
url1 = url1.replace escapeRegExp, '(?:\\$&)'
.replace /\*/g, '.*'
url1 = '^' + url1 + '$'
(new RegExp(url1)).test url2
# 获取URL的queryString
getQs = (url) ->
url = "#{url}".replace /#[^#]*$/, ''
matches = url.match /\?(.*)$/
if matches then matches[1] else ''
###*
* parse a query string into a key-value object
* @param {String} qs
* @return {Object}
###
parseQs = (qs)->
params = {}
canDecode = true
qs
.split '&'
.forEach (el)->
parts = el.split '='
k = parts[0]
v = parts[1] ? ''
if canDecode
try
k = decodeURIComponent k
v = decodeURIComponent v
catch e
canDecode = false
# combine array query param into an real array
if params[ k ]?
if not Array.isArray params[ k ]
params[ k ] = [ params[ k ] ]
params[ k ].push v
else
params[ k ] = v
params
###*
* convert key-val into an querysting: encode(key)=encode(val)
* if val is an array, there will be an auto conversion
* @param {String} key
* @param {String|Array} val
* @return {String}
###
toQueryString = (key, val)->
if Array.isArray val
try
key = decodeURIComponent key
key = key.replace(/[]$/, '') + '[]'
key = encodeURIComponent(key).replace '%20', '+'
catch e
"#{key}" + val.map (el)->
encodeURIComponent(el).replace '%20', '+'
.join "&#{key}="
else
val = encodeURIComponent(val).replace '%20', '+'
"#{key}=#{val}"
# get keywords list(array) in route object
getKwdsInRoute = (router)->
[].concat router.params, RESERVED_HOLDERS, getObjVals router.qsParams
###*
* is route string valid
* return false if invalid
* validate string like {abc}.user.com/{hous}/d.html?hah
* @param {String} route
* @return {Boolean}
###
isRouterStrValid = (route)->
# if the route doesnt has path and query string
# like http://g.cn
# then add a / in the end
route += '/' unless /\w\//.test route
matches = urlComponentReg.exec route
return false unless matches
protocol = matches[1]
# path is host + real path
path = matches[2] + '/' + matches[3]
# query string without prefix ?
qs = matches[5]
# path basic format
return false unless /^(\{\w+\}\.)*(\w+\.)+\w+\/(\{\w+\}|[a-z0-9-_\+=&%@!\.,\*\?\|~\/])*(\{\*\w+\})?$/.test path
# {*named} should only used in the end of the path
return false if /(\{\*\w+\}).+$/.test path
if qs
# query string basic format
return false unless /^(([\w_\+%@!\.,\*\?\|~\/]+=\{\w+\})|([\w_\+%@!\.,\*\?\|~\/]+=[\w_\+%@!\.,\*\?\|~\/]+)|&)*$/.test qs
# /\{\*\w+\}/ for {*named}, not allowed
# /[?&]\{\w+\}/ or ?{named} or &{named}, not allowd
# /\{\w+\}(?!&|$)/ for letter followed not & or eof
return false if /\{\*\w+\}/.test(qs) or /[?&]\{\w+\}/.test(qs) or /\{\w+\}(?!&|$)/.test qs
n = route.replace /\{\*?\w+\}/g, 'xxx'
isUrl n
# // http://www.baidu.com/{g}-{d}/{*abc}?abc={name}&youse={bcsd}
# // http://www.baidu.com/{g}-{d}/{*abc}?abc={name}&youse={bcsd}
# optionalParam = /\((.*?)\)/g
namedParam = /\{(\(\?)?(\w+)\}/g
splatParam = /\{\*(\w+)\}/g
# escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g
escapeRegExp = /[\-\[\]+?.,\\\^$|#\s]/g
queryStrReg = /([\w_\+%@!\.,\*\?\|~\/]+)=\{(\w+)\}/g
###*
* convert a url pattern to a regexp
* @param {String} route url match pattern
* @param {String} redirectUrl url redirect pattern
* @return {Object}
* {
* url: match url, which url will be captured used by chrome
* reg: regexp string can match an url & extract params
* matchUrl: source rule, aka the in-param route
* hasQs: has named params in query string
* params: two array of var name of each named param in path an querystring
* }
###
getRouter = (route, redirectUrl)->
result =
matchUrl: route
redirectUrl : redirectUrl
# if the route doesnt has path and query string
# like http://g.cn
# then add a / in the end
route += '/' unless /\w\//.test route
protocol = route.match /^([\w\*]+)\:\/\//
protocol = if protocol then protocol[1] else '*'
url = protocol + '://'
protocol = '\\w+' if protocol is '*'
# remove protocol
route = route.replace /^([\w\*]+)\:\/\//, ''
# replace query string with *
url += route.replace /\?.*$/, '*'
# replace named holder with * in host
.replace(/^[^\/]*(\.|\{\w+\}|\w+)*\.{\w+\}/, '*')
# replace named holder with * in path
.replace /\{\*?\w+\}.*$/, '*'
# add a asterisk to disable strict match
result.url = url.replace(/\*+$/, '') + '*'
parts = route.split '?'
# route contains more than one ?
if parts.length > 2 then return result
result.hasQs = parts.length is 2
params = []
# hand named params in path
part = parts[0].replace escapeRegExp, '\\$&'
# .replace optionalParam, '(?:$1)?'
.replace namedParam, (match, $1, $2)->
params.push $2
if $1 then match else '([^/?]+)'
.replace splatParam, (match, $1)->
params.push $1
'([^?]*)'
reg = "^#{protocol}:\\/\\/#{part}(?:\\?(.*))?"
result.reg = reg
result.params = params
# hand named params in query string
params = {}
if result.hasQs
parts[1].replace queryStrReg, ($0, $1, $2)->
try
$1 = decodeURIComponent $1
catch e
params[ $1 ] = $2
result.qsParams = params
result.hasQs = !!Object.keys(params).length
result
# pre-defined placeholders
RESERVED_HOLDERS = ['p', 'h', 'm', 'r', 'q', 'u']
# have reserved word in url pattern
# return a reserved words list that has been miss used.
hasReservedWord = (router)->
params = getKwdsInRoute router
res = []
for v in RESERVED_HOLDERS
if v in params or "%#{v}" in params or "=#{v}" in params
res.push v
# remove duplicated names
res = res.filter (v, k)->
k isnt res.indexOf v
return res if res.length
###*
* check the whether router's keywords are unique
* return undefined if valid
* return an array of duplicated names if found in params
* @param {Object} res result returned by getRouter
* @return {Boolean|Array|undefined}
###
isKwdsUniq = (router)->
params = getKwdsInRoute router
res = []
res = params.filter (v, k)-> k isnt params.indexOf v
if res.length
res
# get a list from redirect to url, eg. http://{sub}.github.com/{name}/{protol}
# %name mean encodeURIComponent name
# =name mean decodeURIComponent name
getRedirectParamList = (url)->
matches = url.match(/\{(\w+)\}/g) or []
matches.map (v)-> v.slice 1, -1
###*
* redirect rule valid
* @param {String} redirectUrl
* @return {Boolean}
###
isRedirectRuleValid = (redirectUrl)->
# redirectUrl is empty
return false unless redirectUrl
# no params found in redirect url
return false unless getRedirectParamList(redirectUrl).length
# remove param placeholder and check the url
# comment out this, the result url should be valid
# isUrl redirectUrl.replace(/^\{\w+\}/, '*').replace /^\{\w+\}/g, 'xxx'
return true
###*
* return undefined if no undefined word, or a list contains undefined words
* @param {Object} router a defined word list
* @param {String} url a url pattern that use words in refer
* @return {Array|undefined}
###
hasUndefinedWord = (router, url)->
params = getKwdsInRoute router
res = []
sample = getRedirectParamList url
for v in sample
res.push v if v not in params
if res.length
res
###*
* get a key-value object from the url which match the pattern
* @param {Object} r {reg: ..., params: ''} from getRouter
* @param {String} url a real url that match that pattern
* @return {Object}
###
getUrlValues = (r, url)->
res = {}
try
matches = (new RegExp(r.reg)).exec url
catch e
matches = ''
return null unless matches
# get path values
for v, k in r.params
res[ v ] = matches[ k + 1 ] or ''
# get query string values
if r.hasQs
qsParams = parseQs getQs url
for own k, v of r.qsParams
res[ v ] = qsParams[ k ] or ''
urlComponentReg.exec url
# keep protocol
res.p = RegExp.$1
# keep host
res.h = RegExp.$2
# main domain
res.m = res.h.split('.').slice(-2).join '.'
# path, without the prefix /
res.r = RegExp.$3
# query string without question mark
res.q = RegExp.$5
# the whole url
res.u = url
res
# fill a pattern with data
fillPattern = (pattern, data)->
pattern = pattern.replace /([\w\%+\[\]]+)=\{(\w+)\}/g, ($0, $1, $2)->
val = data[ $2 ] ? ''
toQueryString $1, val
url = pattern.replace /\{(\w+)\}/g, ($0, $1)->
val = data[ $1 ] ? ''
# / in val, like abc/bdc, won't be encoded
# q is query string, do not encode query string again
# u is url, encoded anywhere
if ( $1 isnt 'u' and ~val.indexOf('/')) or $1 is 'q' then val else encodeURIComponent val
url.replace /\?$/, ''
###*
* get target url
* @param {Object} router url pattern to match a url
* @param {String} url a real url that match route
* @return {String} converted url
###
getTargetUrl = (router, url)->
console.log 'getTargetUrl, router: %o, url: %s', router, url
params = getUrlValues router, url
console.log 'params in url: %o', params
return '' unless params
fillPattern router.redirectUrl, params
return {
isProtocol : isProtocol
isIp : isIp
isHost : isHost
isPath : isPath
isUrl : isUrl
i18n : i18n
isSubRule : isSubRule
getQs : getQs
parseQs : parseQs
isRouterStrValid : isRouterStrValid
getRouter : getRouter
getUrlValues : getUrlValues
isRegValid : isRegValid
isRedirectRuleValid : isRedirectRuleValid
hasUndefinedWord : hasUndefinedWord
isKwdsUniq : isKwdsUniq
hasReservedWord : hasReservedWord
getTargetUrl : getTargetUrl
getUrlFromClipboard : getUrlFromClipboard
}
) | 108381 | ((root, factory)->
if typeof define is 'function' and (define.amd or define.cmd)
define ->
factory root
else if typeof exports is 'object'
module.exports = factory root
else
root.utils = factory root
return
)(this, (root) ->
protocols = [ '*', 'https', 'http']
isProtocol = (protocol)->
protocol in protocols
# check an ip addr. eg. 192.168.127.12
ipReg = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$/
isIp = (ip)->
ipReg.test ip
# check a host. eg. google.com, dev.fb.com, etc.
# top level domain's length extend to 10
# for there are so many new TLDs have long names, like .software
hostReg = /^(\*((\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,4})?|([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,10})$/
isHost = (host)->
hostReg.test host
# check a path. eg. path/subpath/file.html?querystring
pathReg = /^[a-z0-9-_\+=&%@!\.,\*\?\|~\/]+$/i
isPath = (path)->
pathReg.test path
# reg to match protocol, host, path, query
urlComponentReg = /^(\*|\w+):\/\/([^/]+)\/([^?]*)(\?(.*))?$/
isUrl = (url)->
matches = urlComponentReg.exec url
return false unless matches
return false unless isProtocol matches[1]
return false unless isHost( matches[2] ) or isIp( matches[2] )
path = matches[3] + matches[4]
return false unless isPath path
return true
###*
* get i18n text
* @param {String} msgid text label id
* @return {String}
###
i18n = (msgid)->
chrome.i18n.getMessage msgid
###*
* get object's values into an array
* @param {Object} o
* @return {Array}
###
getObjVals = (o)->
res = []
for own k, v of o
res.push v
res
# return undefined if valid or a error message
isRegValid = (reg)->
try
new RegExp reg
return
catch e
return e.message
###*
* GET url info url the clipboard, returns {protocol, host, path, search}
* @param {Event} e paste event
* @return {Object}
###
getUrlFromClipboard = (e)->
result = {}
url = e.originalEvent.clipboardData.getData 'text/plain'
return result unless url
# trim hash(search) in url
url = url.replace /#.*$/, ''
i = url.indexOf '://'
url = '*://' + url if i is -1
return result unless url.match urlComponentReg
# extract regexp results right now or things changed
result.protocol = RegExp.$1.toLowerCase()
result.host = RegExp.$2.toLowerCase()
result.path = RegExp.$3
result.search = RegExp.$4
result.raw = url
result
###*
* is rule coverring subRule
* like: *://*.g.com covers http://ad.g.com or http://*.g.com
* exmaple: to detect if a custom rule is conflicted with a block rule
###
isSubRule = (rule, subRule)->
matches = urlComponentReg.exec rule
prtl1 = matches[1]
url1 = matches[2] + matches[3]
matches = urlComponentReg.exec subRule
prtl2 = matches[1]
url2 = matches[2] + matches[3]
return false if prtl1 isnt '*' and prtl1 isnt prtl2
url1 = url1.replace escapeRegExp, '(?:\\$&)'
.replace /\*/g, '.*'
url1 = '^' + url1 + '$'
(new RegExp(url1)).test url2
# 获取URL的queryString
getQs = (url) ->
url = "#{url}".replace /#[^#]*$/, ''
matches = url.match /\?(.*)$/
if matches then matches[1] else ''
###*
* parse a query string into a key-value object
* @param {String} qs
* @return {Object}
###
parseQs = (qs)->
params = {}
canDecode = true
qs
.split '&'
.forEach (el)->
parts = el.split '='
k = parts[0]
v = parts[1] ? ''
if canDecode
try
k = decodeURIComponent k
v = decodeURIComponent v
catch e
canDecode = false
# combine array query param into an real array
if params[ k ]?
if not Array.isArray params[ k ]
params[ k ] = [ params[ k ] ]
params[ k ].push v
else
params[ k ] = v
params
###*
* convert key-val into an querysting: encode(key)=encode(val)
* if val is an array, there will be an auto conversion
* @param {String} key
* @param {String|Array} val
* @return {String}
###
toQueryString = (key, val)->
if Array.isArray val
try
key = decodeURIComponent key
key = key.replace(/[]$/, '') + '[]'
key = encodeURIComponent(key).replace '%20', '+'
catch e
"#{key}" + val.map (el)->
encodeURIComponent(el).replace '%20', '+'
.join "&#{key}="
else
val = encodeURIComponent(val).replace '%20', '+'
"#{key}=#{val}"
# get keywords list(array) in route object
getKwdsInRoute = (router)->
[].concat router.params, RESERVED_HOLDERS, getObjVals router.qsParams
###*
* is route string valid
* return false if invalid
* validate string like {abc}.user.com/{hous}/d.html?hah
* @param {String} route
* @return {Boolean}
###
isRouterStrValid = (route)->
# if the route doesnt has path and query string
# like http://g.cn
# then add a / in the end
route += '/' unless /\w\//.test route
matches = urlComponentReg.exec route
return false unless matches
protocol = matches[1]
# path is host + real path
path = matches[2] + '/' + matches[3]
# query string without prefix ?
qs = matches[5]
# path basic format
return false unless /^(\{\w+\}\.)*(\w+\.)+\w+\/(\{\w+\}|[a-z0-9-_\+=&%@!\.,\*\?\|~\/])*(\{\*\w+\})?$/.test path
# {*named} should only used in the end of the path
return false if /(\{\*\w+\}).+$/.test path
if qs
# query string basic format
return false unless /^(([\w_\+%@!\.,\*\?\|~\/]+=\{\w+\})|([\w_\+%@!\.,\*\?\|~\/]+=[\w_\+%@!\.,\*\?\|~\/]+)|&)*$/.test qs
# /\{\*\w+\}/ for {*named}, not allowed
# /[?&]\{\w+\}/ or ?{named} or &{named}, not allowd
# /\{\w+\}(?!&|$)/ for letter followed not & or eof
return false if /\{\*\w+\}/.test(qs) or /[?&]\{\w+\}/.test(qs) or /\{\w+\}(?!&|$)/.test qs
n = route.replace /\{\*?\w+\}/g, 'xxx'
isUrl n
# // http://www.baidu.com/{g}-{d}/{*abc}?abc={name}&youse={bcsd}
# // http://www.baidu.com/{g}-{d}/{*abc}?abc={name}&youse={bcsd}
# optionalParam = /\((.*?)\)/g
namedParam = /\{(\(\?)?(\w+)\}/g
splatParam = /\{\*(\w+)\}/g
# escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g
escapeRegExp = /[\-\[\]+?.,\\\^$|#\s]/g
queryStrReg = /([\w_\+%@!\.,\*\?\|~\/]+)=\{(\w+)\}/g
###*
* convert a url pattern to a regexp
* @param {String} route url match pattern
* @param {String} redirectUrl url redirect pattern
* @return {Object}
* {
* url: match url, which url will be captured used by chrome
* reg: regexp string can match an url & extract params
* matchUrl: source rule, aka the in-param route
* hasQs: has named params in query string
* params: two array of var name of each named param in path an querystring
* }
###
getRouter = (route, redirectUrl)->
result =
matchUrl: route
redirectUrl : redirectUrl
# if the route doesnt has path and query string
# like http://g.cn
# then add a / in the end
route += '/' unless /\w\//.test route
protocol = route.match /^([\w\*]+)\:\/\//
protocol = if protocol then protocol[1] else '*'
url = protocol + '://'
protocol = '\\w+' if protocol is '*'
# remove protocol
route = route.replace /^([\w\*]+)\:\/\//, ''
# replace query string with *
url += route.replace /\?.*$/, '*'
# replace named holder with * in host
.replace(/^[^\/]*(\.|\{\w+\}|\w+)*\.{\w+\}/, '*')
# replace named holder with * in path
.replace /\{\*?\w+\}.*$/, '*'
# add a asterisk to disable strict match
result.url = url.replace(/\*+$/, '') + '*'
parts = route.split '?'
# route contains more than one ?
if parts.length > 2 then return result
result.hasQs = parts.length is 2
params = []
# hand named params in path
part = parts[0].replace escapeRegExp, '\\$&'
# .replace optionalParam, '(?:$1)?'
.replace namedParam, (match, $1, $2)->
params.push $2
if $1 then match else '([^/?]+)'
.replace splatParam, (match, $1)->
params.push $1
'([^?]*)'
reg = "^#{protocol}:\\/\\/#{part}(?:\\?(.*))?"
result.reg = reg
result.params = params
# hand named params in query string
params = {}
if result.hasQs
parts[1].replace queryStrReg, ($0, $1, $2)->
try
$1 = decodeURIComponent $1
catch e
params[ $1 ] = $2
result.qsParams = params
result.hasQs = !!Object.keys(params).length
result
# pre-defined placeholders
RESERVED_HOLDERS = ['p', 'h', 'm', 'r', 'q', 'u']
# have reserved word in url pattern
# return a reserved words list that has been miss used.
hasReservedWord = (router)->
params = getKwdsInRoute router
res = []
for v in RESERVED_HOLDERS
if v in params or "%#{v}" in params or "=#{v}" in params
res.push v
# remove duplicated names
res = res.filter (v, k)->
k isnt res.indexOf v
return res if res.length
###*
* check the whether router's keywords are unique
* return undefined if valid
* return an array of duplicated names if found in params
* @param {Object} res result returned by getRouter
* @return {Boolean|Array|undefined}
###
isKwdsUniq = (router)->
params = getKwdsInRoute router
res = []
res = params.filter (v, k)-> k isnt params.indexOf v
if res.length
res
# get a list from redirect to url, eg. http://{sub}.github.com/{name}/{protol}
# %name mean encodeURIComponent name
# =name mean decodeURIComponent name
getRedirectParamList = (url)->
matches = url.match(/\{(\w+)\}/g) or []
matches.map (v)-> v.slice 1, -1
###*
* redirect rule valid
* @param {String} redirectUrl
* @return {Boolean}
###
isRedirectRuleValid = (redirectUrl)->
# redirectUrl is empty
return false unless redirectUrl
# no params found in redirect url
return false unless getRedirectParamList(redirectUrl).length
# remove param placeholder and check the url
# comment out this, the result url should be valid
# isUrl redirectUrl.replace(/^\{\w+\}/, '*').replace /^\{\w+\}/g, 'xxx'
return true
###*
* return undefined if no undefined word, or a list contains undefined words
* @param {Object} router a defined word list
* @param {String} url a url pattern that use words in refer
* @return {Array|undefined}
###
hasUndefinedWord = (router, url)->
params = getKwdsInRoute router
res = []
sample = getRedirectParamList url
for v in sample
res.push v if v not in params
if res.length
res
###*
* get a key-value object from the url which match the pattern
* @param {Object} r {reg: ..., params: ''} from getRouter
* @param {String} url a real url that match that pattern
* @return {Object}
###
getUrlValues = (r, url)->
res = {}
try
matches = (new RegExp(r.reg)).exec url
catch e
matches = ''
return null unless matches
# get path values
for v, k in r.params
res[ v ] = matches[ k + 1 ] or ''
# get query string values
if r.hasQs
qsParams = parseQs getQs url
for own k, v of r.qsParams
res[ v ] = qsParams[ k ] or ''
urlComponentReg.exec url
# keep protocol
res.p = RegExp.$1
# keep host
res.h = RegExp.$2
# main domain
res.m = res.h.split('.').slice(-2).join '.'
# path, without the prefix /
res.r = RegExp.$3
# query string without question mark
res.q = RegExp.$5
# the whole url
res.u = url
res
# fill a pattern with data
fillPattern = (pattern, data)->
pattern = pattern.replace /([\w\%+\[\]]+)=\{(\w+)\}/g, ($0, $1, $2)->
val = data[ $2 ] ? ''
toQueryString $1, val
url = pattern.replace /\{(\w+)\}/g, ($0, $1)->
val = data[ $1 ] ? ''
# / in val, like abc/bdc, won't be encoded
# q is query string, do not encode query string again
# u is url, encoded anywhere
if ( $1 isnt 'u' and ~val.indexOf('/')) or $1 is 'q' then val else encodeURIComponent val
url.replace /\?$/, ''
###*
* get target url
* @param {Object} router url pattern to match a url
* @param {String} url a real url that match route
* @return {String} converted url
###
getTargetUrl = (router, url)->
console.log 'getTargetUrl, router: %o, url: %s', router, url
params = getUrlValues router, url
console.log 'params in url: %o', params
return '' unless params
fillPattern router.redirectUrl, params
return {
isProtocol : isProtocol
isIp : isIp
isHost : isHost
isPath : isPath
isUrl : isUrl
i18n : i18n
isSubRule : isSubRule
getQs : getQs
parseQs : parseQs
isRouterStrValid : isRouterStrValid
getRouter : getRouter
getUrlValues : getUrlValues
isRegValid : isRegValid
isRedirectRuleValid : isRedirectRuleValid
hasUndefinedWord : hasUndefinedWord
isKwdsUniq : isKwdsUniq
hasReservedWord : hasReservedWord
getTargetUrl : getTargetUrl
getUrlFromClipboard : getUrlFromClipboard
}
) | true | ((root, factory)->
if typeof define is 'function' and (define.amd or define.cmd)
define ->
factory root
else if typeof exports is 'object'
module.exports = factory root
else
root.utils = factory root
return
)(this, (root) ->
protocols = [ '*', 'https', 'http']
isProtocol = (protocol)->
protocol in protocols
# check an ip addr. eg. PI:IP_ADDRESS:192.168.127.12END_PI
ipReg = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$/
isIp = (ip)->
ipReg.test ip
# check a host. eg. google.com, dev.fb.com, etc.
# top level domain's length extend to 10
# for there are so many new TLDs have long names, like .software
hostReg = /^(\*((\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*\.[a-z]{2,4})?|([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,10})$/
isHost = (host)->
hostReg.test host
# check a path. eg. path/subpath/file.html?querystring
pathReg = /^[a-z0-9-_\+=&%@!\.,\*\?\|~\/]+$/i
isPath = (path)->
pathReg.test path
# reg to match protocol, host, path, query
urlComponentReg = /^(\*|\w+):\/\/([^/]+)\/([^?]*)(\?(.*))?$/
isUrl = (url)->
matches = urlComponentReg.exec url
return false unless matches
return false unless isProtocol matches[1]
return false unless isHost( matches[2] ) or isIp( matches[2] )
path = matches[3] + matches[4]
return false unless isPath path
return true
###*
* get i18n text
* @param {String} msgid text label id
* @return {String}
###
i18n = (msgid)->
chrome.i18n.getMessage msgid
###*
* get object's values into an array
* @param {Object} o
* @return {Array}
###
getObjVals = (o)->
res = []
for own k, v of o
res.push v
res
# return undefined if valid or a error message
isRegValid = (reg)->
try
new RegExp reg
return
catch e
return e.message
###*
* GET url info url the clipboard, returns {protocol, host, path, search}
* @param {Event} e paste event
* @return {Object}
###
getUrlFromClipboard = (e)->
result = {}
url = e.originalEvent.clipboardData.getData 'text/plain'
return result unless url
# trim hash(search) in url
url = url.replace /#.*$/, ''
i = url.indexOf '://'
url = '*://' + url if i is -1
return result unless url.match urlComponentReg
# extract regexp results right now or things changed
result.protocol = RegExp.$1.toLowerCase()
result.host = RegExp.$2.toLowerCase()
result.path = RegExp.$3
result.search = RegExp.$4
result.raw = url
result
###*
* is rule coverring subRule
* like: *://*.g.com covers http://ad.g.com or http://*.g.com
* exmaple: to detect if a custom rule is conflicted with a block rule
###
isSubRule = (rule, subRule)->
matches = urlComponentReg.exec rule
prtl1 = matches[1]
url1 = matches[2] + matches[3]
matches = urlComponentReg.exec subRule
prtl2 = matches[1]
url2 = matches[2] + matches[3]
return false if prtl1 isnt '*' and prtl1 isnt prtl2
url1 = url1.replace escapeRegExp, '(?:\\$&)'
.replace /\*/g, '.*'
url1 = '^' + url1 + '$'
(new RegExp(url1)).test url2
# 获取URL的queryString
getQs = (url) ->
url = "#{url}".replace /#[^#]*$/, ''
matches = url.match /\?(.*)$/
if matches then matches[1] else ''
###*
* parse a query string into a key-value object
* @param {String} qs
* @return {Object}
###
parseQs = (qs)->
params = {}
canDecode = true
qs
.split '&'
.forEach (el)->
parts = el.split '='
k = parts[0]
v = parts[1] ? ''
if canDecode
try
k = decodeURIComponent k
v = decodeURIComponent v
catch e
canDecode = false
# combine array query param into an real array
if params[ k ]?
if not Array.isArray params[ k ]
params[ k ] = [ params[ k ] ]
params[ k ].push v
else
params[ k ] = v
params
###*
* convert key-val into an querysting: encode(key)=encode(val)
* if val is an array, there will be an auto conversion
* @param {String} key
* @param {String|Array} val
* @return {String}
###
toQueryString = (key, val)->
if Array.isArray val
try
key = decodeURIComponent key
key = key.replace(/[]$/, '') + '[]'
key = encodeURIComponent(key).replace '%20', '+'
catch e
"#{key}" + val.map (el)->
encodeURIComponent(el).replace '%20', '+'
.join "&#{key}="
else
val = encodeURIComponent(val).replace '%20', '+'
"#{key}=#{val}"
# get keywords list(array) in route object
getKwdsInRoute = (router)->
[].concat router.params, RESERVED_HOLDERS, getObjVals router.qsParams
###*
* is route string valid
* return false if invalid
* validate string like {abc}.user.com/{hous}/d.html?hah
* @param {String} route
* @return {Boolean}
###
isRouterStrValid = (route)->
# if the route doesnt has path and query string
# like http://g.cn
# then add a / in the end
route += '/' unless /\w\//.test route
matches = urlComponentReg.exec route
return false unless matches
protocol = matches[1]
# path is host + real path
path = matches[2] + '/' + matches[3]
# query string without prefix ?
qs = matches[5]
# path basic format
return false unless /^(\{\w+\}\.)*(\w+\.)+\w+\/(\{\w+\}|[a-z0-9-_\+=&%@!\.,\*\?\|~\/])*(\{\*\w+\})?$/.test path
# {*named} should only used in the end of the path
return false if /(\{\*\w+\}).+$/.test path
if qs
# query string basic format
return false unless /^(([\w_\+%@!\.,\*\?\|~\/]+=\{\w+\})|([\w_\+%@!\.,\*\?\|~\/]+=[\w_\+%@!\.,\*\?\|~\/]+)|&)*$/.test qs
# /\{\*\w+\}/ for {*named}, not allowed
# /[?&]\{\w+\}/ or ?{named} or &{named}, not allowd
# /\{\w+\}(?!&|$)/ for letter followed not & or eof
return false if /\{\*\w+\}/.test(qs) or /[?&]\{\w+\}/.test(qs) or /\{\w+\}(?!&|$)/.test qs
n = route.replace /\{\*?\w+\}/g, 'xxx'
isUrl n
# // http://www.baidu.com/{g}-{d}/{*abc}?abc={name}&youse={bcsd}
# // http://www.baidu.com/{g}-{d}/{*abc}?abc={name}&youse={bcsd}
# optionalParam = /\((.*?)\)/g
namedParam = /\{(\(\?)?(\w+)\}/g
splatParam = /\{\*(\w+)\}/g
# escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g
escapeRegExp = /[\-\[\]+?.,\\\^$|#\s]/g
queryStrReg = /([\w_\+%@!\.,\*\?\|~\/]+)=\{(\w+)\}/g
###*
* convert a url pattern to a regexp
* @param {String} route url match pattern
* @param {String} redirectUrl url redirect pattern
* @return {Object}
* {
* url: match url, which url will be captured used by chrome
* reg: regexp string can match an url & extract params
* matchUrl: source rule, aka the in-param route
* hasQs: has named params in query string
* params: two array of var name of each named param in path an querystring
* }
###
getRouter = (route, redirectUrl)->
result =
matchUrl: route
redirectUrl : redirectUrl
# if the route doesnt has path and query string
# like http://g.cn
# then add a / in the end
route += '/' unless /\w\//.test route
protocol = route.match /^([\w\*]+)\:\/\//
protocol = if protocol then protocol[1] else '*'
url = protocol + '://'
protocol = '\\w+' if protocol is '*'
# remove protocol
route = route.replace /^([\w\*]+)\:\/\//, ''
# replace query string with *
url += route.replace /\?.*$/, '*'
# replace named holder with * in host
.replace(/^[^\/]*(\.|\{\w+\}|\w+)*\.{\w+\}/, '*')
# replace named holder with * in path
.replace /\{\*?\w+\}.*$/, '*'
# add a asterisk to disable strict match
result.url = url.replace(/\*+$/, '') + '*'
parts = route.split '?'
# route contains more than one ?
if parts.length > 2 then return result
result.hasQs = parts.length is 2
params = []
# hand named params in path
part = parts[0].replace escapeRegExp, '\\$&'
# .replace optionalParam, '(?:$1)?'
.replace namedParam, (match, $1, $2)->
params.push $2
if $1 then match else '([^/?]+)'
.replace splatParam, (match, $1)->
params.push $1
'([^?]*)'
reg = "^#{protocol}:\\/\\/#{part}(?:\\?(.*))?"
result.reg = reg
result.params = params
# hand named params in query string
params = {}
if result.hasQs
parts[1].replace queryStrReg, ($0, $1, $2)->
try
$1 = decodeURIComponent $1
catch e
params[ $1 ] = $2
result.qsParams = params
result.hasQs = !!Object.keys(params).length
result
# pre-defined placeholders
RESERVED_HOLDERS = ['p', 'h', 'm', 'r', 'q', 'u']
# have reserved word in url pattern
# return a reserved words list that has been miss used.
hasReservedWord = (router)->
params = getKwdsInRoute router
res = []
for v in RESERVED_HOLDERS
if v in params or "%#{v}" in params or "=#{v}" in params
res.push v
# remove duplicated names
res = res.filter (v, k)->
k isnt res.indexOf v
return res if res.length
###*
* check the whether router's keywords are unique
* return undefined if valid
* return an array of duplicated names if found in params
* @param {Object} res result returned by getRouter
* @return {Boolean|Array|undefined}
###
isKwdsUniq = (router)->
params = getKwdsInRoute router
res = []
res = params.filter (v, k)-> k isnt params.indexOf v
if res.length
res
# get a list from redirect to url, eg. http://{sub}.github.com/{name}/{protol}
# %name mean encodeURIComponent name
# =name mean decodeURIComponent name
getRedirectParamList = (url)->
matches = url.match(/\{(\w+)\}/g) or []
matches.map (v)-> v.slice 1, -1
###*
* redirect rule valid
* @param {String} redirectUrl
* @return {Boolean}
###
isRedirectRuleValid = (redirectUrl)->
# redirectUrl is empty
return false unless redirectUrl
# no params found in redirect url
return false unless getRedirectParamList(redirectUrl).length
# remove param placeholder and check the url
# comment out this, the result url should be valid
# isUrl redirectUrl.replace(/^\{\w+\}/, '*').replace /^\{\w+\}/g, 'xxx'
return true
###*
* return undefined if no undefined word, or a list contains undefined words
* @param {Object} router a defined word list
* @param {String} url a url pattern that use words in refer
* @return {Array|undefined}
###
hasUndefinedWord = (router, url)->
params = getKwdsInRoute router
res = []
sample = getRedirectParamList url
for v in sample
res.push v if v not in params
if res.length
res
###*
* get a key-value object from the url which match the pattern
* @param {Object} r {reg: ..., params: ''} from getRouter
* @param {String} url a real url that match that pattern
* @return {Object}
###
getUrlValues = (r, url)->
res = {}
try
matches = (new RegExp(r.reg)).exec url
catch e
matches = ''
return null unless matches
# get path values
for v, k in r.params
res[ v ] = matches[ k + 1 ] or ''
# get query string values
if r.hasQs
qsParams = parseQs getQs url
for own k, v of r.qsParams
res[ v ] = qsParams[ k ] or ''
urlComponentReg.exec url
# keep protocol
res.p = RegExp.$1
# keep host
res.h = RegExp.$2
# main domain
res.m = res.h.split('.').slice(-2).join '.'
# path, without the prefix /
res.r = RegExp.$3
# query string without question mark
res.q = RegExp.$5
# the whole url
res.u = url
res
# fill a pattern with data
fillPattern = (pattern, data)->
pattern = pattern.replace /([\w\%+\[\]]+)=\{(\w+)\}/g, ($0, $1, $2)->
val = data[ $2 ] ? ''
toQueryString $1, val
url = pattern.replace /\{(\w+)\}/g, ($0, $1)->
val = data[ $1 ] ? ''
# / in val, like abc/bdc, won't be encoded
# q is query string, do not encode query string again
# u is url, encoded anywhere
if ( $1 isnt 'u' and ~val.indexOf('/')) or $1 is 'q' then val else encodeURIComponent val
url.replace /\?$/, ''
###*
* get target url
* @param {Object} router url pattern to match a url
* @param {String} url a real url that match route
* @return {String} converted url
###
getTargetUrl = (router, url)->
console.log 'getTargetUrl, router: %o, url: %s', router, url
params = getUrlValues router, url
console.log 'params in url: %o', params
return '' unless params
fillPattern router.redirectUrl, params
return {
isProtocol : isProtocol
isIp : isIp
isHost : isHost
isPath : isPath
isUrl : isUrl
i18n : i18n
isSubRule : isSubRule
getQs : getQs
parseQs : parseQs
isRouterStrValid : isRouterStrValid
getRouter : getRouter
getUrlValues : getUrlValues
isRegValid : isRegValid
isRedirectRuleValid : isRedirectRuleValid
hasUndefinedWord : hasUndefinedWord
isKwdsUniq : isKwdsUniq
hasReservedWord : hasReservedWord
getTargetUrl : getTargetUrl
getUrlFromClipboard : getUrlFromClipboard
}
) |
[
{
"context": "###\n# express.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# This module do",
"end": 43,
"score": 0.9997939467430115,
"start": 32,
"tag": "NAME",
"value": "Dan Nichols"
}
] | lib/express.coffee | dlnichols/h_media | 0 | ###
# express.coffee
#
# © 2014 Dan Nichols
# See LICENSE for more details
#
# This module does all of our express configuration, except routing (that's in
# a separate module).
###
'use strict'
# External libs
path = require 'path'
express = require 'express'
session = require 'express-session'
logger = require 'morgan'
parser = require 'body-parser'
cookies = require 'cookie-parser'
mongo = require('connect-mongo') session
debug = require('debug') 'hMedia:express'
# Internal libs
env = require './config/environment'
passport = require './passport'
errors = require './errors'
routes = require './routes'
# Middleware
disableCache = require './middleware/disable_cache'
###
# Express configuration
###
debug 'Configuring express...'
module.exports = exports = (app) ->
# Inform express that it is behind a reverse proxy
app.enable 'trust proxy'
# Development specific config
#app.configure 'development', ->
if env.isDevelopment()
app.use require('connect-livereload')()
app.use disableCache
app.use express.static(path.join(env.root, '.tmp'))
app.use express.static(path.join(env.root, 'app'))
app.set 'views', env.root + '/app/views'
if env.isTest()
app.use express.static(path.join(env.root, '.tmp'))
app.use express.static(path.join(env.root, 'app'))
app.set 'views', env.root + '/app/views'
# Config for all environments
app.engine 'html', require('ejs').renderFile
app.set 'view engine', 'html'
if env.logger
app.use logger(env.logger)
app.use parser.json()
app.use cookies()
# Persist sessions with mongo
app.use session {
secret: env.secrets.session
store: new mongo(
url: env.mongo.uri
collection: 'sessions'
, ->
debug 'Mongo connection for session storage open.'
)
resave: false
saveUninitialized: false
}
# Load passport
app.use passport.initialize()
app.use passport.session()
return
| 64969 | ###
# express.coffee
#
# © 2014 <NAME>
# See LICENSE for more details
#
# This module does all of our express configuration, except routing (that's in
# a separate module).
###
'use strict'
# External libs
path = require 'path'
express = require 'express'
session = require 'express-session'
logger = require 'morgan'
parser = require 'body-parser'
cookies = require 'cookie-parser'
mongo = require('connect-mongo') session
debug = require('debug') 'hMedia:express'
# Internal libs
env = require './config/environment'
passport = require './passport'
errors = require './errors'
routes = require './routes'
# Middleware
disableCache = require './middleware/disable_cache'
###
# Express configuration
###
debug 'Configuring express...'
module.exports = exports = (app) ->
# Inform express that it is behind a reverse proxy
app.enable 'trust proxy'
# Development specific config
#app.configure 'development', ->
if env.isDevelopment()
app.use require('connect-livereload')()
app.use disableCache
app.use express.static(path.join(env.root, '.tmp'))
app.use express.static(path.join(env.root, 'app'))
app.set 'views', env.root + '/app/views'
if env.isTest()
app.use express.static(path.join(env.root, '.tmp'))
app.use express.static(path.join(env.root, 'app'))
app.set 'views', env.root + '/app/views'
# Config for all environments
app.engine 'html', require('ejs').renderFile
app.set 'view engine', 'html'
if env.logger
app.use logger(env.logger)
app.use parser.json()
app.use cookies()
# Persist sessions with mongo
app.use session {
secret: env.secrets.session
store: new mongo(
url: env.mongo.uri
collection: 'sessions'
, ->
debug 'Mongo connection for session storage open.'
)
resave: false
saveUninitialized: false
}
# Load passport
app.use passport.initialize()
app.use passport.session()
return
| true | ###
# express.coffee
#
# © 2014 PI:NAME:<NAME>END_PI
# See LICENSE for more details
#
# This module does all of our express configuration, except routing (that's in
# a separate module).
###
'use strict'
# External libs
path = require 'path'
express = require 'express'
session = require 'express-session'
logger = require 'morgan'
parser = require 'body-parser'
cookies = require 'cookie-parser'
mongo = require('connect-mongo') session
debug = require('debug') 'hMedia:express'
# Internal libs
env = require './config/environment'
passport = require './passport'
errors = require './errors'
routes = require './routes'
# Middleware
disableCache = require './middleware/disable_cache'
###
# Express configuration
###
debug 'Configuring express...'
module.exports = exports = (app) ->
# Inform express that it is behind a reverse proxy
app.enable 'trust proxy'
# Development specific config
#app.configure 'development', ->
if env.isDevelopment()
app.use require('connect-livereload')()
app.use disableCache
app.use express.static(path.join(env.root, '.tmp'))
app.use express.static(path.join(env.root, 'app'))
app.set 'views', env.root + '/app/views'
if env.isTest()
app.use express.static(path.join(env.root, '.tmp'))
app.use express.static(path.join(env.root, 'app'))
app.set 'views', env.root + '/app/views'
# Config for all environments
app.engine 'html', require('ejs').renderFile
app.set 'view engine', 'html'
if env.logger
app.use logger(env.logger)
app.use parser.json()
app.use cookies()
# Persist sessions with mongo
app.use session {
secret: env.secrets.session
store: new mongo(
url: env.mongo.uri
collection: 'sessions'
, ->
debug 'Mongo connection for session storage open.'
)
resave: false
saveUninitialized: false
}
# Load passport
app.use passport.initialize()
app.use passport.session()
return
|
[
{
"context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com> \n\nLicensed under the A",
"end": 39,
"score": 0.999886691570282,
"start": 26,
"tag": "NAME",
"value": "Stephan Jorek"
},
{
"context": "###\n© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com>... | src/Action/Expression/Coffeescript.coffee | sjorek/goatee.js | 0 | ###
© Copyright 2013-2014 Stephan Jorek <stephan.jorek@gmail.com>
Licensed 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.
###
Coffee = require 'coffee-script'
{Constants} = require 'goatee/Core/Constants'
{Utility} = require 'goatee/Core/Utility'
{Javascript} = require 'goatee/Action/Expression/Javascript'
exports = module?.exports ? this
###
Coffeescript
@class
@namespace goatee.Action.Expression
###
exports.Coffeescript = class Coffeescript extends Javascript
##
# @param {Object} options
# @constructor
constructor: (options) ->
@options = options ? {
bare : on
inline : on
sourceMap : off
shiftLine : off
}
##
# Cache for compiled expressions
# @type {Object}
_expressionCache = {}
##
# Wrapper for the eval() builtin function to evaluate expressions and
# obtain their value. It wraps the expression in parentheses such
# that object literals are really evaluated to objects. Without the
# wrapping, they are evaluated as block, and create syntax
# errors. Also protects against other syntax errors in the eval()ed
# code and returns null if the eval throws an exception.
#
# @param {String} expression
# @return {Object|null}
evaluateExpression: (expression) ->
(js = _expressionCache[expression])? or \
(js = _expressionCache[expression] = Coffee.compile(expression, @options))
super js
##
# Reference to singleton instance
#
# @static
# @public
# @property
# @type {goatee.Action.Expression.Coffeescript}
@instance: _instance = null
##
# Singleton implementation
#
# @static
# @public
# @method get
# @return {goatee.Action.Expression.Coffeescript}
@get: () ->
_instance ? (_instance = new Coffeescript)
| 51993 | ###
© Copyright 2013-2014 <NAME> <<EMAIL>>
Licensed 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.
###
Coffee = require 'coffee-script'
{Constants} = require 'goatee/Core/Constants'
{Utility} = require 'goatee/Core/Utility'
{Javascript} = require 'goatee/Action/Expression/Javascript'
exports = module?.exports ? this
###
Coffeescript
@class
@namespace goatee.Action.Expression
###
exports.Coffeescript = class Coffeescript extends Javascript
##
# @param {Object} options
# @constructor
constructor: (options) ->
@options = options ? {
bare : on
inline : on
sourceMap : off
shiftLine : off
}
##
# Cache for compiled expressions
# @type {Object}
_expressionCache = {}
##
# Wrapper for the eval() builtin function to evaluate expressions and
# obtain their value. It wraps the expression in parentheses such
# that object literals are really evaluated to objects. Without the
# wrapping, they are evaluated as block, and create syntax
# errors. Also protects against other syntax errors in the eval()ed
# code and returns null if the eval throws an exception.
#
# @param {String} expression
# @return {Object|null}
evaluateExpression: (expression) ->
(js = _expressionCache[expression])? or \
(js = _expressionCache[expression] = Coffee.compile(expression, @options))
super js
##
# Reference to singleton instance
#
# @static
# @public
# @property
# @type {goatee.Action.Expression.Coffeescript}
@instance: _instance = null
##
# Singleton implementation
#
# @static
# @public
# @method get
# @return {goatee.Action.Expression.Coffeescript}
@get: () ->
_instance ? (_instance = new Coffeescript)
| true | ###
© Copyright 2013-2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Licensed 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.
###
Coffee = require 'coffee-script'
{Constants} = require 'goatee/Core/Constants'
{Utility} = require 'goatee/Core/Utility'
{Javascript} = require 'goatee/Action/Expression/Javascript'
exports = module?.exports ? this
###
Coffeescript
@class
@namespace goatee.Action.Expression
###
exports.Coffeescript = class Coffeescript extends Javascript
##
# @param {Object} options
# @constructor
constructor: (options) ->
@options = options ? {
bare : on
inline : on
sourceMap : off
shiftLine : off
}
##
# Cache for compiled expressions
# @type {Object}
_expressionCache = {}
##
# Wrapper for the eval() builtin function to evaluate expressions and
# obtain their value. It wraps the expression in parentheses such
# that object literals are really evaluated to objects. Without the
# wrapping, they are evaluated as block, and create syntax
# errors. Also protects against other syntax errors in the eval()ed
# code and returns null if the eval throws an exception.
#
# @param {String} expression
# @return {Object|null}
evaluateExpression: (expression) ->
(js = _expressionCache[expression])? or \
(js = _expressionCache[expression] = Coffee.compile(expression, @options))
super js
##
# Reference to singleton instance
#
# @static
# @public
# @property
# @type {goatee.Action.Expression.Coffeescript}
@instance: _instance = null
##
# Singleton implementation
#
# @static
# @public
# @method get
# @return {goatee.Action.Expression.Coffeescript}
@get: () ->
_instance ? (_instance = new Coffeescript)
|
[
{
"context": " @res.render.args[0][1].artist.name.should.equal 'Jeff Koons'\n\n it 'bootstraps the artist', ->\n routes",
"end": 1263,
"score": 0.9998757839202881,
"start": 1253,
"tag": "NAME",
"value": "Jeff Koons"
},
{
"context": " @res.render.args[0][1].artist.name.should.... | desktop/apps/artist/test/routes.coffee | craigspaeth/_force-merge | 1 | _ = require 'underscore'
sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
Q = require 'bluebird-q'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../../models/current_user.coffee'
Artist = require '../../../models/artist.coffee'
routes = rewire '../routes'
sections = require '../sections'
artistJSON = require './fixtures'
helpers = require '../view_helpers'
describe 'Artist routes', ->
beforeEach ->
routes.__set__ 'metaphysics', @metaphysics = sinon.stub()
routes.__set__ 'SHOW_ARTIST_CTA_CODE', 'show-me'
@metaphysics.debug = sinon.stub()
@metaphysics.returns Q.resolve artist: artistJSON
@req = params: { id: 'foo' }, get: (->), query: { show_artist_cta_code: 'show-me' }
@res =
render: sinon.stub()
redirect: sinon.stub()
send: sinon.stub()
type: sinon.stub()
locals: sd: APP_URL: 'http://localhost:5000', CURRENT_PATH: '/artist/jeff-koons-1'
describe '#index', ->
it 'renders the artist template', ->
routes.index @req, @res
.then =>
@res.render.args[0][0].should.equal 'index'
@res.render.args[0][1].artist.id.should.equal 'jeff-koons-1'
@res.render.args[0][1].artist.name.should.equal 'Jeff Koons'
it 'bootstraps the artist', ->
routes.index @req, @res
.then =>
@res.locals.sd.ARTIST.should.equal artistJSON
it 'bootstraps the show cta flag', ->
routes.index @req, @res
.then =>
@res.locals.sd.SHOW_ARTIST_CTA.should.equal true
it 'redirects to canonical url', ->
@res.locals.sd.CURRENT_PATH = '/artist/bar'
routes.index @req, @res
.then =>
@res.redirect.args[0][0].should.equal '/artist/jeff-koons-1'
it 'renders a page if there are no artworks to show', ->
response = _.clone artistJSON
response.counts.artworks = 0
@metaphysics.returns Q.resolve artist: response
routes.index @req, @res
.then =>
@res.render.args[0][0].should.equal 'index'
@res.render.args[0][1].artist.id.should.equal 'jeff-koons-1'
@res.render.args[0][1].artist.name.should.equal 'Jeff Koons'
describe '#follow', ->
beforeEach ->
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
it 'redirect to artist page without user', ->
routes.follow @req, @res
@res.redirect.args[0][0].should.equal '/artist/foo'
it 'follows an artist and redirects to the artist page with any query params', ->
@res.redirect = sinon.stub()
@req.user = new CurrentUser fabricate 'user'
@req.query = { medium: 'work-on-paper' }
routes.follow @req, @res
Backbone.sync.args[0][1].url().should.containEql '/api/v1/me/follow/artist'
Backbone.sync.args[0][1].get('artist_id').should.equal 'foo'
Backbone.sync.args[0][2].success()
@res.redirect.args[0][0].should.equal '/artist/foo?medium=work-on-paper'
| 221820 | _ = require 'underscore'
sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
Q = require 'bluebird-q'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../../models/current_user.coffee'
Artist = require '../../../models/artist.coffee'
routes = rewire '../routes'
sections = require '../sections'
artistJSON = require './fixtures'
helpers = require '../view_helpers'
describe 'Artist routes', ->
beforeEach ->
routes.__set__ 'metaphysics', @metaphysics = sinon.stub()
routes.__set__ 'SHOW_ARTIST_CTA_CODE', 'show-me'
@metaphysics.debug = sinon.stub()
@metaphysics.returns Q.resolve artist: artistJSON
@req = params: { id: 'foo' }, get: (->), query: { show_artist_cta_code: 'show-me' }
@res =
render: sinon.stub()
redirect: sinon.stub()
send: sinon.stub()
type: sinon.stub()
locals: sd: APP_URL: 'http://localhost:5000', CURRENT_PATH: '/artist/jeff-koons-1'
describe '#index', ->
it 'renders the artist template', ->
routes.index @req, @res
.then =>
@res.render.args[0][0].should.equal 'index'
@res.render.args[0][1].artist.id.should.equal 'jeff-koons-1'
@res.render.args[0][1].artist.name.should.equal '<NAME>'
it 'bootstraps the artist', ->
routes.index @req, @res
.then =>
@res.locals.sd.ARTIST.should.equal artistJSON
it 'bootstraps the show cta flag', ->
routes.index @req, @res
.then =>
@res.locals.sd.SHOW_ARTIST_CTA.should.equal true
it 'redirects to canonical url', ->
@res.locals.sd.CURRENT_PATH = '/artist/bar'
routes.index @req, @res
.then =>
@res.redirect.args[0][0].should.equal '/artist/jeff-koons-1'
it 'renders a page if there are no artworks to show', ->
response = _.clone artistJSON
response.counts.artworks = 0
@metaphysics.returns Q.resolve artist: response
routes.index @req, @res
.then =>
@res.render.args[0][0].should.equal 'index'
@res.render.args[0][1].artist.id.should.equal 'jeff-koons-1'
@res.render.args[0][1].artist.name.should.equal '<NAME>'
describe '#follow', ->
beforeEach ->
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
it 'redirect to artist page without user', ->
routes.follow @req, @res
@res.redirect.args[0][0].should.equal '/artist/foo'
it 'follows an artist and redirects to the artist page with any query params', ->
@res.redirect = sinon.stub()
@req.user = new CurrentUser fabricate 'user'
@req.query = { medium: 'work-on-paper' }
routes.follow @req, @res
Backbone.sync.args[0][1].url().should.containEql '/api/v1/me/follow/artist'
Backbone.sync.args[0][1].get('artist_id').should.equal 'foo'
Backbone.sync.args[0][2].success()
@res.redirect.args[0][0].should.equal '/artist/foo?medium=work-on-paper'
| true | _ = require 'underscore'
sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
Q = require 'bluebird-q'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../../models/current_user.coffee'
Artist = require '../../../models/artist.coffee'
routes = rewire '../routes'
sections = require '../sections'
artistJSON = require './fixtures'
helpers = require '../view_helpers'
describe 'Artist routes', ->
beforeEach ->
routes.__set__ 'metaphysics', @metaphysics = sinon.stub()
routes.__set__ 'SHOW_ARTIST_CTA_CODE', 'show-me'
@metaphysics.debug = sinon.stub()
@metaphysics.returns Q.resolve artist: artistJSON
@req = params: { id: 'foo' }, get: (->), query: { show_artist_cta_code: 'show-me' }
@res =
render: sinon.stub()
redirect: sinon.stub()
send: sinon.stub()
type: sinon.stub()
locals: sd: APP_URL: 'http://localhost:5000', CURRENT_PATH: '/artist/jeff-koons-1'
describe '#index', ->
it 'renders the artist template', ->
routes.index @req, @res
.then =>
@res.render.args[0][0].should.equal 'index'
@res.render.args[0][1].artist.id.should.equal 'jeff-koons-1'
@res.render.args[0][1].artist.name.should.equal 'PI:NAME:<NAME>END_PI'
it 'bootstraps the artist', ->
routes.index @req, @res
.then =>
@res.locals.sd.ARTIST.should.equal artistJSON
it 'bootstraps the show cta flag', ->
routes.index @req, @res
.then =>
@res.locals.sd.SHOW_ARTIST_CTA.should.equal true
it 'redirects to canonical url', ->
@res.locals.sd.CURRENT_PATH = '/artist/bar'
routes.index @req, @res
.then =>
@res.redirect.args[0][0].should.equal '/artist/jeff-koons-1'
it 'renders a page if there are no artworks to show', ->
response = _.clone artistJSON
response.counts.artworks = 0
@metaphysics.returns Q.resolve artist: response
routes.index @req, @res
.then =>
@res.render.args[0][0].should.equal 'index'
@res.render.args[0][1].artist.id.should.equal 'jeff-koons-1'
@res.render.args[0][1].artist.name.should.equal 'PI:NAME:<NAME>END_PI'
describe '#follow', ->
beforeEach ->
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
it 'redirect to artist page without user', ->
routes.follow @req, @res
@res.redirect.args[0][0].should.equal '/artist/foo'
it 'follows an artist and redirects to the artist page with any query params', ->
@res.redirect = sinon.stub()
@req.user = new CurrentUser fabricate 'user'
@req.query = { medium: 'work-on-paper' }
routes.follow @req, @res
Backbone.sync.args[0][1].url().should.containEql '/api/v1/me/follow/artist'
Backbone.sync.args[0][1].get('artist_id').should.equal 'foo'
Backbone.sync.args[0][2].success()
@res.redirect.args[0][0].should.equal '/artist/foo?medium=work-on-paper'
|
[
{
"context": "idate\\\":\\\"a=candidate:3382296128 2 udp 1845501695 74.137.84.63 59122 typ srflx raddr 192.168.0.105 rport 59122 g",
"end": 1935,
"score": 0.9997318387031555,
"start": 1923,
"tag": "IP_ADDRESS",
"value": "74.137.84.63"
},
{
"context": "udp 1845501695 74.137.84.63 5912... | test/spec/javascripts/unit/services/util_service_spec.coffee | cheshire137/angular-module | 1 | describe "Unit:UtilService", ->
beforeEach(->
angular.mock.module('Camfire');
)
it "should contain an utilService", inject((utilService) ->
expect(utilService).toNotEqual(null)
)
#describe "Unit:UtilService:getIndexByIdAttr", ->
# beforeEach(->
# angular.mock.module('Camfire')
# )
#
# it "should find the correct index when one exists", inject((testUtilService, utilService) ->
# TEST_INDEX = testUtilService.TEST_INDEX
# indexItem = testUtilService.getAnonymousIdexItem()
# modifiedArray = testUtilService.pushItemAt(testUtilService.getAnonymousIndexArray_few(), indexItem, 0)
# expect(utilService.getIndexByIdAttr(modifiedArray, TEST_INDEX, indexItem[TEST_INDEX])).toEqual(0)
#
# indexItem = testUtilService.getAnonymousIdexItem()
# modifiedArray = testUtilService.pushItemAt(testUtilService.getAnonymousIndexArray_few(), indexItem, 1)
# expect(utilService.getIndexByIdAttr(modifiedArray, TEST_INDEX, indexItem[TEST_INDEX])).toEqual(1)
#
# indexItem = testUtilService.getAnonymousIdexItem()
# modifiedArray = testUtilService.pushItemAt(testUtilService.getAnonymousIndexArray_few(), indexItem, 2)
# expect(utilService.getIndexByIdAttr(modifiedArray, TEST_INDEX, indexItem[TEST_INDEX])).toEqual(2)
# )
#
# it "should handle non-existent index", inject((testUtilService, utilService) ->
# expect(utilService.getIndexByIdAttr(testUtilService.getAnonymousIndexArray_few(), 'id', 'non-existent')).toEqual(-1)
# )
#
# it "should handle empty arrays", inject((utilService) ->
# expect(utilService.getIndexByIdAttr([], 'non-id', 'non-value')).toEqual(-1)
# )
describe "Unit:UtilService:parseJson", ->
beforeEach(->
angular.mock.module('Camfire')
)
it "should parse json", inject((testUtilService, utilService) ->
# test = '{"type":"candidate","data":"{\"sdpMLineIndex\":1,\"sdpMid\":\"video\",\"candidate\":\"a=candidate:3382296128 2 udp 1845501695 74.137.84.63 59122 typ srflx raddr 192.168.0.105 rport 59122 generation 0\\r\\n\"}"}'
# debug.log(test)
# utilService.parseJson(test)
)
describe "Unit:UtilService:moveById", ->
beforeEach(->
angular.mock.module('Camfire')
)
it "should move specified value from source to destination", inject((testUtilService, utilService) ->
indexItem = testUtilService.getAnonymousIndexItem()
index = indexItem[testUtilService.TEST_INDEX]
src = testUtilService.getAnonymousIndexArray_few()
src[index] = indexItem
dest = {}
expect(src[index]).toBeDefined()
expect(dest[index]).not.toBeDefined()
utilService.moveById(src, dest, index)
expect(src[index]).not.toBeDefined()
expect(dest[index]).toBeDefined()
)
it "should throw error if source item does not exist", inject((testUtilService, utilService) ->
src = testUtilService.getAnonymousIndexArray_few()
expect(->
utilService.moveById(src, {}, 'non-extent')
).toThrow(new Error("Illegal Argument"))
)
| 176442 | describe "Unit:UtilService", ->
beforeEach(->
angular.mock.module('Camfire');
)
it "should contain an utilService", inject((utilService) ->
expect(utilService).toNotEqual(null)
)
#describe "Unit:UtilService:getIndexByIdAttr", ->
# beforeEach(->
# angular.mock.module('Camfire')
# )
#
# it "should find the correct index when one exists", inject((testUtilService, utilService) ->
# TEST_INDEX = testUtilService.TEST_INDEX
# indexItem = testUtilService.getAnonymousIdexItem()
# modifiedArray = testUtilService.pushItemAt(testUtilService.getAnonymousIndexArray_few(), indexItem, 0)
# expect(utilService.getIndexByIdAttr(modifiedArray, TEST_INDEX, indexItem[TEST_INDEX])).toEqual(0)
#
# indexItem = testUtilService.getAnonymousIdexItem()
# modifiedArray = testUtilService.pushItemAt(testUtilService.getAnonymousIndexArray_few(), indexItem, 1)
# expect(utilService.getIndexByIdAttr(modifiedArray, TEST_INDEX, indexItem[TEST_INDEX])).toEqual(1)
#
# indexItem = testUtilService.getAnonymousIdexItem()
# modifiedArray = testUtilService.pushItemAt(testUtilService.getAnonymousIndexArray_few(), indexItem, 2)
# expect(utilService.getIndexByIdAttr(modifiedArray, TEST_INDEX, indexItem[TEST_INDEX])).toEqual(2)
# )
#
# it "should handle non-existent index", inject((testUtilService, utilService) ->
# expect(utilService.getIndexByIdAttr(testUtilService.getAnonymousIndexArray_few(), 'id', 'non-existent')).toEqual(-1)
# )
#
# it "should handle empty arrays", inject((utilService) ->
# expect(utilService.getIndexByIdAttr([], 'non-id', 'non-value')).toEqual(-1)
# )
describe "Unit:UtilService:parseJson", ->
beforeEach(->
angular.mock.module('Camfire')
)
it "should parse json", inject((testUtilService, utilService) ->
# test = '{"type":"candidate","data":"{\"sdpMLineIndex\":1,\"sdpMid\":\"video\",\"candidate\":\"a=candidate:3382296128 2 udp 1845501695 192.168.3.11 59122 typ srflx raddr 192.168.0.105 rport 59122 generation 0\\r\\n\"}"}'
# debug.log(test)
# utilService.parseJson(test)
)
describe "Unit:UtilService:moveById", ->
beforeEach(->
angular.mock.module('Camfire')
)
it "should move specified value from source to destination", inject((testUtilService, utilService) ->
indexItem = testUtilService.getAnonymousIndexItem()
index = indexItem[testUtilService.TEST_INDEX]
src = testUtilService.getAnonymousIndexArray_few()
src[index] = indexItem
dest = {}
expect(src[index]).toBeDefined()
expect(dest[index]).not.toBeDefined()
utilService.moveById(src, dest, index)
expect(src[index]).not.toBeDefined()
expect(dest[index]).toBeDefined()
)
it "should throw error if source item does not exist", inject((testUtilService, utilService) ->
src = testUtilService.getAnonymousIndexArray_few()
expect(->
utilService.moveById(src, {}, 'non-extent')
).toThrow(new Error("Illegal Argument"))
)
| true | describe "Unit:UtilService", ->
beforeEach(->
angular.mock.module('Camfire');
)
it "should contain an utilService", inject((utilService) ->
expect(utilService).toNotEqual(null)
)
#describe "Unit:UtilService:getIndexByIdAttr", ->
# beforeEach(->
# angular.mock.module('Camfire')
# )
#
# it "should find the correct index when one exists", inject((testUtilService, utilService) ->
# TEST_INDEX = testUtilService.TEST_INDEX
# indexItem = testUtilService.getAnonymousIdexItem()
# modifiedArray = testUtilService.pushItemAt(testUtilService.getAnonymousIndexArray_few(), indexItem, 0)
# expect(utilService.getIndexByIdAttr(modifiedArray, TEST_INDEX, indexItem[TEST_INDEX])).toEqual(0)
#
# indexItem = testUtilService.getAnonymousIdexItem()
# modifiedArray = testUtilService.pushItemAt(testUtilService.getAnonymousIndexArray_few(), indexItem, 1)
# expect(utilService.getIndexByIdAttr(modifiedArray, TEST_INDEX, indexItem[TEST_INDEX])).toEqual(1)
#
# indexItem = testUtilService.getAnonymousIdexItem()
# modifiedArray = testUtilService.pushItemAt(testUtilService.getAnonymousIndexArray_few(), indexItem, 2)
# expect(utilService.getIndexByIdAttr(modifiedArray, TEST_INDEX, indexItem[TEST_INDEX])).toEqual(2)
# )
#
# it "should handle non-existent index", inject((testUtilService, utilService) ->
# expect(utilService.getIndexByIdAttr(testUtilService.getAnonymousIndexArray_few(), 'id', 'non-existent')).toEqual(-1)
# )
#
# it "should handle empty arrays", inject((utilService) ->
# expect(utilService.getIndexByIdAttr([], 'non-id', 'non-value')).toEqual(-1)
# )
describe "Unit:UtilService:parseJson", ->
beforeEach(->
angular.mock.module('Camfire')
)
it "should parse json", inject((testUtilService, utilService) ->
# test = '{"type":"candidate","data":"{\"sdpMLineIndex\":1,\"sdpMid\":\"video\",\"candidate\":\"a=candidate:3382296128 2 udp 1845501695 PI:IP_ADDRESS:192.168.3.11END_PI 59122 typ srflx raddr 192.168.0.105 rport 59122 generation 0\\r\\n\"}"}'
# debug.log(test)
# utilService.parseJson(test)
)
describe "Unit:UtilService:moveById", ->
beforeEach(->
angular.mock.module('Camfire')
)
it "should move specified value from source to destination", inject((testUtilService, utilService) ->
indexItem = testUtilService.getAnonymousIndexItem()
index = indexItem[testUtilService.TEST_INDEX]
src = testUtilService.getAnonymousIndexArray_few()
src[index] = indexItem
dest = {}
expect(src[index]).toBeDefined()
expect(dest[index]).not.toBeDefined()
utilService.moveById(src, dest, index)
expect(src[index]).not.toBeDefined()
expect(dest[index]).toBeDefined()
)
it "should throw error if source item does not exist", inject((testUtilService, utilService) ->
src = testUtilService.getAnonymousIndexArray_few()
expect(->
utilService.moveById(src, {}, 'non-extent')
).toThrow(new Error("Illegal Argument"))
)
|
[
{
"context": "ssociated with you'\n top10_common_password: 'This is a top-10 common password'\n top100_common_passw",
"end": 1241,
"score": 0.9096033573150635,
"start": 1232,
"tag": "PASSWORD",
"value": "This is a"
},
{
"context": " you'\n top10_common_password: 'This ... | src/feedback_i18n.coffee | scoueille/zxcvbn | 0 | feedback_i18n =
en:
use_a_few_words: 'Use a few words, avoid common phrases'
use_mixed_chars: 'Use at least 8 characters with symbols, digits, or uppercase letters'
uncommon_words_are_better: 'Add another word or two. Uncommon words are better.'
straight_rows_of_keys_are_easy: 'Straight rows of keys are easy to guess'
short_keyboard_patterns_are_easy: 'Short keyboard patterns are easy to guess'
use_longer_keyboard_patterns: 'Use a longer keyboard pattern with more turns'
repeated_chars_are_easy: 'Repeats like "aaa" are easy to guess'
repeated_patterns_are_easy: 'Repeats like "abcabcabc" are only slightly harder to guess than "abc"'
avoid_repeated_chars: 'Avoid repeated words and characters'
sequences_are_easy: 'Sequences like abc or 6543 are easy to guess'
avoid_sequences: 'Avoid sequences'
recent_years_are_easy: 'Recent years are easy to guess'
avoid_recent_years: 'Avoid recent years'
avoid_associated_years: 'Avoid years that are associated with you'
dates_are_easy: 'Dates are often easy to guess'
avoid_associated_dates_and_years: 'Avoid dates and years that are associated with you'
top10_common_password: 'This is a top-10 common password'
top100_common_password: 'This is a top-100 common password'
very_common_password: 'This is a very common password'
similar_to_common_password: 'This is similar to a commonly used password'
a_word_is_easy: 'A word by itself is easy to guess'
names_are_easy: 'Names and surnames by themselves are easy to guess'
common_names_are_easy: 'Common names and surnames are easy to guess'
capitalization_doesnt_help: 'Capitalization doesn\'t help very much'
all_uppercase_doesnt_help: 'All-uppercase is almost as easy to guess as all-lowercase'
reverse_doesnt_help: 'Reversed words aren\'t much harder to guess'
substitution_doesnt_help: 'Predictable substitutions like \'@\' instead of \'a\' don\'t help very much'
fr:
use_a_few_words: 'Nous vous conseillons une combinaison de mots (bien sûr, évitez les phrases courantes tout de même). '
use_mixed_chars: 'Ajoutez des majuscules, des chiffres et des symboles. '
uncommon_words_are_better: 'Nous vous conseillons d\'ajouter un ou deux mots (en termes de sécurité, les mots peu utilisés sont les meilleurs). '
straight_rows_of_keys_are_easy: 'Malheureusement, les répétitions de touches sont très faciles à deviner. '
short_keyboard_patterns_are_easy: 'Les petits motifs de clavier sont faciles à deviner. '
use_longer_keyboard_patterns: 'Utilisez un motif sur la clavier plus long avec plus de changement de direction. '
repeated_chars_are_easy: 'Les répétitions de caractères sont parmi les premiers testés par les algorithmes de hacking… '
repeated_patterns_are_easy: 'La répétition de suites de caractères (\'abcabcabc\') est à peine plus difficile à deviner que les suites elles-mêmes (\'abc\'). '
avoid_repeated_chars: 'Pour votre sécurité, évitez les répétitions de mots et de caractères. '
sequences_are_easy: 'Des séquences telles que \'abc\' ou \'6543\' sont bien trop faciles à deviner… '
avoid_sequences: 'Évitez les séquences. '
recent_years_are_easy: 'Les années proches sont faciles à deviner. '
avoid_recent_years: 'Pour votre sécurité, évitez d\'utiliser les années passées. '
avoid_associated_years: 'Pour votre sécurité, nous vous déconseillons d\'utiliser les années qui vous sont associées (date de naissance…). '
dates_are_easy: 'Les dates sont souvent faciles à deviner. '
avoid_associated_dates_and_years: 'Pour votre sécurité, évitez les dates et les années qui vous sont associées. '
top10_common_password: 'Saviez-vous que ce mot de passe fait partie du Top 10 les plus utilisés ? '
top100_common_password: 'Saviez-vous que ce mot de passe fait partie du Top 100 les plus utilisés ? '
very_common_password: 'C\'est un mot de passe très courant que vous indiquez-là… '
similar_to_common_password: 'C\'est similaire à un mot de passe courant. '
a_word_is_easy: 'Méfiez-vous : les mots isolés sont faciles à deviner. '
names_are_easy: 'Méfiez-vous : les noms et prénoms sont faciles à deviner. '
common_names_are_easy: 'Méfiez-vous : les noms et prénoms communs sont faciles à deviner. '
capitalization_doesnt_help: 'Commencer un mot par une majuscule n\'aide pas beaucoup. '
all_uppercase_doesnt_help: 'Saviez-vous qu\'un mot tout en majuscules est presque aussi facile à deviner qu\'un mot tout en minuscules ? '
reverse_doesnt_help: 'Ecrire les mots à l\'envers ne rend pas votre mot de passe plus difficile à deviner, vous savez :) '
substitution_doesnt_help: 'Les substitutions prévisibles (un \'@\' au lieu d\'un \'a\') n\'aident malheureusement pas à rendre les mots de passe plus forts…'
module.exports = feedback_i18n | 156203 | feedback_i18n =
en:
use_a_few_words: 'Use a few words, avoid common phrases'
use_mixed_chars: 'Use at least 8 characters with symbols, digits, or uppercase letters'
uncommon_words_are_better: 'Add another word or two. Uncommon words are better.'
straight_rows_of_keys_are_easy: 'Straight rows of keys are easy to guess'
short_keyboard_patterns_are_easy: 'Short keyboard patterns are easy to guess'
use_longer_keyboard_patterns: 'Use a longer keyboard pattern with more turns'
repeated_chars_are_easy: 'Repeats like "aaa" are easy to guess'
repeated_patterns_are_easy: 'Repeats like "abcabcabc" are only slightly harder to guess than "abc"'
avoid_repeated_chars: 'Avoid repeated words and characters'
sequences_are_easy: 'Sequences like abc or 6543 are easy to guess'
avoid_sequences: 'Avoid sequences'
recent_years_are_easy: 'Recent years are easy to guess'
avoid_recent_years: 'Avoid recent years'
avoid_associated_years: 'Avoid years that are associated with you'
dates_are_easy: 'Dates are often easy to guess'
avoid_associated_dates_and_years: 'Avoid dates and years that are associated with you'
top10_common_password: '<PASSWORD> top-<PASSWORD> password'
top100_common_password: '<PASSWORD>'
very_common_password: '<PASSWORD>'
similar_to_common_password: '<PASSWORD> similar to a commonly used password'
a_word_is_easy: 'A word by itself is easy to guess'
names_are_easy: 'Names and surnames by themselves are easy to guess'
common_names_are_easy: 'Common names and surnames are easy to guess'
capitalization_doesnt_help: 'Capitalization doesn\'t help very much'
all_uppercase_doesnt_help: 'All-uppercase is almost as easy to guess as all-lowercase'
reverse_doesnt_help: 'Reversed words aren\'t much harder to guess'
substitution_doesnt_help: 'Predictable substitutions like \'@\' instead of \'a\' don\'t help very much'
fr:
use_a_few_words: 'Nous vous conseillons une combinaison de mots (bien sûr, évitez les phrases courantes tout de même). '
use_mixed_chars: 'Ajoutez des majuscules, des chiffres et des symboles. '
uncommon_words_are_better: 'Nous vous conseillons d\'ajouter un ou deux mots (en termes de sécurité, les mots peu utilisés sont les meilleurs). '
straight_rows_of_keys_are_easy: 'Malheureusement, les répétitions de touches sont très faciles à deviner. '
short_keyboard_patterns_are_easy: 'Les petits motifs de clavier sont faciles à deviner. '
use_longer_keyboard_patterns: 'Utilisez un motif sur la clavier plus long avec plus de changement de direction. '
repeated_chars_are_easy: 'Les répétitions de caractères sont parmi les premiers testés par les algorithmes de hacking… '
repeated_patterns_are_easy: 'La répétition de suites de caractères (\'abcabcabc\') est à peine plus difficile à deviner que les suites elles-mêmes (\'abc\'). '
avoid_repeated_chars: 'Pour votre sécurité, évitez les répétitions de mots et de caractères. '
sequences_are_easy: 'Des séquences telles que \'abc\' ou \'6543\' sont bien trop faciles à deviner… '
avoid_sequences: 'Évitez les séquences. '
recent_years_are_easy: 'Les années proches sont faciles à deviner. '
avoid_recent_years: 'Pour votre sécurité, évitez d\'utiliser les années passées. '
avoid_associated_years: 'Pour votre sécurité, nous vous déconseillons d\'utiliser les années qui vous sont associées (date de naissance…). '
dates_are_easy: 'Les dates sont souvent faciles à deviner. '
avoid_associated_dates_and_years: 'Pour votre sécurité, évitez les dates et les années qui vous sont associées. '
top10_common_password: 'S<PASSWORD>z-vous que ce mot de passe fait partie du Top 10 les plus utilisés ? '
top100_common_password: 'Saviez-vous que ce mot de passe fait partie du Top 100 les plus utilisés ? '
very_common_password: 'C\'est un mot de passe très courant que vous indiquez-là… '
similar_to_common_password: 'C\'est similaire à un mot de passe courant. '
a_word_is_easy: 'Méfiez-vous : les mots isolés sont faciles à deviner. '
names_are_easy: 'Méfiez-vous : les noms et prénoms sont faciles à deviner. '
common_names_are_easy: 'Méfiez-vous : les noms et prénoms communs sont faciles à deviner. '
capitalization_doesnt_help: 'Commencer un mot par une majuscule n\'aide pas beaucoup. '
all_uppercase_doesnt_help: 'Saviez-vous qu\'un mot tout en majuscules est presque aussi facile à deviner qu\'un mot tout en minuscules ? '
reverse_doesnt_help: 'Ecrire les mots à l\'envers ne rend pas votre mot de passe plus difficile à deviner, vous savez :) '
substitution_doesnt_help: 'Les substitutions prévisibles (un \'@\' au lieu d\'un \'a\') n\'aident malheureusement pas à rendre les mots de passe plus forts…'
module.exports = feedback_i18n | true | feedback_i18n =
en:
use_a_few_words: 'Use a few words, avoid common phrases'
use_mixed_chars: 'Use at least 8 characters with symbols, digits, or uppercase letters'
uncommon_words_are_better: 'Add another word or two. Uncommon words are better.'
straight_rows_of_keys_are_easy: 'Straight rows of keys are easy to guess'
short_keyboard_patterns_are_easy: 'Short keyboard patterns are easy to guess'
use_longer_keyboard_patterns: 'Use a longer keyboard pattern with more turns'
repeated_chars_are_easy: 'Repeats like "aaa" are easy to guess'
repeated_patterns_are_easy: 'Repeats like "abcabcabc" are only slightly harder to guess than "abc"'
avoid_repeated_chars: 'Avoid repeated words and characters'
sequences_are_easy: 'Sequences like abc or 6543 are easy to guess'
avoid_sequences: 'Avoid sequences'
recent_years_are_easy: 'Recent years are easy to guess'
avoid_recent_years: 'Avoid recent years'
avoid_associated_years: 'Avoid years that are associated with you'
dates_are_easy: 'Dates are often easy to guess'
avoid_associated_dates_and_years: 'Avoid dates and years that are associated with you'
top10_common_password: 'PI:PASSWORD:<PASSWORD>END_PI top-PI:PASSWORD:<PASSWORD>END_PI password'
top100_common_password: 'PI:PASSWORD:<PASSWORD>END_PI'
very_common_password: 'PI:PASSWORD:<PASSWORD>END_PI'
similar_to_common_password: 'PI:PASSWORD:<PASSWORD>END_PI similar to a commonly used password'
a_word_is_easy: 'A word by itself is easy to guess'
names_are_easy: 'Names and surnames by themselves are easy to guess'
common_names_are_easy: 'Common names and surnames are easy to guess'
capitalization_doesnt_help: 'Capitalization doesn\'t help very much'
all_uppercase_doesnt_help: 'All-uppercase is almost as easy to guess as all-lowercase'
reverse_doesnt_help: 'Reversed words aren\'t much harder to guess'
substitution_doesnt_help: 'Predictable substitutions like \'@\' instead of \'a\' don\'t help very much'
fr:
use_a_few_words: 'Nous vous conseillons une combinaison de mots (bien sûr, évitez les phrases courantes tout de même). '
use_mixed_chars: 'Ajoutez des majuscules, des chiffres et des symboles. '
uncommon_words_are_better: 'Nous vous conseillons d\'ajouter un ou deux mots (en termes de sécurité, les mots peu utilisés sont les meilleurs). '
straight_rows_of_keys_are_easy: 'Malheureusement, les répétitions de touches sont très faciles à deviner. '
short_keyboard_patterns_are_easy: 'Les petits motifs de clavier sont faciles à deviner. '
use_longer_keyboard_patterns: 'Utilisez un motif sur la clavier plus long avec plus de changement de direction. '
repeated_chars_are_easy: 'Les répétitions de caractères sont parmi les premiers testés par les algorithmes de hacking… '
repeated_patterns_are_easy: 'La répétition de suites de caractères (\'abcabcabc\') est à peine plus difficile à deviner que les suites elles-mêmes (\'abc\'). '
avoid_repeated_chars: 'Pour votre sécurité, évitez les répétitions de mots et de caractères. '
sequences_are_easy: 'Des séquences telles que \'abc\' ou \'6543\' sont bien trop faciles à deviner… '
avoid_sequences: 'Évitez les séquences. '
recent_years_are_easy: 'Les années proches sont faciles à deviner. '
avoid_recent_years: 'Pour votre sécurité, évitez d\'utiliser les années passées. '
avoid_associated_years: 'Pour votre sécurité, nous vous déconseillons d\'utiliser les années qui vous sont associées (date de naissance…). '
dates_are_easy: 'Les dates sont souvent faciles à deviner. '
avoid_associated_dates_and_years: 'Pour votre sécurité, évitez les dates et les années qui vous sont associées. '
top10_common_password: 'SPI:PASSWORD:<PASSWORD>END_PIz-vous que ce mot de passe fait partie du Top 10 les plus utilisés ? '
top100_common_password: 'Saviez-vous que ce mot de passe fait partie du Top 100 les plus utilisés ? '
very_common_password: 'C\'est un mot de passe très courant que vous indiquez-là… '
similar_to_common_password: 'C\'est similaire à un mot de passe courant. '
a_word_is_easy: 'Méfiez-vous : les mots isolés sont faciles à deviner. '
names_are_easy: 'Méfiez-vous : les noms et prénoms sont faciles à deviner. '
common_names_are_easy: 'Méfiez-vous : les noms et prénoms communs sont faciles à deviner. '
capitalization_doesnt_help: 'Commencer un mot par une majuscule n\'aide pas beaucoup. '
all_uppercase_doesnt_help: 'Saviez-vous qu\'un mot tout en majuscules est presque aussi facile à deviner qu\'un mot tout en minuscules ? '
reverse_doesnt_help: 'Ecrire les mots à l\'envers ne rend pas votre mot de passe plus difficile à deviner, vous savez :) '
substitution_doesnt_help: 'Les substitutions prévisibles (un \'@\' au lieu d\'un \'a\') n\'aident malheureusement pas à rendre les mots de passe plus forts…'
module.exports = feedback_i18n |
[
{
"context": "cPath = 'test/fixtures/encryption/.authrc'\n key = '@_$vp€R~k3y'\n auth = null\n host = null\n\n describe 'existan",
"end": 167,
"score": 0.9994346499443054,
"start": 155,
"tag": "KEY",
"value": "'@_$vp€R~k3y"
},
{
"context": "st.encrypt(key).password())\n .t... | test/encryptionSpec.coffee | h2non/node-authrc | 1 | { expect } = require 'chai'
Authrc = require '../lib/authrc'
describe 'Password encryption', ->
authrcPath = 'test/fixtures/encryption/.authrc'
key = '@_$vp€R~k3y'
auth = null
host = null
describe 'existant host with plain password', ->
beforeEach ->
auth = new Authrc authrcPath
beforeEach ->
host = auth.host('http://git.server.org')
it 'should not do an automatic password decryption', ->
expect(host.canDecrypt()).to.be.false
it 'should not be an encrypted password', ->
expect(host.isEncrypted()).to.be.false
it 'should encrypt the password with default cipher', ->
expect(host.encrypt(key).password())
.to.be.equal('ea08d490b880b4bfdb1b95f0e5c908424432ba57413d23b19db2d77a763d3178')
describe 'with supported ciphers', ->
it 'should encrypt the password with AES256', ->
expect(host.encrypt(key, 'aes256').password())
.to.be.equal('6400ff3f33bec8481dc7ead8bb5294fe0ea4b690a9b6fecd1d029ec54b062ccf')
it 'should encrypt the password with Blowfish', ->
expect(host.encrypt(key, 'blowfish').password())
.to.be.equal('41b717a64c6b5753ed5928fd8a53149a7632e4ed1d207c91')
it 'should encrypt the password with Camellia', ->
expect(host.encrypt(key, 'camellia128').password())
.to.be.equal('857c5903cabc19444e7d4393a512b94b89daf9bec48c062d614dc576e6bc8ef6')
it 'should encrypt the password with CAST', ->
expect(host.encrypt(key, 'cast').password())
.to.be.equal('04ad8d25c0f92070d34c1763be723d380a99f7e20666d7d0')
it 'should encrypt the password with IDEA', ->
expect(host.encrypt(key, 'idea').password())
.to.be.equal('f3d3d049ec7f9a0e8de66891fbc63881b765ea965c5fc37c')
it 'should encrypt the password with SEED', ->
expect(host.encrypt(key, 'SEED').password())
.to.be.equal('cfef06c5a7640beca47f36893c2b7667b43c370ba4f7e0cfd971b42b166cd8b4')
describe 'faile suite with non-supported ciphers', ->
it 'should try to encrypt the password with RC4', ->
expect(-> host.encrypt(key, 'rc4')).to.throw(TypeError)
it 'should try to encrypt the password with 3DES', ->
expect(-> host.encrypt(key, '3des')).to.throw(TypeError)
it 'should try to encrypt the password with AES192', ->
expect(-> host.encrypt(key, 'AES512')).to.throw(TypeError)
| 47740 | { expect } = require 'chai'
Authrc = require '../lib/authrc'
describe 'Password encryption', ->
authrcPath = 'test/fixtures/encryption/.authrc'
key = <KEY>'
auth = null
host = null
describe 'existant host with plain password', ->
beforeEach ->
auth = new Authrc authrcPath
beforeEach ->
host = auth.host('http://git.server.org')
it 'should not do an automatic password decryption', ->
expect(host.canDecrypt()).to.be.false
it 'should not be an encrypted password', ->
expect(host.isEncrypted()).to.be.false
it 'should encrypt the password with default cipher', ->
expect(host.encrypt(key).password())
.to.be.equal('<PASSWORD>')
describe 'with supported ciphers', ->
it 'should encrypt the password with AES256', ->
expect(host.encrypt(key, 'aes256').password())
.to.be.equal('<PASSWORD> <KEY> <PASSWORD> <KEY>')
it 'should encrypt the password with Blowfish', ->
expect(host.encrypt(key, 'blowfish').password())
.to.be.equal('<PASSWORD>')
it 'should encrypt the password with Camellia', ->
expect(host.encrypt(key, 'camellia128').password())
.to.be.equal('<PASSWORD>')
it 'should encrypt the password with CAST', ->
expect(host.encrypt(key, 'cast').password())
.to.be.equal('<PASSWORD>')
it 'should encrypt the password with IDEA', ->
expect(host.encrypt(key, 'idea').password())
.to.be.equal('<PASSWORD>')
it 'should encrypt the password with SEED', ->
expect(host.encrypt(key, 'SEED').password())
.to.be.equal('<PASSWORD>')
describe 'faile suite with non-supported ciphers', ->
it 'should try to encrypt the password with RC4', ->
expect(-> host.encrypt(key, 'rc4')).to.throw(TypeError)
it 'should try to encrypt the password with 3DES', ->
expect(-> host.encrypt(key, '3des')).to.throw(TypeError)
it 'should try to encrypt the password with AES192', ->
expect(-> host.encrypt(key, 'AES512')).to.throw(TypeError)
| true | { expect } = require 'chai'
Authrc = require '../lib/authrc'
describe 'Password encryption', ->
authrcPath = 'test/fixtures/encryption/.authrc'
key = PI:KEY:<KEY>END_PI'
auth = null
host = null
describe 'existant host with plain password', ->
beforeEach ->
auth = new Authrc authrcPath
beforeEach ->
host = auth.host('http://git.server.org')
it 'should not do an automatic password decryption', ->
expect(host.canDecrypt()).to.be.false
it 'should not be an encrypted password', ->
expect(host.isEncrypted()).to.be.false
it 'should encrypt the password with default cipher', ->
expect(host.encrypt(key).password())
.to.be.equal('PI:PASSWORD:<PASSWORD>END_PI')
describe 'with supported ciphers', ->
it 'should encrypt the password with AES256', ->
expect(host.encrypt(key, 'aes256').password())
.to.be.equal('PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI')
it 'should encrypt the password with Blowfish', ->
expect(host.encrypt(key, 'blowfish').password())
.to.be.equal('PI:PASSWORD:<PASSWORD>END_PI')
it 'should encrypt the password with Camellia', ->
expect(host.encrypt(key, 'camellia128').password())
.to.be.equal('PI:PASSWORD:<PASSWORD>END_PI')
it 'should encrypt the password with CAST', ->
expect(host.encrypt(key, 'cast').password())
.to.be.equal('PI:PASSWORD:<PASSWORD>END_PI')
it 'should encrypt the password with IDEA', ->
expect(host.encrypt(key, 'idea').password())
.to.be.equal('PI:PASSWORD:<PASSWORD>END_PI')
it 'should encrypt the password with SEED', ->
expect(host.encrypt(key, 'SEED').password())
.to.be.equal('PI:PASSWORD:<PASSWORD>END_PI')
describe 'faile suite with non-supported ciphers', ->
it 'should try to encrypt the password with RC4', ->
expect(-> host.encrypt(key, 'rc4')).to.throw(TypeError)
it 'should try to encrypt the password with 3DES', ->
expect(-> host.encrypt(key, '3des')).to.throw(TypeError)
it 'should try to encrypt the password with AES192', ->
expect(-> host.encrypt(key, 'AES512')).to.throw(TypeError)
|
[
{
"context": "istory.push options.key\n .good_handler key: 'value 1'\n .good_handler key: 'value 2'\n .call -",
"end": 416,
"score": 0.9254453182220459,
"start": 409,
"tag": "KEY",
"value": "value 1"
},
{
"context": "_handler key: 'value 1'\n .good_handler key: 'v... | packages/core/test/api/aspect/after.coffee | chibanemourad/node-nikita | 0 |
nikita = require '../../../src'
{tags} = require '../../test'
return unless tags.api
describe 'api after', ->
describe 'event', ->
it 'is a string and match a action type', ->
history = []
nikita()
.registry.register 'good_handler', (->)
.registry.register 'bad_handler', (->)
.after 'good_handler', ({options}) -> history.push options.key
.good_handler key: 'value 1'
.good_handler key: 'value 2'
.call ->
history.should.eql ['value 1', 'value 2']
.promise()
it 'is an object and match options', ->
history = []
nikita()
.registry.register 'handler', (->)
.after action: 'handler', key: 'value 2', ({options}) ->
history.push options.key
.handler key: 'value 1'
.handler key: 'value 2'
.call ->
history.should.eql ['value 2']
.promise()
describe 'handler', ->
it 'a sync function with sync handler', ->
history = []
nikita()
.registry.register 'sync_fn', ((_) -> history.push 'sync handler' )
.after 'sync_fn', (_) -> history.push 'after sync'
.call -> history.push 'call 1'
.sync_fn -> history.push 'sync callback 1'
.call -> history.push 'call 2'
.sync_fn -> history.push 'sync callback 2'
.call -> history.push 'call 3'
.call ->
history.should.eql [
'call 1', 'sync handler', 'after sync', 'sync callback 1'
'call 2', 'sync handler', 'after sync', 'sync callback 2'
'call 3'
]
.promise()
it 'a sync function with async handler', ->
history = []
nikita()
.registry.register 'afunction', ((_) -> history.push 'sync handler' )
.after 'afunction', (_, callback) ->
setImmediate ->
history.push 'after sync'
callback()
.call -> history.push 'call 1'
.afunction -> history.push 'sync callback 1'
.call -> history.push 'call 2'
.afunction -> history.push 'sync callback 2'
.call -> history.push 'call 3'
.call ->
history.should.eql [
'call 1', 'sync handler', 'after sync', 'sync callback 1'
'call 2', 'sync handler', 'after sync', 'sync callback 2'
'call 3'
]
.promise()
it 'a namespaced sync function with async handler', ->
history = []
nikita()
.registry.register ['a','namespaced','function'], ((_) -> history.push 'sync handler' )
.after ['a','namespaced', 'function'], (_, callback) ->
setImmediate ->
history.push 'after sync'
callback()
.call -> history.push 'call 1'
.a.namespaced.function -> history.push 'sync callback 1'
.call -> history.push 'call 2'
.a.namespaced.function -> history.push 'sync callback 2'
.call -> history.push 'call 3'
.call ->
history.should.eql [
'call 1', 'sync handler', 'after sync', 'sync callback 1'
'call 2', 'sync handler', 'after sync', 'sync callback 2'
'call 3'
]
.promise()
describe 'error', ->
it 'register sync function and throw error', ->
nikita()
.registry.register 'afunction', ( -> )
.after 'afunction', (_) ->
throw Error 'CatchMe'
.afunction (err, status) ->
err.message.should.eql 'CatchMe'
.next (err) ->
err.message.should.eql 'CatchMe'
.promise()
it 'register sync function and throw error', ->
nikita()
.registry.register 'afunction', ( -> )
.after 'afunction', (_, callback) ->
setImmediate -> callback Error 'CatchMe'
.afunction (err, status) ->
err.message.should.eql 'CatchMe'
.next (err) ->
err.message.should.eql 'CatchMe'
.promise()
| 158346 |
nikita = require '../../../src'
{tags} = require '../../test'
return unless tags.api
describe 'api after', ->
describe 'event', ->
it 'is a string and match a action type', ->
history = []
nikita()
.registry.register 'good_handler', (->)
.registry.register 'bad_handler', (->)
.after 'good_handler', ({options}) -> history.push options.key
.good_handler key: '<KEY>'
.good_handler key: '<KEY>'
.call ->
history.should.eql ['value 1', 'value 2']
.promise()
it 'is an object and match options', ->
history = []
nikita()
.registry.register 'handler', (->)
.after action: 'handler', key: 'value 2', ({options}) ->
history.push options.key
.handler key: '<KEY>'
.handler key: 'value <KEY>'
.call ->
history.should.eql ['value 2']
.promise()
describe 'handler', ->
it 'a sync function with sync handler', ->
history = []
nikita()
.registry.register 'sync_fn', ((_) -> history.push 'sync handler' )
.after 'sync_fn', (_) -> history.push 'after sync'
.call -> history.push 'call 1'
.sync_fn -> history.push 'sync callback 1'
.call -> history.push 'call 2'
.sync_fn -> history.push 'sync callback 2'
.call -> history.push 'call 3'
.call ->
history.should.eql [
'call 1', 'sync handler', 'after sync', 'sync callback 1'
'call 2', 'sync handler', 'after sync', 'sync callback 2'
'call 3'
]
.promise()
it 'a sync function with async handler', ->
history = []
nikita()
.registry.register 'afunction', ((_) -> history.push 'sync handler' )
.after 'afunction', (_, callback) ->
setImmediate ->
history.push 'after sync'
callback()
.call -> history.push 'call 1'
.afunction -> history.push 'sync callback 1'
.call -> history.push 'call 2'
.afunction -> history.push 'sync callback 2'
.call -> history.push 'call 3'
.call ->
history.should.eql [
'call 1', 'sync handler', 'after sync', 'sync callback 1'
'call 2', 'sync handler', 'after sync', 'sync callback 2'
'call 3'
]
.promise()
it 'a namespaced sync function with async handler', ->
history = []
nikita()
.registry.register ['a','namespaced','function'], ((_) -> history.push 'sync handler' )
.after ['a','namespaced', 'function'], (_, callback) ->
setImmediate ->
history.push 'after sync'
callback()
.call -> history.push 'call 1'
.a.namespaced.function -> history.push 'sync callback 1'
.call -> history.push 'call 2'
.a.namespaced.function -> history.push 'sync callback 2'
.call -> history.push 'call 3'
.call ->
history.should.eql [
'call 1', 'sync handler', 'after sync', 'sync callback 1'
'call 2', 'sync handler', 'after sync', 'sync callback 2'
'call 3'
]
.promise()
describe 'error', ->
it 'register sync function and throw error', ->
nikita()
.registry.register 'afunction', ( -> )
.after 'afunction', (_) ->
throw Error 'CatchMe'
.afunction (err, status) ->
err.message.should.eql 'CatchMe'
.next (err) ->
err.message.should.eql 'CatchMe'
.promise()
it 'register sync function and throw error', ->
nikita()
.registry.register 'afunction', ( -> )
.after 'afunction', (_, callback) ->
setImmediate -> callback Error 'CatchMe'
.afunction (err, status) ->
err.message.should.eql 'CatchMe'
.next (err) ->
err.message.should.eql 'CatchMe'
.promise()
| true |
nikita = require '../../../src'
{tags} = require '../../test'
return unless tags.api
describe 'api after', ->
describe 'event', ->
it 'is a string and match a action type', ->
history = []
nikita()
.registry.register 'good_handler', (->)
.registry.register 'bad_handler', (->)
.after 'good_handler', ({options}) -> history.push options.key
.good_handler key: 'PI:KEY:<KEY>END_PI'
.good_handler key: 'PI:KEY:<KEY>END_PI'
.call ->
history.should.eql ['value 1', 'value 2']
.promise()
it 'is an object and match options', ->
history = []
nikita()
.registry.register 'handler', (->)
.after action: 'handler', key: 'value 2', ({options}) ->
history.push options.key
.handler key: 'PI:KEY:<KEY>END_PI'
.handler key: 'value PI:KEY:<KEY>END_PI'
.call ->
history.should.eql ['value 2']
.promise()
describe 'handler', ->
it 'a sync function with sync handler', ->
history = []
nikita()
.registry.register 'sync_fn', ((_) -> history.push 'sync handler' )
.after 'sync_fn', (_) -> history.push 'after sync'
.call -> history.push 'call 1'
.sync_fn -> history.push 'sync callback 1'
.call -> history.push 'call 2'
.sync_fn -> history.push 'sync callback 2'
.call -> history.push 'call 3'
.call ->
history.should.eql [
'call 1', 'sync handler', 'after sync', 'sync callback 1'
'call 2', 'sync handler', 'after sync', 'sync callback 2'
'call 3'
]
.promise()
it 'a sync function with async handler', ->
history = []
nikita()
.registry.register 'afunction', ((_) -> history.push 'sync handler' )
.after 'afunction', (_, callback) ->
setImmediate ->
history.push 'after sync'
callback()
.call -> history.push 'call 1'
.afunction -> history.push 'sync callback 1'
.call -> history.push 'call 2'
.afunction -> history.push 'sync callback 2'
.call -> history.push 'call 3'
.call ->
history.should.eql [
'call 1', 'sync handler', 'after sync', 'sync callback 1'
'call 2', 'sync handler', 'after sync', 'sync callback 2'
'call 3'
]
.promise()
it 'a namespaced sync function with async handler', ->
history = []
nikita()
.registry.register ['a','namespaced','function'], ((_) -> history.push 'sync handler' )
.after ['a','namespaced', 'function'], (_, callback) ->
setImmediate ->
history.push 'after sync'
callback()
.call -> history.push 'call 1'
.a.namespaced.function -> history.push 'sync callback 1'
.call -> history.push 'call 2'
.a.namespaced.function -> history.push 'sync callback 2'
.call -> history.push 'call 3'
.call ->
history.should.eql [
'call 1', 'sync handler', 'after sync', 'sync callback 1'
'call 2', 'sync handler', 'after sync', 'sync callback 2'
'call 3'
]
.promise()
describe 'error', ->
it 'register sync function and throw error', ->
nikita()
.registry.register 'afunction', ( -> )
.after 'afunction', (_) ->
throw Error 'CatchMe'
.afunction (err, status) ->
err.message.should.eql 'CatchMe'
.next (err) ->
err.message.should.eql 'CatchMe'
.promise()
it 'register sync function and throw error', ->
nikita()
.registry.register 'afunction', ( -> )
.after 'afunction', (_, callback) ->
setImmediate -> callback Error 'CatchMe'
.afunction (err, status) ->
err.message.should.eql 'CatchMe'
.next (err) ->
err.message.should.eql 'CatchMe'
.promise()
|
[
{
"context": " Person\n\npeopleStore = new People([\n firstName: \"Alex\"\n lastName: \"Rattray\"\n,\n firstName: \"Freeman\"\n ",
"end": 319,
"score": 0.9998290538787842,
"start": 315,
"tag": "NAME",
"value": "Alex"
},
{
"context": "e = new People([\n firstName: \"Alex\"\n last... | index.coffee | rattrayalex/hello-coffee | 0 | console.log "hello!"
React = require('react')
Backbone = require('backbone')
{div, ul, li, input, form, button} = React.DOM
Person = Backbone.Model.extend
fullName: ->
@get('firstName') + " " + @get('lastName')
People = Backbone.Collection.extend
model: Person
peopleStore = new People([
firstName: "Alex"
lastName: "Rattray"
,
firstName: "Freeman"
lastName: "Murray"
])
AddPersonView = React.createClass
handleSubmit: (e) ->
e.preventDefault()
first = @refs.firstName.getDOMNode().value
last = @refs.lastName.getDOMNode().value
@props.people.add({firstName: first, lastName: last})
render: ->
form {onSubmit: @handleSubmit},
input
type: "text"
name: "firstName"
ref: "firstName"
input
type: "text"
name: "lastName"
ref: "lastName"
button
type: "submit"
,
"Submit"
PersonView = React.createClass
componentDidMount: ->
@props.person.on "all", =>
@forceUpdate()
render: ->
ul {},
li {}, "First Name: " + @props.person.get('firstName')
li {}, "Last Name: " + @props.person.get('lastName')
Body = React.createClass
componentDidMount: ->
@props.people.on "add remove reset", =>
@forceUpdate()
render: ->
div {},
"Helloooo mama World!"
div {},
"Add a person: "
AddPersonView({people: @props.people})
div {},
[PersonView({person}) for person in @props.people.models]
rendered = React.render(
Body {people: peopleStore}
document.body
)
| 97813 | console.log "hello!"
React = require('react')
Backbone = require('backbone')
{div, ul, li, input, form, button} = React.DOM
Person = Backbone.Model.extend
fullName: ->
@get('firstName') + " " + @get('lastName')
People = Backbone.Collection.extend
model: Person
peopleStore = new People([
firstName: "<NAME>"
lastName: "<NAME>"
,
firstName: "<NAME>"
lastName: "<NAME>"
])
AddPersonView = React.createClass
handleSubmit: (e) ->
e.preventDefault()
first = @refs.firstName.getDOMNode().value
last = @refs.lastName.getDOMNode().value
@props.people.add({firstName: first, lastName: last})
render: ->
form {onSubmit: @handleSubmit},
input
type: "text"
name: "firstName"
ref: "firstName"
input
type: "text"
name: "<NAME>"
ref: "lastName"
button
type: "submit"
,
"Submit"
PersonView = React.createClass
componentDidMount: ->
@props.person.on "all", =>
@forceUpdate()
render: ->
ul {},
li {}, "First Name: " + @props.person.get('firstName')
li {}, "Last Name: " + @props.person.get('lastName')
Body = React.createClass
componentDidMount: ->
@props.people.on "add remove reset", =>
@forceUpdate()
render: ->
div {},
"Helloooo mama World!"
div {},
"Add a person: "
AddPersonView({people: @props.people})
div {},
[PersonView({person}) for person in @props.people.models]
rendered = React.render(
Body {people: peopleStore}
document.body
)
| true | console.log "hello!"
React = require('react')
Backbone = require('backbone')
{div, ul, li, input, form, button} = React.DOM
Person = Backbone.Model.extend
fullName: ->
@get('firstName') + " " + @get('lastName')
People = Backbone.Collection.extend
model: Person
peopleStore = new People([
firstName: "PI:NAME:<NAME>END_PI"
lastName: "PI:NAME:<NAME>END_PI"
,
firstName: "PI:NAME:<NAME>END_PI"
lastName: "PI:NAME:<NAME>END_PI"
])
AddPersonView = React.createClass
handleSubmit: (e) ->
e.preventDefault()
first = @refs.firstName.getDOMNode().value
last = @refs.lastName.getDOMNode().value
@props.people.add({firstName: first, lastName: last})
render: ->
form {onSubmit: @handleSubmit},
input
type: "text"
name: "firstName"
ref: "firstName"
input
type: "text"
name: "PI:NAME:<NAME>END_PI"
ref: "lastName"
button
type: "submit"
,
"Submit"
PersonView = React.createClass
componentDidMount: ->
@props.person.on "all", =>
@forceUpdate()
render: ->
ul {},
li {}, "First Name: " + @props.person.get('firstName')
li {}, "Last Name: " + @props.person.get('lastName')
Body = React.createClass
componentDidMount: ->
@props.people.on "add remove reset", =>
@forceUpdate()
render: ->
div {},
"Helloooo mama World!"
div {},
"Add a person: "
AddPersonView({people: @props.people})
div {},
[PersonView({person}) for person in @props.people.models]
rendered = React.render(
Body {people: peopleStore}
document.body
)
|
[
{
"context": " = 'debug'\nPANE_APP = 'emp'\nEMP_DEBUG_HOST_KEY = 'emp-debugger.Emp-debugger-host'\nEMP_DEBUG_PORT_KEY = 'emp-debugger.Emp-debugger-",
"end": 543,
"score": 0.9981029033660889,
"start": 513,
"tag": "KEY",
"value": "emp-debugger.Emp-debugger-host"
},
{
"context": "debugg... | lib/view/emp-debugger-setting-view.coffee | jcrom/emp-debugger | 2 | {Disposable, CompositeDisposable} = require 'atom'
{$, $$, View,TextEditorView} = require 'atom-space-pen-views'
emp = require '../exports/emp'
# EmpEditView = require './emp-edit-view'
EmpAppMan = require '../emp_app/emp_app_manage'
EmpBarView = require './emp-setting-bar'
EmpAppManaView = require './emp-app-manage-view'
EmpSnippetsView = require '../debugger/emp_debugger_snippets_view'
# EmpAnalyzeView = require '../analyze/emp-project-ana-view'
PANE_DENUG = 'debug'
PANE_APP = 'emp'
EMP_DEBUG_HOST_KEY = 'emp-debugger.Emp-debugger-host'
EMP_DEBUG_PORT_KEY = 'emp-debugger.Emp-debugger-port'
module.exports =
class EmpDebuggerSettingView extends View
emp_socket_server: null
empDebuggerLogView: null
app_view:null
default_host: 'default'
default_port: '7003'
server_host: null
server_port: null
first_show: true
show_state: false
activ_pane: 'debug'
log_state_pause: "#FF6600"
log_state_show: "#66FF33"
log_state_hide: "#666699"
log_state_close: "#FF1919"
default_name: 'default'
default_color_value: '#FFFFFF'
@content: ->
# console.log 'constructor'
@div class: 'emp-setting tool-panel',=>
@div outlet:"emp_setting_panel", class:'emp-setting-panel', =>
@div outlet:"emp_setting_view", class:'emp-setting-server', =>
# ------------------------ server setting pane ------------------------
@div outlet: 'conf_detail', class: 'emp-setting-row-server', =>
@div class: "emp-setting-con panel-body padded", =>
@div class: "block conf-heading icon icon-gear", "Server Setting"
# ------------------------ server conf pane ------------------------
@div outlet:"emp_conf_pane", class: "emp-setting-con panel-body padded", =>
@label class: "emp-setting-label", "Host "
@div class: 'controls', =>
@div class: 'setting-editor-container', =>
@subview 'emp_set_host', new TextEditorView(mini: true, attributes: {id: 'emp_host', type: 'string'}, placeholderText: 'Editor Server 监听的地址') #from editor view class
@label class: "emp-setting-label", "Port "
@div class: 'controls', =>
@div class: 'setting-editor-container', =>
@subview 'emp_set_port', new TextEditorView(mini: true, attributes: {id: 'emp_port', type: 'string'}, placeholderText: '同Client交互的端口')
@button class: 'btn btn-else btn-success inline-block-tight ', click: 'start_server', "Start Server"
# ------------------------ server state pane ------------------------
@div outlet:"emp_state_pane", class: "emp-setting-con panel-body padded", style:"display:none;", =>
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "Server State : "
@label outlet:"emp_server_st", class: "emp-label-content", "--"
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "Client Number: "
@label outlet:"emp_cl_no", class: "emp-label-content", ""
@button class: 'btn btn-else btn-error inline-block-tight', click: 'stop_server', "Stop Server"
@div class: "emp-btn-group" ,=>
@button class: 'btn btn-else btn-info inline-block-tight', click: 'live_preview', "Live Preview"
@button class: 'btn btn-else btn-info inline-block-tight', click: 'show_enable_views', "Enable Views"
@button class: 'btn btn-else btn-info inline-block-tight', click: 'show_enable_lua', "Enable Lua"
@button class: 'btn btn-else btn-info inline-block-tight', click: 'clear_input_view', "Clear View"
# # ------------------------ log config pane ------------------------
@div outlet: 'log_detail', class: 'emp-setting-row', =>
@div class: "emp-setting-con panel-body padded", =>
@div class: "block conf-heading icon icon-gear", "Log Setting"
@div outlet:"emp_log_pane", class: "emp-setting-con panel-body padded", =>
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "Log State : "
@label outlet:"emp_log_st", class: "emp-label-content", style: "color:#FF1919;", "Close"
@div class: "emp-set-div-content", =>
# @div class: "btn-group", =>
@button outlet: "emp_showlog", class: 'btn btn-else btn-info inline-block-tight icon icon-link-external', click: 'show_log', "Show Log"
@button outlet: "emp_clearlog", class: 'btn btn-else btn-info inline-block-tight icon icon-trashcan', click: 'clear_log', "Clear Log"
@button outlet: "emp_pauselog", class: 'btn btn-else btn-info inline-block-tight icon icon-playback-pause', click: 'pause_log', "Pause Log"
@button outlet: "emp_closelog", class: 'btn btn-else btn-info inline-block-tight icon icon-squirrel', click: 'close_log', "Close Log"
# @button outlet: "emp_closelog", class: 'btn btn-else btn-info inline-block-tight icon icon-squirrel', click: 'test_log', "test Log"
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "ClientID: "
@select outlet: "emp_client_list", class: "form-control", =>
@option outlet:'emp_default_client', value: "default","default"
@label class: "emp-setting-label", "LogColor: "
@select outlet: "emp_log_color_list", class: "form-control", =>
@option outlet:'emp_default_color', value: "default", selected:"selected", "default"
@div class: 'emp-setting-footor', =>
# @ul class:'eul' ,=>
# @button outlet:"emp_footor_btn", class:'btn btn-info inline-block-tight', click: 'hide_setting_view', "Hide"
@ul class:'eul' ,=>
@li outlet:"emp_footor_btn", class:'eli curr',click: 'hide_setting_view', "Hide"
initialize: (serializeState, @emp_socket_server, @empDebuggerLogView, @fa_view) ->
# console.log 'server state view initial'
bar_view = new EmpBarView(this)
@user_set_color = "#000033"
@emp_setting_panel.before(bar_view)
# analyze_view = new EmpAnalyzeView(this)
# @log_detail.after analyze_view
#
snippet_view = new EmpSnippetsView(this)
@log_detail.after snippet_view
@disposable = new CompositeDisposable
@disposable.add atom.commands.add "atom-workspace","emp-debugger:setting-view", => @set_conf()
@server_host = atom.config.get(EMP_DEBUG_HOST_KEY)
@server_port = atom.config.get(EMP_DEBUG_PORT_KEY)
@empDebuggerLogView.set_conf_view(this)
@emp_socket_server.set_conf_view(this)
@defailt_host = @emp_socket_server.get_default_host()
@default_port = @emp_socket_server.get_default_port()
do_test: ->
# @on 'click', '.entry', (e) =>
# # This prevents accidental collapsing when a .entries element is the event target
# # return if e.target.classList.contains('entries')
#
# @entryClicked(e) unless e.shiftKey or e.metaKey or e.ctrlKey
@on 'mousedown', '.entry', (e) =>
@onMouseDown(e)
@on 'mousedown', '.emp-setting-panel', (e) => @resizeStarted(e)
entryClicked: (e) ->
entry = e.currentTarget
isRecursive = e.altKey or false
switch e.originalEvent?.detail ? 1
when 1
@selectEntry(entry)
@openSelectedEntry(false) if entry instanceof FileView
entry.toggleExpansion(isRecursive) if entry instanceof DirectoryView
when 2
if entry instanceof FileView
@unfocus()
else if DirectoryView
entry.toggleExpansion(isRecursive)
false
resizeStarted: =>
$(document).on('mousemove', @resizeTreeView)
$(document).on('mouseup', @resizeStopped)
resizeStopped: =>
$(document).off('mousemove', @resizeTreeView)
$(document).off('mouseup', @resizeStopped)
resizeTreeView: ({pageX, which}) =>
return @resizeStopped() unless which is 1
# if atom.config.get('tree-view.showOnRightSide')
# width = $(document.body).width() - pageX
# else
width = pageX
@width(width)
show_app: ->
# console.log "fa show ~~"
# console.log @app_view
unless @activ_pane is PANE_APP
@create_new_panel()
@emp_setting_view.hide()
@app_view.show()
@app_view.focus()
@activ_pane = PANE_APP
show_debug: ->
unless @activ_pane is PANE_DENUG
unless !@app_view
@app_view.hide()
@emp_setting_view.show()
@emp_setting_view.focus()
@activ_pane = PANE_DENUG
create_new_panel: ->
unless @app_view
@app_view = new EmpAppManaView(this)
@emp_setting_view.before(@app_view)
@app_view.check_os()
@app_view
# Returns an object that can be retrieved when package is activated
serialize: ->
# attached: @panel?.isVisible()
# Tear down any state and detach
destroy: ->
@detach()
detach: ->
@disposable?.dispose()
set_conf: ->
# console.log "panel visible:"
# console.log @panel?.isVisible()
if @first_show
@first_show = false
if @hasParent()
@detach()
@first_show = false
@show_state = false
else
@attach()
@show_state = true
else
if @show_state
# @panel.hide()
this.hide()
@show_state = false
else
# @panel.show()
this.show()
@show_state = true
attach: ->
@panel = atom.workspace.addRightPanel(item:this,visible:true)
# @panel = atom.workspaceView.appendToRight(this)
# atom.workspaceView.prependToRight(this)
@disposable.add new Disposable =>
@panel.destroy()
@panel = null
@init_server_conf_pane()
@init_server_conf()
init_server_conf_pane: ->
if @emp_socket_server.get_server_sate()
@hide_conf_pane()
else
@hide_state_pane()
# @conf_detail.html $$ ->
# @div class: "emp-setting-con panel-body padded", =>
# @div class: "block conf-heading icon icon-gear", "Server Setting"
#
# # ------------------------ server conf pane ------------------------
# @div outlet:"emp_conf_pane", class: "emp-setting-con panel-body padded", =>
# @label class: "emp-setting-label", "Host "
# @div class: 'controls', =>
# @div class: 'setting-editor-container', =>
# @subview "emp_set_host", new TextEditorView(mini: true, attributes: {id: 'emp_host', type: 'string'}, placeholderText: 'Editor Server 监听的地址') #from editor view class
# @label class: "emp-setting-label", "Port "
# @div class: 'controls', =>
# @div class: 'setting-editor-container', =>
# @subview "emp_set_port", new TextEditorView(mini: true, attributes: {id: 'emp_port', type: 'string'}, placeholderText: '同Client交互的端口')
# @button class: 'btn btn-else btn-success inline-block-tight ', click: 'start_server', "Start Server"
init_server_conf: ->
@init_default_value()
@init_server_listen()
@init_log_color_value()
@init_log_conf_listen()
# console.log @test_o
# @test_o.context.style.backgroundColor="#006666"
# @test_o.css('color', "#CC3300")
init_default_value: ->
# console.log atom.config.get('emp-debugger.s_host')
if @server_host is undefined
@server_host = @default_host
atom.config.set(EMP_DEBUG_HOST_KEY, @server_host)
if @server_port is undefined
@server_port = @default_port
atom.config.set(EMP_DEBUG_PORT_KEY, @server_port)
@emp_set_port.setText(@server_port)
@emp_set_host.setText(@server_host)
init_server_listen: ->
# console.log @emp_set_port.getModel()
@emp_set_port.getModel().onDidStopChanging =>
tmp_port = @emp_set_port.getText()
# console.log tmp_port
if @server_port isnt tmp_port
@server_port = tmp_port
atom.config.set(EMP_DEBUG_PORT_KEY, @server_port)
@emp_set_host.getModel().onDidStopChanging =>
tmp_host = @emp_set_host.getText()
# console.log tmp_host
if @server_host isnt tmp_host
@server_host = tmp_host
atom.config.set(EMP_DEBUG_HOST_KEY, @server_host)
# atom.config.set('emp-debugger.s_host', 'value')
# atom.config.observe 'my-package.key', ->
# console.log 'My configuration changed:', atom.config.get('my-package.key')
init_log_color_value: ->
@oLogMaps = @empDebuggerLogView.get_log_store()
aAllLogMaps = @oLogMaps.get_all_log()
for name, view_logs of aAllLogMaps
# console.log name
tmp_color = view_logs.get_color()
tmp_id = view_logs.get_id()
@emp_client_list.append(@create_option("client:#{tmp_id}", tmp_id))
# 设置 log color 为全局记忆的颜色
aDefaultColor = @get_log_default_color()
sGolColor = atom.config.get(emp.EMP_LOG_GLOBAL_COLOR)
for oCol in aDefaultColor
if oCol.value is sGolColor
sOption = @new_select_option(oCol.name, oCol.value)
@emp_log_color_list.css('background-color', oCol.value)
else
sOption = @new_option(oCol.name, oCol.value)
@emp_log_color_list.append(sOption)
init_log_conf_listen: ->
client_id = null
@oLogMaps = @empDebuggerLogView.get_log_store()
@emp_client_list.change =>
console.log "client channge"
client_id = @emp_client_list.val()
console.log client_id
if client_id isnt @default_name
# console.log oLogMaps[client_id]
# console.log @emp_default_color
# @emp_default_color.context.selected = true
@emp_default_color.attr('selected', true)
unless !sTmpCol = @oLogMaps.get_log_col(client_id)
@emp_log_color_list.css('background-color', sTmpCol)
@emp_default_color.val(sTmpCol)
else
if glo_color = atom.config.get(emp.EMP_LOG_GLOBAL_COLOR)
# console.log "option[val=#{glo_color}]"
@emp_log_color_list.find("option[value=#{glo_color}]").attr('selected', true)
else
@emp_default_color.attr('selected', true)
@emp_log_color_list.css('background-color', '')
@emp_default_color.val("#{@default_name}")
@emp_log_color_list.change =>
console.log "color channge"
client_id = @emp_client_list.val()
sSelCol = @emp_log_color_list.val()
console.log sSelCol
if client_id is @default_name
console.log "default id"
# console.log sSelCol
aAllLogMaps = @oLogMaps.get_all_log()
if sSelCol isnt @default_name
atom.config.set(emp.EMP_LOG_GLOBAL_COLOR, sSelCol)
@emp_log_color_list.css('background-color', sSelCol)
# atom.project.glo_color = sSelCol
for cli_id, cli_view of aAllLogMaps
cli_view.set_glo_color sSelCol
else
atom.config.set(emp.EMP_LOG_GLOBAL_COLOR, null)
@emp_default_color.val("#{@default_name}")
@emp_log_color_list.css('background-color', '')
# atom.project.glo_color = null
for cli_id, cli_view of aAllLogMaps
cli_view.set_glo_color null
else
# console.log sSelCol
if sSelCol isnt @default_name
@emp_log_color_list.css('background-color', sSelCol)
client_id = @emp_client_list.val()
@oLogMaps.set_log_col(client_id, sSelCol)
# @log_map[client_id].set_glo_color null
else
@oLogMaps.set_log_gol_col client_id, null
@emp_log_color_list.css('background-color', @oLogMaps.get_log_col(client_id))
refresh_log_view: (@oLogMaps, client_id, sTmpColor)->
@emp_client_list.append(@create_option("client:#{client_id}", client_id))
@emp_log_color_list.append(@create_else_option(sTmpColor))
remove_client: (client_id) ->
# console.log "remove: #{client_id}"
@refresh_state_pane_ln()
@remove_log_view(client_id)
remove_log_view: (client_id)->
# console.log @emp_client_list
@emp_client_list.find("option[id=#{client_id}]").remove()
select_client = @emp_client_list.val()
console.log select_client
console.log (select_client is client_id)
if select_client is client_id
@emp_default_client.attr('selected', true)
@emp_default_color.attr('selected', true)
@emp_log_color_list.css('background-color', @default_color_value)
create_option: (name, value)->
$$ -> @option id:"#{value}", value: value, name
create_else_option: (color)->
$$ -> @option style:"background-color:#{color};", value: color
# -------------------------------------------------------------------------
# view maintain
hide_conf_pane: ->
# console.log "call:hide_conf_pane"
@emp_conf_pane.hide()
@refresh_state_pane()
@emp_state_pane.show()
hide_state_pane: ->
@emp_conf_pane.show()
@emp_state_pane.hide()
refresh_state_pane: ->
if @emp_socket_server.get_server_sate()
@emp_server_st["context"].innerHTML = "On"
@emp_cl_no["context"].innerHTML=@emp_socket_server.get_client_map().get_active_len()
refresh_state_pane_ln: ->
if @emp_socket_server.get_server_sate()
@emp_cl_no["context"].innerHTML=@emp_socket_server.get_client_map().get_active_len()
# -------------------------------------------------------------------------
# util fun
# btn callback
start_server: (event, element) ->
# console.log element
# console.log "port:#{@emp_server_port}"
# console.log "host:#{@emp_server_host}"
new_server_host = @server_host.trim()
new_server_port = @server_port.trim()
# console.log new_server_host
# console.log new_server_port
new_server_host = @default_host unless new_server_host isnt ''
new_server_port = @default_port unless new_server_port isnt ''
# console.log @emp_server_port
new_server_port = @parseValue('number', new_server_port)
console.log "local server start with option parameters: host: #{new_server_host}, port: #{new_server_port}"
@emp_socket_server.init(new_server_host, new_server_port) unless @emp_socket_server.get_server() isnt null
# btn callback
stop_server: (event, element) ->
@emp_socket_server.close()
@hide_state_pane()
# -------------------------------------------------------------------------
# btn for hide the setting view
hide_setting_view: () ->
this.hide()
@show_state = false
# -------------------------------------------------------------------------
live_preview: ->
console.log "live preview"
@fa_view.live_preview()
show_enable_views: ->
console.log "show enable preview"
@fa_view.show_enable_view()
show_enable_lua: ->
console.log "show enbale lua"
@fa_view.show_enable_lua()
# 清除 enable view 和 enable lua 的内容
clear_input_view: ->
@emp_socket_server.get_client_map().clear_all_views()
console.info "清除 View 完成."
emp.show_info "清除 View 完成."
# btn callback for log setting
show_log: ->
# console.log "show_log"
show_state = @empDebuggerLogView.show_log_state()
if show_state
@empDebuggerLogView.hide_log_view()
# @emp_showlog.context.innerHTML = "Show Log"
# @refresh_log_st(@log_state_hide)
else
@empDebuggerLogView.show_log()
# @emp_showlog.context.innerHTML = "Hide Log"
# @refresh_log_st(@log_state_show)
show_log_callback: ->
@emp_showlog.context.innerHTML = "Hide Log"
@refresh_log_st(@log_state_show)
hide_log_callback: ->
@emp_showlog.context.innerHTML = "Show Log"
@refresh_log_st(@log_state_hide)
clear_log: ->
# console.log "clear_log"
@empDebuggerLogView.clear_log()
pause_log: ->
# console.log "stop_log"
pause_state = @empDebuggerLogView.get_pause_state()
if pause_state
@empDebuggerLogView.continue_log()
@emp_pauselog.context.innerHTML = "Pause Log"
@refresh_log_st(@log_state_show)
else
@empDebuggerLogView.stop_log()
@emp_pauselog.context.innerHTML = "Continue Log"
@refresh_log_st(@log_state_pause)
close_log: ->
# console.log "close_log"
@empDebuggerLogView.close_log_view()
@refresh_log_st(@log_state_close)
refresh_log_st: (css_style)->
log_st_str = @empDebuggerLogView.get_log_pane_state()
@emp_log_st.context.innerHTML = log_st_str
@emp_log_st.css('color', css_style)
# -------------------------------------------------------------------------
valueToString: (value) ->
if _.isArray(value)
value.join(", ")
else
value?.toString()
parseValue: (type, value) ->
if value == ''
value = undefined
else if type == 'number'
floatValue = parseFloat(value)
value = floatValue unless isNaN(floatValue)
else if type == 'array'
arrayValue = (value or '').split(',')
value = (val.trim() for val in arrayValue when val)
value
new_option: (name, value=name)->
$$ ->
@option value: value, name
new_select_option: (name, value=name) ->
$$ ->
@option selected:'select', value: value, name
get_log_default_color: ->
return [{value: "#000033", name: "黑"},
{value: "#FFFFFF", name: "白"},
{value: "#FF0000", name: "红"},
{value: "#FFFF33", name: "黄"},
{value: "#0000FF", name: "蓝"},
{value: "#00FF00", name: "绿"},
{value: "#00FFFF", name: "青"},
{value: "#FF6600", name: "橙"},
{value: "#990099", name: "紫"}]
| 150784 | {Disposable, CompositeDisposable} = require 'atom'
{$, $$, View,TextEditorView} = require 'atom-space-pen-views'
emp = require '../exports/emp'
# EmpEditView = require './emp-edit-view'
EmpAppMan = require '../emp_app/emp_app_manage'
EmpBarView = require './emp-setting-bar'
EmpAppManaView = require './emp-app-manage-view'
EmpSnippetsView = require '../debugger/emp_debugger_snippets_view'
# EmpAnalyzeView = require '../analyze/emp-project-ana-view'
PANE_DENUG = 'debug'
PANE_APP = 'emp'
EMP_DEBUG_HOST_KEY = '<KEY>'
EMP_DEBUG_PORT_KEY = '<KEY>'
module.exports =
class EmpDebuggerSettingView extends View
emp_socket_server: null
empDebuggerLogView: null
app_view:null
default_host: 'default'
default_port: '7003'
server_host: null
server_port: null
first_show: true
show_state: false
activ_pane: 'debug'
log_state_pause: "#FF6600"
log_state_show: "#66FF33"
log_state_hide: "#666699"
log_state_close: "#FF1919"
default_name: 'default'
default_color_value: '#FFFFFF'
@content: ->
# console.log 'constructor'
@div class: 'emp-setting tool-panel',=>
@div outlet:"emp_setting_panel", class:'emp-setting-panel', =>
@div outlet:"emp_setting_view", class:'emp-setting-server', =>
# ------------------------ server setting pane ------------------------
@div outlet: 'conf_detail', class: 'emp-setting-row-server', =>
@div class: "emp-setting-con panel-body padded", =>
@div class: "block conf-heading icon icon-gear", "Server Setting"
# ------------------------ server conf pane ------------------------
@div outlet:"emp_conf_pane", class: "emp-setting-con panel-body padded", =>
@label class: "emp-setting-label", "Host "
@div class: 'controls', =>
@div class: 'setting-editor-container', =>
@subview 'emp_set_host', new TextEditorView(mini: true, attributes: {id: 'emp_host', type: 'string'}, placeholderText: 'Editor Server 监听的地址') #from editor view class
@label class: "emp-setting-label", "Port "
@div class: 'controls', =>
@div class: 'setting-editor-container', =>
@subview 'emp_set_port', new TextEditorView(mini: true, attributes: {id: 'emp_port', type: 'string'}, placeholderText: '同Client交互的端口')
@button class: 'btn btn-else btn-success inline-block-tight ', click: 'start_server', "Start Server"
# ------------------------ server state pane ------------------------
@div outlet:"emp_state_pane", class: "emp-setting-con panel-body padded", style:"display:none;", =>
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "Server State : "
@label outlet:"emp_server_st", class: "emp-label-content", "--"
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "Client Number: "
@label outlet:"emp_cl_no", class: "emp-label-content", ""
@button class: 'btn btn-else btn-error inline-block-tight', click: 'stop_server', "Stop Server"
@div class: "emp-btn-group" ,=>
@button class: 'btn btn-else btn-info inline-block-tight', click: 'live_preview', "Live Preview"
@button class: 'btn btn-else btn-info inline-block-tight', click: 'show_enable_views', "Enable Views"
@button class: 'btn btn-else btn-info inline-block-tight', click: 'show_enable_lua', "Enable Lua"
@button class: 'btn btn-else btn-info inline-block-tight', click: 'clear_input_view', "Clear View"
# # ------------------------ log config pane ------------------------
@div outlet: 'log_detail', class: 'emp-setting-row', =>
@div class: "emp-setting-con panel-body padded", =>
@div class: "block conf-heading icon icon-gear", "Log Setting"
@div outlet:"emp_log_pane", class: "emp-setting-con panel-body padded", =>
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "Log State : "
@label outlet:"emp_log_st", class: "emp-label-content", style: "color:#FF1919;", "Close"
@div class: "emp-set-div-content", =>
# @div class: "btn-group", =>
@button outlet: "emp_showlog", class: 'btn btn-else btn-info inline-block-tight icon icon-link-external', click: 'show_log', "Show Log"
@button outlet: "emp_clearlog", class: 'btn btn-else btn-info inline-block-tight icon icon-trashcan', click: 'clear_log', "Clear Log"
@button outlet: "emp_pauselog", class: 'btn btn-else btn-info inline-block-tight icon icon-playback-pause', click: 'pause_log', "Pause Log"
@button outlet: "emp_closelog", class: 'btn btn-else btn-info inline-block-tight icon icon-squirrel', click: 'close_log', "Close Log"
# @button outlet: "emp_closelog", class: 'btn btn-else btn-info inline-block-tight icon icon-squirrel', click: 'test_log', "test Log"
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "ClientID: "
@select outlet: "emp_client_list", class: "form-control", =>
@option outlet:'emp_default_client', value: "default","default"
@label class: "emp-setting-label", "LogColor: "
@select outlet: "emp_log_color_list", class: "form-control", =>
@option outlet:'emp_default_color', value: "default", selected:"selected", "default"
@div class: 'emp-setting-footor', =>
# @ul class:'eul' ,=>
# @button outlet:"emp_footor_btn", class:'btn btn-info inline-block-tight', click: 'hide_setting_view', "Hide"
@ul class:'eul' ,=>
@li outlet:"emp_footor_btn", class:'eli curr',click: 'hide_setting_view', "Hide"
initialize: (serializeState, @emp_socket_server, @empDebuggerLogView, @fa_view) ->
# console.log 'server state view initial'
bar_view = new EmpBarView(this)
@user_set_color = "#000033"
@emp_setting_panel.before(bar_view)
# analyze_view = new EmpAnalyzeView(this)
# @log_detail.after analyze_view
#
snippet_view = new EmpSnippetsView(this)
@log_detail.after snippet_view
@disposable = new CompositeDisposable
@disposable.add atom.commands.add "atom-workspace","emp-debugger:setting-view", => @set_conf()
@server_host = atom.config.get(EMP_DEBUG_HOST_KEY)
@server_port = atom.config.get(EMP_DEBUG_PORT_KEY)
@empDebuggerLogView.set_conf_view(this)
@emp_socket_server.set_conf_view(this)
@defailt_host = @emp_socket_server.get_default_host()
@default_port = @emp_socket_server.get_default_port()
do_test: ->
# @on 'click', '.entry', (e) =>
# # This prevents accidental collapsing when a .entries element is the event target
# # return if e.target.classList.contains('entries')
#
# @entryClicked(e) unless e.shiftKey or e.metaKey or e.ctrlKey
@on 'mousedown', '.entry', (e) =>
@onMouseDown(e)
@on 'mousedown', '.emp-setting-panel', (e) => @resizeStarted(e)
entryClicked: (e) ->
entry = e.currentTarget
isRecursive = e.altKey or false
switch e.originalEvent?.detail ? 1
when 1
@selectEntry(entry)
@openSelectedEntry(false) if entry instanceof FileView
entry.toggleExpansion(isRecursive) if entry instanceof DirectoryView
when 2
if entry instanceof FileView
@unfocus()
else if DirectoryView
entry.toggleExpansion(isRecursive)
false
resizeStarted: =>
$(document).on('mousemove', @resizeTreeView)
$(document).on('mouseup', @resizeStopped)
resizeStopped: =>
$(document).off('mousemove', @resizeTreeView)
$(document).off('mouseup', @resizeStopped)
resizeTreeView: ({pageX, which}) =>
return @resizeStopped() unless which is 1
# if atom.config.get('tree-view.showOnRightSide')
# width = $(document.body).width() - pageX
# else
width = pageX
@width(width)
show_app: ->
# console.log "fa show ~~"
# console.log @app_view
unless @activ_pane is PANE_APP
@create_new_panel()
@emp_setting_view.hide()
@app_view.show()
@app_view.focus()
@activ_pane = PANE_APP
show_debug: ->
unless @activ_pane is PANE_DENUG
unless !@app_view
@app_view.hide()
@emp_setting_view.show()
@emp_setting_view.focus()
@activ_pane = PANE_DENUG
create_new_panel: ->
unless @app_view
@app_view = new EmpAppManaView(this)
@emp_setting_view.before(@app_view)
@app_view.check_os()
@app_view
# Returns an object that can be retrieved when package is activated
serialize: ->
# attached: @panel?.isVisible()
# Tear down any state and detach
destroy: ->
@detach()
detach: ->
@disposable?.dispose()
set_conf: ->
# console.log "panel visible:"
# console.log @panel?.isVisible()
if @first_show
@first_show = false
if @hasParent()
@detach()
@first_show = false
@show_state = false
else
@attach()
@show_state = true
else
if @show_state
# @panel.hide()
this.hide()
@show_state = false
else
# @panel.show()
this.show()
@show_state = true
attach: ->
@panel = atom.workspace.addRightPanel(item:this,visible:true)
# @panel = atom.workspaceView.appendToRight(this)
# atom.workspaceView.prependToRight(this)
@disposable.add new Disposable =>
@panel.destroy()
@panel = null
@init_server_conf_pane()
@init_server_conf()
init_server_conf_pane: ->
if @emp_socket_server.get_server_sate()
@hide_conf_pane()
else
@hide_state_pane()
# @conf_detail.html $$ ->
# @div class: "emp-setting-con panel-body padded", =>
# @div class: "block conf-heading icon icon-gear", "Server Setting"
#
# # ------------------------ server conf pane ------------------------
# @div outlet:"emp_conf_pane", class: "emp-setting-con panel-body padded", =>
# @label class: "emp-setting-label", "Host "
# @div class: 'controls', =>
# @div class: 'setting-editor-container', =>
# @subview "emp_set_host", new TextEditorView(mini: true, attributes: {id: 'emp_host', type: 'string'}, placeholderText: 'Editor Server 监听的地址') #from editor view class
# @label class: "emp-setting-label", "Port "
# @div class: 'controls', =>
# @div class: 'setting-editor-container', =>
# @subview "emp_set_port", new TextEditorView(mini: true, attributes: {id: 'emp_port', type: 'string'}, placeholderText: '同Client交互的端口')
# @button class: 'btn btn-else btn-success inline-block-tight ', click: 'start_server', "Start Server"
init_server_conf: ->
@init_default_value()
@init_server_listen()
@init_log_color_value()
@init_log_conf_listen()
# console.log @test_o
# @test_o.context.style.backgroundColor="#006666"
# @test_o.css('color', "#CC3300")
init_default_value: ->
# console.log atom.config.get('emp-debugger.s_host')
if @server_host is undefined
@server_host = @default_host
atom.config.set(EMP_DEBUG_HOST_KEY, @server_host)
if @server_port is undefined
@server_port = @default_port
atom.config.set(EMP_DEBUG_PORT_KEY, @server_port)
@emp_set_port.setText(@server_port)
@emp_set_host.setText(@server_host)
init_server_listen: ->
# console.log @emp_set_port.getModel()
@emp_set_port.getModel().onDidStopChanging =>
tmp_port = @emp_set_port.getText()
# console.log tmp_port
if @server_port isnt tmp_port
@server_port = tmp_port
atom.config.set(EMP_DEBUG_PORT_KEY, @server_port)
@emp_set_host.getModel().onDidStopChanging =>
tmp_host = @emp_set_host.getText()
# console.log tmp_host
if @server_host isnt tmp_host
@server_host = tmp_host
atom.config.set(EMP_DEBUG_HOST_KEY, @server_host)
# atom.config.set('emp-debugger.s_host', 'value')
# atom.config.observe 'my-package.key', ->
# console.log 'My configuration changed:', atom.config.get('my-package.key')
init_log_color_value: ->
@oLogMaps = @empDebuggerLogView.get_log_store()
aAllLogMaps = @oLogMaps.get_all_log()
for name, view_logs of aAllLogMaps
# console.log name
tmp_color = view_logs.get_color()
tmp_id = view_logs.get_id()
@emp_client_list.append(@create_option("client:#{tmp_id}", tmp_id))
# 设置 log color 为全局记忆的颜色
aDefaultColor = @get_log_default_color()
sGolColor = atom.config.get(emp.EMP_LOG_GLOBAL_COLOR)
for oCol in aDefaultColor
if oCol.value is sGolColor
sOption = @new_select_option(oCol.name, oCol.value)
@emp_log_color_list.css('background-color', oCol.value)
else
sOption = @new_option(oCol.name, oCol.value)
@emp_log_color_list.append(sOption)
init_log_conf_listen: ->
client_id = null
@oLogMaps = @empDebuggerLogView.get_log_store()
@emp_client_list.change =>
console.log "client channge"
client_id = @emp_client_list.val()
console.log client_id
if client_id isnt @default_name
# console.log oLogMaps[client_id]
# console.log @emp_default_color
# @emp_default_color.context.selected = true
@emp_default_color.attr('selected', true)
unless !sTmpCol = @oLogMaps.get_log_col(client_id)
@emp_log_color_list.css('background-color', sTmpCol)
@emp_default_color.val(sTmpCol)
else
if glo_color = atom.config.get(emp.EMP_LOG_GLOBAL_COLOR)
# console.log "option[val=#{glo_color}]"
@emp_log_color_list.find("option[value=#{glo_color}]").attr('selected', true)
else
@emp_default_color.attr('selected', true)
@emp_log_color_list.css('background-color', '')
@emp_default_color.val("#{@default_name}")
@emp_log_color_list.change =>
console.log "color channge"
client_id = @emp_client_list.val()
sSelCol = @emp_log_color_list.val()
console.log sSelCol
if client_id is @default_name
console.log "default id"
# console.log sSelCol
aAllLogMaps = @oLogMaps.get_all_log()
if sSelCol isnt @default_name
atom.config.set(emp.EMP_LOG_GLOBAL_COLOR, sSelCol)
@emp_log_color_list.css('background-color', sSelCol)
# atom.project.glo_color = sSelCol
for cli_id, cli_view of aAllLogMaps
cli_view.set_glo_color sSelCol
else
atom.config.set(emp.EMP_LOG_GLOBAL_COLOR, null)
@emp_default_color.val("#{@default_name}")
@emp_log_color_list.css('background-color', '')
# atom.project.glo_color = null
for cli_id, cli_view of aAllLogMaps
cli_view.set_glo_color null
else
# console.log sSelCol
if sSelCol isnt @default_name
@emp_log_color_list.css('background-color', sSelCol)
client_id = @emp_client_list.val()
@oLogMaps.set_log_col(client_id, sSelCol)
# @log_map[client_id].set_glo_color null
else
@oLogMaps.set_log_gol_col client_id, null
@emp_log_color_list.css('background-color', @oLogMaps.get_log_col(client_id))
refresh_log_view: (@oLogMaps, client_id, sTmpColor)->
@emp_client_list.append(@create_option("client:#{client_id}", client_id))
@emp_log_color_list.append(@create_else_option(sTmpColor))
remove_client: (client_id) ->
# console.log "remove: #{client_id}"
@refresh_state_pane_ln()
@remove_log_view(client_id)
remove_log_view: (client_id)->
# console.log @emp_client_list
@emp_client_list.find("option[id=#{client_id}]").remove()
select_client = @emp_client_list.val()
console.log select_client
console.log (select_client is client_id)
if select_client is client_id
@emp_default_client.attr('selected', true)
@emp_default_color.attr('selected', true)
@emp_log_color_list.css('background-color', @default_color_value)
create_option: (name, value)->
$$ -> @option id:"#{value}", value: value, name
create_else_option: (color)->
$$ -> @option style:"background-color:#{color};", value: color
# -------------------------------------------------------------------------
# view maintain
hide_conf_pane: ->
# console.log "call:hide_conf_pane"
@emp_conf_pane.hide()
@refresh_state_pane()
@emp_state_pane.show()
hide_state_pane: ->
@emp_conf_pane.show()
@emp_state_pane.hide()
refresh_state_pane: ->
if @emp_socket_server.get_server_sate()
@emp_server_st["context"].innerHTML = "On"
@emp_cl_no["context"].innerHTML=@emp_socket_server.get_client_map().get_active_len()
refresh_state_pane_ln: ->
if @emp_socket_server.get_server_sate()
@emp_cl_no["context"].innerHTML=@emp_socket_server.get_client_map().get_active_len()
# -------------------------------------------------------------------------
# util fun
# btn callback
start_server: (event, element) ->
# console.log element
# console.log "port:#{@emp_server_port}"
# console.log "host:#{@emp_server_host}"
new_server_host = @server_host.trim()
new_server_port = @server_port.trim()
# console.log new_server_host
# console.log new_server_port
new_server_host = @default_host unless new_server_host isnt ''
new_server_port = @default_port unless new_server_port isnt ''
# console.log @emp_server_port
new_server_port = @parseValue('number', new_server_port)
console.log "local server start with option parameters: host: #{new_server_host}, port: #{new_server_port}"
@emp_socket_server.init(new_server_host, new_server_port) unless @emp_socket_server.get_server() isnt null
# btn callback
stop_server: (event, element) ->
@emp_socket_server.close()
@hide_state_pane()
# -------------------------------------------------------------------------
# btn for hide the setting view
hide_setting_view: () ->
this.hide()
@show_state = false
# -------------------------------------------------------------------------
live_preview: ->
console.log "live preview"
@fa_view.live_preview()
show_enable_views: ->
console.log "show enable preview"
@fa_view.show_enable_view()
show_enable_lua: ->
console.log "show enbale lua"
@fa_view.show_enable_lua()
# 清除 enable view 和 enable lua 的内容
clear_input_view: ->
@emp_socket_server.get_client_map().clear_all_views()
console.info "清除 View 完成."
emp.show_info "清除 View 完成."
# btn callback for log setting
show_log: ->
# console.log "show_log"
show_state = @empDebuggerLogView.show_log_state()
if show_state
@empDebuggerLogView.hide_log_view()
# @emp_showlog.context.innerHTML = "Show Log"
# @refresh_log_st(@log_state_hide)
else
@empDebuggerLogView.show_log()
# @emp_showlog.context.innerHTML = "Hide Log"
# @refresh_log_st(@log_state_show)
show_log_callback: ->
@emp_showlog.context.innerHTML = "Hide Log"
@refresh_log_st(@log_state_show)
hide_log_callback: ->
@emp_showlog.context.innerHTML = "Show Log"
@refresh_log_st(@log_state_hide)
clear_log: ->
# console.log "clear_log"
@empDebuggerLogView.clear_log()
pause_log: ->
# console.log "stop_log"
pause_state = @empDebuggerLogView.get_pause_state()
if pause_state
@empDebuggerLogView.continue_log()
@emp_pauselog.context.innerHTML = "Pause Log"
@refresh_log_st(@log_state_show)
else
@empDebuggerLogView.stop_log()
@emp_pauselog.context.innerHTML = "Continue Log"
@refresh_log_st(@log_state_pause)
close_log: ->
# console.log "close_log"
@empDebuggerLogView.close_log_view()
@refresh_log_st(@log_state_close)
refresh_log_st: (css_style)->
log_st_str = @empDebuggerLogView.get_log_pane_state()
@emp_log_st.context.innerHTML = log_st_str
@emp_log_st.css('color', css_style)
# -------------------------------------------------------------------------
valueToString: (value) ->
if _.isArray(value)
value.join(", ")
else
value?.toString()
parseValue: (type, value) ->
if value == ''
value = undefined
else if type == 'number'
floatValue = parseFloat(value)
value = floatValue unless isNaN(floatValue)
else if type == 'array'
arrayValue = (value or '').split(',')
value = (val.trim() for val in arrayValue when val)
value
new_option: (name, value=name)->
$$ ->
@option value: value, name
new_select_option: (name, value=name) ->
$$ ->
@option selected:'select', value: value, name
get_log_default_color: ->
return [{value: "#000033", name: "黑"},
{value: "#FFFFFF", name: "白"},
{value: "#FF0000", name: "红"},
{value: "#FFFF33", name: "黄"},
{value: "#0000FF", name: "蓝"},
{value: "#00FF00", name: "绿"},
{value: "#00FFFF", name: "青"},
{value: "#FF6600", name: "橙"},
{value: "#990099", name: "紫"}]
| true | {Disposable, CompositeDisposable} = require 'atom'
{$, $$, View,TextEditorView} = require 'atom-space-pen-views'
emp = require '../exports/emp'
# EmpEditView = require './emp-edit-view'
EmpAppMan = require '../emp_app/emp_app_manage'
EmpBarView = require './emp-setting-bar'
EmpAppManaView = require './emp-app-manage-view'
EmpSnippetsView = require '../debugger/emp_debugger_snippets_view'
# EmpAnalyzeView = require '../analyze/emp-project-ana-view'
PANE_DENUG = 'debug'
PANE_APP = 'emp'
EMP_DEBUG_HOST_KEY = 'PI:KEY:<KEY>END_PI'
EMP_DEBUG_PORT_KEY = 'PI:KEY:<KEY>END_PI'
module.exports =
class EmpDebuggerSettingView extends View
emp_socket_server: null
empDebuggerLogView: null
app_view:null
default_host: 'default'
default_port: '7003'
server_host: null
server_port: null
first_show: true
show_state: false
activ_pane: 'debug'
log_state_pause: "#FF6600"
log_state_show: "#66FF33"
log_state_hide: "#666699"
log_state_close: "#FF1919"
default_name: 'default'
default_color_value: '#FFFFFF'
@content: ->
# console.log 'constructor'
@div class: 'emp-setting tool-panel',=>
@div outlet:"emp_setting_panel", class:'emp-setting-panel', =>
@div outlet:"emp_setting_view", class:'emp-setting-server', =>
# ------------------------ server setting pane ------------------------
@div outlet: 'conf_detail', class: 'emp-setting-row-server', =>
@div class: "emp-setting-con panel-body padded", =>
@div class: "block conf-heading icon icon-gear", "Server Setting"
# ------------------------ server conf pane ------------------------
@div outlet:"emp_conf_pane", class: "emp-setting-con panel-body padded", =>
@label class: "emp-setting-label", "Host "
@div class: 'controls', =>
@div class: 'setting-editor-container', =>
@subview 'emp_set_host', new TextEditorView(mini: true, attributes: {id: 'emp_host', type: 'string'}, placeholderText: 'Editor Server 监听的地址') #from editor view class
@label class: "emp-setting-label", "Port "
@div class: 'controls', =>
@div class: 'setting-editor-container', =>
@subview 'emp_set_port', new TextEditorView(mini: true, attributes: {id: 'emp_port', type: 'string'}, placeholderText: '同Client交互的端口')
@button class: 'btn btn-else btn-success inline-block-tight ', click: 'start_server', "Start Server"
# ------------------------ server state pane ------------------------
@div outlet:"emp_state_pane", class: "emp-setting-con panel-body padded", style:"display:none;", =>
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "Server State : "
@label outlet:"emp_server_st", class: "emp-label-content", "--"
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "Client Number: "
@label outlet:"emp_cl_no", class: "emp-label-content", ""
@button class: 'btn btn-else btn-error inline-block-tight', click: 'stop_server', "Stop Server"
@div class: "emp-btn-group" ,=>
@button class: 'btn btn-else btn-info inline-block-tight', click: 'live_preview', "Live Preview"
@button class: 'btn btn-else btn-info inline-block-tight', click: 'show_enable_views', "Enable Views"
@button class: 'btn btn-else btn-info inline-block-tight', click: 'show_enable_lua', "Enable Lua"
@button class: 'btn btn-else btn-info inline-block-tight', click: 'clear_input_view', "Clear View"
# # ------------------------ log config pane ------------------------
@div outlet: 'log_detail', class: 'emp-setting-row', =>
@div class: "emp-setting-con panel-body padded", =>
@div class: "block conf-heading icon icon-gear", "Log Setting"
@div outlet:"emp_log_pane", class: "emp-setting-con panel-body padded", =>
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "Log State : "
@label outlet:"emp_log_st", class: "emp-label-content", style: "color:#FF1919;", "Close"
@div class: "emp-set-div-content", =>
# @div class: "btn-group", =>
@button outlet: "emp_showlog", class: 'btn btn-else btn-info inline-block-tight icon icon-link-external', click: 'show_log', "Show Log"
@button outlet: "emp_clearlog", class: 'btn btn-else btn-info inline-block-tight icon icon-trashcan', click: 'clear_log', "Clear Log"
@button outlet: "emp_pauselog", class: 'btn btn-else btn-info inline-block-tight icon icon-playback-pause', click: 'pause_log', "Pause Log"
@button outlet: "emp_closelog", class: 'btn btn-else btn-info inline-block-tight icon icon-squirrel', click: 'close_log', "Close Log"
# @button outlet: "emp_closelog", class: 'btn btn-else btn-info inline-block-tight icon icon-squirrel', click: 'test_log', "test Log"
@div class: "emp-set-div-content", =>
@label class: "emp-setting-label", "ClientID: "
@select outlet: "emp_client_list", class: "form-control", =>
@option outlet:'emp_default_client', value: "default","default"
@label class: "emp-setting-label", "LogColor: "
@select outlet: "emp_log_color_list", class: "form-control", =>
@option outlet:'emp_default_color', value: "default", selected:"selected", "default"
@div class: 'emp-setting-footor', =>
# @ul class:'eul' ,=>
# @button outlet:"emp_footor_btn", class:'btn btn-info inline-block-tight', click: 'hide_setting_view', "Hide"
@ul class:'eul' ,=>
@li outlet:"emp_footor_btn", class:'eli curr',click: 'hide_setting_view', "Hide"
initialize: (serializeState, @emp_socket_server, @empDebuggerLogView, @fa_view) ->
# console.log 'server state view initial'
bar_view = new EmpBarView(this)
@user_set_color = "#000033"
@emp_setting_panel.before(bar_view)
# analyze_view = new EmpAnalyzeView(this)
# @log_detail.after analyze_view
#
snippet_view = new EmpSnippetsView(this)
@log_detail.after snippet_view
@disposable = new CompositeDisposable
@disposable.add atom.commands.add "atom-workspace","emp-debugger:setting-view", => @set_conf()
@server_host = atom.config.get(EMP_DEBUG_HOST_KEY)
@server_port = atom.config.get(EMP_DEBUG_PORT_KEY)
@empDebuggerLogView.set_conf_view(this)
@emp_socket_server.set_conf_view(this)
@defailt_host = @emp_socket_server.get_default_host()
@default_port = @emp_socket_server.get_default_port()
do_test: ->
# @on 'click', '.entry', (e) =>
# # This prevents accidental collapsing when a .entries element is the event target
# # return if e.target.classList.contains('entries')
#
# @entryClicked(e) unless e.shiftKey or e.metaKey or e.ctrlKey
@on 'mousedown', '.entry', (e) =>
@onMouseDown(e)
@on 'mousedown', '.emp-setting-panel', (e) => @resizeStarted(e)
entryClicked: (e) ->
entry = e.currentTarget
isRecursive = e.altKey or false
switch e.originalEvent?.detail ? 1
when 1
@selectEntry(entry)
@openSelectedEntry(false) if entry instanceof FileView
entry.toggleExpansion(isRecursive) if entry instanceof DirectoryView
when 2
if entry instanceof FileView
@unfocus()
else if DirectoryView
entry.toggleExpansion(isRecursive)
false
resizeStarted: =>
$(document).on('mousemove', @resizeTreeView)
$(document).on('mouseup', @resizeStopped)
resizeStopped: =>
$(document).off('mousemove', @resizeTreeView)
$(document).off('mouseup', @resizeStopped)
resizeTreeView: ({pageX, which}) =>
return @resizeStopped() unless which is 1
# if atom.config.get('tree-view.showOnRightSide')
# width = $(document.body).width() - pageX
# else
width = pageX
@width(width)
show_app: ->
# console.log "fa show ~~"
# console.log @app_view
unless @activ_pane is PANE_APP
@create_new_panel()
@emp_setting_view.hide()
@app_view.show()
@app_view.focus()
@activ_pane = PANE_APP
show_debug: ->
unless @activ_pane is PANE_DENUG
unless !@app_view
@app_view.hide()
@emp_setting_view.show()
@emp_setting_view.focus()
@activ_pane = PANE_DENUG
create_new_panel: ->
unless @app_view
@app_view = new EmpAppManaView(this)
@emp_setting_view.before(@app_view)
@app_view.check_os()
@app_view
# Returns an object that can be retrieved when package is activated
serialize: ->
# attached: @panel?.isVisible()
# Tear down any state and detach
destroy: ->
@detach()
detach: ->
@disposable?.dispose()
set_conf: ->
# console.log "panel visible:"
# console.log @panel?.isVisible()
if @first_show
@first_show = false
if @hasParent()
@detach()
@first_show = false
@show_state = false
else
@attach()
@show_state = true
else
if @show_state
# @panel.hide()
this.hide()
@show_state = false
else
# @panel.show()
this.show()
@show_state = true
attach: ->
@panel = atom.workspace.addRightPanel(item:this,visible:true)
# @panel = atom.workspaceView.appendToRight(this)
# atom.workspaceView.prependToRight(this)
@disposable.add new Disposable =>
@panel.destroy()
@panel = null
@init_server_conf_pane()
@init_server_conf()
init_server_conf_pane: ->
if @emp_socket_server.get_server_sate()
@hide_conf_pane()
else
@hide_state_pane()
# @conf_detail.html $$ ->
# @div class: "emp-setting-con panel-body padded", =>
# @div class: "block conf-heading icon icon-gear", "Server Setting"
#
# # ------------------------ server conf pane ------------------------
# @div outlet:"emp_conf_pane", class: "emp-setting-con panel-body padded", =>
# @label class: "emp-setting-label", "Host "
# @div class: 'controls', =>
# @div class: 'setting-editor-container', =>
# @subview "emp_set_host", new TextEditorView(mini: true, attributes: {id: 'emp_host', type: 'string'}, placeholderText: 'Editor Server 监听的地址') #from editor view class
# @label class: "emp-setting-label", "Port "
# @div class: 'controls', =>
# @div class: 'setting-editor-container', =>
# @subview "emp_set_port", new TextEditorView(mini: true, attributes: {id: 'emp_port', type: 'string'}, placeholderText: '同Client交互的端口')
# @button class: 'btn btn-else btn-success inline-block-tight ', click: 'start_server', "Start Server"
init_server_conf: ->
@init_default_value()
@init_server_listen()
@init_log_color_value()
@init_log_conf_listen()
# console.log @test_o
# @test_o.context.style.backgroundColor="#006666"
# @test_o.css('color', "#CC3300")
init_default_value: ->
# console.log atom.config.get('emp-debugger.s_host')
if @server_host is undefined
@server_host = @default_host
atom.config.set(EMP_DEBUG_HOST_KEY, @server_host)
if @server_port is undefined
@server_port = @default_port
atom.config.set(EMP_DEBUG_PORT_KEY, @server_port)
@emp_set_port.setText(@server_port)
@emp_set_host.setText(@server_host)
init_server_listen: ->
# console.log @emp_set_port.getModel()
@emp_set_port.getModel().onDidStopChanging =>
tmp_port = @emp_set_port.getText()
# console.log tmp_port
if @server_port isnt tmp_port
@server_port = tmp_port
atom.config.set(EMP_DEBUG_PORT_KEY, @server_port)
@emp_set_host.getModel().onDidStopChanging =>
tmp_host = @emp_set_host.getText()
# console.log tmp_host
if @server_host isnt tmp_host
@server_host = tmp_host
atom.config.set(EMP_DEBUG_HOST_KEY, @server_host)
# atom.config.set('emp-debugger.s_host', 'value')
# atom.config.observe 'my-package.key', ->
# console.log 'My configuration changed:', atom.config.get('my-package.key')
init_log_color_value: ->
@oLogMaps = @empDebuggerLogView.get_log_store()
aAllLogMaps = @oLogMaps.get_all_log()
for name, view_logs of aAllLogMaps
# console.log name
tmp_color = view_logs.get_color()
tmp_id = view_logs.get_id()
@emp_client_list.append(@create_option("client:#{tmp_id}", tmp_id))
# 设置 log color 为全局记忆的颜色
aDefaultColor = @get_log_default_color()
sGolColor = atom.config.get(emp.EMP_LOG_GLOBAL_COLOR)
for oCol in aDefaultColor
if oCol.value is sGolColor
sOption = @new_select_option(oCol.name, oCol.value)
@emp_log_color_list.css('background-color', oCol.value)
else
sOption = @new_option(oCol.name, oCol.value)
@emp_log_color_list.append(sOption)
init_log_conf_listen: ->
client_id = null
@oLogMaps = @empDebuggerLogView.get_log_store()
@emp_client_list.change =>
console.log "client channge"
client_id = @emp_client_list.val()
console.log client_id
if client_id isnt @default_name
# console.log oLogMaps[client_id]
# console.log @emp_default_color
# @emp_default_color.context.selected = true
@emp_default_color.attr('selected', true)
unless !sTmpCol = @oLogMaps.get_log_col(client_id)
@emp_log_color_list.css('background-color', sTmpCol)
@emp_default_color.val(sTmpCol)
else
if glo_color = atom.config.get(emp.EMP_LOG_GLOBAL_COLOR)
# console.log "option[val=#{glo_color}]"
@emp_log_color_list.find("option[value=#{glo_color}]").attr('selected', true)
else
@emp_default_color.attr('selected', true)
@emp_log_color_list.css('background-color', '')
@emp_default_color.val("#{@default_name}")
@emp_log_color_list.change =>
console.log "color channge"
client_id = @emp_client_list.val()
sSelCol = @emp_log_color_list.val()
console.log sSelCol
if client_id is @default_name
console.log "default id"
# console.log sSelCol
aAllLogMaps = @oLogMaps.get_all_log()
if sSelCol isnt @default_name
atom.config.set(emp.EMP_LOG_GLOBAL_COLOR, sSelCol)
@emp_log_color_list.css('background-color', sSelCol)
# atom.project.glo_color = sSelCol
for cli_id, cli_view of aAllLogMaps
cli_view.set_glo_color sSelCol
else
atom.config.set(emp.EMP_LOG_GLOBAL_COLOR, null)
@emp_default_color.val("#{@default_name}")
@emp_log_color_list.css('background-color', '')
# atom.project.glo_color = null
for cli_id, cli_view of aAllLogMaps
cli_view.set_glo_color null
else
# console.log sSelCol
if sSelCol isnt @default_name
@emp_log_color_list.css('background-color', sSelCol)
client_id = @emp_client_list.val()
@oLogMaps.set_log_col(client_id, sSelCol)
# @log_map[client_id].set_glo_color null
else
@oLogMaps.set_log_gol_col client_id, null
@emp_log_color_list.css('background-color', @oLogMaps.get_log_col(client_id))
refresh_log_view: (@oLogMaps, client_id, sTmpColor)->
@emp_client_list.append(@create_option("client:#{client_id}", client_id))
@emp_log_color_list.append(@create_else_option(sTmpColor))
remove_client: (client_id) ->
# console.log "remove: #{client_id}"
@refresh_state_pane_ln()
@remove_log_view(client_id)
remove_log_view: (client_id)->
# console.log @emp_client_list
@emp_client_list.find("option[id=#{client_id}]").remove()
select_client = @emp_client_list.val()
console.log select_client
console.log (select_client is client_id)
if select_client is client_id
@emp_default_client.attr('selected', true)
@emp_default_color.attr('selected', true)
@emp_log_color_list.css('background-color', @default_color_value)
create_option: (name, value)->
$$ -> @option id:"#{value}", value: value, name
create_else_option: (color)->
$$ -> @option style:"background-color:#{color};", value: color
# -------------------------------------------------------------------------
# view maintain
hide_conf_pane: ->
# console.log "call:hide_conf_pane"
@emp_conf_pane.hide()
@refresh_state_pane()
@emp_state_pane.show()
hide_state_pane: ->
@emp_conf_pane.show()
@emp_state_pane.hide()
refresh_state_pane: ->
if @emp_socket_server.get_server_sate()
@emp_server_st["context"].innerHTML = "On"
@emp_cl_no["context"].innerHTML=@emp_socket_server.get_client_map().get_active_len()
refresh_state_pane_ln: ->
if @emp_socket_server.get_server_sate()
@emp_cl_no["context"].innerHTML=@emp_socket_server.get_client_map().get_active_len()
# -------------------------------------------------------------------------
# util fun
# btn callback
start_server: (event, element) ->
# console.log element
# console.log "port:#{@emp_server_port}"
# console.log "host:#{@emp_server_host}"
new_server_host = @server_host.trim()
new_server_port = @server_port.trim()
# console.log new_server_host
# console.log new_server_port
new_server_host = @default_host unless new_server_host isnt ''
new_server_port = @default_port unless new_server_port isnt ''
# console.log @emp_server_port
new_server_port = @parseValue('number', new_server_port)
console.log "local server start with option parameters: host: #{new_server_host}, port: #{new_server_port}"
@emp_socket_server.init(new_server_host, new_server_port) unless @emp_socket_server.get_server() isnt null
# btn callback
stop_server: (event, element) ->
@emp_socket_server.close()
@hide_state_pane()
# -------------------------------------------------------------------------
# btn for hide the setting view
hide_setting_view: () ->
this.hide()
@show_state = false
# -------------------------------------------------------------------------
live_preview: ->
console.log "live preview"
@fa_view.live_preview()
show_enable_views: ->
console.log "show enable preview"
@fa_view.show_enable_view()
show_enable_lua: ->
console.log "show enbale lua"
@fa_view.show_enable_lua()
# 清除 enable view 和 enable lua 的内容
clear_input_view: ->
@emp_socket_server.get_client_map().clear_all_views()
console.info "清除 View 完成."
emp.show_info "清除 View 完成."
# btn callback for log setting
show_log: ->
# console.log "show_log"
show_state = @empDebuggerLogView.show_log_state()
if show_state
@empDebuggerLogView.hide_log_view()
# @emp_showlog.context.innerHTML = "Show Log"
# @refresh_log_st(@log_state_hide)
else
@empDebuggerLogView.show_log()
# @emp_showlog.context.innerHTML = "Hide Log"
# @refresh_log_st(@log_state_show)
show_log_callback: ->
@emp_showlog.context.innerHTML = "Hide Log"
@refresh_log_st(@log_state_show)
hide_log_callback: ->
@emp_showlog.context.innerHTML = "Show Log"
@refresh_log_st(@log_state_hide)
clear_log: ->
# console.log "clear_log"
@empDebuggerLogView.clear_log()
pause_log: ->
# console.log "stop_log"
pause_state = @empDebuggerLogView.get_pause_state()
if pause_state
@empDebuggerLogView.continue_log()
@emp_pauselog.context.innerHTML = "Pause Log"
@refresh_log_st(@log_state_show)
else
@empDebuggerLogView.stop_log()
@emp_pauselog.context.innerHTML = "Continue Log"
@refresh_log_st(@log_state_pause)
close_log: ->
# console.log "close_log"
@empDebuggerLogView.close_log_view()
@refresh_log_st(@log_state_close)
refresh_log_st: (css_style)->
log_st_str = @empDebuggerLogView.get_log_pane_state()
@emp_log_st.context.innerHTML = log_st_str
@emp_log_st.css('color', css_style)
# -------------------------------------------------------------------------
valueToString: (value) ->
if _.isArray(value)
value.join(", ")
else
value?.toString()
parseValue: (type, value) ->
if value == ''
value = undefined
else if type == 'number'
floatValue = parseFloat(value)
value = floatValue unless isNaN(floatValue)
else if type == 'array'
arrayValue = (value or '').split(',')
value = (val.trim() for val in arrayValue when val)
value
new_option: (name, value=name)->
$$ ->
@option value: value, name
new_select_option: (name, value=name) ->
$$ ->
@option selected:'select', value: value, name
get_log_default_color: ->
return [{value: "#000033", name: "黑"},
{value: "#FFFFFF", name: "白"},
{value: "#FF0000", name: "红"},
{value: "#FFFF33", name: "黄"},
{value: "#0000FF", name: "蓝"},
{value: "#00FF00", name: "绿"},
{value: "#00FFFF", name: "青"},
{value: "#FF6600", name: "橙"},
{value: "#990099", name: "紫"}]
|
[
{
"context": "er: process.env.HUBOT_IRC_SERVER\n password: process.env.HUBOT_IRC_PASSWORD\n nickpass: process.env.HUBOT_IRC_NICKSERV_PA",
"end": 4675,
"score": 0.9652094841003418,
"start": 4645,
"tag": "PASSWORD",
"value": "process.env.HUBOT_IRC_PASSWORD"
},
{
"context": ... | src/irc.coffee | 02strich/hubot-irc-framework | 0 | # Hubot dependencies
{Robot, Adapter, TextMessage, EnterMessage, LeaveMessage, Response} = require 'hubot'
# Custom Response class that adds a sendPrivate method
class IrcResponse extends Response
sendPrivate: (strings...) ->
@robot.adapter.sendPrivate @envelope, strings...
# Irc library
Irc = require 'irc-framework'
Log = require('log')
logger = new Log process.env.HUBOT_LOG_LEVEL or 'info'
class IrcBot extends Adapter
send: (envelope, strings...) ->
# Use @notice if SEND_NOTICE_MODE is set
return @notice envelope, strings if process.env.HUBOT_IRC_SEND_NOTICE_MODE?
target = @_getTargetFromEnvelope envelope
unless target
return logger.error "ERROR: Not sure who to send to. envelope=", envelope
for str in strings
for strline in str.split('\n')
logger.info "#{target} #{strline}"
@bot.say target, strline
sendPrivate: (envelope, strings...) ->
# Remove the room from the envelope and send as private message to user
logger.info 'sendPrivate'
if envelope.room
delete envelope.room
if envelope.user?.room
delete envelope.user.room
@send envelope, strings...
topic: (envelope, strings...) ->
data = strings.join " / "
channel = envelope.room
@bot.send 'TOPIC', channel, data
emote: (envelope, strings...) ->
# Use @notice if SEND_NOTICE_MODE is set
return @notice envelope, strings if process.env.HUBOT_IRC_SEND_NOTICE_MODE?
target = @_getTargetFromEnvelope envelope
unless target
return logger.error "ERROR: Not sure who to send to. envelope=", envelope
for str in strings
@bot.action target, str
notice: (envelope, strings...) ->
target = @_getTargetFromEnvelope envelope
unless target
return logger.warn "Notice: no target found", envelope
# Flatten out strings from send
flattened = []
for str in strings
if typeof str != 'undefined'
for line in str.toString().split(/\r?\n/)
if Array.isArray line
flattened = flattened.concat line
else
flattened.push line
for str in flattened
if not str?
continue
@bot.notice target, str
reply: (envelope, strings...) ->
for str in strings
@send envelope.user, "#{envelope.user.name}: #{str}"
join: (channel) ->
self = @
@bot.join channel, () ->
logger.info('joined %s', channel)
selfUser = self.getUserFromName self.robot.name
self.receive new EnterMessage(selfUser)
part: (channel) ->
self = @
@bot.part channel, () ->
logger.info('left %s', channel)
selfUser = self.getUserFromName self.robot.name
self.receive new LeaveMessage(selfUser)
getUserFromName: (name) ->
return @robot.brain.userForName(name) if @robot.brain?.userForName?
# Deprecated in 3.0.0
return @userForName name
getUserFromId: (id) ->
# TODO: Add logic to convert object if name matches
return @robot.brain.userForId(id) if @robot.brain?.userForId?
# Deprecated in 3.0.0
return @userForId id
createUser: (channel, from) ->
user = @getUserFromId from
user.name = from
if channel.match(/^[&#]/)
user.room = channel
else
user.room = null
user
kick: (channel, client, message) ->
@bot.emit 'raw',
command: 'KICK'
nick: process.env.HUBOT_IRC_NICK
args: [ channel, client, message ]
command: (command, strings...) ->
@bot.send command, strings...
checkCanStart: ->
if not process.env.HUBOT_IRC_NICK and not @robot.name
throw new Error("HUBOT_IRC_NICK is not defined; try: export HUBOT_IRC_NICK='mybot'")
else if not process.env.HUBOT_IRC_ROOMS
throw new Error("HUBOT_IRC_ROOMS is not defined; try: export HUBOT_IRC_ROOMS='#myroom'")
else if not process.env.HUBOT_IRC_SERVER
throw new Error("HUBOT_IRC_SERVER is not defined: try: export HUBOT_IRC_SERVER='irc.myserver.com'")
unfloodProtection: (unflood) ->
unflood == 'true' or !isNaN(parseInt(unflood))
unfloodProtectionDelay: (unflood) ->
unfloodProtection = @unfloodProtection(unflood)
unfloodValue = parseInt(unflood) or 1000
if unfloodProtection
unfloodValue
else
0
run: ->
self = @
do @checkCanStart
options =
nick: process.env.HUBOT_IRC_NICK or @robot.name
realName: process.env.HUBOT_IRC_REALNAME
port: process.env.HUBOT_IRC_PORT
rooms: process.env.HUBOT_IRC_ROOMS.split(",")
ignoreUsers: process.env.HUBOT_IRC_IGNORE_USERS?.split(",") or []
server: process.env.HUBOT_IRC_SERVER
password: process.env.HUBOT_IRC_PASSWORD
nickpass: process.env.HUBOT_IRC_NICKSERV_PASSWORD
nickusername: process.env.HUBOT_IRC_NICKSERV_USERNAME
connectCommand: process.env.HUBOT_IRC_CONNECT_COMMAND
fakessl: process.env.HUBOT_IRC_SERVER_FAKE_SSL?
certExpired: process.env.HUBOT_IRC_SERVER_CERT_EXPIRED?
unflood: process.env.HUBOT_IRC_UNFLOOD
debug: process.env.HUBOT_IRC_DEBUG?
usessl: process.env.HUBOT_IRC_USESSL?
userName: process.env.HUBOT_IRC_USERNAME
connect_options =
host: options.server
port: options.port
nick: options.nick
username: options.userName
password: options.password
ssl: options.usessl
# Override the response to provide a sendPrivate method
@robot.Response = IrcResponse
@robot.name = options.nick
bot = new Irc.Client
bot.connect connect_options
if options.debug
bot.on 'raw', (e) ->
logger.info "RAW: " + e
bot.on 'registered', () ->
bot.join room for room in options.rooms
next_id = 1
user_id = {}
if options.nickpass?
identify_args = ""
if options.nickusername?
identify_args += "#{options.nickusername} "
identify_args += "#{options.nickpass}"
bot.addListener 'notice', (from, to, text) ->
if from is 'NickServ' and text.toLowerCase().indexOf('identify') isnt -1
bot.say 'NickServ', "identify #{identify_args}"
else if options.nickpass and from is 'NickServ' and
(text.indexOf('Password accepted') isnt -1 or
text.indexOf('identified') isnt -1)
for room in options.rooms
@join room
if options.connectCommand?
bot.addListener 'registered', (message) ->
# The 'registered' event is fired when you are connected to the server
strings = options.connectCommand.split " "
self.command strings.shift(), strings...
bot.addListener 'names', (channel, nicks) ->
for nick of nicks
self.createUser channel, nick
bot.addListener 'notice', (event) ->
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', event.nick)
# we'll ignore this message if it's from someone we want to ignore
return
logger.info "NOTICE from #{event.nick} to #{event.target}: #{event.message}"
user = self.createUser event.target, event.nick
self.receive new TextMessage(user, event.message)
bot.addListener 'message', (event) ->
if options.nick.toLowerCase() == event.target.toLowerCase()
# this is a private message, let the 'pm' listener handle it
return
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', event.nick)
# we'll ignore this message if it's from someone we want to ignore
return
logger.debug "From #{event.nick} to #{event.target}: #{event.message}"
user = self.createUser event.target, event.nick
if user.room
logger.debug "#{event.target} <#{event.nick}> #{event.message}"
else
unless event.message.indexOf(event.target) == 0
message = "#{event.target}: #{event.msg}"
logger.debug "msg <#{event.nick}> #{event.msg}"
self.receive new TextMessage(user, event.message)
bot.addListener 'action', (event) ->
logger.debug " * From #{event.nick} to #{event.target}: #{event.message}"
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', from)
# we'll ignore this message if it's from someone we want to ignore
return
user = self.createUser event.target, event.nick
if user.room
logger.debug "#{event.target} * #{event.nick} #{event.message}"
else
logger.debug "msg <#{event.nick}> #{event.message}"
self.receive new TextMessage(user, event.message)
#bot.addListener 'error', (message) ->
# logger.error('ERROR: %s: %s', message.command, message.args.join(' '))
bot.addListener 'privmsg', (event) ->
logger.info('Got private message from %s: %s', event.nick, event.message)
if process.env.HUBOT_IRC_PRIVATE
return
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', nick)
# we'll ignore this message if it's from someone we want to ignore
return
nameLength = options.nick.length
if event.message.slice(0, nameLength).toLowerCase() != options.nick.toLowerCase()
message = "#{options.nick} #{event.message}"
else
message = event.message
self.receive new TextMessage({reply_to: event.nick, name: event.nick}, 'message')
bot.addListener 'join', (event) ->
logger.info('%s has joined %s', event.nick, event.channel)
user = self.createUser event.channel, event.nick
user.room = event.channel
self.receive new EnterMessage(user)
bot.addListener 'part', (event) ->
logger.info('%s has left %s: %s', event.nick, event.channel, event.message)
user = self.createUser '', event.nick
user.room = event.channel
msg = new LeaveMessage user
msg.text = event.message
self.receive msg
bot.addListener 'quit', (event) ->
logger.info '%s has quit: %s', event.nick, event.message
#for ch in channels
# user = self.createUser '', who
# user.room = ch
# msg = new LeaveMessage user
# msg.text = reason
# self.receive msg
bot.addListener 'kick', (event) ->
logger.info('%s was kicked from %s by %s: %s', event.nick, event.channel, event.kicked, event.message)
bot.addListener 'invite', (event) ->
logger.info('%s invited you to join %s', event.nick, event.channel)
if event.invited in options.ignoreUsers
logger.info('Ignoring user: %s', from)
# we'll ignore this message if it's from someone we want to ignore
return
if not process.env.HUBOT_IRC_PRIVATE or process.env.HUBOT_IRC_IGNOREINVITE
bot.join channel
@bot = bot
self.emit "connected"
_getTargetFromEnvelope: (envelope) ->
user = null
room = null
target = null
# as of hubot 2.4.2, the first param to send() is an object with 'user'
# and 'room' data inside. detect the old style here.
if envelope.reply_to
user = envelope
else
# expand envelope
user = envelope.user
room = envelope.room
if user
# most common case - we're replying to a user in a room
if user.room
target = user.room
# reply directly
else if user.name
target = user.name
# replying to pm
else if user.reply_to
target = user.reply_to
# allows user to be an id string
else if user.search?(/@/) != -1
target = user
else if room
# this will happen if someone uses robot.messageRoom(jid, ...)
target = room
target
exports.use = (robot) ->
new IrcBot robot
| 135502 | # Hubot dependencies
{Robot, Adapter, TextMessage, EnterMessage, LeaveMessage, Response} = require 'hubot'
# Custom Response class that adds a sendPrivate method
class IrcResponse extends Response
sendPrivate: (strings...) ->
@robot.adapter.sendPrivate @envelope, strings...
# Irc library
Irc = require 'irc-framework'
Log = require('log')
logger = new Log process.env.HUBOT_LOG_LEVEL or 'info'
class IrcBot extends Adapter
send: (envelope, strings...) ->
# Use @notice if SEND_NOTICE_MODE is set
return @notice envelope, strings if process.env.HUBOT_IRC_SEND_NOTICE_MODE?
target = @_getTargetFromEnvelope envelope
unless target
return logger.error "ERROR: Not sure who to send to. envelope=", envelope
for str in strings
for strline in str.split('\n')
logger.info "#{target} #{strline}"
@bot.say target, strline
sendPrivate: (envelope, strings...) ->
# Remove the room from the envelope and send as private message to user
logger.info 'sendPrivate'
if envelope.room
delete envelope.room
if envelope.user?.room
delete envelope.user.room
@send envelope, strings...
topic: (envelope, strings...) ->
data = strings.join " / "
channel = envelope.room
@bot.send 'TOPIC', channel, data
emote: (envelope, strings...) ->
# Use @notice if SEND_NOTICE_MODE is set
return @notice envelope, strings if process.env.HUBOT_IRC_SEND_NOTICE_MODE?
target = @_getTargetFromEnvelope envelope
unless target
return logger.error "ERROR: Not sure who to send to. envelope=", envelope
for str in strings
@bot.action target, str
notice: (envelope, strings...) ->
target = @_getTargetFromEnvelope envelope
unless target
return logger.warn "Notice: no target found", envelope
# Flatten out strings from send
flattened = []
for str in strings
if typeof str != 'undefined'
for line in str.toString().split(/\r?\n/)
if Array.isArray line
flattened = flattened.concat line
else
flattened.push line
for str in flattened
if not str?
continue
@bot.notice target, str
reply: (envelope, strings...) ->
for str in strings
@send envelope.user, "#{envelope.user.name}: #{str}"
join: (channel) ->
self = @
@bot.join channel, () ->
logger.info('joined %s', channel)
selfUser = self.getUserFromName self.robot.name
self.receive new EnterMessage(selfUser)
part: (channel) ->
self = @
@bot.part channel, () ->
logger.info('left %s', channel)
selfUser = self.getUserFromName self.robot.name
self.receive new LeaveMessage(selfUser)
getUserFromName: (name) ->
return @robot.brain.userForName(name) if @robot.brain?.userForName?
# Deprecated in 3.0.0
return @userForName name
getUserFromId: (id) ->
# TODO: Add logic to convert object if name matches
return @robot.brain.userForId(id) if @robot.brain?.userForId?
# Deprecated in 3.0.0
return @userForId id
createUser: (channel, from) ->
user = @getUserFromId from
user.name = from
if channel.match(/^[&#]/)
user.room = channel
else
user.room = null
user
kick: (channel, client, message) ->
@bot.emit 'raw',
command: 'KICK'
nick: process.env.HUBOT_IRC_NICK
args: [ channel, client, message ]
command: (command, strings...) ->
@bot.send command, strings...
checkCanStart: ->
if not process.env.HUBOT_IRC_NICK and not @robot.name
throw new Error("HUBOT_IRC_NICK is not defined; try: export HUBOT_IRC_NICK='mybot'")
else if not process.env.HUBOT_IRC_ROOMS
throw new Error("HUBOT_IRC_ROOMS is not defined; try: export HUBOT_IRC_ROOMS='#myroom'")
else if not process.env.HUBOT_IRC_SERVER
throw new Error("HUBOT_IRC_SERVER is not defined: try: export HUBOT_IRC_SERVER='irc.myserver.com'")
unfloodProtection: (unflood) ->
unflood == 'true' or !isNaN(parseInt(unflood))
unfloodProtectionDelay: (unflood) ->
unfloodProtection = @unfloodProtection(unflood)
unfloodValue = parseInt(unflood) or 1000
if unfloodProtection
unfloodValue
else
0
run: ->
self = @
do @checkCanStart
options =
nick: process.env.HUBOT_IRC_NICK or @robot.name
realName: process.env.HUBOT_IRC_REALNAME
port: process.env.HUBOT_IRC_PORT
rooms: process.env.HUBOT_IRC_ROOMS.split(",")
ignoreUsers: process.env.HUBOT_IRC_IGNORE_USERS?.split(",") or []
server: process.env.HUBOT_IRC_SERVER
password: <PASSWORD>
nickpass: <PASSWORD>.HUBOT_IRC_NICKSERV_PASSWORD
nickusername: process.env.HUBOT_IRC_NICKSERV_USERNAME
connectCommand: process.env.HUBOT_IRC_CONNECT_COMMAND
fakessl: process.env.HUBOT_IRC_SERVER_FAKE_SSL?
certExpired: process.env.HUBOT_IRC_SERVER_CERT_EXPIRED?
unflood: process.env.HUBOT_IRC_UNFLOOD
debug: process.env.HUBOT_IRC_DEBUG?
usessl: process.env.HUBOT_IRC_USESSL?
userName: process.env.HUBOT_IRC_USERNAME
connect_options =
host: options.server
port: options.port
nick: options.nick
username: options.userName
password: <PASSWORD>
ssl: options.usessl
# Override the response to provide a sendPrivate method
@robot.Response = IrcResponse
@robot.name = options.nick
bot = new Irc.Client
bot.connect connect_options
if options.debug
bot.on 'raw', (e) ->
logger.info "RAW: " + e
bot.on 'registered', () ->
bot.join room for room in options.rooms
next_id = 1
user_id = {}
if options.nickpass?
identify_args = ""
if options.nickusername?
identify_args += "#{options.nickusername} "
identify_args += "#{options.nickpass}"
bot.addListener 'notice', (from, to, text) ->
if from is 'NickServ' and text.toLowerCase().indexOf('identify') isnt -1
bot.say 'NickServ', "identify #{identify_args}"
else if options.nickpass and from is 'NickServ' and
(text.indexOf('Password accepted') isnt -1 or
text.indexOf('identified') isnt -1)
for room in options.rooms
@join room
if options.connectCommand?
bot.addListener 'registered', (message) ->
# The 'registered' event is fired when you are connected to the server
strings = options.connectCommand.split " "
self.command strings.shift(), strings...
bot.addListener 'names', (channel, nicks) ->
for nick of nicks
self.createUser channel, nick
bot.addListener 'notice', (event) ->
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', event.nick)
# we'll ignore this message if it's from someone we want to ignore
return
logger.info "NOTICE from #{event.nick} to #{event.target}: #{event.message}"
user = self.createUser event.target, event.nick
self.receive new TextMessage(user, event.message)
bot.addListener 'message', (event) ->
if options.nick.toLowerCase() == event.target.toLowerCase()
# this is a private message, let the 'pm' listener handle it
return
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', event.nick)
# we'll ignore this message if it's from someone we want to ignore
return
logger.debug "From #{event.nick} to #{event.target}: #{event.message}"
user = self.createUser event.target, event.nick
if user.room
logger.debug "#{event.target} <#{event.nick}> #{event.message}"
else
unless event.message.indexOf(event.target) == 0
message = "#{event.target}: #{event.msg}"
logger.debug "msg <#{event.nick}> #{event.msg}"
self.receive new TextMessage(user, event.message)
bot.addListener 'action', (event) ->
logger.debug " * From #{event.nick} to #{event.target}: #{event.message}"
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', from)
# we'll ignore this message if it's from someone we want to ignore
return
user = self.createUser event.target, event.nick
if user.room
logger.debug "#{event.target} * #{event.nick} #{event.message}"
else
logger.debug "msg <#{event.nick}> #{event.message}"
self.receive new TextMessage(user, event.message)
#bot.addListener 'error', (message) ->
# logger.error('ERROR: %s: %s', message.command, message.args.join(' '))
bot.addListener 'privmsg', (event) ->
logger.info('Got private message from %s: %s', event.nick, event.message)
if process.env.HUBOT_IRC_PRIVATE
return
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', nick)
# we'll ignore this message if it's from someone we want to ignore
return
nameLength = options.nick.length
if event.message.slice(0, nameLength).toLowerCase() != options.nick.toLowerCase()
message = "#{options.nick} #{event.message}"
else
message = event.message
self.receive new TextMessage({reply_to: event.nick, name: event.nick}, 'message')
bot.addListener 'join', (event) ->
logger.info('%s has joined %s', event.nick, event.channel)
user = self.createUser event.channel, event.nick
user.room = event.channel
self.receive new EnterMessage(user)
bot.addListener 'part', (event) ->
logger.info('%s has left %s: %s', event.nick, event.channel, event.message)
user = self.createUser '', event.nick
user.room = event.channel
msg = new LeaveMessage user
msg.text = event.message
self.receive msg
bot.addListener 'quit', (event) ->
logger.info '%s has quit: %s', event.nick, event.message
#for ch in channels
# user = self.createUser '', who
# user.room = ch
# msg = new LeaveMessage user
# msg.text = reason
# self.receive msg
bot.addListener 'kick', (event) ->
logger.info('%s was kicked from %s by %s: %s', event.nick, event.channel, event.kicked, event.message)
bot.addListener 'invite', (event) ->
logger.info('%s invited you to join %s', event.nick, event.channel)
if event.invited in options.ignoreUsers
logger.info('Ignoring user: %s', from)
# we'll ignore this message if it's from someone we want to ignore
return
if not process.env.HUBOT_IRC_PRIVATE or process.env.HUBOT_IRC_IGNOREINVITE
bot.join channel
@bot = bot
self.emit "connected"
_getTargetFromEnvelope: (envelope) ->
user = null
room = null
target = null
# as of hubot 2.4.2, the first param to send() is an object with 'user'
# and 'room' data inside. detect the old style here.
if envelope.reply_to
user = envelope
else
# expand envelope
user = envelope.user
room = envelope.room
if user
# most common case - we're replying to a user in a room
if user.room
target = user.room
# reply directly
else if user.name
target = user.name
# replying to pm
else if user.reply_to
target = user.reply_to
# allows user to be an id string
else if user.search?(/@/) != -1
target = user
else if room
# this will happen if someone uses robot.messageRoom(jid, ...)
target = room
target
exports.use = (robot) ->
new IrcBot robot
| true | # Hubot dependencies
{Robot, Adapter, TextMessage, EnterMessage, LeaveMessage, Response} = require 'hubot'
# Custom Response class that adds a sendPrivate method
class IrcResponse extends Response
sendPrivate: (strings...) ->
@robot.adapter.sendPrivate @envelope, strings...
# Irc library
Irc = require 'irc-framework'
Log = require('log')
logger = new Log process.env.HUBOT_LOG_LEVEL or 'info'
class IrcBot extends Adapter
send: (envelope, strings...) ->
# Use @notice if SEND_NOTICE_MODE is set
return @notice envelope, strings if process.env.HUBOT_IRC_SEND_NOTICE_MODE?
target = @_getTargetFromEnvelope envelope
unless target
return logger.error "ERROR: Not sure who to send to. envelope=", envelope
for str in strings
for strline in str.split('\n')
logger.info "#{target} #{strline}"
@bot.say target, strline
sendPrivate: (envelope, strings...) ->
# Remove the room from the envelope and send as private message to user
logger.info 'sendPrivate'
if envelope.room
delete envelope.room
if envelope.user?.room
delete envelope.user.room
@send envelope, strings...
topic: (envelope, strings...) ->
data = strings.join " / "
channel = envelope.room
@bot.send 'TOPIC', channel, data
emote: (envelope, strings...) ->
# Use @notice if SEND_NOTICE_MODE is set
return @notice envelope, strings if process.env.HUBOT_IRC_SEND_NOTICE_MODE?
target = @_getTargetFromEnvelope envelope
unless target
return logger.error "ERROR: Not sure who to send to. envelope=", envelope
for str in strings
@bot.action target, str
notice: (envelope, strings...) ->
target = @_getTargetFromEnvelope envelope
unless target
return logger.warn "Notice: no target found", envelope
# Flatten out strings from send
flattened = []
for str in strings
if typeof str != 'undefined'
for line in str.toString().split(/\r?\n/)
if Array.isArray line
flattened = flattened.concat line
else
flattened.push line
for str in flattened
if not str?
continue
@bot.notice target, str
reply: (envelope, strings...) ->
for str in strings
@send envelope.user, "#{envelope.user.name}: #{str}"
join: (channel) ->
self = @
@bot.join channel, () ->
logger.info('joined %s', channel)
selfUser = self.getUserFromName self.robot.name
self.receive new EnterMessage(selfUser)
part: (channel) ->
self = @
@bot.part channel, () ->
logger.info('left %s', channel)
selfUser = self.getUserFromName self.robot.name
self.receive new LeaveMessage(selfUser)
getUserFromName: (name) ->
return @robot.brain.userForName(name) if @robot.brain?.userForName?
# Deprecated in 3.0.0
return @userForName name
getUserFromId: (id) ->
# TODO: Add logic to convert object if name matches
return @robot.brain.userForId(id) if @robot.brain?.userForId?
# Deprecated in 3.0.0
return @userForId id
createUser: (channel, from) ->
user = @getUserFromId from
user.name = from
if channel.match(/^[&#]/)
user.room = channel
else
user.room = null
user
kick: (channel, client, message) ->
@bot.emit 'raw',
command: 'KICK'
nick: process.env.HUBOT_IRC_NICK
args: [ channel, client, message ]
command: (command, strings...) ->
@bot.send command, strings...
checkCanStart: ->
if not process.env.HUBOT_IRC_NICK and not @robot.name
throw new Error("HUBOT_IRC_NICK is not defined; try: export HUBOT_IRC_NICK='mybot'")
else if not process.env.HUBOT_IRC_ROOMS
throw new Error("HUBOT_IRC_ROOMS is not defined; try: export HUBOT_IRC_ROOMS='#myroom'")
else if not process.env.HUBOT_IRC_SERVER
throw new Error("HUBOT_IRC_SERVER is not defined: try: export HUBOT_IRC_SERVER='irc.myserver.com'")
unfloodProtection: (unflood) ->
unflood == 'true' or !isNaN(parseInt(unflood))
unfloodProtectionDelay: (unflood) ->
unfloodProtection = @unfloodProtection(unflood)
unfloodValue = parseInt(unflood) or 1000
if unfloodProtection
unfloodValue
else
0
run: ->
self = @
do @checkCanStart
options =
nick: process.env.HUBOT_IRC_NICK or @robot.name
realName: process.env.HUBOT_IRC_REALNAME
port: process.env.HUBOT_IRC_PORT
rooms: process.env.HUBOT_IRC_ROOMS.split(",")
ignoreUsers: process.env.HUBOT_IRC_IGNORE_USERS?.split(",") or []
server: process.env.HUBOT_IRC_SERVER
password: PI:PASSWORD:<PASSWORD>END_PI
nickpass: PI:PASSWORD:<PASSWORD>END_PI.HUBOT_IRC_NICKSERV_PASSWORD
nickusername: process.env.HUBOT_IRC_NICKSERV_USERNAME
connectCommand: process.env.HUBOT_IRC_CONNECT_COMMAND
fakessl: process.env.HUBOT_IRC_SERVER_FAKE_SSL?
certExpired: process.env.HUBOT_IRC_SERVER_CERT_EXPIRED?
unflood: process.env.HUBOT_IRC_UNFLOOD
debug: process.env.HUBOT_IRC_DEBUG?
usessl: process.env.HUBOT_IRC_USESSL?
userName: process.env.HUBOT_IRC_USERNAME
connect_options =
host: options.server
port: options.port
nick: options.nick
username: options.userName
password: PI:PASSWORD:<PASSWORD>END_PI
ssl: options.usessl
# Override the response to provide a sendPrivate method
@robot.Response = IrcResponse
@robot.name = options.nick
bot = new Irc.Client
bot.connect connect_options
if options.debug
bot.on 'raw', (e) ->
logger.info "RAW: " + e
bot.on 'registered', () ->
bot.join room for room in options.rooms
next_id = 1
user_id = {}
if options.nickpass?
identify_args = ""
if options.nickusername?
identify_args += "#{options.nickusername} "
identify_args += "#{options.nickpass}"
bot.addListener 'notice', (from, to, text) ->
if from is 'NickServ' and text.toLowerCase().indexOf('identify') isnt -1
bot.say 'NickServ', "identify #{identify_args}"
else if options.nickpass and from is 'NickServ' and
(text.indexOf('Password accepted') isnt -1 or
text.indexOf('identified') isnt -1)
for room in options.rooms
@join room
if options.connectCommand?
bot.addListener 'registered', (message) ->
# The 'registered' event is fired when you are connected to the server
strings = options.connectCommand.split " "
self.command strings.shift(), strings...
bot.addListener 'names', (channel, nicks) ->
for nick of nicks
self.createUser channel, nick
bot.addListener 'notice', (event) ->
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', event.nick)
# we'll ignore this message if it's from someone we want to ignore
return
logger.info "NOTICE from #{event.nick} to #{event.target}: #{event.message}"
user = self.createUser event.target, event.nick
self.receive new TextMessage(user, event.message)
bot.addListener 'message', (event) ->
if options.nick.toLowerCase() == event.target.toLowerCase()
# this is a private message, let the 'pm' listener handle it
return
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', event.nick)
# we'll ignore this message if it's from someone we want to ignore
return
logger.debug "From #{event.nick} to #{event.target}: #{event.message}"
user = self.createUser event.target, event.nick
if user.room
logger.debug "#{event.target} <#{event.nick}> #{event.message}"
else
unless event.message.indexOf(event.target) == 0
message = "#{event.target}: #{event.msg}"
logger.debug "msg <#{event.nick}> #{event.msg}"
self.receive new TextMessage(user, event.message)
bot.addListener 'action', (event) ->
logger.debug " * From #{event.nick} to #{event.target}: #{event.message}"
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', from)
# we'll ignore this message if it's from someone we want to ignore
return
user = self.createUser event.target, event.nick
if user.room
logger.debug "#{event.target} * #{event.nick} #{event.message}"
else
logger.debug "msg <#{event.nick}> #{event.message}"
self.receive new TextMessage(user, event.message)
#bot.addListener 'error', (message) ->
# logger.error('ERROR: %s: %s', message.command, message.args.join(' '))
bot.addListener 'privmsg', (event) ->
logger.info('Got private message from %s: %s', event.nick, event.message)
if process.env.HUBOT_IRC_PRIVATE
return
if event.nick in options.ignoreUsers
logger.info('Ignoring user: %s', nick)
# we'll ignore this message if it's from someone we want to ignore
return
nameLength = options.nick.length
if event.message.slice(0, nameLength).toLowerCase() != options.nick.toLowerCase()
message = "#{options.nick} #{event.message}"
else
message = event.message
self.receive new TextMessage({reply_to: event.nick, name: event.nick}, 'message')
bot.addListener 'join', (event) ->
logger.info('%s has joined %s', event.nick, event.channel)
user = self.createUser event.channel, event.nick
user.room = event.channel
self.receive new EnterMessage(user)
bot.addListener 'part', (event) ->
logger.info('%s has left %s: %s', event.nick, event.channel, event.message)
user = self.createUser '', event.nick
user.room = event.channel
msg = new LeaveMessage user
msg.text = event.message
self.receive msg
bot.addListener 'quit', (event) ->
logger.info '%s has quit: %s', event.nick, event.message
#for ch in channels
# user = self.createUser '', who
# user.room = ch
# msg = new LeaveMessage user
# msg.text = reason
# self.receive msg
bot.addListener 'kick', (event) ->
logger.info('%s was kicked from %s by %s: %s', event.nick, event.channel, event.kicked, event.message)
bot.addListener 'invite', (event) ->
logger.info('%s invited you to join %s', event.nick, event.channel)
if event.invited in options.ignoreUsers
logger.info('Ignoring user: %s', from)
# we'll ignore this message if it's from someone we want to ignore
return
if not process.env.HUBOT_IRC_PRIVATE or process.env.HUBOT_IRC_IGNOREINVITE
bot.join channel
@bot = bot
self.emit "connected"
_getTargetFromEnvelope: (envelope) ->
user = null
room = null
target = null
# as of hubot 2.4.2, the first param to send() is an object with 'user'
# and 'room' data inside. detect the old style here.
if envelope.reply_to
user = envelope
else
# expand envelope
user = envelope.user
room = envelope.room
if user
# most common case - we're replying to a user in a room
if user.room
target = user.room
# reply directly
else if user.name
target = user.name
# replying to pm
else if user.reply_to
target = user.reply_to
# allows user to be an id string
else if user.search?(/@/) != -1
target = user
else if room
# this will happen if someone uses robot.messageRoom(jid, ...)
target = room
target
exports.use = (robot) ->
new IrcBot robot
|
[
{
"context": " for the query limit to given tags\n#\n# Author:\n# carsonmcdonald\n# drdamour\n\n\nzlib = require('zlib');\n\n# API key",
"end": 348,
"score": 0.9990109801292419,
"start": 334,
"tag": "USERNAME",
"value": "carsonmcdonald"
},
{
"context": "t to given tags\n#\n# Auth... | src/scripts/sosearch.coffee | Reelhouse/hubot-scripts | 1,450 | # Description:
# Search stack overflow and provide links to the first 5 questions
#
# Dependencies:
# none
#
# Configuration:
# None
#
# Commands:
# hubot sosearch [me] <query> - Search for the query
# hubot sosearch [me] <query> with tags <tag list sperated by ,> - Search for the query limit to given tags
#
# Author:
# carsonmcdonald
# drdamour
zlib = require('zlib');
# API keys are public for Stackapps
hubot_stackapps_apikey = 'BeOjD228tEOZP6gbYoChsg'
module.exports = (robot) ->
robot.respond /sosearch( me)? (.*)/i, (msg) ->
re = RegExp("(.*) with tags (.*)", "i")
opts = msg.match[2].match(re)
if opts?
soSearch msg, opts[1], opts[2].split(',')
else
soSearch msg, msg.match[2], []
soSearch = (msg, search, tags) ->
data = ""
msg.http("http://api.stackoverflow.com/1.1/search")
.query
intitle: encodeURIComponent(search)
key: hubot_stackapps_apikey
tagged: encodeURIComponent(tags.join(':'))
.get( (err, req)->
req.addListener "response", (res)->
output = res
#pattern stolen from http://stackoverflow.com/questions/10207762/how-to-use-request-or-http-module-to-read-gzip-page-into-a-string
if res.headers['content-encoding'] is 'gzip'
output = zlib.createGunzip()
res.pipe(output)
output.on 'data', (d)->
data += d.toString('utf-8')
output.on 'end', ()->
parsedData = JSON.parse(data)
if parsedData.error
msg.send "Error searching stack overflow: #{parsedData.error.message}"
return
if parsedData.total > 0
qs = for question in parsedData.questions[0..5]
"http://www.stackoverflow.com/questions/#{question.question_id} - #{question.title}"
if parsedData.total-5 > 0
qs.push "#{parsedData.total-5} more..."
for ans in qs
msg.send ans
else
msg.reply "No questions found matching that search."
)()
| 27192 | # Description:
# Search stack overflow and provide links to the first 5 questions
#
# Dependencies:
# none
#
# Configuration:
# None
#
# Commands:
# hubot sosearch [me] <query> - Search for the query
# hubot sosearch [me] <query> with tags <tag list sperated by ,> - Search for the query limit to given tags
#
# Author:
# carsonmcdonald
# drdamour
zlib = require('zlib');
# API keys are public for Stackapps
hubot_stackapps_apikey = '<KEY>'
module.exports = (robot) ->
robot.respond /sosearch( me)? (.*)/i, (msg) ->
re = RegExp("(.*) with tags (.*)", "i")
opts = msg.match[2].match(re)
if opts?
soSearch msg, opts[1], opts[2].split(',')
else
soSearch msg, msg.match[2], []
soSearch = (msg, search, tags) ->
data = ""
msg.http("http://api.stackoverflow.com/1.1/search")
.query
intitle: encodeURIComponent(search)
key: hubot_stackapps_apikey
tagged: encodeURIComponent(tags.join(':'))
.get( (err, req)->
req.addListener "response", (res)->
output = res
#pattern stolen from http://stackoverflow.com/questions/10207762/how-to-use-request-or-http-module-to-read-gzip-page-into-a-string
if res.headers['content-encoding'] is 'gzip'
output = zlib.createGunzip()
res.pipe(output)
output.on 'data', (d)->
data += d.toString('utf-8')
output.on 'end', ()->
parsedData = JSON.parse(data)
if parsedData.error
msg.send "Error searching stack overflow: #{parsedData.error.message}"
return
if parsedData.total > 0
qs = for question in parsedData.questions[0..5]
"http://www.stackoverflow.com/questions/#{question.question_id} - #{question.title}"
if parsedData.total-5 > 0
qs.push "#{parsedData.total-5} more..."
for ans in qs
msg.send ans
else
msg.reply "No questions found matching that search."
)()
| true | # Description:
# Search stack overflow and provide links to the first 5 questions
#
# Dependencies:
# none
#
# Configuration:
# None
#
# Commands:
# hubot sosearch [me] <query> - Search for the query
# hubot sosearch [me] <query> with tags <tag list sperated by ,> - Search for the query limit to given tags
#
# Author:
# carsonmcdonald
# drdamour
zlib = require('zlib');
# API keys are public for Stackapps
hubot_stackapps_apikey = 'PI:KEY:<KEY>END_PI'
module.exports = (robot) ->
robot.respond /sosearch( me)? (.*)/i, (msg) ->
re = RegExp("(.*) with tags (.*)", "i")
opts = msg.match[2].match(re)
if opts?
soSearch msg, opts[1], opts[2].split(',')
else
soSearch msg, msg.match[2], []
soSearch = (msg, search, tags) ->
data = ""
msg.http("http://api.stackoverflow.com/1.1/search")
.query
intitle: encodeURIComponent(search)
key: hubot_stackapps_apikey
tagged: encodeURIComponent(tags.join(':'))
.get( (err, req)->
req.addListener "response", (res)->
output = res
#pattern stolen from http://stackoverflow.com/questions/10207762/how-to-use-request-or-http-module-to-read-gzip-page-into-a-string
if res.headers['content-encoding'] is 'gzip'
output = zlib.createGunzip()
res.pipe(output)
output.on 'data', (d)->
data += d.toString('utf-8')
output.on 'end', ()->
parsedData = JSON.parse(data)
if parsedData.error
msg.send "Error searching stack overflow: #{parsedData.error.message}"
return
if parsedData.total > 0
qs = for question in parsedData.questions[0..5]
"http://www.stackoverflow.com/questions/#{question.question_id} - #{question.title}"
if parsedData.total-5 > 0
qs.push "#{parsedData.total-5} more..."
for ans in qs
msg.send ans
else
msg.reply "No questions found matching that search."
)()
|
[
{
"context": "xt = new Array()\n param1 = 'foo'\n param2 = 'bar'\n progressCalled = 0\n def.progress((value1,",
"end": 9687,
"score": 0.8687973618507385,
"start": 9684,
"tag": "PASSWORD",
"value": "bar"
}
] | test/DeferredSpec.coffee | Mumakil/Standalone-Deferred | 5 | root = @
describe "Deferred object", ->
it("Should initialize to state 'pending'", ->
ready = new Deferred()
expect(ready.state()).toEqual('pending')
)
it("Should move to 'resolved' state when resolved", ->
ready = new Deferred()
ready.resolve()
expect(ready.state()).toEqual('resolved')
)
it("Should move to 'rejected' state when rejected", ->
ready = new Deferred()
ready.reject()
expect(ready.state()).toEqual('rejected')
)
it("Should not change state after resolving or rejecting", ->
ready = new Deferred()
ready.resolve()
ready.reject()
expect(ready.state()).toEqual('resolved')
ready = new Deferred()
ready.reject()
ready.resolve()
expect(ready.state()).toEqual('rejected')
)
it("Should execute done and always callback after resolving and not execute fail callback", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
ready.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
ready.resolve()
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
expect(alwaysFired).toEqual(1)
)
it("Should execute fail and always callback after rejecting and not execute done callback", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
ready.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
ready.reject()
expect(doneFired).toEqual(0)
expect(failFired).toEqual(1)
expect(alwaysFired).toEqual(1)
)
it("Should execute callbacks added with then", ->
doneFired = 0
failFired = 0
ready = new Deferred()
ready.then(
->
doneFired += 1
,
->
failFired += 1
)
ready.resolve()
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
)
it("Should execute done after resolve immediately and not execute fail at all", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
ready.resolve()
ready.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
expect(alwaysFired).toEqual(1)
)
it("Should resolve and reject with context", ->
context = new Array()
ready = new Deferred()
ready.done(->
expect(@).toEqual(context)
)
ready.resolveWith(context)
ready = new Deferred()
ready.reject(->
expect(@).toEqual(context)
)
ready.rejectWith(context)
)
it("Should resolve with arguments", ->
ready = new Deferred()
ready.done((firstArg, secondArg) ->
expect(firstArg).toEqual(123)
expect(secondArg).toEqual('foo')
expect(@).toEqual(root)
)
ready.resolve(123, 'foo')
)
it("Should reject with arguments", ->
context = new Array()
ready = new Deferred()
ready.fail((firstArg, secondArg) ->
expect(firstArg).toEqual(123)
expect(secondArg).toEqual('foo')
expect(@).toEqual(context)
)
ready.rejectWith(context, 123, 'foo')
)
it("Should fire done with context and arguments after resolving", ->
context = new Array()
ready = new Deferred()
ready.resolveWith(context, 12345)
ready.done((arg)->
expect(arg).toEqual(12345)
expect(@).toEqual(context)
)
)
it("Should execute fn passed to constructor", ->
executed = 0
passedParam = null
ready = new Deferred((param)->
passedParam = param
@done(->
executed += 1
)
)
ready.resolve()
expect(executed).toEqual(1)
expect(passedParam).toEqual(ready)
)
describe "Promise object", ->
it("Should be given from deferred", ->
ready = new Deferred()
promise = ready.promise()
expect(promise.constructor.name).toEqual('Promise')
)
it("Should execute done and always when deferred is resolved", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
promise = ready.promise()
promise.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
ready.resolve()
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
expect(alwaysFired).toEqual(1)
)
it("Should reject with correct context", ->
failFired = 0
context = new Array()
ready = new Deferred()
promise = ready.promise()
ready.rejectWith(context, 1234, 'foo')
promise.fail((firstArg, secondArg) ->
expect(@).toEqual(context)
expect(firstArg).toEqual(1234)
expect(secondArg).toEqual('foo')
failFired += 1
)
expect(failFired).toEqual(1)
)
describe "Deferred.when", ->
it("Should give back a resolved promise object when called without arguments", ->
promise = Deferred.when()
expect(promise.constructor.name).toEqual('Promise')
expect(promise.state()).toEqual('resolved')
)
it("Should return single deferred's promise", ->
ready = new Deferred()
promise = Deferred.when(ready)
expect(promise).toEqual(ready.promise())
)
it("Should resolve when all deferreds resolve", ->
deferreds = [new Deferred(), new Deferred(), new Deferred()]
doneFired = 0
promise = Deferred.when(deferreds[0], deferreds[1], deferreds[2])
promise.done((args...)->
expect(args).toEqual([[1, 2], [3, 4], [5, 6]])
doneFired += 1
)
deferreds[1].resolve(3, 4)
expect(promise.state()).toEqual('pending')
deferreds[0].resolve(1, 2)
expect(promise.state()).toEqual('pending')
deferreds[2].resolve(5, 6)
expect(promise.state()).toEqual('resolved')
expect(doneFired).toEqual(1)
)
it("Should reject when first deferred rejects", ->
deferreds = [new Deferred(), new Deferred(), new Deferred()]
failFired = 0
promise = Deferred.when(deferreds[0], deferreds[1], deferreds[2])
promise.fail((firstArg, secondArg) ->
expect(firstArg).toEqual('foo')
expect(secondArg).toEqual(1234)
failFired += 1
)
deferreds[0].resolve()
expect(promise.state()).toEqual('pending')
deferreds[1].reject('foo', 1234)
expect(promise.state()).toEqual('rejected')
expect(failFired).toEqual(1)
)
describe 'Deferred.pipe()', ->
it("Should fire normally without parameters", ->
doneFired = 0
failFired = 0
param = 'foo'
context = new Array()
deferred = new Deferred()
deferred.pipe().done((value)->
expect(value).toEqual(param)
expect(@).toEqual(context)
doneFired += 1
).fail((value)->
failFired += 1
)
deferred.resolveWith(context, param)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
deferred = new Deferred()
deferred.pipe().done((value)->
doneFired += 1
).fail((value) ->
expect(value).toEqual(param)
expect(@).toEqual(context)
failFired += 1
)
deferred.rejectWith(context, param)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(1)
)
it("Should filter with function", ->
doneFired = 0
failFired = 0
param1 = 'foo'
param2 = 'bar'
context = new Array()
deferred = new Deferred()
deferred.pipe(
(string1, string2)->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
string1 + string2
).done((value)->
expect(value).toEqual(param1 + param2)
expect(@).toEqual(context)
doneFired += 1
).fail((value)->
failFired += 1
)
deferred.resolveWith(context, param1, param2)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
deferred = new Deferred()
deferred.pipe(
null,
(string1, string2) ->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
string1 + string2
).done((value)->
doneFired += 1
).fail((value) ->
expect(value).toEqual(param1 + param2)
expect(@).toEqual(context)
failFired += 1
)
deferred.rejectWith(context, param1, param2)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(1)
)
it('Should filter with another observable', ->
doneFired = 0
failFired = 0
param1 = 'foo'
param2 = 'bar'
context = new Array()
deferred = new Deferred()
pipeDeferred = new Deferred()
deferred.pipe(
(string1, string2)->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
pipeDeferred.rejectWith(@, string1, string2).promise()
).fail((passed1, passed2)->
expect(passed1).toEqual(param1)
expect(passed2).toEqual(param2)
expect(@).toEqual(context)
failFired += 1
).done((value)->
doneFired += 1
)
deferred.resolveWith(context, param1, param2)
expect(doneFired).toEqual(0)
expect(failFired).toEqual(1)
deferred = new Deferred()
pipeDeferred = new Deferred()
deferred.pipe(
null,
(string1, string2) ->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
pipeDeferred.resolveWith(context, param1, param2)
).fail((value)->
failFired += 1
).done((passed1, passed2) ->
expect(passed1).toEqual(param1)
expect(passed2).toEqual(param2)
expect(@).toEqual(context)
doneFired += 1
)
deferred.reject(param1, param2)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(1)
)
describe 'Progress and notify', ->
it('Should notify with correct context', ->
def = new Deferred()
context = new Array()
param1 = 'foo'
param2 = 'bar'
progressCalled = 0
def.progress((value1, value2) ->
progressCalled += 1
expect(value1).toEqual(param1)
expect(value2).toEqual(param2)
expect(@).toEqual(context)
)
def.notifyWith(context, param1, param2)
def.notifyWith(context, param1, param2)
expect(progressCalled).toEqual(2)
def.resolve()
def.notify()
expect(progressCalled).toEqual(2)
)
| 28239 | root = @
describe "Deferred object", ->
it("Should initialize to state 'pending'", ->
ready = new Deferred()
expect(ready.state()).toEqual('pending')
)
it("Should move to 'resolved' state when resolved", ->
ready = new Deferred()
ready.resolve()
expect(ready.state()).toEqual('resolved')
)
it("Should move to 'rejected' state when rejected", ->
ready = new Deferred()
ready.reject()
expect(ready.state()).toEqual('rejected')
)
it("Should not change state after resolving or rejecting", ->
ready = new Deferred()
ready.resolve()
ready.reject()
expect(ready.state()).toEqual('resolved')
ready = new Deferred()
ready.reject()
ready.resolve()
expect(ready.state()).toEqual('rejected')
)
it("Should execute done and always callback after resolving and not execute fail callback", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
ready.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
ready.resolve()
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
expect(alwaysFired).toEqual(1)
)
it("Should execute fail and always callback after rejecting and not execute done callback", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
ready.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
ready.reject()
expect(doneFired).toEqual(0)
expect(failFired).toEqual(1)
expect(alwaysFired).toEqual(1)
)
it("Should execute callbacks added with then", ->
doneFired = 0
failFired = 0
ready = new Deferred()
ready.then(
->
doneFired += 1
,
->
failFired += 1
)
ready.resolve()
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
)
it("Should execute done after resolve immediately and not execute fail at all", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
ready.resolve()
ready.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
expect(alwaysFired).toEqual(1)
)
it("Should resolve and reject with context", ->
context = new Array()
ready = new Deferred()
ready.done(->
expect(@).toEqual(context)
)
ready.resolveWith(context)
ready = new Deferred()
ready.reject(->
expect(@).toEqual(context)
)
ready.rejectWith(context)
)
it("Should resolve with arguments", ->
ready = new Deferred()
ready.done((firstArg, secondArg) ->
expect(firstArg).toEqual(123)
expect(secondArg).toEqual('foo')
expect(@).toEqual(root)
)
ready.resolve(123, 'foo')
)
it("Should reject with arguments", ->
context = new Array()
ready = new Deferred()
ready.fail((firstArg, secondArg) ->
expect(firstArg).toEqual(123)
expect(secondArg).toEqual('foo')
expect(@).toEqual(context)
)
ready.rejectWith(context, 123, 'foo')
)
it("Should fire done with context and arguments after resolving", ->
context = new Array()
ready = new Deferred()
ready.resolveWith(context, 12345)
ready.done((arg)->
expect(arg).toEqual(12345)
expect(@).toEqual(context)
)
)
it("Should execute fn passed to constructor", ->
executed = 0
passedParam = null
ready = new Deferred((param)->
passedParam = param
@done(->
executed += 1
)
)
ready.resolve()
expect(executed).toEqual(1)
expect(passedParam).toEqual(ready)
)
describe "Promise object", ->
it("Should be given from deferred", ->
ready = new Deferred()
promise = ready.promise()
expect(promise.constructor.name).toEqual('Promise')
)
it("Should execute done and always when deferred is resolved", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
promise = ready.promise()
promise.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
ready.resolve()
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
expect(alwaysFired).toEqual(1)
)
it("Should reject with correct context", ->
failFired = 0
context = new Array()
ready = new Deferred()
promise = ready.promise()
ready.rejectWith(context, 1234, 'foo')
promise.fail((firstArg, secondArg) ->
expect(@).toEqual(context)
expect(firstArg).toEqual(1234)
expect(secondArg).toEqual('foo')
failFired += 1
)
expect(failFired).toEqual(1)
)
describe "Deferred.when", ->
it("Should give back a resolved promise object when called without arguments", ->
promise = Deferred.when()
expect(promise.constructor.name).toEqual('Promise')
expect(promise.state()).toEqual('resolved')
)
it("Should return single deferred's promise", ->
ready = new Deferred()
promise = Deferred.when(ready)
expect(promise).toEqual(ready.promise())
)
it("Should resolve when all deferreds resolve", ->
deferreds = [new Deferred(), new Deferred(), new Deferred()]
doneFired = 0
promise = Deferred.when(deferreds[0], deferreds[1], deferreds[2])
promise.done((args...)->
expect(args).toEqual([[1, 2], [3, 4], [5, 6]])
doneFired += 1
)
deferreds[1].resolve(3, 4)
expect(promise.state()).toEqual('pending')
deferreds[0].resolve(1, 2)
expect(promise.state()).toEqual('pending')
deferreds[2].resolve(5, 6)
expect(promise.state()).toEqual('resolved')
expect(doneFired).toEqual(1)
)
it("Should reject when first deferred rejects", ->
deferreds = [new Deferred(), new Deferred(), new Deferred()]
failFired = 0
promise = Deferred.when(deferreds[0], deferreds[1], deferreds[2])
promise.fail((firstArg, secondArg) ->
expect(firstArg).toEqual('foo')
expect(secondArg).toEqual(1234)
failFired += 1
)
deferreds[0].resolve()
expect(promise.state()).toEqual('pending')
deferreds[1].reject('foo', 1234)
expect(promise.state()).toEqual('rejected')
expect(failFired).toEqual(1)
)
describe 'Deferred.pipe()', ->
it("Should fire normally without parameters", ->
doneFired = 0
failFired = 0
param = 'foo'
context = new Array()
deferred = new Deferred()
deferred.pipe().done((value)->
expect(value).toEqual(param)
expect(@).toEqual(context)
doneFired += 1
).fail((value)->
failFired += 1
)
deferred.resolveWith(context, param)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
deferred = new Deferred()
deferred.pipe().done((value)->
doneFired += 1
).fail((value) ->
expect(value).toEqual(param)
expect(@).toEqual(context)
failFired += 1
)
deferred.rejectWith(context, param)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(1)
)
it("Should filter with function", ->
doneFired = 0
failFired = 0
param1 = 'foo'
param2 = 'bar'
context = new Array()
deferred = new Deferred()
deferred.pipe(
(string1, string2)->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
string1 + string2
).done((value)->
expect(value).toEqual(param1 + param2)
expect(@).toEqual(context)
doneFired += 1
).fail((value)->
failFired += 1
)
deferred.resolveWith(context, param1, param2)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
deferred = new Deferred()
deferred.pipe(
null,
(string1, string2) ->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
string1 + string2
).done((value)->
doneFired += 1
).fail((value) ->
expect(value).toEqual(param1 + param2)
expect(@).toEqual(context)
failFired += 1
)
deferred.rejectWith(context, param1, param2)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(1)
)
it('Should filter with another observable', ->
doneFired = 0
failFired = 0
param1 = 'foo'
param2 = 'bar'
context = new Array()
deferred = new Deferred()
pipeDeferred = new Deferred()
deferred.pipe(
(string1, string2)->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
pipeDeferred.rejectWith(@, string1, string2).promise()
).fail((passed1, passed2)->
expect(passed1).toEqual(param1)
expect(passed2).toEqual(param2)
expect(@).toEqual(context)
failFired += 1
).done((value)->
doneFired += 1
)
deferred.resolveWith(context, param1, param2)
expect(doneFired).toEqual(0)
expect(failFired).toEqual(1)
deferred = new Deferred()
pipeDeferred = new Deferred()
deferred.pipe(
null,
(string1, string2) ->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
pipeDeferred.resolveWith(context, param1, param2)
).fail((value)->
failFired += 1
).done((passed1, passed2) ->
expect(passed1).toEqual(param1)
expect(passed2).toEqual(param2)
expect(@).toEqual(context)
doneFired += 1
)
deferred.reject(param1, param2)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(1)
)
describe 'Progress and notify', ->
it('Should notify with correct context', ->
def = new Deferred()
context = new Array()
param1 = 'foo'
param2 = '<PASSWORD>'
progressCalled = 0
def.progress((value1, value2) ->
progressCalled += 1
expect(value1).toEqual(param1)
expect(value2).toEqual(param2)
expect(@).toEqual(context)
)
def.notifyWith(context, param1, param2)
def.notifyWith(context, param1, param2)
expect(progressCalled).toEqual(2)
def.resolve()
def.notify()
expect(progressCalled).toEqual(2)
)
| true | root = @
describe "Deferred object", ->
it("Should initialize to state 'pending'", ->
ready = new Deferred()
expect(ready.state()).toEqual('pending')
)
it("Should move to 'resolved' state when resolved", ->
ready = new Deferred()
ready.resolve()
expect(ready.state()).toEqual('resolved')
)
it("Should move to 'rejected' state when rejected", ->
ready = new Deferred()
ready.reject()
expect(ready.state()).toEqual('rejected')
)
it("Should not change state after resolving or rejecting", ->
ready = new Deferred()
ready.resolve()
ready.reject()
expect(ready.state()).toEqual('resolved')
ready = new Deferred()
ready.reject()
ready.resolve()
expect(ready.state()).toEqual('rejected')
)
it("Should execute done and always callback after resolving and not execute fail callback", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
ready.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
ready.resolve()
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
expect(alwaysFired).toEqual(1)
)
it("Should execute fail and always callback after rejecting and not execute done callback", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
ready.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
ready.reject()
expect(doneFired).toEqual(0)
expect(failFired).toEqual(1)
expect(alwaysFired).toEqual(1)
)
it("Should execute callbacks added with then", ->
doneFired = 0
failFired = 0
ready = new Deferred()
ready.then(
->
doneFired += 1
,
->
failFired += 1
)
ready.resolve()
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
)
it("Should execute done after resolve immediately and not execute fail at all", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
ready.resolve()
ready.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
expect(alwaysFired).toEqual(1)
)
it("Should resolve and reject with context", ->
context = new Array()
ready = new Deferred()
ready.done(->
expect(@).toEqual(context)
)
ready.resolveWith(context)
ready = new Deferred()
ready.reject(->
expect(@).toEqual(context)
)
ready.rejectWith(context)
)
it("Should resolve with arguments", ->
ready = new Deferred()
ready.done((firstArg, secondArg) ->
expect(firstArg).toEqual(123)
expect(secondArg).toEqual('foo')
expect(@).toEqual(root)
)
ready.resolve(123, 'foo')
)
it("Should reject with arguments", ->
context = new Array()
ready = new Deferred()
ready.fail((firstArg, secondArg) ->
expect(firstArg).toEqual(123)
expect(secondArg).toEqual('foo')
expect(@).toEqual(context)
)
ready.rejectWith(context, 123, 'foo')
)
it("Should fire done with context and arguments after resolving", ->
context = new Array()
ready = new Deferred()
ready.resolveWith(context, 12345)
ready.done((arg)->
expect(arg).toEqual(12345)
expect(@).toEqual(context)
)
)
it("Should execute fn passed to constructor", ->
executed = 0
passedParam = null
ready = new Deferred((param)->
passedParam = param
@done(->
executed += 1
)
)
ready.resolve()
expect(executed).toEqual(1)
expect(passedParam).toEqual(ready)
)
describe "Promise object", ->
it("Should be given from deferred", ->
ready = new Deferred()
promise = ready.promise()
expect(promise.constructor.name).toEqual('Promise')
)
it("Should execute done and always when deferred is resolved", ->
doneFired = 0
failFired = 0
alwaysFired = 0
ready = new Deferred()
promise = ready.promise()
promise.done(->
doneFired += 1
).fail(->
failFired += 1
).always(->
alwaysFired += 1
)
ready.resolve()
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
expect(alwaysFired).toEqual(1)
)
it("Should reject with correct context", ->
failFired = 0
context = new Array()
ready = new Deferred()
promise = ready.promise()
ready.rejectWith(context, 1234, 'foo')
promise.fail((firstArg, secondArg) ->
expect(@).toEqual(context)
expect(firstArg).toEqual(1234)
expect(secondArg).toEqual('foo')
failFired += 1
)
expect(failFired).toEqual(1)
)
describe "Deferred.when", ->
it("Should give back a resolved promise object when called without arguments", ->
promise = Deferred.when()
expect(promise.constructor.name).toEqual('Promise')
expect(promise.state()).toEqual('resolved')
)
it("Should return single deferred's promise", ->
ready = new Deferred()
promise = Deferred.when(ready)
expect(promise).toEqual(ready.promise())
)
it("Should resolve when all deferreds resolve", ->
deferreds = [new Deferred(), new Deferred(), new Deferred()]
doneFired = 0
promise = Deferred.when(deferreds[0], deferreds[1], deferreds[2])
promise.done((args...)->
expect(args).toEqual([[1, 2], [3, 4], [5, 6]])
doneFired += 1
)
deferreds[1].resolve(3, 4)
expect(promise.state()).toEqual('pending')
deferreds[0].resolve(1, 2)
expect(promise.state()).toEqual('pending')
deferreds[2].resolve(5, 6)
expect(promise.state()).toEqual('resolved')
expect(doneFired).toEqual(1)
)
it("Should reject when first deferred rejects", ->
deferreds = [new Deferred(), new Deferred(), new Deferred()]
failFired = 0
promise = Deferred.when(deferreds[0], deferreds[1], deferreds[2])
promise.fail((firstArg, secondArg) ->
expect(firstArg).toEqual('foo')
expect(secondArg).toEqual(1234)
failFired += 1
)
deferreds[0].resolve()
expect(promise.state()).toEqual('pending')
deferreds[1].reject('foo', 1234)
expect(promise.state()).toEqual('rejected')
expect(failFired).toEqual(1)
)
describe 'Deferred.pipe()', ->
it("Should fire normally without parameters", ->
doneFired = 0
failFired = 0
param = 'foo'
context = new Array()
deferred = new Deferred()
deferred.pipe().done((value)->
expect(value).toEqual(param)
expect(@).toEqual(context)
doneFired += 1
).fail((value)->
failFired += 1
)
deferred.resolveWith(context, param)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
deferred = new Deferred()
deferred.pipe().done((value)->
doneFired += 1
).fail((value) ->
expect(value).toEqual(param)
expect(@).toEqual(context)
failFired += 1
)
deferred.rejectWith(context, param)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(1)
)
it("Should filter with function", ->
doneFired = 0
failFired = 0
param1 = 'foo'
param2 = 'bar'
context = new Array()
deferred = new Deferred()
deferred.pipe(
(string1, string2)->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
string1 + string2
).done((value)->
expect(value).toEqual(param1 + param2)
expect(@).toEqual(context)
doneFired += 1
).fail((value)->
failFired += 1
)
deferred.resolveWith(context, param1, param2)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(0)
deferred = new Deferred()
deferred.pipe(
null,
(string1, string2) ->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
string1 + string2
).done((value)->
doneFired += 1
).fail((value) ->
expect(value).toEqual(param1 + param2)
expect(@).toEqual(context)
failFired += 1
)
deferred.rejectWith(context, param1, param2)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(1)
)
it('Should filter with another observable', ->
doneFired = 0
failFired = 0
param1 = 'foo'
param2 = 'bar'
context = new Array()
deferred = new Deferred()
pipeDeferred = new Deferred()
deferred.pipe(
(string1, string2)->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
pipeDeferred.rejectWith(@, string1, string2).promise()
).fail((passed1, passed2)->
expect(passed1).toEqual(param1)
expect(passed2).toEqual(param2)
expect(@).toEqual(context)
failFired += 1
).done((value)->
doneFired += 1
)
deferred.resolveWith(context, param1, param2)
expect(doneFired).toEqual(0)
expect(failFired).toEqual(1)
deferred = new Deferred()
pipeDeferred = new Deferred()
deferred.pipe(
null,
(string1, string2) ->
expect(string1).toEqual(param1)
expect(string2).toEqual(param2)
pipeDeferred.resolveWith(context, param1, param2)
).fail((value)->
failFired += 1
).done((passed1, passed2) ->
expect(passed1).toEqual(param1)
expect(passed2).toEqual(param2)
expect(@).toEqual(context)
doneFired += 1
)
deferred.reject(param1, param2)
expect(doneFired).toEqual(1)
expect(failFired).toEqual(1)
)
describe 'Progress and notify', ->
it('Should notify with correct context', ->
def = new Deferred()
context = new Array()
param1 = 'foo'
param2 = 'PI:PASSWORD:<PASSWORD>END_PI'
progressCalled = 0
def.progress((value1, value2) ->
progressCalled += 1
expect(value1).toEqual(param1)
expect(value2).toEqual(param2)
expect(@).toEqual(context)
)
def.notifyWith(context, param1, param2)
def.notifyWith(context, param1, param2)
expect(progressCalled).toEqual(2)
def.resolve()
def.notify()
expect(progressCalled).toEqual(2)
)
|
[
{
"context": "ken =\n attributeHash: true\n token: 'ATTRHASH'\n tokenString: @buffer.substring(@buff",
"end": 10593,
"score": 0.6797395348548889,
"start": 10589,
"tag": "USERNAME",
"value": "ATTR"
},
{
"context": "=\n attributeHash: true\n token: 'A... | src/tokiniser.coffee | uglyog/clientside-haml-js | 19 | ###
HAML Tokiniser: This class is responsible for parsing the haml source into tokens
###
class Tokeniser
currentLineMatcher: /[^\n]*/g
tokenMatchers:
whitespace: /[ \t]+/g,
element: /%[a-zA-Z][a-zA-Z0-9]*/g,
idSelector: /#[a-zA-Z_\-][a-zA-Z0-9_\-]*/g,
classSelector: /\.[a-zA-Z0-9_\-]+/g,
identifier: /[a-zA-Z][a-zA-Z0-9\-]*/g,
quotedString: /[\'][^\'\n]*[\']/g,
quotedString2: /[\"][^\"\n]*[\"]/g,
comment: /\-#/g,
escapeHtml: /\&=/g,
unescapeHtml: /\!=/g,
objectReference: /\[[a-zA-Z_@][a-zA-Z0-9_]*\]/g,
doctype: /!!!/g,
continueLine: /\|\s*\n/g,
filter: /:\w+/g
constructor: (options) ->
@buffer = null
@bufferIndex = null
@prevToken = null
@token = null
if options.templateId?
template = document.getElementById(options.templateId)
if template
@buffer = template.text
@bufferIndex = 0
else
throw "Did not find a template with ID '" + options.templateId + "'"
else if options.template?
@buffer = options.template
@bufferIndex = 0
else if options.templateUrl?
errorFn = (jqXHR, textStatus, errorThrown) ->
throw "Failed to fetch haml template at URL #{options.templateUrl}: #{textStatus} #{errorThrown}"
successFn = (data) =>
@buffer = data
@bufferIndex = 0
jQuery.ajax
url: options.templateUrl
success: successFn
error: errorFn
dataType: 'text'
async: false
beforeSend: (xhr) ->
xhr.withCredentials = true
###
Try to match a token with the given regexp
###
matchToken: (matcher) ->
matcher.lastIndex = @bufferIndex
result = matcher.exec(@buffer)
if result?.index == @bufferIndex then result[0]
###
Match a multi-character token
###
matchMultiCharToken: (matcher, token, tokenStr) ->
if !@token
matched = @matchToken(matcher)
if matched
@token = token
@token.tokenString = tokenStr?(matched) ? matched
@token.matched = matched
@advanceCharsInBuffer(matched.length)
###
Match a single character token
###
matchSingleCharToken: (ch, token) ->
if !@token and @buffer.charAt(@bufferIndex) == ch
@token = token
@token.tokenString = ch
@token.matched = ch
@advanceCharsInBuffer(1)
###
Match and return the next token in the input buffer
###
getNextToken: () ->
throw haml.HamlRuntime.templateError(@lineNumber, @characterNumber, @currentLine,
"An internal parser error has occurred in the HAML parser") if isNaN(@bufferIndex)
@prevToken = @token
@token = null
if @buffer == null or @buffer.length == @bufferIndex
@token = { eof: true, token: 'EOF' }
else
@initLine()
if !@token
ch = @buffer.charCodeAt(@bufferIndex)
ch1 = @buffer.charCodeAt(@bufferIndex + 1)
if ch == 10 or (ch == 13 and ch1 == 10)
@token = { eol: true, token: 'EOL' }
if ch == 13 and ch1 == 10
@advanceCharsInBuffer(2)
@token.matched = String.fromCharCode(ch) + String.fromCharCode(ch1)
else
@advanceCharsInBuffer(1)
@token.matched = String.fromCharCode(ch)
@characterNumber = 0
@currentLine = @getCurrentLine()
@matchMultiCharToken(@tokenMatchers.whitespace, { ws: true, token: 'WS' })
@matchMultiCharToken(@tokenMatchers.continueLine, { continueLine: true, token: 'CONTINUELINE' })
@matchMultiCharToken(@tokenMatchers.element, { element: true, token: 'ELEMENT' }, (matched) -> matched.substring(1) )
@matchMultiCharToken(@tokenMatchers.idSelector, { idSelector: true, token: 'ID' }, (matched) -> matched.substring(1) )
@matchMultiCharToken(@tokenMatchers.classSelector, { classSelector: true, token: 'CLASS' }, (matched) -> matched.substring(1) )
@matchMultiCharToken(@tokenMatchers.identifier, { identifier: true, token: 'IDENTIFIER' })
@matchMultiCharToken(@tokenMatchers.doctype, { doctype: true, token: 'DOCTYPE' })
@matchMultiCharToken(@tokenMatchers.filter, { filter: true, token: 'FILTER' }, (matched) -> matched.substring(1) )
if !@token
str = @matchToken(@tokenMatchers.quotedString)
str = @matchToken(@tokenMatchers.quotedString2) if not str
if str
@token = { string: true, token: 'STRING', tokenString: str.substring(1, str.length - 1), matched: str }
@advanceCharsInBuffer(str.length)
@matchMultiCharToken(@tokenMatchers.comment, { comment: true, token: 'COMMENT' })
@matchMultiCharToken(@tokenMatchers.escapeHtml, { escapeHtml: true, token: 'ESCAPEHTML' })
@matchMultiCharToken(@tokenMatchers.unescapeHtml, { unescapeHtml: true, token: 'UNESCAPEHTML' })
@matchMultiCharToken(@tokenMatchers.objectReference, { objectReference: true, token: 'OBJECTREFERENCE' }, (matched) ->
matched.substring(1, matched.length - 1)
)
if !@token and @buffer and @buffer.charAt(@bufferIndex) == '{' and !@prevToken.ws
@matchJavascriptHash()
@matchSingleCharToken('(', { openBracket: true, token: 'OPENBRACKET' })
@matchSingleCharToken(')', { closeBracket: true, token: 'CLOSEBRACKET' })
@matchSingleCharToken('=', { equal: true, token: 'EQUAL' })
@matchSingleCharToken('/', { slash: true, token: 'SLASH' })
@matchSingleCharToken('!', { exclamation: true, token: 'EXCLAMATION' })
@matchSingleCharToken('-', { minus: true, token: 'MINUS' })
@matchSingleCharToken('&', { amp: true, token: 'AMP' })
@matchSingleCharToken('<', { lt: true, token: 'LT' })
@matchSingleCharToken('>', { gt: true, token: 'GT' })
@matchSingleCharToken('~', { tilde: true, token: 'TILDE' })
if @token == null
@token =
unknown: true
token: 'UNKNOWN'
matched: @buffer.charAt(@bufferIndex)
@advanceCharsInBuffer(1)
@token
###
Look ahead a number of tokens and return the token found
###
lookAhead: (numberOfTokens) ->
token = null
if numberOfTokens > 0
currentToken = @token
prevToken = @prevToken
currentLine = @currentLine
lineNumber = @lineNumber
characterNumber = @characterNumber
bufferIndex = @bufferIndex
i = 0
token = this.getNextToken() while i++ < numberOfTokens
@token = currentToken
@prevToken = prevToken
@currentLine = currentLine
@lineNumber = lineNumber
@characterNumber = characterNumber
@bufferIndex = bufferIndex
token
###
Initilise the line and character counters
###
initLine: () ->
if !@currentLine and @currentLine isnt ""
@currentLine = @getCurrentLine()
@lineNumber = 1
@characterNumber = 0
###
Returns the current line in the input buffer
###
getCurrentLine: (index) ->
@currentLineMatcher.lastIndex = @bufferIndex + (index ? 0)
line = @currentLineMatcher.exec(@buffer)
if line then line[0] else ''
###
Returns an error string filled out with the line and character counters
###
parseError: (error) ->
haml.HamlRuntime.templateError(@lineNumber, @characterNumber, @currentLine, error)
###
Skips to the end of the line and returns the string that was skipped
###
skipToEOLorEOF: ->
text = ''
unless @token.eof or @token.eol
text += @token.matched if @token.matched?
@currentLineMatcher.lastIndex = @bufferIndex
line = @currentLineMatcher.exec(@buffer)
if line and line.index == @bufferIndex
contents = (_.str || _).rtrim(line[0])
if (_.str || _).endsWith(contents, '|')
text += contents.substring(0, contents.length - 1)
@advanceCharsInBuffer(contents.length - 1)
@getNextToken()
text += @parseMultiLine()
else
text += line[0]
@advanceCharsInBuffer(line[0].length)
@getNextToken()
text
###
Parses a multiline code block and returns the parsed text
###
parseMultiLine: ->
text = ''
while @token.continueLine
@currentLineMatcher.lastIndex = @bufferIndex
line = @currentLineMatcher.exec(@buffer)
if line and line.index == @bufferIndex
contents = (_.str || _).rtrim(line[0])
if (_.str || _).endsWith(contents, '|')
text += contents.substring(0, contents.length - 1)
@advanceCharsInBuffer(contents.length - 1)
@getNextToken()
text
###
Advances the input buffer pointer by a number of characters, updating the line and character counters
###
advanceCharsInBuffer: (numChars) ->
i = 0
while i < numChars
ch = @buffer.charCodeAt(@bufferIndex + i)
ch1 = @buffer.charCodeAt(@bufferIndex + i + 1)
if ch == 13 and ch1 == 10
@lineNumber++
@characterNumber = 0
@currentLine = @getCurrentLine(i)
i++
else if ch == 10
@lineNumber++
@characterNumber = 0
@currentLine = @getCurrentLine(i)
else
@characterNumber++
i++
@bufferIndex += numChars
###
Returns the current line and character counters
###
currentParsePoint: ->
{
lineNumber: @lineNumber,
characterNumber: @characterNumber,
currentLine: @currentLine
}
###
Pushes back the current token onto the front of the input buffer
###
pushBackToken: ->
if !@token.eof
@bufferIndex -= @token.matched.length
@token = @prevToken
###
Is the current token an end of line or end of input buffer
###
isEolOrEof: ->
@token.eol or @token.eof
###
Match a Javascript Hash {...}
###
matchJavascriptHash: ->
currentIndent = @calculateCurrentIndent()
i = @bufferIndex + 1
characterNumberStart = @characterNumber
lineNumberStart = @lineNumber
braceCount = 1
while i < @buffer.length and (braceCount > 1 or @buffer.charAt(i) isnt '}')
ch = @buffer.charAt(i)
chCode = @buffer.charCodeAt(i)
if ch == '{'
braceCount++
i++
else if ch == '}'
braceCount--
i++
else if chCode == 10 or chCode == 13
i++
else
i++
if i == @buffer.length
@characterNumber = characterNumberStart + 1
@lineNumber = lineNumberStart
throw @parseError('Error parsing attribute hash - Did not find a terminating "}"')
else
@token =
attributeHash: true
token: 'ATTRHASH'
tokenString: @buffer.substring(@bufferIndex, i + 1)
matched: @buffer.substring(@bufferIndex, i + 1)
@advanceCharsInBuffer(i - @bufferIndex + 1)
###
Calculate the indent value of the current line
###
calculateCurrentIndent: ->
@tokenMatchers.whitespace.lastIndex = 0
result = @tokenMatchers.whitespace.exec(@currentLine)
if result?.index == 0
@calculateIndent(result[0])
else
0
###
Calculate the indent level of the provided whitespace
###
calculateIndent: (whitespace) ->
indent = 0
i = 0
while i < whitespace.length
if whitespace.charCodeAt(i) == 9
indent += 2
else
indent++
i++
Math.floor((indent + 1) / 2) | 92787 | ###
HAML Tokiniser: This class is responsible for parsing the haml source into tokens
###
class Tokeniser
currentLineMatcher: /[^\n]*/g
tokenMatchers:
whitespace: /[ \t]+/g,
element: /%[a-zA-Z][a-zA-Z0-9]*/g,
idSelector: /#[a-zA-Z_\-][a-zA-Z0-9_\-]*/g,
classSelector: /\.[a-zA-Z0-9_\-]+/g,
identifier: /[a-zA-Z][a-zA-Z0-9\-]*/g,
quotedString: /[\'][^\'\n]*[\']/g,
quotedString2: /[\"][^\"\n]*[\"]/g,
comment: /\-#/g,
escapeHtml: /\&=/g,
unescapeHtml: /\!=/g,
objectReference: /\[[a-zA-Z_@][a-zA-Z0-9_]*\]/g,
doctype: /!!!/g,
continueLine: /\|\s*\n/g,
filter: /:\w+/g
constructor: (options) ->
@buffer = null
@bufferIndex = null
@prevToken = null
@token = null
if options.templateId?
template = document.getElementById(options.templateId)
if template
@buffer = template.text
@bufferIndex = 0
else
throw "Did not find a template with ID '" + options.templateId + "'"
else if options.template?
@buffer = options.template
@bufferIndex = 0
else if options.templateUrl?
errorFn = (jqXHR, textStatus, errorThrown) ->
throw "Failed to fetch haml template at URL #{options.templateUrl}: #{textStatus} #{errorThrown}"
successFn = (data) =>
@buffer = data
@bufferIndex = 0
jQuery.ajax
url: options.templateUrl
success: successFn
error: errorFn
dataType: 'text'
async: false
beforeSend: (xhr) ->
xhr.withCredentials = true
###
Try to match a token with the given regexp
###
matchToken: (matcher) ->
matcher.lastIndex = @bufferIndex
result = matcher.exec(@buffer)
if result?.index == @bufferIndex then result[0]
###
Match a multi-character token
###
matchMultiCharToken: (matcher, token, tokenStr) ->
if !@token
matched = @matchToken(matcher)
if matched
@token = token
@token.tokenString = tokenStr?(matched) ? matched
@token.matched = matched
@advanceCharsInBuffer(matched.length)
###
Match a single character token
###
matchSingleCharToken: (ch, token) ->
if !@token and @buffer.charAt(@bufferIndex) == ch
@token = token
@token.tokenString = ch
@token.matched = ch
@advanceCharsInBuffer(1)
###
Match and return the next token in the input buffer
###
getNextToken: () ->
throw haml.HamlRuntime.templateError(@lineNumber, @characterNumber, @currentLine,
"An internal parser error has occurred in the HAML parser") if isNaN(@bufferIndex)
@prevToken = @token
@token = null
if @buffer == null or @buffer.length == @bufferIndex
@token = { eof: true, token: 'EOF' }
else
@initLine()
if !@token
ch = @buffer.charCodeAt(@bufferIndex)
ch1 = @buffer.charCodeAt(@bufferIndex + 1)
if ch == 10 or (ch == 13 and ch1 == 10)
@token = { eol: true, token: 'EOL' }
if ch == 13 and ch1 == 10
@advanceCharsInBuffer(2)
@token.matched = String.fromCharCode(ch) + String.fromCharCode(ch1)
else
@advanceCharsInBuffer(1)
@token.matched = String.fromCharCode(ch)
@characterNumber = 0
@currentLine = @getCurrentLine()
@matchMultiCharToken(@tokenMatchers.whitespace, { ws: true, token: 'WS' })
@matchMultiCharToken(@tokenMatchers.continueLine, { continueLine: true, token: 'CONTINUELINE' })
@matchMultiCharToken(@tokenMatchers.element, { element: true, token: 'ELEMENT' }, (matched) -> matched.substring(1) )
@matchMultiCharToken(@tokenMatchers.idSelector, { idSelector: true, token: 'ID' }, (matched) -> matched.substring(1) )
@matchMultiCharToken(@tokenMatchers.classSelector, { classSelector: true, token: 'CLASS' }, (matched) -> matched.substring(1) )
@matchMultiCharToken(@tokenMatchers.identifier, { identifier: true, token: 'IDENTIFIER' })
@matchMultiCharToken(@tokenMatchers.doctype, { doctype: true, token: 'DOCTYPE' })
@matchMultiCharToken(@tokenMatchers.filter, { filter: true, token: 'FILTER' }, (matched) -> matched.substring(1) )
if !@token
str = @matchToken(@tokenMatchers.quotedString)
str = @matchToken(@tokenMatchers.quotedString2) if not str
if str
@token = { string: true, token: 'STRING', tokenString: str.substring(1, str.length - 1), matched: str }
@advanceCharsInBuffer(str.length)
@matchMultiCharToken(@tokenMatchers.comment, { comment: true, token: 'COMMENT' })
@matchMultiCharToken(@tokenMatchers.escapeHtml, { escapeHtml: true, token: 'ESCAPEHTML' })
@matchMultiCharToken(@tokenMatchers.unescapeHtml, { unescapeHtml: true, token: 'UNESCAPEHTML' })
@matchMultiCharToken(@tokenMatchers.objectReference, { objectReference: true, token: 'OBJECTREFERENCE' }, (matched) ->
matched.substring(1, matched.length - 1)
)
if !@token and @buffer and @buffer.charAt(@bufferIndex) == '{' and !@prevToken.ws
@matchJavascriptHash()
@matchSingleCharToken('(', { openBracket: true, token: 'OPENBRACKET' })
@matchSingleCharToken(')', { closeBracket: true, token: 'CLOSEBRACKET' })
@matchSingleCharToken('=', { equal: true, token: 'EQUAL' })
@matchSingleCharToken('/', { slash: true, token: 'SLASH' })
@matchSingleCharToken('!', { exclamation: true, token: 'EXCLAMATION' })
@matchSingleCharToken('-', { minus: true, token: 'MINUS' })
@matchSingleCharToken('&', { amp: true, token: 'AMP' })
@matchSingleCharToken('<', { lt: true, token: 'LT' })
@matchSingleCharToken('>', { gt: true, token: 'GT' })
@matchSingleCharToken('~', { tilde: true, token: 'TILDE' })
if @token == null
@token =
unknown: true
token: 'UNKNOWN'
matched: @buffer.charAt(@bufferIndex)
@advanceCharsInBuffer(1)
@token
###
Look ahead a number of tokens and return the token found
###
lookAhead: (numberOfTokens) ->
token = null
if numberOfTokens > 0
currentToken = @token
prevToken = @prevToken
currentLine = @currentLine
lineNumber = @lineNumber
characterNumber = @characterNumber
bufferIndex = @bufferIndex
i = 0
token = this.getNextToken() while i++ < numberOfTokens
@token = currentToken
@prevToken = prevToken
@currentLine = currentLine
@lineNumber = lineNumber
@characterNumber = characterNumber
@bufferIndex = bufferIndex
token
###
Initilise the line and character counters
###
initLine: () ->
if !@currentLine and @currentLine isnt ""
@currentLine = @getCurrentLine()
@lineNumber = 1
@characterNumber = 0
###
Returns the current line in the input buffer
###
getCurrentLine: (index) ->
@currentLineMatcher.lastIndex = @bufferIndex + (index ? 0)
line = @currentLineMatcher.exec(@buffer)
if line then line[0] else ''
###
Returns an error string filled out with the line and character counters
###
parseError: (error) ->
haml.HamlRuntime.templateError(@lineNumber, @characterNumber, @currentLine, error)
###
Skips to the end of the line and returns the string that was skipped
###
skipToEOLorEOF: ->
text = ''
unless @token.eof or @token.eol
text += @token.matched if @token.matched?
@currentLineMatcher.lastIndex = @bufferIndex
line = @currentLineMatcher.exec(@buffer)
if line and line.index == @bufferIndex
contents = (_.str || _).rtrim(line[0])
if (_.str || _).endsWith(contents, '|')
text += contents.substring(0, contents.length - 1)
@advanceCharsInBuffer(contents.length - 1)
@getNextToken()
text += @parseMultiLine()
else
text += line[0]
@advanceCharsInBuffer(line[0].length)
@getNextToken()
text
###
Parses a multiline code block and returns the parsed text
###
parseMultiLine: ->
text = ''
while @token.continueLine
@currentLineMatcher.lastIndex = @bufferIndex
line = @currentLineMatcher.exec(@buffer)
if line and line.index == @bufferIndex
contents = (_.str || _).rtrim(line[0])
if (_.str || _).endsWith(contents, '|')
text += contents.substring(0, contents.length - 1)
@advanceCharsInBuffer(contents.length - 1)
@getNextToken()
text
###
Advances the input buffer pointer by a number of characters, updating the line and character counters
###
advanceCharsInBuffer: (numChars) ->
i = 0
while i < numChars
ch = @buffer.charCodeAt(@bufferIndex + i)
ch1 = @buffer.charCodeAt(@bufferIndex + i + 1)
if ch == 13 and ch1 == 10
@lineNumber++
@characterNumber = 0
@currentLine = @getCurrentLine(i)
i++
else if ch == 10
@lineNumber++
@characterNumber = 0
@currentLine = @getCurrentLine(i)
else
@characterNumber++
i++
@bufferIndex += numChars
###
Returns the current line and character counters
###
currentParsePoint: ->
{
lineNumber: @lineNumber,
characterNumber: @characterNumber,
currentLine: @currentLine
}
###
Pushes back the current token onto the front of the input buffer
###
pushBackToken: ->
if !@token.eof
@bufferIndex -= @token.matched.length
@token = @prevToken
###
Is the current token an end of line or end of input buffer
###
isEolOrEof: ->
@token.eol or @token.eof
###
Match a Javascript Hash {...}
###
matchJavascriptHash: ->
currentIndent = @calculateCurrentIndent()
i = @bufferIndex + 1
characterNumberStart = @characterNumber
lineNumberStart = @lineNumber
braceCount = 1
while i < @buffer.length and (braceCount > 1 or @buffer.charAt(i) isnt '}')
ch = @buffer.charAt(i)
chCode = @buffer.charCodeAt(i)
if ch == '{'
braceCount++
i++
else if ch == '}'
braceCount--
i++
else if chCode == 10 or chCode == 13
i++
else
i++
if i == @buffer.length
@characterNumber = characterNumberStart + 1
@lineNumber = lineNumberStart
throw @parseError('Error parsing attribute hash - Did not find a terminating "}"')
else
@token =
attributeHash: true
token: 'ATTR<PASSWORD>'
tokenString: @buffer.substring(@bufferIndex, i + 1)
matched: @buffer.substring(@bufferIndex, i + 1)
@advanceCharsInBuffer(i - @bufferIndex + 1)
###
Calculate the indent value of the current line
###
calculateCurrentIndent: ->
@tokenMatchers.whitespace.lastIndex = 0
result = @tokenMatchers.whitespace.exec(@currentLine)
if result?.index == 0
@calculateIndent(result[0])
else
0
###
Calculate the indent level of the provided whitespace
###
calculateIndent: (whitespace) ->
indent = 0
i = 0
while i < whitespace.length
if whitespace.charCodeAt(i) == 9
indent += 2
else
indent++
i++
Math.floor((indent + 1) / 2) | true | ###
HAML Tokiniser: This class is responsible for parsing the haml source into tokens
###
class Tokeniser
currentLineMatcher: /[^\n]*/g
tokenMatchers:
whitespace: /[ \t]+/g,
element: /%[a-zA-Z][a-zA-Z0-9]*/g,
idSelector: /#[a-zA-Z_\-][a-zA-Z0-9_\-]*/g,
classSelector: /\.[a-zA-Z0-9_\-]+/g,
identifier: /[a-zA-Z][a-zA-Z0-9\-]*/g,
quotedString: /[\'][^\'\n]*[\']/g,
quotedString2: /[\"][^\"\n]*[\"]/g,
comment: /\-#/g,
escapeHtml: /\&=/g,
unescapeHtml: /\!=/g,
objectReference: /\[[a-zA-Z_@][a-zA-Z0-9_]*\]/g,
doctype: /!!!/g,
continueLine: /\|\s*\n/g,
filter: /:\w+/g
constructor: (options) ->
@buffer = null
@bufferIndex = null
@prevToken = null
@token = null
if options.templateId?
template = document.getElementById(options.templateId)
if template
@buffer = template.text
@bufferIndex = 0
else
throw "Did not find a template with ID '" + options.templateId + "'"
else if options.template?
@buffer = options.template
@bufferIndex = 0
else if options.templateUrl?
errorFn = (jqXHR, textStatus, errorThrown) ->
throw "Failed to fetch haml template at URL #{options.templateUrl}: #{textStatus} #{errorThrown}"
successFn = (data) =>
@buffer = data
@bufferIndex = 0
jQuery.ajax
url: options.templateUrl
success: successFn
error: errorFn
dataType: 'text'
async: false
beforeSend: (xhr) ->
xhr.withCredentials = true
###
Try to match a token with the given regexp
###
matchToken: (matcher) ->
matcher.lastIndex = @bufferIndex
result = matcher.exec(@buffer)
if result?.index == @bufferIndex then result[0]
###
Match a multi-character token
###
matchMultiCharToken: (matcher, token, tokenStr) ->
if !@token
matched = @matchToken(matcher)
if matched
@token = token
@token.tokenString = tokenStr?(matched) ? matched
@token.matched = matched
@advanceCharsInBuffer(matched.length)
###
Match a single character token
###
matchSingleCharToken: (ch, token) ->
if !@token and @buffer.charAt(@bufferIndex) == ch
@token = token
@token.tokenString = ch
@token.matched = ch
@advanceCharsInBuffer(1)
###
Match and return the next token in the input buffer
###
getNextToken: () ->
throw haml.HamlRuntime.templateError(@lineNumber, @characterNumber, @currentLine,
"An internal parser error has occurred in the HAML parser") if isNaN(@bufferIndex)
@prevToken = @token
@token = null
if @buffer == null or @buffer.length == @bufferIndex
@token = { eof: true, token: 'EOF' }
else
@initLine()
if !@token
ch = @buffer.charCodeAt(@bufferIndex)
ch1 = @buffer.charCodeAt(@bufferIndex + 1)
if ch == 10 or (ch == 13 and ch1 == 10)
@token = { eol: true, token: 'EOL' }
if ch == 13 and ch1 == 10
@advanceCharsInBuffer(2)
@token.matched = String.fromCharCode(ch) + String.fromCharCode(ch1)
else
@advanceCharsInBuffer(1)
@token.matched = String.fromCharCode(ch)
@characterNumber = 0
@currentLine = @getCurrentLine()
@matchMultiCharToken(@tokenMatchers.whitespace, { ws: true, token: 'WS' })
@matchMultiCharToken(@tokenMatchers.continueLine, { continueLine: true, token: 'CONTINUELINE' })
@matchMultiCharToken(@tokenMatchers.element, { element: true, token: 'ELEMENT' }, (matched) -> matched.substring(1) )
@matchMultiCharToken(@tokenMatchers.idSelector, { idSelector: true, token: 'ID' }, (matched) -> matched.substring(1) )
@matchMultiCharToken(@tokenMatchers.classSelector, { classSelector: true, token: 'CLASS' }, (matched) -> matched.substring(1) )
@matchMultiCharToken(@tokenMatchers.identifier, { identifier: true, token: 'IDENTIFIER' })
@matchMultiCharToken(@tokenMatchers.doctype, { doctype: true, token: 'DOCTYPE' })
@matchMultiCharToken(@tokenMatchers.filter, { filter: true, token: 'FILTER' }, (matched) -> matched.substring(1) )
if !@token
str = @matchToken(@tokenMatchers.quotedString)
str = @matchToken(@tokenMatchers.quotedString2) if not str
if str
@token = { string: true, token: 'STRING', tokenString: str.substring(1, str.length - 1), matched: str }
@advanceCharsInBuffer(str.length)
@matchMultiCharToken(@tokenMatchers.comment, { comment: true, token: 'COMMENT' })
@matchMultiCharToken(@tokenMatchers.escapeHtml, { escapeHtml: true, token: 'ESCAPEHTML' })
@matchMultiCharToken(@tokenMatchers.unescapeHtml, { unescapeHtml: true, token: 'UNESCAPEHTML' })
@matchMultiCharToken(@tokenMatchers.objectReference, { objectReference: true, token: 'OBJECTREFERENCE' }, (matched) ->
matched.substring(1, matched.length - 1)
)
if !@token and @buffer and @buffer.charAt(@bufferIndex) == '{' and !@prevToken.ws
@matchJavascriptHash()
@matchSingleCharToken('(', { openBracket: true, token: 'OPENBRACKET' })
@matchSingleCharToken(')', { closeBracket: true, token: 'CLOSEBRACKET' })
@matchSingleCharToken('=', { equal: true, token: 'EQUAL' })
@matchSingleCharToken('/', { slash: true, token: 'SLASH' })
@matchSingleCharToken('!', { exclamation: true, token: 'EXCLAMATION' })
@matchSingleCharToken('-', { minus: true, token: 'MINUS' })
@matchSingleCharToken('&', { amp: true, token: 'AMP' })
@matchSingleCharToken('<', { lt: true, token: 'LT' })
@matchSingleCharToken('>', { gt: true, token: 'GT' })
@matchSingleCharToken('~', { tilde: true, token: 'TILDE' })
if @token == null
@token =
unknown: true
token: 'UNKNOWN'
matched: @buffer.charAt(@bufferIndex)
@advanceCharsInBuffer(1)
@token
###
Look ahead a number of tokens and return the token found
###
lookAhead: (numberOfTokens) ->
token = null
if numberOfTokens > 0
currentToken = @token
prevToken = @prevToken
currentLine = @currentLine
lineNumber = @lineNumber
characterNumber = @characterNumber
bufferIndex = @bufferIndex
i = 0
token = this.getNextToken() while i++ < numberOfTokens
@token = currentToken
@prevToken = prevToken
@currentLine = currentLine
@lineNumber = lineNumber
@characterNumber = characterNumber
@bufferIndex = bufferIndex
token
###
Initilise the line and character counters
###
initLine: () ->
if !@currentLine and @currentLine isnt ""
@currentLine = @getCurrentLine()
@lineNumber = 1
@characterNumber = 0
###
Returns the current line in the input buffer
###
getCurrentLine: (index) ->
@currentLineMatcher.lastIndex = @bufferIndex + (index ? 0)
line = @currentLineMatcher.exec(@buffer)
if line then line[0] else ''
###
Returns an error string filled out with the line and character counters
###
parseError: (error) ->
haml.HamlRuntime.templateError(@lineNumber, @characterNumber, @currentLine, error)
###
Skips to the end of the line and returns the string that was skipped
###
skipToEOLorEOF: ->
text = ''
unless @token.eof or @token.eol
text += @token.matched if @token.matched?
@currentLineMatcher.lastIndex = @bufferIndex
line = @currentLineMatcher.exec(@buffer)
if line and line.index == @bufferIndex
contents = (_.str || _).rtrim(line[0])
if (_.str || _).endsWith(contents, '|')
text += contents.substring(0, contents.length - 1)
@advanceCharsInBuffer(contents.length - 1)
@getNextToken()
text += @parseMultiLine()
else
text += line[0]
@advanceCharsInBuffer(line[0].length)
@getNextToken()
text
###
Parses a multiline code block and returns the parsed text
###
parseMultiLine: ->
text = ''
while @token.continueLine
@currentLineMatcher.lastIndex = @bufferIndex
line = @currentLineMatcher.exec(@buffer)
if line and line.index == @bufferIndex
contents = (_.str || _).rtrim(line[0])
if (_.str || _).endsWith(contents, '|')
text += contents.substring(0, contents.length - 1)
@advanceCharsInBuffer(contents.length - 1)
@getNextToken()
text
###
Advances the input buffer pointer by a number of characters, updating the line and character counters
###
advanceCharsInBuffer: (numChars) ->
i = 0
while i < numChars
ch = @buffer.charCodeAt(@bufferIndex + i)
ch1 = @buffer.charCodeAt(@bufferIndex + i + 1)
if ch == 13 and ch1 == 10
@lineNumber++
@characterNumber = 0
@currentLine = @getCurrentLine(i)
i++
else if ch == 10
@lineNumber++
@characterNumber = 0
@currentLine = @getCurrentLine(i)
else
@characterNumber++
i++
@bufferIndex += numChars
###
Returns the current line and character counters
###
currentParsePoint: ->
{
lineNumber: @lineNumber,
characterNumber: @characterNumber,
currentLine: @currentLine
}
###
Pushes back the current token onto the front of the input buffer
###
pushBackToken: ->
if !@token.eof
@bufferIndex -= @token.matched.length
@token = @prevToken
###
Is the current token an end of line or end of input buffer
###
isEolOrEof: ->
@token.eol or @token.eof
###
Match a Javascript Hash {...}
###
matchJavascriptHash: ->
currentIndent = @calculateCurrentIndent()
i = @bufferIndex + 1
characterNumberStart = @characterNumber
lineNumberStart = @lineNumber
braceCount = 1
while i < @buffer.length and (braceCount > 1 or @buffer.charAt(i) isnt '}')
ch = @buffer.charAt(i)
chCode = @buffer.charCodeAt(i)
if ch == '{'
braceCount++
i++
else if ch == '}'
braceCount--
i++
else if chCode == 10 or chCode == 13
i++
else
i++
if i == @buffer.length
@characterNumber = characterNumberStart + 1
@lineNumber = lineNumberStart
throw @parseError('Error parsing attribute hash - Did not find a terminating "}"')
else
@token =
attributeHash: true
token: 'ATTRPI:PASSWORD:<PASSWORD>END_PI'
tokenString: @buffer.substring(@bufferIndex, i + 1)
matched: @buffer.substring(@bufferIndex, i + 1)
@advanceCharsInBuffer(i - @bufferIndex + 1)
###
Calculate the indent value of the current line
###
calculateCurrentIndent: ->
@tokenMatchers.whitespace.lastIndex = 0
result = @tokenMatchers.whitespace.exec(@currentLine)
if result?.index == 0
@calculateIndent(result[0])
else
0
###
Calculate the indent level of the provided whitespace
###
calculateIndent: (whitespace) ->
indent = 0
i = 0
while i < whitespace.length
if whitespace.charCodeAt(i) == 9
indent += 2
else
indent++
i++
Math.floor((indent + 1) / 2) |
[
{
"context": "type conversions with shorter notations.\n# @author Toru Nagashima\n###\n\n'use strict'\n\nastUtils = require '../eslint-",
"end": 109,
"score": 0.9998782277107239,
"start": 95,
"tag": "NAME",
"value": "Toru Nagashima"
}
] | src/rules/no-implicit-coercion.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview A rule to disallow the type conversions with shorter notations.
# @author Toru Nagashima
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/
ALLOWABLE_OPERATORS = ['~', '!!', '+', '*']
###*
# Parses and normalizes an option object.
# @param {Object} options - An option object to parse.
# @returns {Object} The parsed and normalized option object.
###
parseOptions = (options) ->
boolean: if 'boolean' of options then Boolean options.boolean else yes
number: if 'number' of options then Boolean options.number else yes
string: if 'string' of options then Boolean options.string else yes
allow: options.allow or []
###*
# Checks whether or not a node is a double logical nigating.
# @param {ASTNode} node - An UnaryExpression node to check.
# @returns {boolean} Whether or not the node is a double logical nigating.
###
isDoubleLogicalNegating = (node) ->
node.operator is '!' and
node.argument.type is 'UnaryExpression' and
node.argument.operator is '!'
###*
# Checks whether or not a node is a binary negating of `.indexOf()` method calling.
# @param {ASTNode} node - An UnaryExpression node to check.
# @returns {boolean} Whether or not the node is a binary negating of `.indexOf()` method calling.
###
isBinaryNegatingOfIndexOf = (node) ->
node.operator is '~' and
node.argument.type is 'CallExpression' and
node.argument.callee.type is 'MemberExpression' and
node.argument.callee.property.type is 'Identifier' and
INDEX_OF_PATTERN.test node.argument.callee.property.name
###*
# Checks whether or not a node is a multiplying by one.
# @param {BinaryExpression} node - A BinaryExpression node to check.
# @returns {boolean} Whether or not the node is a multiplying by one.
###
isMultiplyByOne = (node) ->
node.operator is '*' and
((node.left.type is 'Literal' and node.left.value is 1) or
(node.right.type is 'Literal' and node.right.value is 1))
###*
# Checks whether the result of a node is numeric or not
# @param {ASTNode} node The node to test
# @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call
###
isNumeric = (node) ->
(node.type is 'Literal' and typeof node.value is 'number') or
(node.type is 'CallExpression' and
node.callee.name in ['Number', 'parseInt', 'parseFloat'])
###*
# Returns the first non-numeric operand in a BinaryExpression. Designed to be
# used from bottom to up since it walks up the BinaryExpression trees using
# node.parent to find the result.
# @param {BinaryExpression} node The BinaryExpression node to be walked up on
# @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null
###
getNonNumericOperand = (node) ->
{left} = node
{right} = node
return right if right.type isnt 'BinaryExpression' and not isNumeric right
return left if left.type isnt 'BinaryExpression' and not isNumeric left
null
###*
# Checks whether a node is an empty string literal or not.
# @param {ASTNode} node The node to check.
# @returns {boolean} Whether or not the passed in node is an
# empty string literal or not.
###
isEmptyString = (node) ->
astUtils.isStringLiteral(node) and
(node.value is '' or
(node.type is 'TemplateLiteral' and
node.quasis.length is 1 and
node.quasis[0].value.cooked is ''))
###*
# Checks whether or not a node is a concatenating with an empty string.
# @param {ASTNode} node - A BinaryExpression node to check.
# @returns {boolean} Whether or not the node is a concatenating with an empty string.
###
isConcatWithEmptyString = (node) ->
node.operator is '+' and
((isEmptyString(node.left) and not astUtils.isStringLiteral(node.right)) or
(isEmptyString(node.right) and not astUtils.isStringLiteral node.left))
###*
# Checks whether or not a node is appended with an empty string.
# @param {ASTNode} node - An AssignmentExpression node to check.
# @returns {boolean} Whether or not the node is appended with an empty string.
###
isAppendEmptyString = (node) ->
node.operator is '+=' and isEmptyString node.right
###*
# Returns the operand that is not an empty string from a flagged BinaryExpression.
# @param {ASTNode} node - The flagged BinaryExpression node to check.
# @returns {ASTNode} The operand that is not an empty string from a flagged BinaryExpression.
###
getNonEmptyOperand = (node) ->
if isEmptyString node.left then node.right else node.left
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow shorthand type conversions'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/no-implicit-coercion'
fixable: 'code'
schema: [
type: 'object'
properties:
boolean: type: 'boolean'
number: type: 'boolean'
string: type: 'boolean'
allow:
type: 'array'
items: enum: ALLOWABLE_OPERATORS
uniqueItems: yes
additionalProperties: no
]
create: (context) ->
options = parseOptions context.options[0] or {}
sourceCode = context.getSourceCode()
###*
# Reports an error and autofixes the node
# @param {ASTNode} node - An ast node to report the error on.
# @param {string} recommendation - The recommended code for the issue
# @param {bool} shouldFix - Whether this report should fix the node
# @returns {void}
###
report = (node, recommendation, shouldFix) ->
context.report {
node
message: 'use `{{recommendation}}` instead.'
data: {recommendation}
fix: (fixer) ->
return null unless shouldFix
tokenBefore = sourceCode.getTokenBefore node
return fixer.replaceText node, " #{recommendation}" if (
tokenBefore and
tokenBefore.range[1] is node.range[0] and
not astUtils.canTokensBeAdjacent tokenBefore, recommendation
)
fixer.replaceText node, recommendation
}
UnaryExpression: (node) ->
# !!foo
operatorAllowed = options.allow.indexOf('!!') >= 0
if (
not operatorAllowed and
options.boolean and
isDoubleLogicalNegating node
)
recommendation = "Boolean(#{sourceCode.getText node.argument.argument})"
report node, recommendation, yes
# ~foo.indexOf(bar)
operatorAllowed = options.allow.indexOf('~') >= 0
if (
not operatorAllowed and
options.boolean and
isBinaryNegatingOfIndexOf node
)
recommendation = "#{sourceCode.getText node.argument} isnt -1"
report node, recommendation, no
# +foo
operatorAllowed = options.allow.indexOf('+') >= 0
if (
not operatorAllowed and
options.number and
node.operator is '+' and
not isNumeric node.argument
)
recommendation = "Number(#{sourceCode.getText node.argument})"
report node, recommendation, yes
# Use `:exit` to prevent double reporting
'BinaryExpression:exit': (node) ->
# 1 * foo
operatorAllowed = options.allow.indexOf('*') >= 0
nonNumericOperand =
not operatorAllowed and
options.number and
isMultiplyByOne(node) and
getNonNumericOperand node
if nonNumericOperand
recommendation = "Number(#{sourceCode.getText nonNumericOperand})"
report node, recommendation, yes
# "" + foo
operatorAllowed = options.allow.indexOf('+') >= 0
if not operatorAllowed and options.string and isConcatWithEmptyString node
recommendation = "String(#{sourceCode.getText getNonEmptyOperand node})"
report node, recommendation, yes
AssignmentExpression: (node) ->
# foo += ""
operatorAllowed = options.allow.indexOf('+') >= 0
if not operatorAllowed and options.string and isAppendEmptyString node
code = sourceCode.getText getNonEmptyOperand node
recommendation = "#{code} = String(#{code})"
report node, recommendation, yes
| 53698 | ###*
# @fileoverview A rule to disallow the type conversions with shorter notations.
# @author <NAME>
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/
ALLOWABLE_OPERATORS = ['~', '!!', '+', '*']
###*
# Parses and normalizes an option object.
# @param {Object} options - An option object to parse.
# @returns {Object} The parsed and normalized option object.
###
parseOptions = (options) ->
boolean: if 'boolean' of options then Boolean options.boolean else yes
number: if 'number' of options then Boolean options.number else yes
string: if 'string' of options then Boolean options.string else yes
allow: options.allow or []
###*
# Checks whether or not a node is a double logical nigating.
# @param {ASTNode} node - An UnaryExpression node to check.
# @returns {boolean} Whether or not the node is a double logical nigating.
###
isDoubleLogicalNegating = (node) ->
node.operator is '!' and
node.argument.type is 'UnaryExpression' and
node.argument.operator is '!'
###*
# Checks whether or not a node is a binary negating of `.indexOf()` method calling.
# @param {ASTNode} node - An UnaryExpression node to check.
# @returns {boolean} Whether or not the node is a binary negating of `.indexOf()` method calling.
###
isBinaryNegatingOfIndexOf = (node) ->
node.operator is '~' and
node.argument.type is 'CallExpression' and
node.argument.callee.type is 'MemberExpression' and
node.argument.callee.property.type is 'Identifier' and
INDEX_OF_PATTERN.test node.argument.callee.property.name
###*
# Checks whether or not a node is a multiplying by one.
# @param {BinaryExpression} node - A BinaryExpression node to check.
# @returns {boolean} Whether or not the node is a multiplying by one.
###
isMultiplyByOne = (node) ->
node.operator is '*' and
((node.left.type is 'Literal' and node.left.value is 1) or
(node.right.type is 'Literal' and node.right.value is 1))
###*
# Checks whether the result of a node is numeric or not
# @param {ASTNode} node The node to test
# @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call
###
isNumeric = (node) ->
(node.type is 'Literal' and typeof node.value is 'number') or
(node.type is 'CallExpression' and
node.callee.name in ['Number', 'parseInt', 'parseFloat'])
###*
# Returns the first non-numeric operand in a BinaryExpression. Designed to be
# used from bottom to up since it walks up the BinaryExpression trees using
# node.parent to find the result.
# @param {BinaryExpression} node The BinaryExpression node to be walked up on
# @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null
###
getNonNumericOperand = (node) ->
{left} = node
{right} = node
return right if right.type isnt 'BinaryExpression' and not isNumeric right
return left if left.type isnt 'BinaryExpression' and not isNumeric left
null
###*
# Checks whether a node is an empty string literal or not.
# @param {ASTNode} node The node to check.
# @returns {boolean} Whether or not the passed in node is an
# empty string literal or not.
###
isEmptyString = (node) ->
astUtils.isStringLiteral(node) and
(node.value is '' or
(node.type is 'TemplateLiteral' and
node.quasis.length is 1 and
node.quasis[0].value.cooked is ''))
###*
# Checks whether or not a node is a concatenating with an empty string.
# @param {ASTNode} node - A BinaryExpression node to check.
# @returns {boolean} Whether or not the node is a concatenating with an empty string.
###
isConcatWithEmptyString = (node) ->
node.operator is '+' and
((isEmptyString(node.left) and not astUtils.isStringLiteral(node.right)) or
(isEmptyString(node.right) and not astUtils.isStringLiteral node.left))
###*
# Checks whether or not a node is appended with an empty string.
# @param {ASTNode} node - An AssignmentExpression node to check.
# @returns {boolean} Whether or not the node is appended with an empty string.
###
isAppendEmptyString = (node) ->
node.operator is '+=' and isEmptyString node.right
###*
# Returns the operand that is not an empty string from a flagged BinaryExpression.
# @param {ASTNode} node - The flagged BinaryExpression node to check.
# @returns {ASTNode} The operand that is not an empty string from a flagged BinaryExpression.
###
getNonEmptyOperand = (node) ->
if isEmptyString node.left then node.right else node.left
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow shorthand type conversions'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/no-implicit-coercion'
fixable: 'code'
schema: [
type: 'object'
properties:
boolean: type: 'boolean'
number: type: 'boolean'
string: type: 'boolean'
allow:
type: 'array'
items: enum: ALLOWABLE_OPERATORS
uniqueItems: yes
additionalProperties: no
]
create: (context) ->
options = parseOptions context.options[0] or {}
sourceCode = context.getSourceCode()
###*
# Reports an error and autofixes the node
# @param {ASTNode} node - An ast node to report the error on.
# @param {string} recommendation - The recommended code for the issue
# @param {bool} shouldFix - Whether this report should fix the node
# @returns {void}
###
report = (node, recommendation, shouldFix) ->
context.report {
node
message: 'use `{{recommendation}}` instead.'
data: {recommendation}
fix: (fixer) ->
return null unless shouldFix
tokenBefore = sourceCode.getTokenBefore node
return fixer.replaceText node, " #{recommendation}" if (
tokenBefore and
tokenBefore.range[1] is node.range[0] and
not astUtils.canTokensBeAdjacent tokenBefore, recommendation
)
fixer.replaceText node, recommendation
}
UnaryExpression: (node) ->
# !!foo
operatorAllowed = options.allow.indexOf('!!') >= 0
if (
not operatorAllowed and
options.boolean and
isDoubleLogicalNegating node
)
recommendation = "Boolean(#{sourceCode.getText node.argument.argument})"
report node, recommendation, yes
# ~foo.indexOf(bar)
operatorAllowed = options.allow.indexOf('~') >= 0
if (
not operatorAllowed and
options.boolean and
isBinaryNegatingOfIndexOf node
)
recommendation = "#{sourceCode.getText node.argument} isnt -1"
report node, recommendation, no
# +foo
operatorAllowed = options.allow.indexOf('+') >= 0
if (
not operatorAllowed and
options.number and
node.operator is '+' and
not isNumeric node.argument
)
recommendation = "Number(#{sourceCode.getText node.argument})"
report node, recommendation, yes
# Use `:exit` to prevent double reporting
'BinaryExpression:exit': (node) ->
# 1 * foo
operatorAllowed = options.allow.indexOf('*') >= 0
nonNumericOperand =
not operatorAllowed and
options.number and
isMultiplyByOne(node) and
getNonNumericOperand node
if nonNumericOperand
recommendation = "Number(#{sourceCode.getText nonNumericOperand})"
report node, recommendation, yes
# "" + foo
operatorAllowed = options.allow.indexOf('+') >= 0
if not operatorAllowed and options.string and isConcatWithEmptyString node
recommendation = "String(#{sourceCode.getText getNonEmptyOperand node})"
report node, recommendation, yes
AssignmentExpression: (node) ->
# foo += ""
operatorAllowed = options.allow.indexOf('+') >= 0
if not operatorAllowed and options.string and isAppendEmptyString node
code = sourceCode.getText getNonEmptyOperand node
recommendation = "#{code} = String(#{code})"
report node, recommendation, yes
| true | ###*
# @fileoverview A rule to disallow the type conversions with shorter notations.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
INDEX_OF_PATTERN = /^(?:i|lastI)ndexOf$/
ALLOWABLE_OPERATORS = ['~', '!!', '+', '*']
###*
# Parses and normalizes an option object.
# @param {Object} options - An option object to parse.
# @returns {Object} The parsed and normalized option object.
###
parseOptions = (options) ->
boolean: if 'boolean' of options then Boolean options.boolean else yes
number: if 'number' of options then Boolean options.number else yes
string: if 'string' of options then Boolean options.string else yes
allow: options.allow or []
###*
# Checks whether or not a node is a double logical nigating.
# @param {ASTNode} node - An UnaryExpression node to check.
# @returns {boolean} Whether or not the node is a double logical nigating.
###
isDoubleLogicalNegating = (node) ->
node.operator is '!' and
node.argument.type is 'UnaryExpression' and
node.argument.operator is '!'
###*
# Checks whether or not a node is a binary negating of `.indexOf()` method calling.
# @param {ASTNode} node - An UnaryExpression node to check.
# @returns {boolean} Whether or not the node is a binary negating of `.indexOf()` method calling.
###
isBinaryNegatingOfIndexOf = (node) ->
node.operator is '~' and
node.argument.type is 'CallExpression' and
node.argument.callee.type is 'MemberExpression' and
node.argument.callee.property.type is 'Identifier' and
INDEX_OF_PATTERN.test node.argument.callee.property.name
###*
# Checks whether or not a node is a multiplying by one.
# @param {BinaryExpression} node - A BinaryExpression node to check.
# @returns {boolean} Whether or not the node is a multiplying by one.
###
isMultiplyByOne = (node) ->
node.operator is '*' and
((node.left.type is 'Literal' and node.left.value is 1) or
(node.right.type is 'Literal' and node.right.value is 1))
###*
# Checks whether the result of a node is numeric or not
# @param {ASTNode} node The node to test
# @returns {boolean} true if the node is a number literal or a `Number()`, `parseInt` or `parseFloat` call
###
isNumeric = (node) ->
(node.type is 'Literal' and typeof node.value is 'number') or
(node.type is 'CallExpression' and
node.callee.name in ['Number', 'parseInt', 'parseFloat'])
###*
# Returns the first non-numeric operand in a BinaryExpression. Designed to be
# used from bottom to up since it walks up the BinaryExpression trees using
# node.parent to find the result.
# @param {BinaryExpression} node The BinaryExpression node to be walked up on
# @returns {ASTNode|null} The first non-numeric item in the BinaryExpression tree or null
###
getNonNumericOperand = (node) ->
{left} = node
{right} = node
return right if right.type isnt 'BinaryExpression' and not isNumeric right
return left if left.type isnt 'BinaryExpression' and not isNumeric left
null
###*
# Checks whether a node is an empty string literal or not.
# @param {ASTNode} node The node to check.
# @returns {boolean} Whether or not the passed in node is an
# empty string literal or not.
###
isEmptyString = (node) ->
astUtils.isStringLiteral(node) and
(node.value is '' or
(node.type is 'TemplateLiteral' and
node.quasis.length is 1 and
node.quasis[0].value.cooked is ''))
###*
# Checks whether or not a node is a concatenating with an empty string.
# @param {ASTNode} node - A BinaryExpression node to check.
# @returns {boolean} Whether or not the node is a concatenating with an empty string.
###
isConcatWithEmptyString = (node) ->
node.operator is '+' and
((isEmptyString(node.left) and not astUtils.isStringLiteral(node.right)) or
(isEmptyString(node.right) and not astUtils.isStringLiteral node.left))
###*
# Checks whether or not a node is appended with an empty string.
# @param {ASTNode} node - An AssignmentExpression node to check.
# @returns {boolean} Whether or not the node is appended with an empty string.
###
isAppendEmptyString = (node) ->
node.operator is '+=' and isEmptyString node.right
###*
# Returns the operand that is not an empty string from a flagged BinaryExpression.
# @param {ASTNode} node - The flagged BinaryExpression node to check.
# @returns {ASTNode} The operand that is not an empty string from a flagged BinaryExpression.
###
getNonEmptyOperand = (node) ->
if isEmptyString node.left then node.right else node.left
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow shorthand type conversions'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/no-implicit-coercion'
fixable: 'code'
schema: [
type: 'object'
properties:
boolean: type: 'boolean'
number: type: 'boolean'
string: type: 'boolean'
allow:
type: 'array'
items: enum: ALLOWABLE_OPERATORS
uniqueItems: yes
additionalProperties: no
]
create: (context) ->
options = parseOptions context.options[0] or {}
sourceCode = context.getSourceCode()
###*
# Reports an error and autofixes the node
# @param {ASTNode} node - An ast node to report the error on.
# @param {string} recommendation - The recommended code for the issue
# @param {bool} shouldFix - Whether this report should fix the node
# @returns {void}
###
report = (node, recommendation, shouldFix) ->
context.report {
node
message: 'use `{{recommendation}}` instead.'
data: {recommendation}
fix: (fixer) ->
return null unless shouldFix
tokenBefore = sourceCode.getTokenBefore node
return fixer.replaceText node, " #{recommendation}" if (
tokenBefore and
tokenBefore.range[1] is node.range[0] and
not astUtils.canTokensBeAdjacent tokenBefore, recommendation
)
fixer.replaceText node, recommendation
}
UnaryExpression: (node) ->
# !!foo
operatorAllowed = options.allow.indexOf('!!') >= 0
if (
not operatorAllowed and
options.boolean and
isDoubleLogicalNegating node
)
recommendation = "Boolean(#{sourceCode.getText node.argument.argument})"
report node, recommendation, yes
# ~foo.indexOf(bar)
operatorAllowed = options.allow.indexOf('~') >= 0
if (
not operatorAllowed and
options.boolean and
isBinaryNegatingOfIndexOf node
)
recommendation = "#{sourceCode.getText node.argument} isnt -1"
report node, recommendation, no
# +foo
operatorAllowed = options.allow.indexOf('+') >= 0
if (
not operatorAllowed and
options.number and
node.operator is '+' and
not isNumeric node.argument
)
recommendation = "Number(#{sourceCode.getText node.argument})"
report node, recommendation, yes
# Use `:exit` to prevent double reporting
'BinaryExpression:exit': (node) ->
# 1 * foo
operatorAllowed = options.allow.indexOf('*') >= 0
nonNumericOperand =
not operatorAllowed and
options.number and
isMultiplyByOne(node) and
getNonNumericOperand node
if nonNumericOperand
recommendation = "Number(#{sourceCode.getText nonNumericOperand})"
report node, recommendation, yes
# "" + foo
operatorAllowed = options.allow.indexOf('+') >= 0
if not operatorAllowed and options.string and isConcatWithEmptyString node
recommendation = "String(#{sourceCode.getText getNonEmptyOperand node})"
report node, recommendation, yes
AssignmentExpression: (node) ->
# foo += ""
operatorAllowed = options.allow.indexOf('+') >= 0
if not operatorAllowed and options.string and isAppendEmptyString node
code = sourceCode.getText getNonEmptyOperand node
recommendation = "#{code} = String(#{code})"
report node, recommendation, yes
|
[
{
"context": " document.documentElement.style[key]?\n\n key = key[0].toUpperCase() + key.slice 1\n prefixes = ['webkit', 'moz', 'ms', ",
"end": 6749,
"score": 0.9457796216011047,
"start": 6731,
"tag": "KEY",
"value": "0].toUpperCase() +"
},
{
"context": "t.style[key]?\n\n key = ke... | src/util/vdom.coffee | thebigbrain/mathbox | 862 | # Quick'n'dirty Virtual DOM diffing
# with a poor man's React for components
#
# This is for rendering HTML with data from a GL readback. See DOM examples.
HEAP = []
id = 0
# Static render components
Types = {
###
# el('example', props, children);
example: MathBox.DOM.createClass({
render: (el, props, children) ->
# VDOM node
return el('span', { className: "foo" }, "Hello World")
})
###
}
descriptor = () ->
id: id++
type: null
props: null
children: null
rendered: null
instance: null
hint = (n) ->
n *= 2
n = Math.max 0, HEAP.length - n
HEAP.push descriptor() for i in [0...n]
element = (type, props, children) ->
el = if HEAP.length then HEAP.pop() else descriptor()
el.type = type ? 'div'
el.props = props ? null
el.children = children ? null
# Can't use `arguments` here to pass children as direct args, it de-optimizes label emitters
el
recycle = (el) ->
return unless el.type
children = el.children
el.type = el.props = el.children = el.instance = null
HEAP.push el
recycle child for child in children if children?
return
apply = (el, last, node, parent, index) ->
if el?
if !last?
# New node
return mount el, parent, index
else
# Literal DOM node
if el instanceof Node
same = el == last
return if same
else
# Check compatibility
same = typeof el == typeof last and
last != null and el != null and
el.type == last.type
if !same
# Not compatible: unmount and remount
unmount last.instance, node
node.remove()
return mount el, parent, index
else
# Maintain component ref
el.instance = last.instance
# Check if it's a component
type = if el.type?.isComponentClass then el.type else Types[el.type]
# Prepare to diff props and children
props = last?.props
nextProps = el .props
children = last?.children ? null
nextChildren = el .children
nextProps.children = nextChildren if nextProps?
# Component
if type?
# See if it changed
dirty = node._COMPONENT_DIRTY
dirty = true if props? != nextProps?
dirty = true if children != nextChildren
if props? and nextProps?
dirty = true for key of props when !nextProps.hasOwnProperty key if !dirty
dirty = true for key, value of nextProps when (ref = props[key]) != value if !dirty
if dirty
comp = last.instance
el.props ?= {}
el.props[k] ?= v for k, v of comp.defaultProps
el.props.children = el.children
comp.willReceiveProps? el.props
should = node._COMPONENT_FORCE || (comp.shouldUpdate?(el.props) ? true)
if should
nextState = comp.getNextState()
comp.willUpdate? el.props, nextState
prevProps = comp.props
prevState = comp.applyNextState()
comp.props = el.props
comp.children = el.children
if should
el = el.rendered = comp.render? element, el.props, el.children
apply el, last.rendered, node, parent, index
comp.didUpdate? prevProps, prevState
return
else
# VDOM node
unset node, key, props[key] for key of props when !nextProps.hasOwnProperty key if props?
set node, key, value, ref for key, value of nextProps when (ref = props[key]) != value and key != 'children' if nextProps?
# Diff children
if nextChildren?
if typeof nextChildren in ['string', 'number']
# Insert text directly
if nextChildren != children
node.textContent = nextChildren
else
if nextChildren.type?
# Single child
apply nextChildren, children, node.childNodes[0], node, 0
else
# Diff children
childNodes = node.childNodes
if children?
apply child, children[i], childNodes[i], node, i for child, i in nextChildren
else
apply child, null, childNodes[i], node, i for child, i in nextChildren
else if children?
# Unmount all child components
unmount null, node
# Remove all children
node.innerHTML = ''
return
if last?
# Removed node
unmount last.instance, node
last.node.remove()
mount = (el, parent, index = 0) ->
type = if el.type?.isComponentClass then el.type else Types[el.type]
# Literal DOM node
if el instanceof Node
node = el
else
if type?
# Component
ctor = if el.type?.isComponentClass then el.type else Types[el.type]
# No component class found
if !ctor
el = el.rendered = element 'noscript'
node = mount el, parent, index
return node
# Construct component class
el.instance = comp = new ctor parent
el.props ?= {}
el.props[k] ?= v for k, v of comp.defaultProps
el.props.children = el.children
# Do initial state transition
comp.props = el.props
comp.children = el.children
comp.setState comp.getInitialState?()
comp.willMount?()
# Render
el = el.rendered = comp.render? element, el.props, el.children
node = mount el, parent, index
# Finish mounting and remember component/node association
comp.didMount? el
node._COMPONENT = comp
return node
else if typeof el in ['string', 'number']
# Text
node = document.createTextNode el
else
# VDOM Node
node = document.createElement el.type
set node, key, value for key, value of el.props
children = el.children
if children?
if typeof children in ['string', 'number']
# Insert text directly
node.textContent = children
else
if children.type?
# Single child
mount children, node, 0
else
# Insert children
mount child, node, i for child, i in children
parent.insertBefore node, parent.childNodes[index]
return node
unmount = (comp, node) ->
if comp
comp.willUnmount?()
delete comp[k] for k of comp
for child in node.childNodes
unmount child._COMPONENT, child
delete child._COMPONENT
prop = (key) ->
return true if typeof document == 'undefined'
return key if document.documentElement.style[key]?
key = key[0].toUpperCase() + key.slice 1
prefixes = ['webkit', 'moz', 'ms', 'o']
return prefix + key for prefix in prefixes when document.documentElement.style[prefix + key]?
map = {}
map[key] = prop key for key in ['transform']
set = (node, key, value, orig) ->
if key == 'style'
for k, v of value when orig?[k] != v
node.style[map[k] ? k] = v
return
if node[key]?
node[key] = value
return
if node instanceof Node
node.setAttribute key, value
return
unset = (node, key, orig) ->
if key == 'style'
for k, v of orig
node.style[map[k] ? k] = ''
return
if node[key]?
node[key] = undefined
if node instanceof Node
node.removeAttribute key
return
createClass = (prototype) ->
aliases = {
willMount: 'componentWillMount'
didMount: 'componentDidMount'
willReceiveProps: 'componentWillReceiveProps'
shouldUpdate: 'shouldComponentUpdate'
willUpdate: 'componentWillUpdate'
didUpdate: 'componentDidUpdate'
willUnmount: 'componentWillUnmount'
}
prototype[a] ?= prototype[b] for a, b of aliases
class Component
constructor: (node, @props = {}, @state = null, @children = null) ->
bind = (f, self) -> if typeof f == 'function' then f.bind self else f
@[k] = bind v, @ for k, v of prototype
nextState = null
@setState = (state) ->
nextState ?= if state then nextState ? {} else null
nextState[k] = v for k, v of state
node._COMPONENT_DIRTY = true
return
@forceUpdate = () ->
node._COMPONENT_FORCE = node._COMPONENT_DIRTY = true
el = node
while el = el.parentNode
if el._COMPONENT
el._COMPONENT_FORCE = true
@getNextState = () -> nextState
@applyNextState = () ->
node._COMPONENT_FORCE = node._COMPONENT_DIRTY = false
prevState = @state
[nextState, @state] = [null, nextState]
prevState
return
Component.isComponentClass = true
Component.prototype.defaultProps = prototype.getDefaultProps?() ? {}
Component
module.exports = {element, recycle, apply, hint, Types, createClass} | 89508 | # Quick'n'dirty Virtual DOM diffing
# with a poor man's React for components
#
# This is for rendering HTML with data from a GL readback. See DOM examples.
HEAP = []
id = 0
# Static render components
Types = {
###
# el('example', props, children);
example: MathBox.DOM.createClass({
render: (el, props, children) ->
# VDOM node
return el('span', { className: "foo" }, "Hello World")
})
###
}
descriptor = () ->
id: id++
type: null
props: null
children: null
rendered: null
instance: null
hint = (n) ->
n *= 2
n = Math.max 0, HEAP.length - n
HEAP.push descriptor() for i in [0...n]
element = (type, props, children) ->
el = if HEAP.length then HEAP.pop() else descriptor()
el.type = type ? 'div'
el.props = props ? null
el.children = children ? null
# Can't use `arguments` here to pass children as direct args, it de-optimizes label emitters
el
recycle = (el) ->
return unless el.type
children = el.children
el.type = el.props = el.children = el.instance = null
HEAP.push el
recycle child for child in children if children?
return
apply = (el, last, node, parent, index) ->
if el?
if !last?
# New node
return mount el, parent, index
else
# Literal DOM node
if el instanceof Node
same = el == last
return if same
else
# Check compatibility
same = typeof el == typeof last and
last != null and el != null and
el.type == last.type
if !same
# Not compatible: unmount and remount
unmount last.instance, node
node.remove()
return mount el, parent, index
else
# Maintain component ref
el.instance = last.instance
# Check if it's a component
type = if el.type?.isComponentClass then el.type else Types[el.type]
# Prepare to diff props and children
props = last?.props
nextProps = el .props
children = last?.children ? null
nextChildren = el .children
nextProps.children = nextChildren if nextProps?
# Component
if type?
# See if it changed
dirty = node._COMPONENT_DIRTY
dirty = true if props? != nextProps?
dirty = true if children != nextChildren
if props? and nextProps?
dirty = true for key of props when !nextProps.hasOwnProperty key if !dirty
dirty = true for key, value of nextProps when (ref = props[key]) != value if !dirty
if dirty
comp = last.instance
el.props ?= {}
el.props[k] ?= v for k, v of comp.defaultProps
el.props.children = el.children
comp.willReceiveProps? el.props
should = node._COMPONENT_FORCE || (comp.shouldUpdate?(el.props) ? true)
if should
nextState = comp.getNextState()
comp.willUpdate? el.props, nextState
prevProps = comp.props
prevState = comp.applyNextState()
comp.props = el.props
comp.children = el.children
if should
el = el.rendered = comp.render? element, el.props, el.children
apply el, last.rendered, node, parent, index
comp.didUpdate? prevProps, prevState
return
else
# VDOM node
unset node, key, props[key] for key of props when !nextProps.hasOwnProperty key if props?
set node, key, value, ref for key, value of nextProps when (ref = props[key]) != value and key != 'children' if nextProps?
# Diff children
if nextChildren?
if typeof nextChildren in ['string', 'number']
# Insert text directly
if nextChildren != children
node.textContent = nextChildren
else
if nextChildren.type?
# Single child
apply nextChildren, children, node.childNodes[0], node, 0
else
# Diff children
childNodes = node.childNodes
if children?
apply child, children[i], childNodes[i], node, i for child, i in nextChildren
else
apply child, null, childNodes[i], node, i for child, i in nextChildren
else if children?
# Unmount all child components
unmount null, node
# Remove all children
node.innerHTML = ''
return
if last?
# Removed node
unmount last.instance, node
last.node.remove()
mount = (el, parent, index = 0) ->
type = if el.type?.isComponentClass then el.type else Types[el.type]
# Literal DOM node
if el instanceof Node
node = el
else
if type?
# Component
ctor = if el.type?.isComponentClass then el.type else Types[el.type]
# No component class found
if !ctor
el = el.rendered = element 'noscript'
node = mount el, parent, index
return node
# Construct component class
el.instance = comp = new ctor parent
el.props ?= {}
el.props[k] ?= v for k, v of comp.defaultProps
el.props.children = el.children
# Do initial state transition
comp.props = el.props
comp.children = el.children
comp.setState comp.getInitialState?()
comp.willMount?()
# Render
el = el.rendered = comp.render? element, el.props, el.children
node = mount el, parent, index
# Finish mounting and remember component/node association
comp.didMount? el
node._COMPONENT = comp
return node
else if typeof el in ['string', 'number']
# Text
node = document.createTextNode el
else
# VDOM Node
node = document.createElement el.type
set node, key, value for key, value of el.props
children = el.children
if children?
if typeof children in ['string', 'number']
# Insert text directly
node.textContent = children
else
if children.type?
# Single child
mount children, node, 0
else
# Insert children
mount child, node, i for child, i in children
parent.insertBefore node, parent.childNodes[index]
return node
unmount = (comp, node) ->
if comp
comp.willUnmount?()
delete comp[k] for k of comp
for child in node.childNodes
unmount child._COMPONENT, child
delete child._COMPONENT
prop = (key) ->
return true if typeof document == 'undefined'
return key if document.documentElement.style[key]?
key = key[<KEY> key.<KEY> <KEY>
prefixes = ['webkit', 'moz', 'ms', 'o']
return prefix + key for prefix in prefixes when document.documentElement.style[prefix + key]?
map = {}
map[key] = prop key for key in ['transform']
set = (node, key, value, orig) ->
if key == 'style'
for k, v of value when orig?[k] != v
node.style[map[k] ? k] = v
return
if node[key]?
node[key] = value
return
if node instanceof Node
node.setAttribute key, value
return
unset = (node, key, orig) ->
if key == 'style'
for k, v of orig
node.style[map[k] ? k] = ''
return
if node[key]?
node[key] = undefined
if node instanceof Node
node.removeAttribute key
return
createClass = (prototype) ->
aliases = {
willMount: 'componentWillMount'
didMount: 'componentDidMount'
willReceiveProps: 'componentWillReceiveProps'
shouldUpdate: 'shouldComponentUpdate'
willUpdate: 'componentWillUpdate'
didUpdate: 'componentDidUpdate'
willUnmount: 'componentWillUnmount'
}
prototype[a] ?= prototype[b] for a, b of aliases
class Component
constructor: (node, @props = {}, @state = null, @children = null) ->
bind = (f, self) -> if typeof f == 'function' then f.bind self else f
@[k] = bind v, @ for k, v of prototype
nextState = null
@setState = (state) ->
nextState ?= if state then nextState ? {} else null
nextState[k] = v for k, v of state
node._COMPONENT_DIRTY = true
return
@forceUpdate = () ->
node._COMPONENT_FORCE = node._COMPONENT_DIRTY = true
el = node
while el = el.parentNode
if el._COMPONENT
el._COMPONENT_FORCE = true
@getNextState = () -> nextState
@applyNextState = () ->
node._COMPONENT_FORCE = node._COMPONENT_DIRTY = false
prevState = @state
[nextState, @state] = [null, nextState]
prevState
return
Component.isComponentClass = true
Component.prototype.defaultProps = prototype.getDefaultProps?() ? {}
Component
module.exports = {element, recycle, apply, hint, Types, createClass} | true | # Quick'n'dirty Virtual DOM diffing
# with a poor man's React for components
#
# This is for rendering HTML with data from a GL readback. See DOM examples.
HEAP = []
id = 0
# Static render components
Types = {
###
# el('example', props, children);
example: MathBox.DOM.createClass({
render: (el, props, children) ->
# VDOM node
return el('span', { className: "foo" }, "Hello World")
})
###
}
descriptor = () ->
id: id++
type: null
props: null
children: null
rendered: null
instance: null
hint = (n) ->
n *= 2
n = Math.max 0, HEAP.length - n
HEAP.push descriptor() for i in [0...n]
element = (type, props, children) ->
el = if HEAP.length then HEAP.pop() else descriptor()
el.type = type ? 'div'
el.props = props ? null
el.children = children ? null
# Can't use `arguments` here to pass children as direct args, it de-optimizes label emitters
el
recycle = (el) ->
return unless el.type
children = el.children
el.type = el.props = el.children = el.instance = null
HEAP.push el
recycle child for child in children if children?
return
apply = (el, last, node, parent, index) ->
if el?
if !last?
# New node
return mount el, parent, index
else
# Literal DOM node
if el instanceof Node
same = el == last
return if same
else
# Check compatibility
same = typeof el == typeof last and
last != null and el != null and
el.type == last.type
if !same
# Not compatible: unmount and remount
unmount last.instance, node
node.remove()
return mount el, parent, index
else
# Maintain component ref
el.instance = last.instance
# Check if it's a component
type = if el.type?.isComponentClass then el.type else Types[el.type]
# Prepare to diff props and children
props = last?.props
nextProps = el .props
children = last?.children ? null
nextChildren = el .children
nextProps.children = nextChildren if nextProps?
# Component
if type?
# See if it changed
dirty = node._COMPONENT_DIRTY
dirty = true if props? != nextProps?
dirty = true if children != nextChildren
if props? and nextProps?
dirty = true for key of props when !nextProps.hasOwnProperty key if !dirty
dirty = true for key, value of nextProps when (ref = props[key]) != value if !dirty
if dirty
comp = last.instance
el.props ?= {}
el.props[k] ?= v for k, v of comp.defaultProps
el.props.children = el.children
comp.willReceiveProps? el.props
should = node._COMPONENT_FORCE || (comp.shouldUpdate?(el.props) ? true)
if should
nextState = comp.getNextState()
comp.willUpdate? el.props, nextState
prevProps = comp.props
prevState = comp.applyNextState()
comp.props = el.props
comp.children = el.children
if should
el = el.rendered = comp.render? element, el.props, el.children
apply el, last.rendered, node, parent, index
comp.didUpdate? prevProps, prevState
return
else
# VDOM node
unset node, key, props[key] for key of props when !nextProps.hasOwnProperty key if props?
set node, key, value, ref for key, value of nextProps when (ref = props[key]) != value and key != 'children' if nextProps?
# Diff children
if nextChildren?
if typeof nextChildren in ['string', 'number']
# Insert text directly
if nextChildren != children
node.textContent = nextChildren
else
if nextChildren.type?
# Single child
apply nextChildren, children, node.childNodes[0], node, 0
else
# Diff children
childNodes = node.childNodes
if children?
apply child, children[i], childNodes[i], node, i for child, i in nextChildren
else
apply child, null, childNodes[i], node, i for child, i in nextChildren
else if children?
# Unmount all child components
unmount null, node
# Remove all children
node.innerHTML = ''
return
if last?
# Removed node
unmount last.instance, node
last.node.remove()
mount = (el, parent, index = 0) ->
type = if el.type?.isComponentClass then el.type else Types[el.type]
# Literal DOM node
if el instanceof Node
node = el
else
if type?
# Component
ctor = if el.type?.isComponentClass then el.type else Types[el.type]
# No component class found
if !ctor
el = el.rendered = element 'noscript'
node = mount el, parent, index
return node
# Construct component class
el.instance = comp = new ctor parent
el.props ?= {}
el.props[k] ?= v for k, v of comp.defaultProps
el.props.children = el.children
# Do initial state transition
comp.props = el.props
comp.children = el.children
comp.setState comp.getInitialState?()
comp.willMount?()
# Render
el = el.rendered = comp.render? element, el.props, el.children
node = mount el, parent, index
# Finish mounting and remember component/node association
comp.didMount? el
node._COMPONENT = comp
return node
else if typeof el in ['string', 'number']
# Text
node = document.createTextNode el
else
# VDOM Node
node = document.createElement el.type
set node, key, value for key, value of el.props
children = el.children
if children?
if typeof children in ['string', 'number']
# Insert text directly
node.textContent = children
else
if children.type?
# Single child
mount children, node, 0
else
# Insert children
mount child, node, i for child, i in children
parent.insertBefore node, parent.childNodes[index]
return node
unmount = (comp, node) ->
if comp
comp.willUnmount?()
delete comp[k] for k of comp
for child in node.childNodes
unmount child._COMPONENT, child
delete child._COMPONENT
prop = (key) ->
return true if typeof document == 'undefined'
return key if document.documentElement.style[key]?
key = key[PI:KEY:<KEY>END_PI key.PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI
prefixes = ['webkit', 'moz', 'ms', 'o']
return prefix + key for prefix in prefixes when document.documentElement.style[prefix + key]?
map = {}
map[key] = prop key for key in ['transform']
set = (node, key, value, orig) ->
if key == 'style'
for k, v of value when orig?[k] != v
node.style[map[k] ? k] = v
return
if node[key]?
node[key] = value
return
if node instanceof Node
node.setAttribute key, value
return
unset = (node, key, orig) ->
if key == 'style'
for k, v of orig
node.style[map[k] ? k] = ''
return
if node[key]?
node[key] = undefined
if node instanceof Node
node.removeAttribute key
return
createClass = (prototype) ->
aliases = {
willMount: 'componentWillMount'
didMount: 'componentDidMount'
willReceiveProps: 'componentWillReceiveProps'
shouldUpdate: 'shouldComponentUpdate'
willUpdate: 'componentWillUpdate'
didUpdate: 'componentDidUpdate'
willUnmount: 'componentWillUnmount'
}
prototype[a] ?= prototype[b] for a, b of aliases
class Component
constructor: (node, @props = {}, @state = null, @children = null) ->
bind = (f, self) -> if typeof f == 'function' then f.bind self else f
@[k] = bind v, @ for k, v of prototype
nextState = null
@setState = (state) ->
nextState ?= if state then nextState ? {} else null
nextState[k] = v for k, v of state
node._COMPONENT_DIRTY = true
return
@forceUpdate = () ->
node._COMPONENT_FORCE = node._COMPONENT_DIRTY = true
el = node
while el = el.parentNode
if el._COMPONENT
el._COMPONENT_FORCE = true
@getNextState = () -> nextState
@applyNextState = () ->
node._COMPONENT_FORCE = node._COMPONENT_DIRTY = false
prevState = @state
[nextState, @state] = [null, nextState]
prevState
return
Component.isComponentClass = true
Component.prototype.defaultProps = prototype.getDefaultProps?() ? {}
Component
module.exports = {element, recycle, apply, hint, Types, createClass} |
[
{
"context": "\n# xPersonOpenedBy: '',\n# xPersonAssignedTo: 'John Doe',\n# fOpen: '0',\n# xStatus: 'Responded',\n# f",
"end": 752,
"score": 0.9998600482940674,
"start": 744,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " dtGMTClosed: 'Aug 3, 2010',\n# iLastReplyB... | src/plugins/helpspot.coffee | abachman/pat-the-campfire-bot | 2 | # mess around with your helpspot installation
{_} = require 'underscore'
http = require 'http'
querystring = require 'querystring'
# parsing XML api, there seems to be a problem with json responses
DomJS = require('dom-js').DomJS
find_child_by_name = (_dom, name) ->
if name == _dom.name
return _dom
else if _dom.children && _dom.children.length > 0
for child in _dom.children
result = find_child_by_name(child, name)
return result if result?
logger = ( d ) ->
try
console.log "#{d.message.created_at}: #{d.message.body}"
# { xRequest: '20000',
# fOpenedVia: 'Email',
# xOpenedViaId: 'Logged in staff member',
# xPortal: '0',
# xMailboxToSendFrom: '1',
# xPersonOpenedBy: '',
# xPersonAssignedTo: 'John Doe',
# fOpen: '0',
# xStatus: 'Responded',
# fUrgent: '0',
# xCategory: 'Our Product',
# dtGMTOpened: 'Aug 3, 2010',
# dtGMTClosed: 'Aug 3, 2010',
# iLastReplyBy: 'John Doe',
# fTrash: '0',
# dtGMTTrashed: '',
# sRequestPassword: 'aaaaaa',
# sTitle: 'RE: Something I heard',
# sUserId: '',
# sFirstName: 'M.',
# sLastName: 'Robotic',
# sEmail: 'bolton@michael.net',
# sPhone: '',
# Custom1: '',
# Custom2: '',
# fullname: 'M. Robotic',
# reportingTags: { tag: [ [Object], [Object] ] },
# request_history:
# { item:
# { '70000': [Object],
# '70001': [Object],
# '70002': [Object],
# '70003': [Object] } } }
class HelpspotAPI
constructor: (@config) ->
get_request: (request_id, callback) ->
api_client = http.createClient 80, @config.helpspot_hostname
query = querystring.stringify
method: 'private.request.get'
xRequest: request_id
output: 'json'
username: @config.helpspot_username
password: @config.helpspot_password
options =
method: 'GET'
path : @config.helpspot_path + "/api/index.php?" + query
request = api_client.request options.method, options.path, host: @config.helpspot_hostname
request.end()
request.on 'response', (response) ->
data = ''
response.on 'data', (chunk) ->
data += chunk
response.on 'end', () ->
console.log "GOT end EVENT ON HELPSPOT API with data #{ data }!"
try
results = JSON.parse data
callback results
catch e
console.log "Failed to parse Helpspot API response on end: #{ e.message }"
response.on 'close', () ->
console.log "GOT close EVENT ON HELPSPOT API!"
try
results = JSON.parse data
callback results
catch e
console.log "Failed to parse Helpspot API response on close: #{ e.message }"
# link directly to a support request. Link template is an env variable with $
# where the request ID should be.
class Helpspot
name: "Helpspot"
constructor: () ->
@room_id_matcher = /(^|[^a-zA-Z0-9])(\d{5})($|[^a-zA-Z0-9])/ # try to avoid matching git hashes, etc
@room_link_template = process.env.helpspot_link_template
@api = new HelpspotAPI
helpspot_hostname: process.env.helpspot_hostname
helpspot_path: process.env.helpspot_path
helpspot_username: process.env.helpspot_username
helpspot_password: process.env.helpspot_password
link_to_ticket: (message, room) ->
request_id = @room_id_matcher.exec(message)[2]
@api.get_request request_id, (results) =>
if results && results.xRequest == request_id
link = "[#{results.xCategory}] #{results.sTitle} \n" + @room_link_template.replace('$', request_id)
room.speak "#{ link }", logger
ticket_status: (message, room) ->
request_id = @room_id_matcher.exec(message)[2]
@api.get_request request_id, (request) =>
if request && request.xRequest == request_id
link = @room_link_template.replace('$', request_id)
out = "#{ link } \n\n"
out += "assigned to: #{ request.xPersonAssignedTo.split(' ')[0] } \n"
out += "from: #{ request.fullname } \n"
out += "subject: #{ request.sTitle } \n"
out += "category: #{ request.xCategory } \n"
out += "status: #{ request.xStatus } \n"
out += "opened: #{ request.dtGMTOpened } \n"
if request.dtGMTClosed && request.dtGMTClosed.length
out += "closed: #{ request.dtGMTClosed } \n"
room.paste out, logger
else
room.speak "I couldn't find a ticket with id: #{ request_id }", logger
listen: (msg, room, env) ->
body = msg.body
return unless @api.config.helpspot_hostname? and
@api.config.helpspot_path? and
@api.config.helpspot_username? and
@api.config.helpspot_password?
if @room_id_matcher.test(body)
# message has a request...
# status update?
if /pat/i.test(body) && /status/i.test(body)
console.log "getting helpspot status: #{ @room_id_matcher.exec(msg.body)[2] }"
@ticket_status body, room
else
console.log "posting helpspot link: #{ @room_id_matcher.exec(msg.body)[2] }"
@link_to_ticket body, room
module.exports = new Helpspot
| 146371 | # mess around with your helpspot installation
{_} = require 'underscore'
http = require 'http'
querystring = require 'querystring'
# parsing XML api, there seems to be a problem with json responses
DomJS = require('dom-js').DomJS
find_child_by_name = (_dom, name) ->
if name == _dom.name
return _dom
else if _dom.children && _dom.children.length > 0
for child in _dom.children
result = find_child_by_name(child, name)
return result if result?
logger = ( d ) ->
try
console.log "#{d.message.created_at}: #{d.message.body}"
# { xRequest: '20000',
# fOpenedVia: 'Email',
# xOpenedViaId: 'Logged in staff member',
# xPortal: '0',
# xMailboxToSendFrom: '1',
# xPersonOpenedBy: '',
# xPersonAssignedTo: '<NAME>',
# fOpen: '0',
# xStatus: 'Responded',
# fUrgent: '0',
# xCategory: 'Our Product',
# dtGMTOpened: 'Aug 3, 2010',
# dtGMTClosed: 'Aug 3, 2010',
# iLastReplyBy: '<NAME>',
# fTrash: '0',
# dtGMTTrashed: '',
# sRequestPassword: '<PASSWORD>',
# sTitle: 'RE: Something I heard',
# sUserId: '',
# sFirstName: '<NAME>.',
# sLastName: '<NAME>',
# sEmail: '<EMAIL>',
# sPhone: '',
# Custom1: '',
# Custom2: '',
# fullname: '<NAME>',
# reportingTags: { tag: [ [Object], [Object] ] },
# request_history:
# { item:
# { '70000': [Object],
# '70001': [Object],
# '70002': [Object],
# '70003': [Object] } } }
class HelpspotAPI
constructor: (@config) ->
get_request: (request_id, callback) ->
api_client = http.createClient 80, @config.helpspot_hostname
query = querystring.stringify
method: 'private.request.get'
xRequest: request_id
output: 'json'
username: @config.helpspot_username
password: <PASSWORD>
options =
method: 'GET'
path : @config.helpspot_path + "/api/index.php?" + query
request = api_client.request options.method, options.path, host: @config.helpspot_hostname
request.end()
request.on 'response', (response) ->
data = ''
response.on 'data', (chunk) ->
data += chunk
response.on 'end', () ->
console.log "GOT end EVENT ON HELPSPOT API with data #{ data }!"
try
results = JSON.parse data
callback results
catch e
console.log "Failed to parse Helpspot API response on end: #{ e.message }"
response.on 'close', () ->
console.log "GOT close EVENT ON HELPSPOT API!"
try
results = JSON.parse data
callback results
catch e
console.log "Failed to parse Helpspot API response on close: #{ e.message }"
# link directly to a support request. Link template is an env variable with $
# where the request ID should be.
class Helpspot
name: "Helpspot"
constructor: () ->
@room_id_matcher = /(^|[^a-zA-Z0-9])(\d{5})($|[^a-zA-Z0-9])/ # try to avoid matching git hashes, etc
@room_link_template = process.env.helpspot_link_template
@api = new HelpspotAPI
helpspot_hostname: process.env.helpspot_hostname
helpspot_path: process.env.helpspot_path
helpspot_username: process.env.helpspot_username
helpspot_password: process.env.helpspot_password
link_to_ticket: (message, room) ->
request_id = @room_id_matcher.exec(message)[2]
@api.get_request request_id, (results) =>
if results && results.xRequest == request_id
link = "[#{results.xCategory}] #{results.sTitle} \n" + @room_link_template.replace('$', request_id)
room.speak "#{ link }", logger
ticket_status: (message, room) ->
request_id = @room_id_matcher.exec(message)[2]
@api.get_request request_id, (request) =>
if request && request.xRequest == request_id
link = @room_link_template.replace('$', request_id)
out = "#{ link } \n\n"
out += "assigned to: #{ request.xPersonAssignedTo.split(' ')[0] } \n"
out += "from: #{ request.fullname } \n"
out += "subject: #{ request.sTitle } \n"
out += "category: #{ request.xCategory } \n"
out += "status: #{ request.xStatus } \n"
out += "opened: #{ request.dtGMTOpened } \n"
if request.dtGMTClosed && request.dtGMTClosed.length
out += "closed: #{ request.dtGMTClosed } \n"
room.paste out, logger
else
room.speak "I couldn't find a ticket with id: #{ request_id }", logger
listen: (msg, room, env) ->
body = msg.body
return unless @api.config.helpspot_hostname? and
@api.config.helpspot_path? and
@api.config.helpspot_username? and
@api.config.helpspot_password?
if @room_id_matcher.test(body)
# message has a request...
# status update?
if /pat/i.test(body) && /status/i.test(body)
console.log "getting helpspot status: #{ @room_id_matcher.exec(msg.body)[2] }"
@ticket_status body, room
else
console.log "posting helpspot link: #{ @room_id_matcher.exec(msg.body)[2] }"
@link_to_ticket body, room
module.exports = new Helpspot
| true | # mess around with your helpspot installation
{_} = require 'underscore'
http = require 'http'
querystring = require 'querystring'
# parsing XML api, there seems to be a problem with json responses
DomJS = require('dom-js').DomJS
find_child_by_name = (_dom, name) ->
if name == _dom.name
return _dom
else if _dom.children && _dom.children.length > 0
for child in _dom.children
result = find_child_by_name(child, name)
return result if result?
logger = ( d ) ->
try
console.log "#{d.message.created_at}: #{d.message.body}"
# { xRequest: '20000',
# fOpenedVia: 'Email',
# xOpenedViaId: 'Logged in staff member',
# xPortal: '0',
# xMailboxToSendFrom: '1',
# xPersonOpenedBy: '',
# xPersonAssignedTo: 'PI:NAME:<NAME>END_PI',
# fOpen: '0',
# xStatus: 'Responded',
# fUrgent: '0',
# xCategory: 'Our Product',
# dtGMTOpened: 'Aug 3, 2010',
# dtGMTClosed: 'Aug 3, 2010',
# iLastReplyBy: 'PI:NAME:<NAME>END_PI',
# fTrash: '0',
# dtGMTTrashed: '',
# sRequestPassword: 'PI:PASSWORD:<PASSWORD>END_PI',
# sTitle: 'RE: Something I heard',
# sUserId: '',
# sFirstName: 'PI:NAME:<NAME>END_PI.',
# sLastName: 'PI:NAME:<NAME>END_PI',
# sEmail: 'PI:EMAIL:<EMAIL>END_PI',
# sPhone: '',
# Custom1: '',
# Custom2: '',
# fullname: 'PI:NAME:<NAME>END_PI',
# reportingTags: { tag: [ [Object], [Object] ] },
# request_history:
# { item:
# { '70000': [Object],
# '70001': [Object],
# '70002': [Object],
# '70003': [Object] } } }
class HelpspotAPI
constructor: (@config) ->
get_request: (request_id, callback) ->
api_client = http.createClient 80, @config.helpspot_hostname
query = querystring.stringify
method: 'private.request.get'
xRequest: request_id
output: 'json'
username: @config.helpspot_username
password: PI:PASSWORD:<PASSWORD>END_PI
options =
method: 'GET'
path : @config.helpspot_path + "/api/index.php?" + query
request = api_client.request options.method, options.path, host: @config.helpspot_hostname
request.end()
request.on 'response', (response) ->
data = ''
response.on 'data', (chunk) ->
data += chunk
response.on 'end', () ->
console.log "GOT end EVENT ON HELPSPOT API with data #{ data }!"
try
results = JSON.parse data
callback results
catch e
console.log "Failed to parse Helpspot API response on end: #{ e.message }"
response.on 'close', () ->
console.log "GOT close EVENT ON HELPSPOT API!"
try
results = JSON.parse data
callback results
catch e
console.log "Failed to parse Helpspot API response on close: #{ e.message }"
# link directly to a support request. Link template is an env variable with $
# where the request ID should be.
class Helpspot
name: "Helpspot"
constructor: () ->
@room_id_matcher = /(^|[^a-zA-Z0-9])(\d{5})($|[^a-zA-Z0-9])/ # try to avoid matching git hashes, etc
@room_link_template = process.env.helpspot_link_template
@api = new HelpspotAPI
helpspot_hostname: process.env.helpspot_hostname
helpspot_path: process.env.helpspot_path
helpspot_username: process.env.helpspot_username
helpspot_password: process.env.helpspot_password
link_to_ticket: (message, room) ->
request_id = @room_id_matcher.exec(message)[2]
@api.get_request request_id, (results) =>
if results && results.xRequest == request_id
link = "[#{results.xCategory}] #{results.sTitle} \n" + @room_link_template.replace('$', request_id)
room.speak "#{ link }", logger
ticket_status: (message, room) ->
request_id = @room_id_matcher.exec(message)[2]
@api.get_request request_id, (request) =>
if request && request.xRequest == request_id
link = @room_link_template.replace('$', request_id)
out = "#{ link } \n\n"
out += "assigned to: #{ request.xPersonAssignedTo.split(' ')[0] } \n"
out += "from: #{ request.fullname } \n"
out += "subject: #{ request.sTitle } \n"
out += "category: #{ request.xCategory } \n"
out += "status: #{ request.xStatus } \n"
out += "opened: #{ request.dtGMTOpened } \n"
if request.dtGMTClosed && request.dtGMTClosed.length
out += "closed: #{ request.dtGMTClosed } \n"
room.paste out, logger
else
room.speak "I couldn't find a ticket with id: #{ request_id }", logger
listen: (msg, room, env) ->
body = msg.body
return unless @api.config.helpspot_hostname? and
@api.config.helpspot_path? and
@api.config.helpspot_username? and
@api.config.helpspot_password?
if @room_id_matcher.test(body)
# message has a request...
# status update?
if /pat/i.test(body) && /status/i.test(body)
console.log "getting helpspot status: #{ @room_id_matcher.exec(msg.body)[2] }"
@ticket_status body, room
else
console.log "posting helpspot link: #{ @room_id_matcher.exec(msg.body)[2] }"
@link_to_ticket body, room
module.exports = new Helpspot
|
[
{
"context": "cription\n# They see me rolling.\n#\n# Author:\n# ivey\n\n\nmodule.exports = (robot) ->\n robot.hear /l",
"end": 55,
"score": 0.5424510836601257,
"start": 55,
"tag": "NAME",
"value": ""
},
{
"context": "ription\n# They see me rolling.\n#\n# Author:\n# ivey\n\... | scripts/rolling.coffee | RiotGamesMinions/lefay | 7 | # Description
# They see me rolling.
#
# Author:
# ivey
module.exports = (robot) ->
robot.hear /let's roll|see me rollin/i, (msg) ->
msg.send "http://mlkshk.com/r/PWID.gif" | 136458 | # Description
# They see me rolling.
#
# Author:
# <NAME> ivey
module.exports = (robot) ->
robot.hear /let's roll|see me rollin/i, (msg) ->
msg.send "http://mlkshk.com/r/PWID.gif" | true | # Description
# They see me rolling.
#
# Author:
# PI:NAME:<NAME>END_PI ivey
module.exports = (robot) ->
robot.hear /let's roll|see me rollin/i, (msg) ->
msg.send "http://mlkshk.com/r/PWID.gif" |
[
{
"context": ", 'sync'\n @orderedSets = new OrderedSets key: 'browse:featured-genes'\n\n afterEach ->\n Backbone.sync.restore()\n\n d",
"end": 324,
"score": 0.8696529269218445,
"start": 303,
"tag": "KEY",
"value": "browse:featured-genes"
}
] | src/mobile/test/collections/ordered_sets.test.coffee | jo-rs/force | 0 | sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
OrderedSets = rewire '../../collections/ordered_sets.coffee'
{ fabricate } = require '@artsy/antigravity'
describe 'OrderedSets', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@orderedSets = new OrderedSets key: 'browse:featured-genes'
afterEach ->
Backbone.sync.restore()
describe '#fetchSets', ->
beforeEach ->
@fetchSpy = sinon.stub()
@orderedSets.model::fetchItems = @fetchSpy
@orderedSets.add [fabricate 'ordered_set']
@orderedSets.add [fabricate 'ordered_set']
it 'should call #fetchItems for set in the collection', ->
@orderedSets.fetchSets()
@fetchSpy.calledTwice.should.be.ok()
it 'should return a promise', ->
@orderedSets.fetchSets().constructor.name.should.equal 'Promise'
it 'should be thennable', ->
@orderedSets.fetchSets()
describe '#fetchAll', ->
beforeEach ->
@orderedSets.fetch = sinon.stub().returns then: (cb) -> cb()
@orderedSets.model::fetchItems = sinon.stub()
it 'triggers sync:complete when it is done', (done) ->
@orderedSets.on 'sync:complete', done
@orderedSets.fetchAll()
return
it 'should be thennable', (done) ->
@orderedSets.fetchAll().then -> done()
return
| 160901 | sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
OrderedSets = rewire '../../collections/ordered_sets.coffee'
{ fabricate } = require '@artsy/antigravity'
describe 'OrderedSets', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@orderedSets = new OrderedSets key: '<KEY>'
afterEach ->
Backbone.sync.restore()
describe '#fetchSets', ->
beforeEach ->
@fetchSpy = sinon.stub()
@orderedSets.model::fetchItems = @fetchSpy
@orderedSets.add [fabricate 'ordered_set']
@orderedSets.add [fabricate 'ordered_set']
it 'should call #fetchItems for set in the collection', ->
@orderedSets.fetchSets()
@fetchSpy.calledTwice.should.be.ok()
it 'should return a promise', ->
@orderedSets.fetchSets().constructor.name.should.equal 'Promise'
it 'should be thennable', ->
@orderedSets.fetchSets()
describe '#fetchAll', ->
beforeEach ->
@orderedSets.fetch = sinon.stub().returns then: (cb) -> cb()
@orderedSets.model::fetchItems = sinon.stub()
it 'triggers sync:complete when it is done', (done) ->
@orderedSets.on 'sync:complete', done
@orderedSets.fetchAll()
return
it 'should be thennable', (done) ->
@orderedSets.fetchAll().then -> done()
return
| true | sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
OrderedSets = rewire '../../collections/ordered_sets.coffee'
{ fabricate } = require '@artsy/antigravity'
describe 'OrderedSets', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@orderedSets = new OrderedSets key: 'PI:KEY:<KEY>END_PI'
afterEach ->
Backbone.sync.restore()
describe '#fetchSets', ->
beforeEach ->
@fetchSpy = sinon.stub()
@orderedSets.model::fetchItems = @fetchSpy
@orderedSets.add [fabricate 'ordered_set']
@orderedSets.add [fabricate 'ordered_set']
it 'should call #fetchItems for set in the collection', ->
@orderedSets.fetchSets()
@fetchSpy.calledTwice.should.be.ok()
it 'should return a promise', ->
@orderedSets.fetchSets().constructor.name.should.equal 'Promise'
it 'should be thennable', ->
@orderedSets.fetchSets()
describe '#fetchAll', ->
beforeEach ->
@orderedSets.fetch = sinon.stub().returns then: (cb) -> cb()
@orderedSets.model::fetchItems = sinon.stub()
it 'triggers sync:complete when it is done', (done) ->
@orderedSets.on 'sync:complete', done
@orderedSets.fetchAll()
return
it 'should be thennable', (done) ->
@orderedSets.fetchAll().then -> done()
return
|
[
{
"context": "u-container\">\n <div class=\"item\">\n Fichier(s)\n <div class=\"sub-menu\">\n <",
"end": 621,
"score": 0.9280226230621338,
"start": 614,
"tag": "NAME",
"value": "Fichier"
}
] | coffee/interBody.coffee | Nyura95/Eletron-DRH | 0 | class interBody
constructor: () ->
#fdsfdsf
changeTitle: (title) ->
$("#title").html title
createSidebar: (sidebar) ->
$("#sidebar").css "display", "inline-block"
$("#main-content").css "width", "79%"
@headerSidebar side.place, side.gif, side.title for side in sidebar
headerSidebar: (header, gif, title) ->
$("#sidebar").append "<div class='#{header}-item'><i class='#{gif}'></i>#{title}</div>"
createSysbar: (sysbar) ->
$("#menu-container").append "<div class='item'>"
window.interBody = interBody
###
<div class="menu-container">
<div class="item">
Fichier(s)
<div class="sub-menu">
<div class="sub-item" data-menu="click">
1 menu
</div>
</div>
</div>
</div>
###
| 35613 | class interBody
constructor: () ->
#fdsfdsf
changeTitle: (title) ->
$("#title").html title
createSidebar: (sidebar) ->
$("#sidebar").css "display", "inline-block"
$("#main-content").css "width", "79%"
@headerSidebar side.place, side.gif, side.title for side in sidebar
headerSidebar: (header, gif, title) ->
$("#sidebar").append "<div class='#{header}-item'><i class='#{gif}'></i>#{title}</div>"
createSysbar: (sysbar) ->
$("#menu-container").append "<div class='item'>"
window.interBody = interBody
###
<div class="menu-container">
<div class="item">
<NAME>(s)
<div class="sub-menu">
<div class="sub-item" data-menu="click">
1 menu
</div>
</div>
</div>
</div>
###
| true | class interBody
constructor: () ->
#fdsfdsf
changeTitle: (title) ->
$("#title").html title
createSidebar: (sidebar) ->
$("#sidebar").css "display", "inline-block"
$("#main-content").css "width", "79%"
@headerSidebar side.place, side.gif, side.title for side in sidebar
headerSidebar: (header, gif, title) ->
$("#sidebar").append "<div class='#{header}-item'><i class='#{gif}'></i>#{title}</div>"
createSysbar: (sysbar) ->
$("#menu-container").append "<div class='item'>"
window.interBody = interBody
###
<div class="menu-container">
<div class="item">
PI:NAME:<NAME>END_PI(s)
<div class="sub-menu">
<div class="sub-item" data-menu="click">
1 menu
</div>
</div>
</div>
</div>
###
|
[
{
"context": " authors: [\n {\n name: \"Jun\"\n id: '123'\n },\n {\n ",
"end": 1919,
"score": 0.9993566274642944,
"start": 1916,
"tag": "NAME",
"value": "Jun"
},
{
"context": "'123'\n },\n {\n name: ... | src/desktop/apps/rss/test/news.test.coffee | jo-rs/force | 0 | _ = require 'underscore'
fs = require 'fs'
newsTemplate = require('jade').compileFile(require.resolve '../templates/news.jade')
articleTemplate = require('jade').compileFile(require.resolve '../templates/article.jade')
sd =
APP_URL: 'http://localhost'
{ fabricate } = require '@artsy/antigravity'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
moment = require 'moment'
{ toSentence } = require 'underscore.string'
{ resize } = require '../../../components/resizer'
describe '/rss', ->
describe 'news', ->
it 'renders no news', ->
rendered = newsTemplate(sd: sd, articles: new Articles)
rendered.should.containEql '<title>Artsy News</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/news" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Featured Artsy articles.</description>'
it 'renders articles', ->
articles = new Articles [
new Article(thumbnail_title: 'Hello', published_at: new Date().toISOString(), contributing_authors: [], description: 'A piece about the Whitney.'),
new Article(thumbnail_title: 'World', published_at: new Date().toISOString(), contributing_authors: [])
]
rendered = newsTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql '<title>Artsy News</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/news" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Featured Artsy articles.</description>'
rendered.should.containEql '<item><title>Hello</title>'
rendered.should.containEql '<item><title>World</title>'
rendered.should.containEql '<description>A piece about the Whitney.</description>'
it 'renders authors', ->
article = new Article
authors: [
{
name: "Jun"
id: '123'
},
{
name: "Owen"
id: '456'
}
]
rendered = newsTemplate(sd: sd, articles: new Articles(article), moment: moment)
rendered.should.containEql '<author>Jun and Owen</author>'
it 'renders categories', ->
article = new Article
vertical:
name: 'Art'
id: '123'
rendered = newsTemplate(sd: sd, articles: new Articles(article), moment: moment)
rendered.should.containEql '<category>Art</category>'
it 'renders enclosures on video articles', ->
article = new Article
layout: 'video'
media:
url: 'https://artsymedia.mp4'
credits: '<p>Director</p><p>Marina Cashdan</p>'
description: '<p>Sample Description</p>'
rendered = newsTemplate(sd: sd, articles: new Articles(article), moment: moment)
rendered.should.containEql '<enclosure url="https://artsymedia.mp4" length="0" type="video/mp4">'
it 'renders enclosures on news articles', ->
articles = [
{
layout: 'news',
thumbnail_image: 'artsy.net/jpg.jpg'
},
]
rendered = newsTemplate(sd: sd, articles: new Articles(articles), moment: moment)
rendered.should.containEql '/images/og_image.jpg'
it 'renders enclosures on non-video articles', ->
articles = [
{
layout: 'standard',
thumbnail_image: 'artsy.net/jpg.jpg'
},
{
layout: 'standard',
thumbnail_image: 'artsy.net/jpeg.jpeg'
},
{
layout: 'standard',
thumbnail_image: 'artsy.net/png.png'
}
]
rendered = newsTemplate(sd: sd, articles: new Articles(articles), moment: moment)
rendered.should.containEql '<enclosure url="artsy.net/jpg.jpg" length="0" type="image/jpeg">'
rendered.should.containEql '<enclosure url="artsy.net/jpeg.jpeg" length="0" type="image/jpeg">'
rendered.should.containEql '<enclosure url="artsy.net/png.png" length="0" type="image/png">'
describe 'article', ->
it 'renders the lead paragraph and body text', ->
article = new Article(
lead_paragraph: 'Andy Foobar never wanted fame.'
sections: [
{
type: 'text'
body: 'But sometimes fame chooses you.'
}
]
contributing_authors: []
)
rendered = articleTemplate(sd: sd, article: article)
rendered.should.containEql 'Andy Foobar never wanted fame.But sometimes fame chooses you.'
it 'renders news source', ->
article = new Article(
lead_paragraph: 'Andy Foobar never wanted fame.'
sections: [
{
type: 'text'
body: 'But sometimes fame chooses you.'
}
]
contributing_authors: []
source: {
title: 'New York Times',
url: 'http://artsy.net'
}
)
rendered = articleTemplate(sd: sd, article: article)
rendered.should.containEql '<p>via <a href="http://artsy.net">New York Times</a>'
it 'renders images, artworks, social_embed and image_collection', ->
article = new Article(
lead_paragraph: 'Andy Foobar never wanted fame.'
sections: [
{
type: 'image'
url: 'http://artsy.net/image1.jpg'
caption: '<p>The first caption</p>'
},
{
type: 'image_collection',
layout: 'overflow_fillwidth',
images: [
{
type: 'artwork'
id: '5321b73dc9dc2458c4000196'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between as Image Collection",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "October Gallery",
slug: "october-gallery"
},
artists: [{
name: "Govinda Sah 'Azad'",
slug: "govinda-sah-azad"
},
{
name: "Andy Warhol",
slug: "andy-warhol"
},
{
name: "Joe Fun",
slug: "joe-fun"
}]
},{
type: 'image'
url: "http://artsy.net/image2.jpg",
caption: "<p>The second caption</p>",
},
]
},
{
type: 'social_embed'
url: 'https://twitter.com/artsy/status/978997552061272064'
}
]
contributing_authors: []
)
rendered = articleTemplate(sd: sd, article: article, resize: resize, _: _, toSentence: toSentence)
rendered.should.containEql "In Between as Image Collection, 2015. <br/>Govinda Sah 'Azad', Andy Warhol and Joe Fun<br/>October Gallery"
rendered.should.containEql "<p>The first caption</p>"
rendered.should.containEql "<p>The second caption</p>"
rendered.should.containEql 'https://twitter.com/artsy/status/978997552061272064'
it 'renders media', ->
article = new Article
media:
url: 'https://artsymedia.mp4'
credits: '<p>Director</p><p>Marina Cashdan</p>'
description: '<p>Sample Description</p>'
rendered = articleTemplate
sd: sd
article: article
resize: resize
_: _
toSentence: toSentence
rendered.should.containEql 'src="https://artsymedia.mp4"'
rendered.should.containEql '<p>Director</p><p>Marina Cashdan</p>'
rendered.should.containEql '<p>Sample Description</p>'
| 207074 | _ = require 'underscore'
fs = require 'fs'
newsTemplate = require('jade').compileFile(require.resolve '../templates/news.jade')
articleTemplate = require('jade').compileFile(require.resolve '../templates/article.jade')
sd =
APP_URL: 'http://localhost'
{ fabricate } = require '@artsy/antigravity'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
moment = require 'moment'
{ toSentence } = require 'underscore.string'
{ resize } = require '../../../components/resizer'
describe '/rss', ->
describe 'news', ->
it 'renders no news', ->
rendered = newsTemplate(sd: sd, articles: new Articles)
rendered.should.containEql '<title>Artsy News</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/news" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Featured Artsy articles.</description>'
it 'renders articles', ->
articles = new Articles [
new Article(thumbnail_title: 'Hello', published_at: new Date().toISOString(), contributing_authors: [], description: 'A piece about the Whitney.'),
new Article(thumbnail_title: 'World', published_at: new Date().toISOString(), contributing_authors: [])
]
rendered = newsTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql '<title>Artsy News</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/news" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Featured Artsy articles.</description>'
rendered.should.containEql '<item><title>Hello</title>'
rendered.should.containEql '<item><title>World</title>'
rendered.should.containEql '<description>A piece about the Whitney.</description>'
it 'renders authors', ->
article = new Article
authors: [
{
name: "<NAME>"
id: '123'
},
{
name: "<NAME>"
id: '456'
}
]
rendered = newsTemplate(sd: sd, articles: new Articles(article), moment: moment)
rendered.should.containEql '<author><NAME></author>'
it 'renders categories', ->
article = new Article
vertical:
name: 'Art'
id: '123'
rendered = newsTemplate(sd: sd, articles: new Articles(article), moment: moment)
rendered.should.containEql '<category>Art</category>'
it 'renders enclosures on video articles', ->
article = new Article
layout: 'video'
media:
url: 'https://artsymedia.mp4'
credits: '<p>Director</p><p><NAME></p>'
description: '<p>Sample Description</p>'
rendered = newsTemplate(sd: sd, articles: new Articles(article), moment: moment)
rendered.should.containEql '<enclosure url="https://artsymedia.mp4" length="0" type="video/mp4">'
it 'renders enclosures on news articles', ->
articles = [
{
layout: 'news',
thumbnail_image: 'artsy.net/jpg.jpg'
},
]
rendered = newsTemplate(sd: sd, articles: new Articles(articles), moment: moment)
rendered.should.containEql '/images/og_image.jpg'
it 'renders enclosures on non-video articles', ->
articles = [
{
layout: 'standard',
thumbnail_image: 'artsy.net/jpg.jpg'
},
{
layout: 'standard',
thumbnail_image: 'artsy.net/jpeg.jpeg'
},
{
layout: 'standard',
thumbnail_image: 'artsy.net/png.png'
}
]
rendered = newsTemplate(sd: sd, articles: new Articles(articles), moment: moment)
rendered.should.containEql '<enclosure url="artsy.net/jpg.jpg" length="0" type="image/jpeg">'
rendered.should.containEql '<enclosure url="artsy.net/jpeg.jpeg" length="0" type="image/jpeg">'
rendered.should.containEql '<enclosure url="artsy.net/png.png" length="0" type="image/png">'
describe 'article', ->
it 'renders the lead paragraph and body text', ->
article = new Article(
lead_paragraph: '<NAME> never wanted fame.'
sections: [
{
type: 'text'
body: 'But sometimes fame chooses you.'
}
]
contributing_authors: []
)
rendered = articleTemplate(sd: sd, article: article)
rendered.should.containEql '<NAME> never wanted fame.But sometimes fame chooses you.'
it 'renders news source', ->
article = new Article(
lead_paragraph: '<NAME> never wanted fame.'
sections: [
{
type: 'text'
body: 'But sometimes fame chooses you.'
}
]
contributing_authors: []
source: {
title: 'New York Times',
url: 'http://artsy.net'
}
)
rendered = articleTemplate(sd: sd, article: article)
rendered.should.containEql '<p>via <a href="http://artsy.net">New York Times</a>'
it 'renders images, artworks, social_embed and image_collection', ->
article = new Article(
lead_paragraph: '<NAME> never wanted fame.'
sections: [
{
type: 'image'
url: 'http://artsy.net/image1.jpg'
caption: '<p>The first caption</p>'
},
{
type: 'image_collection',
layout: 'overflow_fillwidth',
images: [
{
type: 'artwork'
id: '5321b73dc9dc2458c4000196'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between as Image Collection",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "Oct<NAME>",
slug: "october-gallery"
},
artists: [{
name: "<NAME>'",
slug: "<NAME>-sah-azad"
},
{
name: "<NAME>",
slug: "<NAME>-<NAME>"
},
{
name: "<NAME>",
slug: "<NAME>-<NAME>"
}]
},{
type: 'image'
url: "http://artsy.net/image2.jpg",
caption: "<p>The second caption</p>",
},
]
},
{
type: 'social_embed'
url: 'https://twitter.com/artsy/status/978997552061272064'
}
]
contributing_authors: []
)
rendered = articleTemplate(sd: sd, article: article, resize: resize, _: _, toSentence: toSentence)
rendered.should.containEql "In Between as Image Collection, 2015. <br/><NAME> '<NAME>', <NAME> and Jo<NAME> Fun<br/>October Gallery"
rendered.should.containEql "<p>The first caption</p>"
rendered.should.containEql "<p>The second caption</p>"
rendered.should.containEql 'https://twitter.com/artsy/status/978997552061272064'
it 'renders media', ->
article = new Article
media:
url: 'https://artsymedia.mp4'
credits: '<p>Director</p><p><NAME></p>'
description: '<p>Sample Description</p>'
rendered = articleTemplate
sd: sd
article: article
resize: resize
_: _
toSentence: toSentence
rendered.should.containEql 'src="https://artsymedia.mp4"'
rendered.should.containEql '<p>Director</p><p><NAME></p>'
rendered.should.containEql '<p>Sample Description</p>'
| true | _ = require 'underscore'
fs = require 'fs'
newsTemplate = require('jade').compileFile(require.resolve '../templates/news.jade')
articleTemplate = require('jade').compileFile(require.resolve '../templates/article.jade')
sd =
APP_URL: 'http://localhost'
{ fabricate } = require '@artsy/antigravity'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
moment = require 'moment'
{ toSentence } = require 'underscore.string'
{ resize } = require '../../../components/resizer'
describe '/rss', ->
describe 'news', ->
it 'renders no news', ->
rendered = newsTemplate(sd: sd, articles: new Articles)
rendered.should.containEql '<title>Artsy News</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/news" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Featured Artsy articles.</description>'
it 'renders articles', ->
articles = new Articles [
new Article(thumbnail_title: 'Hello', published_at: new Date().toISOString(), contributing_authors: [], description: 'A piece about the Whitney.'),
new Article(thumbnail_title: 'World', published_at: new Date().toISOString(), contributing_authors: [])
]
rendered = newsTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql '<title>Artsy News</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/news" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Featured Artsy articles.</description>'
rendered.should.containEql '<item><title>Hello</title>'
rendered.should.containEql '<item><title>World</title>'
rendered.should.containEql '<description>A piece about the Whitney.</description>'
it 'renders authors', ->
article = new Article
authors: [
{
name: "PI:NAME:<NAME>END_PI"
id: '123'
},
{
name: "PI:NAME:<NAME>END_PI"
id: '456'
}
]
rendered = newsTemplate(sd: sd, articles: new Articles(article), moment: moment)
rendered.should.containEql '<author>PI:NAME:<NAME>END_PI</author>'
it 'renders categories', ->
article = new Article
vertical:
name: 'Art'
id: '123'
rendered = newsTemplate(sd: sd, articles: new Articles(article), moment: moment)
rendered.should.containEql '<category>Art</category>'
it 'renders enclosures on video articles', ->
article = new Article
layout: 'video'
media:
url: 'https://artsymedia.mp4'
credits: '<p>Director</p><p>PI:NAME:<NAME>END_PI</p>'
description: '<p>Sample Description</p>'
rendered = newsTemplate(sd: sd, articles: new Articles(article), moment: moment)
rendered.should.containEql '<enclosure url="https://artsymedia.mp4" length="0" type="video/mp4">'
it 'renders enclosures on news articles', ->
articles = [
{
layout: 'news',
thumbnail_image: 'artsy.net/jpg.jpg'
},
]
rendered = newsTemplate(sd: sd, articles: new Articles(articles), moment: moment)
rendered.should.containEql '/images/og_image.jpg'
it 'renders enclosures on non-video articles', ->
articles = [
{
layout: 'standard',
thumbnail_image: 'artsy.net/jpg.jpg'
},
{
layout: 'standard',
thumbnail_image: 'artsy.net/jpeg.jpeg'
},
{
layout: 'standard',
thumbnail_image: 'artsy.net/png.png'
}
]
rendered = newsTemplate(sd: sd, articles: new Articles(articles), moment: moment)
rendered.should.containEql '<enclosure url="artsy.net/jpg.jpg" length="0" type="image/jpeg">'
rendered.should.containEql '<enclosure url="artsy.net/jpeg.jpeg" length="0" type="image/jpeg">'
rendered.should.containEql '<enclosure url="artsy.net/png.png" length="0" type="image/png">'
describe 'article', ->
it 'renders the lead paragraph and body text', ->
article = new Article(
lead_paragraph: 'PI:NAME:<NAME>END_PI never wanted fame.'
sections: [
{
type: 'text'
body: 'But sometimes fame chooses you.'
}
]
contributing_authors: []
)
rendered = articleTemplate(sd: sd, article: article)
rendered.should.containEql 'PI:NAME:<NAME>END_PI never wanted fame.But sometimes fame chooses you.'
it 'renders news source', ->
article = new Article(
lead_paragraph: 'PI:NAME:<NAME>END_PI never wanted fame.'
sections: [
{
type: 'text'
body: 'But sometimes fame chooses you.'
}
]
contributing_authors: []
source: {
title: 'New York Times',
url: 'http://artsy.net'
}
)
rendered = articleTemplate(sd: sd, article: article)
rendered.should.containEql '<p>via <a href="http://artsy.net">New York Times</a>'
it 'renders images, artworks, social_embed and image_collection', ->
article = new Article(
lead_paragraph: 'PI:NAME:<NAME>END_PI never wanted fame.'
sections: [
{
type: 'image'
url: 'http://artsy.net/image1.jpg'
caption: '<p>The first caption</p>'
},
{
type: 'image_collection',
layout: 'overflow_fillwidth',
images: [
{
type: 'artwork'
id: '5321b73dc9dc2458c4000196'
slug: "govinda-sah-azad-in-between-1",
date: "2015",
title: "In Between as Image Collection",
image: "https://d32dm0rphc51dk.cloudfront.net/zjr8iMxGUQAVU83wi_oXaQ/larger.jpg",
partner: {
name: "OctPI:NAME:<NAME>END_PI",
slug: "october-gallery"
},
artists: [{
name: "PI:NAME:<NAME>END_PI'",
slug: "PI:NAME:<NAME>END_PI-sah-azad"
},
{
name: "PI:NAME:<NAME>END_PI",
slug: "PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI"
},
{
name: "PI:NAME:<NAME>END_PI",
slug: "PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI"
}]
},{
type: 'image'
url: "http://artsy.net/image2.jpg",
caption: "<p>The second caption</p>",
},
]
},
{
type: 'social_embed'
url: 'https://twitter.com/artsy/status/978997552061272064'
}
]
contributing_authors: []
)
rendered = articleTemplate(sd: sd, article: article, resize: resize, _: _, toSentence: toSentence)
rendered.should.containEql "In Between as Image Collection, 2015. <br/>PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI', PI:NAME:<NAME>END_PI and JoPI:NAME:<NAME>END_PI Fun<br/>October Gallery"
rendered.should.containEql "<p>The first caption</p>"
rendered.should.containEql "<p>The second caption</p>"
rendered.should.containEql 'https://twitter.com/artsy/status/978997552061272064'
it 'renders media', ->
article = new Article
media:
url: 'https://artsymedia.mp4'
credits: '<p>Director</p><p>PI:NAME:<NAME>END_PI</p>'
description: '<p>Sample Description</p>'
rendered = articleTemplate
sd: sd
article: article
resize: resize
_: _
toSentence: toSentence
rendered.should.containEql 'src="https://artsymedia.mp4"'
rendered.should.containEql '<p>Director</p><p>PI:NAME:<NAME>END_PI</p>'
rendered.should.containEql '<p>Sample Description</p>'
|
[
{
"context": "#!\n# api.prabhatkumar.org® [v0.0.1]\n# @author : Prabhat Kumar [http://prabhatkumar.org/]\n# @copyright : Prabhat",
"end": 66,
"score": 0.9998875856399536,
"start": 53,
"tag": "NAME",
"value": "Prabhat Kumar"
}
] | source/API/code/assets/coffee/lib/repository.coffee | iammachine/prabhatkumar.org | 1 | ###!
# api.prabhatkumar.org® [v0.0.1]
# @author : Prabhat Kumar [http://prabhatkumar.org/]
# @copyright : Prabhat Kumar [http://prabhatkumar.org/]
###
### @Invoking strict mode ###
'use strict'
| 11571 | ###!
# api.prabhatkumar.org® [v0.0.1]
# @author : <NAME> [http://prabhatkumar.org/]
# @copyright : Prabhat Kumar [http://prabhatkumar.org/]
###
### @Invoking strict mode ###
'use strict'
| true | ###!
# api.prabhatkumar.org® [v0.0.1]
# @author : PI:NAME:<NAME>END_PI [http://prabhatkumar.org/]
# @copyright : Prabhat Kumar [http://prabhatkumar.org/]
###
### @Invoking strict mode ###
'use strict'
|
[
{
"context": ")\n\n\n # SSDP configuration.\n ssdp:\n address: '239.255.255.250' # Address and port for broadcast messages.\n p",
"end": 979,
"score": 0.9997140169143677,
"start": 964,
"tag": "IP_ADDRESS",
"value": "239.255.255.250"
},
{
"context": "pe() }\n { friendly... | lib/devices/Device.coffee | Loghorn/node-upnp-device | 20 | # Properties and functionality common for all devices,
# as specified in [UPnP Device Architecture 1.0] [1].
#
# [1]: http://upnp.org/sdcps-and-certification/standards/device-architecture-documents/
"use strict"
dgram = require 'dgram'
fs = require 'fs'
http = require 'http'
os = require 'os'
makeUuid = require 'node-uuid'
xml = require 'xml'
parser = require 'http-string-parser'
{ HttpError } = require '../errors'
_ = require '../utils'
# `Device` extends [`DeviceControlProtocol`](DeviceControlProtocol.html) with
# properties and methods common to devices and services.
DeviceControlProtocol = require '../DeviceControlProtocol'
class Device extends DeviceControlProtocol
constructor: (@name, address) ->
super
@address = address if address?
# Socket for listening and sending messages on SSDP broadcast address.
@broadcastSocket = dgram.createSocket 'udp4', @ssdpListener
@init()
# SSDP configuration.
ssdp:
address: '239.255.255.250' # Address and port for broadcast messages.
port: 1900
timeout: 1800
ttl: 4
# Asynchronous operations to get and set some device properties.
init: (cb) ->
_.async.parallel
address: (cb) => if @address? then cb null, @address else cb null, '0.0.0.0'
uuid: (cb) => @getUuid cb
port: (cb) =>
@httpServer = http.createServer(@httpListener)
@httpServer.listen 0, @address, (err) -> cb err, @address().port
(err, res) =>
return @emit 'error', err if err?
@uuid = "uuid:#{res.uuid}"
@address = res.address
@httpPort = res.port
@broadcastSocket.bind @ssdp.port, =>
@broadcastSocket.addMembership @ssdp.address
@broadcastSocket.setMulticastTTL @ssdp.ttl
@addServices()
@ssdpAnnounce()
console.log "Web server listening on http://#{@address}:#{@httpPort}"
@emit 'ready'
# When HTTP and SSDP servers are started, we add and initialize services.
addServices: ->
@services = {}
for serviceType in @serviceTypes
@services[serviceType] = new @serviceReferences[serviceType] @
# Generate HTTP headers from `customHeaders` object.
makeSsdpMessage: (reqType, customHeaders) ->
# These headers are included in all SSDP messages. Setting their value
# to `null` makes `makeHeaders()` add default values.
for header in [ 'cache-control', 'server', 'usn', 'location' ]
customHeaders[header] = null
headers = @makeHeaders customHeaders
# First line of message string.
# We build the string as an array first for `join()` convenience.
message =
if reqType is 'ok'
[ "HTTP/1.1 200 OK" ]
else
[ "#{reqType.toUpperCase()} * HTTP/1.1" ]
# Add header key/value pairs.
message.push "#{h.toUpperCase()}: #{v}" for h, v of headers
# Add carriage returns and newlines as specified by HTTP.
message.push '\r\n'
new Buffer message.join '\r\n'
# Generate an object with HTTP headers for HTTP and SSDP messages.
# Adds defaults and uppercases headers.
makeHeaders: (customHeaders) ->
# If key exists in `customHeaders` but is `null`, use these defaults.
defaultHeaders =
'cache-control': "max-age=#{@ssdp.timeout}"
'content-type': 'text/xml; charset="utf-8"'
ext: ''
host: "#{@ssdp.address}:#{@ssdp.port}"
location: @makeUrl '/device/description'
server: [
"#{os.type()}/#{os.release()}"
"UPnP/#{@upnp.version.join('.')}"
"#{@name}/1.0" ].join ' '
usn: @uuid +
if @uuid is (customHeaders.nt or customHeaders.st) then ''
else '::' + (customHeaders.nt or customHeaders.st)
headers = {}
for header of customHeaders
headers[header.toUpperCase()] = customHeaders[header] or defaultHeaders[header.toLowerCase()]
headers
# Make `nt` header values. 3 with device info, plus 1 per service.
makeNotificationTypes: ->
[ 'upnp:rootdevice', @uuid, @makeType() ]
.concat(@makeType.call service for name, service of @services)
# Parse SSDP headers using the HTTP module parser.
parseRequest: (msg, rinfo, cb) ->
req = parser.parseRequest(msg)
{ method, headers } = req
mx = null
st = null
for header of headers
switch header.toLowerCase()
when 'mx'
mx = headers[header]
when 'st'
st = headers[header]
{ address, port } = rinfo
cb null, { method, mx, st, address, port }
# Attempt UUID persistance of devices across restarts.
getUuid: (cb) ->
uuidFile = "#{__dirname}/../../upnp-uuid"
fs.readFile uuidFile, 'utf8', (err, file) =>
data = try JSON.parse file; catch e then {}
uuid = data[@type]?[@name]
unless uuid?
(data[@type]?={})[@name] = uuid = makeUuid()
fs.writeFile uuidFile, JSON.stringify data
# Always call back with UUID, existing or new.
cb null, uuid
# Build device description XML document.
buildDescription: ->
'<?xml version="1.0"?>' + xml [ { root: [
{ _attr: { xmlns: @makeNS() } }
{ specVersion: [ { major: @upnp.version[0] }
{ minor: @upnp.version[1] } ] }
{ device: [
{ deviceType: @makeType() }
{ friendlyName: @friendlyName ? "#{@name} @ #{os.hostname()}".substr(0, 64) }
{ manufacturer: @manufacturer ? 'UPnP Device for Node.js' }
{ modelName: @name.substr(0, 32) }
{ UDN: @uuid }
{ serviceList:
{ service: service.buildServiceElement() } for name, service of @services
} ] }
] } ]
# HTTP request listener
httpListener: (req, res) =>
# console.log "#{req.url} requested by #{req.headers['user-agent']} at #{req.client.remoteAddress}."
# HTTP request handler.
handler = (req, cb) =>
# URLs are like `/device|service/action/[serviceType]`.
[category, serviceType, action, id] = req.url.split('/')[1..]
switch category
when 'device'
cb null, @buildDescription()
when 'service'
@services[serviceType].requestHandler { action, req, id }, cb
else
cb new HttpError 404
handler req, (err, data, headers) =>
if err?
# See UDA for error details.
console.log "Responded with #{err.code}: #{err.message} for #{req.url}."
res.writeHead err.code, 'Content-Type': 'text/plain'
res.write "#{err.code} - #{err.message}"
else
# Make a header object for response.
# `null` means use `makeHeaders` function's default value.
headers ?= {}
headers['server'] ?= null
if data?
headers['Content-Type'] ?= null
headers['Content-Length'] ?= Buffer.byteLength(data)
res.writeHead 200, @makeHeaders headers
res.write data if data?
res.end()
# Reuse broadcast socket for messages.
ssdpBroadcast: (type) ->
messages = for nt in @makeNotificationTypes()
@makeSsdpMessage('notify', nt: nt, nts: "ssdp:#{type}", host: null)
_.async.forEach messages,
(msg, cb) => @broadcastSocket.send msg, 0, msg.length, @ssdp.port, @ssdp.address, cb
(err) -> console.log err if err?
# UDP message queue (to avoid opening too many file descriptors).
ssdpSend: (messages, address, port) ->
@ssdpMessages.push { messages, address, port }
ssdpMessages: _.async.queue (task, queueCb) ->
{ messages, address, port } = task
socket = dgram.createSocket 'udp4'
socket.bind()
_.async.forEach messages,
(msg, cb) -> socket.send msg, 0, msg.length, port, address, cb
(err) ->
console.log err if err?
socket.close()
queueCb()
, 5 # Max concurrent sockets
# Listen for SSDP searches.
ssdpListener: (msg, rinfo) =>
# Wait between 0 and maxWait seconds before answering to avoid flooding
# control points.
answer = (address, port) =>
@ssdpSend(@makeSsdpMessage('ok',
st: st, ext: null
) for st in @makeNotificationTypes()
address
port)
answerAfter = (maxWait, address, port) ->
wait = Math.floor Math.random() * (parseInt(maxWait)) * 1000
# console.log "Replying to search request from #{address}:#{port} in #{wait}ms."
setTimeout answer, wait, address, port
respondTo = [ 'ssdp:all', 'upnp:rootdevice', @makeType(), @uuid ]
@parseRequest msg.toString(), rinfo, (err, req) ->
if req.method is 'M-SEARCH' and req.st in respondTo
answerAfter req.mx, req.address, req.port
# Notify the network about the device.
ssdpAnnounce: ->
# To "kill" any instances that haven't timed out on control points yet,
# first send `byebye` message.
@ssdpBroadcast 'byebye'
@ssdpBroadcast 'alive'
# Keep advertising the device at a random interval less than half of
# SSDP timeout, as per spec.
makeTimeout = => Math.floor Math.random() * ((@ssdp.timeout / 2) * 1000)
announce = =>
setTimeout =>
@ssdpBroadcast('alive')
announce()
, makeTimeout()
announce()
module.exports = Device
| 187791 | # Properties and functionality common for all devices,
# as specified in [UPnP Device Architecture 1.0] [1].
#
# [1]: http://upnp.org/sdcps-and-certification/standards/device-architecture-documents/
"use strict"
dgram = require 'dgram'
fs = require 'fs'
http = require 'http'
os = require 'os'
makeUuid = require 'node-uuid'
xml = require 'xml'
parser = require 'http-string-parser'
{ HttpError } = require '../errors'
_ = require '../utils'
# `Device` extends [`DeviceControlProtocol`](DeviceControlProtocol.html) with
# properties and methods common to devices and services.
DeviceControlProtocol = require '../DeviceControlProtocol'
class Device extends DeviceControlProtocol
constructor: (@name, address) ->
super
@address = address if address?
# Socket for listening and sending messages on SSDP broadcast address.
@broadcastSocket = dgram.createSocket 'udp4', @ssdpListener
@init()
# SSDP configuration.
ssdp:
address: '172.16.17.32' # Address and port for broadcast messages.
port: 1900
timeout: 1800
ttl: 4
# Asynchronous operations to get and set some device properties.
init: (cb) ->
_.async.parallel
address: (cb) => if @address? then cb null, @address else cb null, '0.0.0.0'
uuid: (cb) => @getUuid cb
port: (cb) =>
@httpServer = http.createServer(@httpListener)
@httpServer.listen 0, @address, (err) -> cb err, @address().port
(err, res) =>
return @emit 'error', err if err?
@uuid = "uuid:#{res.uuid}"
@address = res.address
@httpPort = res.port
@broadcastSocket.bind @ssdp.port, =>
@broadcastSocket.addMembership @ssdp.address
@broadcastSocket.setMulticastTTL @ssdp.ttl
@addServices()
@ssdpAnnounce()
console.log "Web server listening on http://#{@address}:#{@httpPort}"
@emit 'ready'
# When HTTP and SSDP servers are started, we add and initialize services.
addServices: ->
@services = {}
for serviceType in @serviceTypes
@services[serviceType] = new @serviceReferences[serviceType] @
# Generate HTTP headers from `customHeaders` object.
makeSsdpMessage: (reqType, customHeaders) ->
# These headers are included in all SSDP messages. Setting their value
# to `null` makes `makeHeaders()` add default values.
for header in [ 'cache-control', 'server', 'usn', 'location' ]
customHeaders[header] = null
headers = @makeHeaders customHeaders
# First line of message string.
# We build the string as an array first for `join()` convenience.
message =
if reqType is 'ok'
[ "HTTP/1.1 200 OK" ]
else
[ "#{reqType.toUpperCase()} * HTTP/1.1" ]
# Add header key/value pairs.
message.push "#{h.toUpperCase()}: #{v}" for h, v of headers
# Add carriage returns and newlines as specified by HTTP.
message.push '\r\n'
new Buffer message.join '\r\n'
# Generate an object with HTTP headers for HTTP and SSDP messages.
# Adds defaults and uppercases headers.
makeHeaders: (customHeaders) ->
# If key exists in `customHeaders` but is `null`, use these defaults.
defaultHeaders =
'cache-control': "max-age=#{@ssdp.timeout}"
'content-type': 'text/xml; charset="utf-8"'
ext: ''
host: "#{@ssdp.address}:#{@ssdp.port}"
location: @makeUrl '/device/description'
server: [
"#{os.type()}/#{os.release()}"
"UPnP/#{@upnp.version.join('.')}"
"#{@name}/1.0" ].join ' '
usn: @uuid +
if @uuid is (customHeaders.nt or customHeaders.st) then ''
else '::' + (customHeaders.nt or customHeaders.st)
headers = {}
for header of customHeaders
headers[header.toUpperCase()] = customHeaders[header] or defaultHeaders[header.toLowerCase()]
headers
# Make `nt` header values. 3 with device info, plus 1 per service.
makeNotificationTypes: ->
[ 'upnp:rootdevice', @uuid, @makeType() ]
.concat(@makeType.call service for name, service of @services)
# Parse SSDP headers using the HTTP module parser.
parseRequest: (msg, rinfo, cb) ->
req = parser.parseRequest(msg)
{ method, headers } = req
mx = null
st = null
for header of headers
switch header.toLowerCase()
when 'mx'
mx = headers[header]
when 'st'
st = headers[header]
{ address, port } = rinfo
cb null, { method, mx, st, address, port }
# Attempt UUID persistance of devices across restarts.
getUuid: (cb) ->
uuidFile = "#{__dirname}/../../upnp-uuid"
fs.readFile uuidFile, 'utf8', (err, file) =>
data = try JSON.parse file; catch e then {}
uuid = data[@type]?[@name]
unless uuid?
(data[@type]?={})[@name] = uuid = makeUuid()
fs.writeFile uuidFile, JSON.stringify data
# Always call back with UUID, existing or new.
cb null, uuid
# Build device description XML document.
buildDescription: ->
'<?xml version="1.0"?>' + xml [ { root: [
{ _attr: { xmlns: @makeNS() } }
{ specVersion: [ { major: @upnp.version[0] }
{ minor: @upnp.version[1] } ] }
{ device: [
{ deviceType: @makeType() }
{ friendlyName: @friendlyName ? "#{@name} @ #{os.hostname()}".substr(0, 64) }
{ manufacturer: @manufacturer ? 'UPnP Device for Node.js' }
{ modelName: @name.substr(0, 32) }
{ UDN: @uuid }
{ serviceList:
{ service: service.buildServiceElement() } for name, service of @services
} ] }
] } ]
# HTTP request listener
httpListener: (req, res) =>
# console.log "#{req.url} requested by #{req.headers['user-agent']} at #{req.client.remoteAddress}."
# HTTP request handler.
handler = (req, cb) =>
# URLs are like `/device|service/action/[serviceType]`.
[category, serviceType, action, id] = req.url.split('/')[1..]
switch category
when 'device'
cb null, @buildDescription()
when 'service'
@services[serviceType].requestHandler { action, req, id }, cb
else
cb new HttpError 404
handler req, (err, data, headers) =>
if err?
# See UDA for error details.
console.log "Responded with #{err.code}: #{err.message} for #{req.url}."
res.writeHead err.code, 'Content-Type': 'text/plain'
res.write "#{err.code} - #{err.message}"
else
# Make a header object for response.
# `null` means use `makeHeaders` function's default value.
headers ?= {}
headers['server'] ?= null
if data?
headers['Content-Type'] ?= null
headers['Content-Length'] ?= Buffer.byteLength(data)
res.writeHead 200, @makeHeaders headers
res.write data if data?
res.end()
# Reuse broadcast socket for messages.
ssdpBroadcast: (type) ->
messages = for nt in @makeNotificationTypes()
@makeSsdpMessage('notify', nt: nt, nts: "ssdp:#{type}", host: null)
_.async.forEach messages,
(msg, cb) => @broadcastSocket.send msg, 0, msg.length, @ssdp.port, @ssdp.address, cb
(err) -> console.log err if err?
# UDP message queue (to avoid opening too many file descriptors).
ssdpSend: (messages, address, port) ->
@ssdpMessages.push { messages, address, port }
ssdpMessages: _.async.queue (task, queueCb) ->
{ messages, address, port } = task
socket = dgram.createSocket 'udp4'
socket.bind()
_.async.forEach messages,
(msg, cb) -> socket.send msg, 0, msg.length, port, address, cb
(err) ->
console.log err if err?
socket.close()
queueCb()
, 5 # Max concurrent sockets
# Listen for SSDP searches.
ssdpListener: (msg, rinfo) =>
# Wait between 0 and maxWait seconds before answering to avoid flooding
# control points.
answer = (address, port) =>
@ssdpSend(@makeSsdpMessage('ok',
st: st, ext: null
) for st in @makeNotificationTypes()
address
port)
answerAfter = (maxWait, address, port) ->
wait = Math.floor Math.random() * (parseInt(maxWait)) * 1000
# console.log "Replying to search request from #{address}:#{port} in #{wait}ms."
setTimeout answer, wait, address, port
respondTo = [ 'ssdp:all', 'upnp:rootdevice', @makeType(), @uuid ]
@parseRequest msg.toString(), rinfo, (err, req) ->
if req.method is 'M-SEARCH' and req.st in respondTo
answerAfter req.mx, req.address, req.port
# Notify the network about the device.
ssdpAnnounce: ->
# To "kill" any instances that haven't timed out on control points yet,
# first send `byebye` message.
@ssdpBroadcast 'byebye'
@ssdpBroadcast 'alive'
# Keep advertising the device at a random interval less than half of
# SSDP timeout, as per spec.
makeTimeout = => Math.floor Math.random() * ((@ssdp.timeout / 2) * 1000)
announce = =>
setTimeout =>
@ssdpBroadcast('alive')
announce()
, makeTimeout()
announce()
module.exports = Device
| true | # Properties and functionality common for all devices,
# as specified in [UPnP Device Architecture 1.0] [1].
#
# [1]: http://upnp.org/sdcps-and-certification/standards/device-architecture-documents/
"use strict"
dgram = require 'dgram'
fs = require 'fs'
http = require 'http'
os = require 'os'
makeUuid = require 'node-uuid'
xml = require 'xml'
parser = require 'http-string-parser'
{ HttpError } = require '../errors'
_ = require '../utils'
# `Device` extends [`DeviceControlProtocol`](DeviceControlProtocol.html) with
# properties and methods common to devices and services.
DeviceControlProtocol = require '../DeviceControlProtocol'
class Device extends DeviceControlProtocol
constructor: (@name, address) ->
super
@address = address if address?
# Socket for listening and sending messages on SSDP broadcast address.
@broadcastSocket = dgram.createSocket 'udp4', @ssdpListener
@init()
# SSDP configuration.
ssdp:
address: 'PI:IP_ADDRESS:172.16.17.32END_PI' # Address and port for broadcast messages.
port: 1900
timeout: 1800
ttl: 4
# Asynchronous operations to get and set some device properties.
init: (cb) ->
_.async.parallel
address: (cb) => if @address? then cb null, @address else cb null, '0.0.0.0'
uuid: (cb) => @getUuid cb
port: (cb) =>
@httpServer = http.createServer(@httpListener)
@httpServer.listen 0, @address, (err) -> cb err, @address().port
(err, res) =>
return @emit 'error', err if err?
@uuid = "uuid:#{res.uuid}"
@address = res.address
@httpPort = res.port
@broadcastSocket.bind @ssdp.port, =>
@broadcastSocket.addMembership @ssdp.address
@broadcastSocket.setMulticastTTL @ssdp.ttl
@addServices()
@ssdpAnnounce()
console.log "Web server listening on http://#{@address}:#{@httpPort}"
@emit 'ready'
# When HTTP and SSDP servers are started, we add and initialize services.
addServices: ->
@services = {}
for serviceType in @serviceTypes
@services[serviceType] = new @serviceReferences[serviceType] @
# Generate HTTP headers from `customHeaders` object.
makeSsdpMessage: (reqType, customHeaders) ->
# These headers are included in all SSDP messages. Setting their value
# to `null` makes `makeHeaders()` add default values.
for header in [ 'cache-control', 'server', 'usn', 'location' ]
customHeaders[header] = null
headers = @makeHeaders customHeaders
# First line of message string.
# We build the string as an array first for `join()` convenience.
message =
if reqType is 'ok'
[ "HTTP/1.1 200 OK" ]
else
[ "#{reqType.toUpperCase()} * HTTP/1.1" ]
# Add header key/value pairs.
message.push "#{h.toUpperCase()}: #{v}" for h, v of headers
# Add carriage returns and newlines as specified by HTTP.
message.push '\r\n'
new Buffer message.join '\r\n'
# Generate an object with HTTP headers for HTTP and SSDP messages.
# Adds defaults and uppercases headers.
makeHeaders: (customHeaders) ->
# If key exists in `customHeaders` but is `null`, use these defaults.
defaultHeaders =
'cache-control': "max-age=#{@ssdp.timeout}"
'content-type': 'text/xml; charset="utf-8"'
ext: ''
host: "#{@ssdp.address}:#{@ssdp.port}"
location: @makeUrl '/device/description'
server: [
"#{os.type()}/#{os.release()}"
"UPnP/#{@upnp.version.join('.')}"
"#{@name}/1.0" ].join ' '
usn: @uuid +
if @uuid is (customHeaders.nt or customHeaders.st) then ''
else '::' + (customHeaders.nt or customHeaders.st)
headers = {}
for header of customHeaders
headers[header.toUpperCase()] = customHeaders[header] or defaultHeaders[header.toLowerCase()]
headers
# Make `nt` header values. 3 with device info, plus 1 per service.
makeNotificationTypes: ->
[ 'upnp:rootdevice', @uuid, @makeType() ]
.concat(@makeType.call service for name, service of @services)
# Parse SSDP headers using the HTTP module parser.
parseRequest: (msg, rinfo, cb) ->
req = parser.parseRequest(msg)
{ method, headers } = req
mx = null
st = null
for header of headers
switch header.toLowerCase()
when 'mx'
mx = headers[header]
when 'st'
st = headers[header]
{ address, port } = rinfo
cb null, { method, mx, st, address, port }
# Attempt UUID persistance of devices across restarts.
getUuid: (cb) ->
uuidFile = "#{__dirname}/../../upnp-uuid"
fs.readFile uuidFile, 'utf8', (err, file) =>
data = try JSON.parse file; catch e then {}
uuid = data[@type]?[@name]
unless uuid?
(data[@type]?={})[@name] = uuid = makeUuid()
fs.writeFile uuidFile, JSON.stringify data
# Always call back with UUID, existing or new.
cb null, uuid
# Build device description XML document.
buildDescription: ->
'<?xml version="1.0"?>' + xml [ { root: [
{ _attr: { xmlns: @makeNS() } }
{ specVersion: [ { major: @upnp.version[0] }
{ minor: @upnp.version[1] } ] }
{ device: [
{ deviceType: @makeType() }
{ friendlyName: @friendlyName ? "#{@name} @ #{os.hostname()}".substr(0, 64) }
{ manufacturer: @manufacturer ? 'UPnP Device for Node.js' }
{ modelName: @name.substr(0, 32) }
{ UDN: @uuid }
{ serviceList:
{ service: service.buildServiceElement() } for name, service of @services
} ] }
] } ]
# HTTP request listener
httpListener: (req, res) =>
# console.log "#{req.url} requested by #{req.headers['user-agent']} at #{req.client.remoteAddress}."
# HTTP request handler.
handler = (req, cb) =>
# URLs are like `/device|service/action/[serviceType]`.
[category, serviceType, action, id] = req.url.split('/')[1..]
switch category
when 'device'
cb null, @buildDescription()
when 'service'
@services[serviceType].requestHandler { action, req, id }, cb
else
cb new HttpError 404
handler req, (err, data, headers) =>
if err?
# See UDA for error details.
console.log "Responded with #{err.code}: #{err.message} for #{req.url}."
res.writeHead err.code, 'Content-Type': 'text/plain'
res.write "#{err.code} - #{err.message}"
else
# Make a header object for response.
# `null` means use `makeHeaders` function's default value.
headers ?= {}
headers['server'] ?= null
if data?
headers['Content-Type'] ?= null
headers['Content-Length'] ?= Buffer.byteLength(data)
res.writeHead 200, @makeHeaders headers
res.write data if data?
res.end()
# Reuse broadcast socket for messages.
ssdpBroadcast: (type) ->
messages = for nt in @makeNotificationTypes()
@makeSsdpMessage('notify', nt: nt, nts: "ssdp:#{type}", host: null)
_.async.forEach messages,
(msg, cb) => @broadcastSocket.send msg, 0, msg.length, @ssdp.port, @ssdp.address, cb
(err) -> console.log err if err?
# UDP message queue (to avoid opening too many file descriptors).
ssdpSend: (messages, address, port) ->
@ssdpMessages.push { messages, address, port }
ssdpMessages: _.async.queue (task, queueCb) ->
{ messages, address, port } = task
socket = dgram.createSocket 'udp4'
socket.bind()
_.async.forEach messages,
(msg, cb) -> socket.send msg, 0, msg.length, port, address, cb
(err) ->
console.log err if err?
socket.close()
queueCb()
, 5 # Max concurrent sockets
# Listen for SSDP searches.
ssdpListener: (msg, rinfo) =>
# Wait between 0 and maxWait seconds before answering to avoid flooding
# control points.
answer = (address, port) =>
@ssdpSend(@makeSsdpMessage('ok',
st: st, ext: null
) for st in @makeNotificationTypes()
address
port)
answerAfter = (maxWait, address, port) ->
wait = Math.floor Math.random() * (parseInt(maxWait)) * 1000
# console.log "Replying to search request from #{address}:#{port} in #{wait}ms."
setTimeout answer, wait, address, port
respondTo = [ 'ssdp:all', 'upnp:rootdevice', @makeType(), @uuid ]
@parseRequest msg.toString(), rinfo, (err, req) ->
if req.method is 'M-SEARCH' and req.st in respondTo
answerAfter req.mx, req.address, req.port
# Notify the network about the device.
ssdpAnnounce: ->
# To "kill" any instances that haven't timed out on control points yet,
# first send `byebye` message.
@ssdpBroadcast 'byebye'
@ssdpBroadcast 'alive'
# Keep advertising the device at a random interval less than half of
# SSDP timeout, as per spec.
makeTimeout = => Math.floor Math.random() * ((@ssdp.timeout / 2) * 1000)
announce = =>
setTimeout =>
@ssdpBroadcast('alive')
announce()
, makeTimeout()
announce()
module.exports = Device
|
[
{
"context": "# product =\n# name: 'Plum Jam'\n# producer: Meteor.users.findOne()._id\n# pro",
"end": 31,
"score": 0.9769915342330933,
"start": 23,
"tag": "NAME",
"value": "Plum Jam"
},
{
"context": "published).toBe true\n# expect(p.name).toBe 'Plum Jam'\n# expect(p... | tests/jasmine/server-disabled/integration/products.spec.coffee | redhead-web/meteor-foodcoop | 11 | # product =
# name: 'Plum Jam'
# producer: Meteor.users.findOne()._id
# producerName: Meteor.users.findOne().name
# price: 5
# unitOfMeasure: "400 g jar"
# categories: ["processed goods", "jam", "fruit", "vegan"]
# stocklevel: 50
# published: true
#
#
# describe "Products Collection", ->
#
# it "should be able to insert a very simple product", (done) ->
#
# Products.insert product, (err, id) ->
# expect(err).toBeNull()
#
# expect(id).toBeDefined()
#
# p = Products.findOne id
#
# expect(p.published).toBe true
# expect(p.name).toBe 'Plum Jam'
# expect(p.price).toBe 5
# done()
#
# it "should decrease stock levels when a user adds an item to their cart", (done) ->
# id = Products.insert product
#
# Meteor.call "addToCart", product, 10, (error) ->
# expect error
# .toBeUndefined()
# done()
| 186308 | # product =
# name: '<NAME>'
# producer: Meteor.users.findOne()._id
# producerName: Meteor.users.findOne().name
# price: 5
# unitOfMeasure: "400 g jar"
# categories: ["processed goods", "jam", "fruit", "vegan"]
# stocklevel: 50
# published: true
#
#
# describe "Products Collection", ->
#
# it "should be able to insert a very simple product", (done) ->
#
# Products.insert product, (err, id) ->
# expect(err).toBeNull()
#
# expect(id).toBeDefined()
#
# p = Products.findOne id
#
# expect(p.published).toBe true
# expect(p.name).toBe '<NAME>'
# expect(p.price).toBe 5
# done()
#
# it "should decrease stock levels when a user adds an item to their cart", (done) ->
# id = Products.insert product
#
# Meteor.call "addToCart", product, 10, (error) ->
# expect error
# .toBeUndefined()
# done()
| true | # product =
# name: 'PI:NAME:<NAME>END_PI'
# producer: Meteor.users.findOne()._id
# producerName: Meteor.users.findOne().name
# price: 5
# unitOfMeasure: "400 g jar"
# categories: ["processed goods", "jam", "fruit", "vegan"]
# stocklevel: 50
# published: true
#
#
# describe "Products Collection", ->
#
# it "should be able to insert a very simple product", (done) ->
#
# Products.insert product, (err, id) ->
# expect(err).toBeNull()
#
# expect(id).toBeDefined()
#
# p = Products.findOne id
#
# expect(p.published).toBe true
# expect(p.name).toBe 'PI:NAME:<NAME>END_PI'
# expect(p.price).toBe 5
# done()
#
# it "should decrease stock levels when a user adds an item to their cart", (done) ->
# id = Products.insert product
#
# Meteor.call "addToCart", product, 10, (error) ->
# expect error
# .toBeUndefined()
# done()
|
[
{
"context": "ningPinAttempt: 2\n\n # M2FA\n _m2fa:\n pubKey: \"04\"+\"78c0837ded209265ea8131283585f71c5bddf7ffafe04ccdd",
"end": 500,
"score": 0.8641830086708069,
"start": 496,
"tag": "KEY",
"value": "04\"+"
},
{
"context": "inAttempt: 2\n\n # M2FA\n _m2fa:\n pubKey: \"04\... | app/spec/utils/dongle/mock_dongle.coffee | romanornr/ledger-wallet-crw | 173 |
States =
# Dongle juste created, not initialized.
UNDEFINED: undefined
# PIN required.
LOCKED: 'locked'
# PIN has been verified.
UNLOCKED: 'unlocked'
# No seed present, dongle must be setup.
BLANK: 'blank'
# Dongle has been unplugged.
DISCONNECTED: 'disconnected'
# An error appended, user must unplug/replug dongle.
ERROR: 'error'
Errors = @ledger.errors
class ledger.dongle.MockDongle extends EventEmitter
_xpubs: []
_remainingPinAttempt: 2
# M2FA
_m2fa:
pubKey: "04"+"78c0837ded209265ea8131283585f71c5bddf7ffafe04ccddb8fe10b3edc7833"+"d6dee70c3b9040e1a1a01c5cc04fcbf9b4de612e688d09245ef5f9135413cc1d"
privKey: "80"+"dbd39adafe3a007706e61a17e0c56849146cfe95849afef7ede15a43a1984491"+"7e960af3"
sessionKey: ''
pairingKeyHex: ''
nonceHex: ''
challengeIndexes: ''
challengeResponses: ''
keycard: ''
constructor: (pin, seed, pairingKeyHex = undefined, isInBootloaderMode = no) ->
super
@_m2fa = _.clone(@_m2fa)
@_m2fa.pairingKeyHex = pairingKeyHex
@_isInBootloaderMode = isInBootloaderMode
@state = States.UNDEFINED
@_setState(States.BLANK)
@_setup(pin, seed, yes) if pin? and seed?
isInBootloaderMode: -> @_isInBootloaderMode
disconnect: () ->
@emit 'disconnected', @
@_setState(States.DISCONNECTED)
connect: () ->
@emit 'connected', @
@_setState(States.LOCKED)
# Return asynchronosly state. Wait until a state is set.
# @param [Function] callback Optional argument
# @return [Q.Promise]
getState: (callback=undefined) -> ledger.defer(callback).resolve(@state).promise
# @return [Integer] Firmware version, 0x20010000010f for example.
getIntFirmwareVersion: ->
parseInt(0x0001040d.toString(HEX), 16)
###
Gets the raw version {ByteString} of the dongle.
@param [Boolean] isInBootLoaderMode Must be true if the current dongle is in bootloader mode.
@param [Boolean] forceBl Force the call in BootLoader mode
@param [Function] callback Called once the version is retrieved. The callback must be prototyped like size `(version, error) ->`
@return [Q.Promise]
###
getRawFirmwareVersion: (isInBootLoaderMode, forceBl=no, checkHiddenReloader = no, callback=undefined) ->
d = ledger.defer(callback)
try
d.resolve ['00000020', '00010001']
catch
d.rejectWithError(ledger.errors.UnknowError, error)
console.error("Fail to getRawFirmwareVersion :", error)
d.promise
# @param [String] pin ASCII encoded
# @param [Function] callback Optional argument
# @return [Q.Promise]
unlockWithPinCode: (pin, callback=undefined) ->
Errors.throw(Errors.DongleAlreadyUnlock) if @state isnt States.LOCKED
d = ledger.defer(callback)
if pin is @_pin
@_setState(States.UNLOCKED)
@_remainingPinAttempt = 3
d.resolve()
else
console.error("Fail to unlockWithPinCode 1 :", '63c' + @_remainingPinAttempt)
error = @_handleErrorCode('63c' + @_remainingPinAttempt)
@_remainingPinAttempt -= 1
d.reject(error)
d.promise
lock: () ->
if @state isnt ledger.dongle.States.BLANK and @state?
@_setState(States.LOCKED)
# @return [Q.Promise] resolve with a Number, reject with a ledger Error.
getRemainingPinAttempt: (callback=undefined) ->
d = ledger.defer(callback)
if @_remainingPinAttempt < 0
d.resolve(@_remainingPinAttempt)
else
d.reject(@_handleErrorCode('6985'))
d.promise
setup: (pin, restoreSeed, callback=undefined) ->
@_setup(pin, restoreSeed, no, callback)
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise]
getPublicAddress: (path, callback=undefined) ->
d = ledger.defer(callback)
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED && @state isnt States.UNDEFINED
res = @getPublicAddressSync(path)
_.defer -> d.resolve(res)
return d.promise
getPublicAddressSync: (path) ->
node = @_getNodeFromPath(path)
bitcoinAddress: new ByteString node.getAddress().toString(), ASCII
chainCode: new ByteString (Convert.toHexByte(n) for n in node.chainCode).join(''), HEX
publicKey: new ByteString do (->
node.pubKey.compressed = false
node.pubKey.toHex()
)
, HEX
signMessage: (message, {path, pubKey}, callback=undefined) ->
d = ledger.defer(callback)
node = @_getNodeFromPath(path)
d.resolve bitcoin.Message.sign(node.privKey, message).toString('base64')
d.promise
getBitIdAddress: (subpath=undefined, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state isnt States.UNLOCKED
[subpath, callback] = [callback, subpath] if ! callback && typeof subpath == 'function'
path = ledger.dongle.BitIdRootPath
path += "/#{subpath}" if subpath?
@getPublicAddress(path, callback)
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
getExtendedPublicKey: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
d = ledger.defer(callback)
return d.resolve(@_xpubs[path]).promise if @_xpubs[path]?
xpub = new ledger.wallet.ExtendedPublicKey(@, path)
xpub.initialize () =>
@_xpubs[path] = xpub
d.resolve(xpub)
d.promise
isCertified: (callback=undefined) ->
d = ledger.defer(callback)
d.resolve(@)
d.promise
isBetaCertified: (callback=undefined) ->
d = ledger.defer(callback)
d.resolve(@)
d.promise
# @return [Q.Promise]
isFirmwareUpdateAvailable: (callback=undefined) -> ledger.defer(callback).resolve(false).promise
###
@param [Array<Object>] inputs
@param [Array] associatedKeysets
@param changePath
@param [String] recipientAddress
@param [Amount] amount
@param [Amount] fee
@param [Integer] lockTime
@param [Integer] sighashType
@param [String] authorization hex encoded
@param [Object] resumeData
@return [Q.Promise] Resolve with resumeData
###
createPaymentTransaction: (inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData, network) ->
d = ledger.defer()
result = {}
if _.isEmpty resumeData
txb = new bitcoin.TransactionBuilder()
# Create rawTxs from inputs
rawTxs = for input in inputs
[splittedTx, outputIndex] = input
rawTxBuffer = splittedTx.version
rawTxBuffer = rawTxBuffer.concat(new ByteString(Convert.toHexByte(splittedTx.inputs.length), HEX))
for input in splittedTx.inputs
rawTxBuffer = rawTxBuffer.concat(input.prevout).concat(new ByteString(Convert.toHexByte(input.script.length), HEX)).concat(input.script).concat(input.sequence)
rawTxBuffer = rawTxBuffer.concat(new ByteString(Convert.toHexByte(splittedTx.outputs.length), HEX))
for output in splittedTx.outputs
rawTxBuffer = rawTxBuffer.concat(output.amount).concat(new ByteString(Convert.toHexByte(output.script.length), HEX)).concat(output.script)
rawTxBuffer = rawTxBuffer.concat(splittedTx.locktime)
[rawTxBuffer, outputIndex]
values = []
balance = Bitcoin.BigInteger.valueOf(0)
# Add Input
for [rawTx, outputIndex] in rawTxs
tx = bitcoin.Transaction.fromHex(rawTx.toString())
txb.addInput(tx, outputIndex)
values.push(tx.outs[outputIndex].value)
# Create balance
for val, i in values
balance = balance.add Bitcoin.BigInteger.valueOf(val)
# Create change
change = (balance.toString() - fees.toSatoshiNumber()) - amount.toSatoshiNumber()
# Create scriptPubKey
scriptPubKeyStart = Convert.toHexByte(bitcoin.opcodes.OP_DUP) + Convert.toHexByte(bitcoin.opcodes.OP_HASH160) + 14
scriptPubKeyEnd = Convert.toHexByte(bitcoin.opcodes.OP_EQUALVERIFY) + Convert.toHexByte(bitcoin.opcodes.OP_CHECKSIG)
# recipient addr
scriptPubKey = bitcoin.Script.fromHex(scriptPubKeyStart + @_getPubKeyHashFromBase58(recipientAddress).toString() + scriptPubKeyEnd)
txb.addOutput(scriptPubKey, amount.toSatoshiNumber())
# change addr
scriptPubKey = bitcoin.Script.fromHex(scriptPubKeyStart + @_getPubKeyHashFromBase58(@_getNodeFromPath(changePath).getAddress().toString()).toString() + scriptPubKeyEnd)
if change isnt 0
txb.addOutput(scriptPubKey, change)
# Signature
for path, index in associatedKeysets
txb.sign(index, @_getNodeFromPath(associatedKeysets[index]).privKey)
# Keycard
keycard = ledger.keycard.generateKeycardFromSeed('dfaeee53c3d280707bbe27720d522ac1')
charsQuestion = []
indexes = [] # charQuestion indexes of recipient address
charsResponse = []
for i in [0..3]
randomNum = _.random recipientAddress.length - 1
charsQuestion.push recipientAddress.charAt randomNum
charsResponse.push keycard[charsQuestion[i]]
indexes.push Convert.toHexByte randomNum
result.authorizationReference = indexes.join('')
result.publicKeys = []
result.publicKeys.push recipientAddress
result.txb = txb
result.charsResponse = "0" + charsResponse.join('0')
# M2fa
if @_m2fa.pairingKeyHex?
amount = '0000000000000000' + amount._value.toRadix(16)
amount = amount.substr(amount.length - 16, 16)
fees = '0000000000000000' + fees._value.toRadix(16)
fees = fees.substr(fees.length - 16, 16)
change = '0000000000000000' + new BigInteger(change.toString()).toRadix(16)
change = change.substr(change.length - 16, 16)
sizeAddress = Convert.toHexByte recipientAddress.length
pin = new ByteString(charsResponse.join(''), ASCII).toString(HEX)
m2faData = pin + amount + fees + change + sizeAddress + (new ByteString(recipientAddress, ASCII).toString(HEX))
padding = m2faData.length % 8
m2faData = _.str.rpad m2faData, m2faData.length + (8 - padding), '0'
# Encrypt
cipher = new JSUCrypt.cipher.DES(JSUCrypt.padder.None , JSUCrypt.cipher.MODE_CBC)
key = new JSUCrypt.key.DESKey(@_m2fa.pairingKeyHex)
cipher.init(key, JSUCrypt.cipher.MODE_ENCRYPT)
m2faData = cipher.update(m2faData)
m2faDataHex = (Convert.toHexByte(v) for v in m2faData).join('')
# Set authorizations
result.authorizationRequired = 3
result.authorizationPaired = m2faDataHex
result.indexesKeyCard = '04' + indexes.join('') + m2faDataHex
else
result.authorizationRequired = 2
result.authorizationPaired = undefined
result.indexesKeyCard = indexes.join('')
l 'result', result
l 'm2fa', @_m2fa
result
else
l 'resumeData', resumeData
# Check keycard and m2fa validity
m2faResponse = new ByteString((v.charAt(1) for v in resumeData.charsResponse.match(/.{2}/g)).join(''), ASCII).toString(HEX)
if resumeData.charsResponse isnt authorization and m2faResponse isnt authorization
_.delay (-> d.rejectWithError(Errors.WrongPinCode)), 1000
# Build raw tx
try
result = resumeData.txb.build().toHex()
catch
_.delay (-> d.rejectWithError(Errors.SignatureError)), 1000
_.delay (-> d.resolve(result)), 1000 # Dirty delay fix, odd but necessary
d.promise
splitTransaction: (input) ->
bitExt = new BitcoinExternal()
bitExt.splitTransaction(new ByteString(input.raw, HEX))
# @param [String] pubKey public key, hex encoded. # Remote screen uncompressed public key - 65 length
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve with a 32 bytes length pairing blob hex encoded. # Pairing blob : 8 bytes random nonce and (4 bytes keycard challenge + 16 bytes pairing key) encrypted by the session key # Challenge
initiateSecureScreen: (pubKey, callback=undefined) ->
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! pubKey.match(/^[0-9A-Fa-f]{130}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid pubKey : #{pubKey}")
else
###
The remote screen public key is sent to the dongle, which generates
a cleartext random 8 bytes nonce,
a 4 bytes challenge on the printed keycard
and a random 16 bytes 3DES-2 pairing key, concatenated and encrypted using 3DES CBC and the generated session key
###
# ECDH key exchange
ecdhdomain = JSUCrypt.ECFp.getEcDomainByName("secp256k1")
ecdhprivkey = new JSUCrypt.key.EcFpPrivateKey(256, ecdhdomain, @_m2fa.privKey.match(/^(\w{2})(\w{64})(01)?(\w{8})$/)[2])
ecdh = new JSUCrypt.keyagreement.ECDH_SVDP(ecdhprivkey)
aKey = pubKey.match(/^(\w{2})(\w{64})(\w{64})$/)
secret = ecdh.generate(new JSUCrypt.ECFp.AffinePoint(aKey[2], aKey[3], ecdhdomain.curve)) # 32 bytes secret is obtained
# Split into two 16 bytes components S1 and S2. S1 and S2 are XORed to produce a 16 bytes 3DES-2 session key
@_m2fa.sessionKey = (Convert.toHexByte(secret[i] ^ secret[16+i]) for i in [0...16]).join('')
# Challenge (keycard indexes) - 4 bytes
@_m2fa.keycard = ledger.keycard.generateKeycardFromSeed('dfaeee53c3d280707bbe27720d522ac1')
@_m2fa.challengeIndexes = ''
@_m2fa.challengeResponses = ''
for i in [0..3]
num = _.random(ledger.crypto.Base58.concatAlphabet().length - 1)
@_m2fa.challengeIndexes += Convert.toHexByte(ledger.crypto.Base58.concatAlphabet().charCodeAt(num) - 0x30)
@_m2fa.challengeResponses += '0' + @_m2fa.keycard[ledger.crypto.Base58.concatAlphabet().charAt(num)]
# Crypted challenge - challenheHex + PairingKeyHex - 24 bytes
blob = @_m2fa.challengeIndexes + @_m2fa.pairingKeyHex + "00000000"
cipher = new JSUCrypt.cipher.DES(JSUCrypt.padder.None, JSUCrypt.cipher.MODE_CBC)
key = new JSUCrypt.key.DESKey(@_m2fa.sessionKey)
cipher.init(key, JSUCrypt.cipher.MODE_ENCRYPT)
cryptedBlob = cipher.update(blob)
cryptedBlobHex = (Convert.toHexByte(v) for v in cryptedBlob).join('')
# 8 bytes Nonce
nonce = crypto.getRandomValues new Uint8Array(8)
@_m2fa.nonceHex = (Convert.toHexByte(v) for v in nonce).join('')
# concat Nonce + (challenge + pairingKey)
res = @_m2fa.nonceHex + cryptedBlobHex
d.resolve(res)
d.promise
# @param [String] resp challenge response, hex encoded. #Encrypted nonce and challenge response + padding - 16 length
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
confirmSecureScreen: (challengeResp, callback=undefined) ->
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! challengeResp.match(/^[0-9A-Fa-f]{32}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid challenge resp : #{challengeResp}")
else
# Decipher
cipher = new JSUCrypt.cipher.DES(JSUCrypt.padder.None, JSUCrypt.cipher.MODE_CBC)
key = new JSUCrypt.key.DESKey(@_m2fa.sessionKey)
cipher.init(key, JSUCrypt.cipher.MODE_DECRYPT)
challengeRespDecipher = cipher.update(challengeResp)
challengeRespDecipher = (Convert.toHexByte(v) for v in challengeRespDecipher).join('')
#l 'challengeRespDecipher', challengeRespDecipher
# Verify Challenge
[nonce, challenge, padding] = [challengeRespDecipher[0...16], challengeRespDecipher[16...24], challengeRespDecipher[24..-1]]
#l [nonce, challenge, padding]
if nonce is @_m2fa.nonceHex and challenge is @_m2fa.challengeResponses
@_clearPairingInfo()
d.resolve()
else
@_clearPairingInfo(yes)
d.reject('Pairing fail - Invalid status 1 - 6a80')
d.promise
getStringFirmwareVersion: ->
'1.0.1'
_generatePairingKeyHex: ->
pairingKey = crypto.getRandomValues new Uint8Array(16)
@_m2fa.pairingKeyHex = (Convert.toHexByte(v) for v in pairingKey).join('')
_clearPairingInfo: (isErr) ->
if isErr
@_m2fa = _.omit(@_m2fa, ['challengeIndexes', 'sessionKey', 'nonceHex', 'challengeIndexes', 'challengeResponses', 'keycard', 'pairingKeyHex'])
else
@_m2fa = _.omit(@_m2fa, ['challengeIndexes', 'sessionKey', 'nonceHex', 'challengeIndexes', 'challengeResponses', 'keycard'])
# Get PubKeyHash from base58
_getPubKeyHashFromBase58: (addr) ->
arr = ledger.crypto.Base58.decode(addr)
buffer = JSUCrypt.utils.byteArrayToHexStr(arr)
x = new ByteString(buffer, HEX)
pubKeyHash = x.bytes(0, x.length - 4).bytes(1) # remove network 1 byte at the beginning, remove checksum 4 bytes at the end
pubKeyHash
_setState: (newState, args...) ->
[@state, oldState] = [newState, @state]
@emit "state:#{@state}", @state, args...
@emit 'state:changed', @state
_setup: (pin, restoreSeed, isPowerCycle, callback=undefined) ->
d = ledger.defer(callback)
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
[restoreSeed, callback] = [callback, restoreSeed] if ! callback && typeof restoreSeed == 'function'
Throw new Error('Setup need a seed') if not restoreSeed?
@_pin = pin
@_masterNode = bitcoin.HDNode.fromSeedHex restoreSeed, ledger.config.network.bitcoinjs
# Validate seed
if restoreSeed?
bytesSeed = new ByteString(restoreSeed, HEX)
if bytesSeed.length != 64
e('Invalid seed :', restoreSeed)
if isPowerCycle then @_setState States.LOCKED else _.defer => @_setState States.DISCONNECTED
d.resolve()
return d.promise
_getNodeFromPath: (path) ->
path = path.split('/')
node = @_masterNode
for item in path
[index, hardened] = item.split "'"
node = if hardened? then node.deriveHardened parseInt(index) else node = node.derive index
node
# Set appropriate state, and return corresponding Error
# @param [String] errorCode
# @return [Error]
_handleErrorCode: (errorCode) ->
if errorCode.match("6982") # Pin required
@_setState(States.LOCKED)
error = Errors.new(Errors.DongleLocked, errorCode)
else if errorCode.match("6985") # Error ?
@_setState(States.BLANK)
error = Errors.new(Errors.BlankDongle, errorCode)
else if errorCode.match("6faa")
@_setState(States.ERROR)
error = Errors.new(Errors.UnknowError, errorCode)
else if errorCode.match(/63c\d/)
error = Errors.new(Errors.WrongPinCode, errorCode)
error.retryCount = parseInt(errorCode.substr(-1))
if error.retryCount == 0
@_setState(States.BLANK)
error.code = Errors.DongleLocked
else
@_setState(States.ERROR)
else
@_setState(States.UnknowError)
error = Errors.new(Errors.UnknowError, errorCode)
l 'ERROR', error
return error | 124624 |
States =
# Dongle juste created, not initialized.
UNDEFINED: undefined
# PIN required.
LOCKED: 'locked'
# PIN has been verified.
UNLOCKED: 'unlocked'
# No seed present, dongle must be setup.
BLANK: 'blank'
# Dongle has been unplugged.
DISCONNECTED: 'disconnected'
# An error appended, user must unplug/replug dongle.
ERROR: 'error'
Errors = @ledger.errors
class ledger.dongle.MockDongle extends EventEmitter
_xpubs: []
_remainingPinAttempt: 2
# M2FA
_m2fa:
pubKey: "<KEY>"<KEY>"<KEY>"
privKey: "<KEY>"<KEY>"+"<KEY>"
sessionKey: ''
pairingKeyHex: ''
nonceHex: ''
challengeIndexes: ''
challengeResponses: ''
keycard: ''
constructor: (pin, seed, pairingKeyHex = undefined, isInBootloaderMode = no) ->
super
@_m2fa = _.clone(@_m2fa)
@_m2fa.pairingKeyHex = pairingKeyHex
@_isInBootloaderMode = isInBootloaderMode
@state = States.UNDEFINED
@_setState(States.BLANK)
@_setup(pin, seed, yes) if pin? and seed?
isInBootloaderMode: -> @_isInBootloaderMode
disconnect: () ->
@emit 'disconnected', @
@_setState(States.DISCONNECTED)
connect: () ->
@emit 'connected', @
@_setState(States.LOCKED)
# Return asynchronosly state. Wait until a state is set.
# @param [Function] callback Optional argument
# @return [Q.Promise]
getState: (callback=undefined) -> ledger.defer(callback).resolve(@state).promise
# @return [Integer] Firmware version, 0x20010000010f for example.
getIntFirmwareVersion: ->
parseInt(0x0001040d.toString(HEX), 16)
###
Gets the raw version {ByteString} of the dongle.
@param [Boolean] isInBootLoaderMode Must be true if the current dongle is in bootloader mode.
@param [Boolean] forceBl Force the call in BootLoader mode
@param [Function] callback Called once the version is retrieved. The callback must be prototyped like size `(version, error) ->`
@return [Q.Promise]
###
getRawFirmwareVersion: (isInBootLoaderMode, forceBl=no, checkHiddenReloader = no, callback=undefined) ->
d = ledger.defer(callback)
try
d.resolve ['00000020', '00010001']
catch
d.rejectWithError(ledger.errors.UnknowError, error)
console.error("Fail to getRawFirmwareVersion :", error)
d.promise
# @param [String] pin ASCII encoded
# @param [Function] callback Optional argument
# @return [Q.Promise]
unlockWithPinCode: (pin, callback=undefined) ->
Errors.throw(Errors.DongleAlreadyUnlock) if @state isnt States.LOCKED
d = ledger.defer(callback)
if pin is @_pin
@_setState(States.UNLOCKED)
@_remainingPinAttempt = 3
d.resolve()
else
console.error("Fail to unlockWithPinCode 1 :", '63c' + @_remainingPinAttempt)
error = @_handleErrorCode('63c' + @_remainingPinAttempt)
@_remainingPinAttempt -= 1
d.reject(error)
d.promise
lock: () ->
if @state isnt ledger.dongle.States.BLANK and @state?
@_setState(States.LOCKED)
# @return [Q.Promise] resolve with a Number, reject with a ledger Error.
getRemainingPinAttempt: (callback=undefined) ->
d = ledger.defer(callback)
if @_remainingPinAttempt < 0
d.resolve(@_remainingPinAttempt)
else
d.reject(@_handleErrorCode('6985'))
d.promise
setup: (pin, restoreSeed, callback=undefined) ->
@_setup(pin, restoreSeed, no, callback)
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise]
getPublicAddress: (path, callback=undefined) ->
d = ledger.defer(callback)
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED && @state isnt States.UNDEFINED
res = @getPublicAddressSync(path)
_.defer -> d.resolve(res)
return d.promise
getPublicAddressSync: (path) ->
node = @_getNodeFromPath(path)
bitcoinAddress: new ByteString node.getAddress().toString(), ASCII
chainCode: new ByteString (Convert.toHexByte(n) for n in node.chainCode).join(''), HEX
publicKey: new ByteString do (->
node.pubKey.compressed = false
node.pubKey.toHex()
)
, HEX
signMessage: (message, {path, pubKey}, callback=undefined) ->
d = ledger.defer(callback)
node = @_getNodeFromPath(path)
d.resolve bitcoin.Message.sign(node.privKey, message).toString('base64')
d.promise
getBitIdAddress: (subpath=undefined, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state isnt States.UNLOCKED
[subpath, callback] = [callback, subpath] if ! callback && typeof subpath == 'function'
path = ledger.dongle.BitIdRootPath
path += "/#{subpath}" if subpath?
@getPublicAddress(path, callback)
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
getExtendedPublicKey: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
d = ledger.defer(callback)
return d.resolve(@_xpubs[path]).promise if @_xpubs[path]?
xpub = new ledger.wallet.ExtendedPublicKey(@, path)
xpub.initialize () =>
@_xpubs[path] = xpub
d.resolve(xpub)
d.promise
isCertified: (callback=undefined) ->
d = ledger.defer(callback)
d.resolve(@)
d.promise
isBetaCertified: (callback=undefined) ->
d = ledger.defer(callback)
d.resolve(@)
d.promise
# @return [Q.Promise]
isFirmwareUpdateAvailable: (callback=undefined) -> ledger.defer(callback).resolve(false).promise
###
@param [Array<Object>] inputs
@param [Array] associatedKeysets
@param changePath
@param [String] recipientAddress
@param [Amount] amount
@param [Amount] fee
@param [Integer] lockTime
@param [Integer] sighashType
@param [String] authorization hex encoded
@param [Object] resumeData
@return [Q.Promise] Resolve with resumeData
###
createPaymentTransaction: (inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData, network) ->
d = ledger.defer()
result = {}
if _.isEmpty resumeData
txb = new bitcoin.TransactionBuilder()
# Create rawTxs from inputs
rawTxs = for input in inputs
[splittedTx, outputIndex] = input
rawTxBuffer = splittedTx.version
rawTxBuffer = rawTxBuffer.concat(new ByteString(Convert.toHexByte(splittedTx.inputs.length), HEX))
for input in splittedTx.inputs
rawTxBuffer = rawTxBuffer.concat(input.prevout).concat(new ByteString(Convert.toHexByte(input.script.length), HEX)).concat(input.script).concat(input.sequence)
rawTxBuffer = rawTxBuffer.concat(new ByteString(Convert.toHexByte(splittedTx.outputs.length), HEX))
for output in splittedTx.outputs
rawTxBuffer = rawTxBuffer.concat(output.amount).concat(new ByteString(Convert.toHexByte(output.script.length), HEX)).concat(output.script)
rawTxBuffer = rawTxBuffer.concat(splittedTx.locktime)
[rawTxBuffer, outputIndex]
values = []
balance = Bitcoin.BigInteger.valueOf(0)
# Add Input
for [rawTx, outputIndex] in rawTxs
tx = bitcoin.Transaction.fromHex(rawTx.toString())
txb.addInput(tx, outputIndex)
values.push(tx.outs[outputIndex].value)
# Create balance
for val, i in values
balance = balance.add Bitcoin.BigInteger.valueOf(val)
# Create change
change = (balance.toString() - fees.toSatoshiNumber()) - amount.toSatoshiNumber()
# Create scriptPubKey
scriptPubKeyStart = Convert.toHexByte(bitcoin.opcodes.OP_DUP) + Convert.toHexByte(bitcoin.opcodes.OP_HASH160) + 14
scriptPubKeyEnd = Convert.toHexByte(bitcoin.opcodes.OP_EQUALVERIFY) + Convert.toHexByte(bitcoin.opcodes.OP_CHECKSIG)
# recipient addr
scriptPubKey = bitcoin.Script.fromHex(scriptPubKeyStart + @_getPubKeyHashFromBase58(recipientAddress).toString() + scriptPubKeyEnd)
txb.addOutput(scriptPubKey, amount.toSatoshiNumber())
# change addr
scriptPubKey = bitcoin.Script.fromHex(scriptPubKeyStart + @_getPubKeyHashFromBase58(@_getNodeFromPath(changePath).getAddress().toString()).toString() + scriptPubKeyEnd)
if change isnt 0
txb.addOutput(scriptPubKey, change)
# Signature
for path, index in associatedKeysets
txb.sign(index, @_getNodeFromPath(associatedKeysets[index]).privKey)
# Keycard
keycard = ledger.keycard.generateKeycardFromSeed('<KEY>')
charsQuestion = []
indexes = [] # charQuestion indexes of recipient address
charsResponse = []
for i in [0..3]
randomNum = _.random recipientAddress.length - 1
charsQuestion.push recipientAddress.charAt randomNum
charsResponse.push keycard[charsQuestion[i]]
indexes.push Convert.toHexByte randomNum
result.authorizationReference = indexes.join('')
result.publicKeys = []
result.publicKeys.push recipientAddress
result.txb = txb
result.charsResponse = "0" + charsResponse.join('0')
# M2fa
if @_m2fa.pairingKeyHex?
amount = '0000000000000000' + amount._value.toRadix(16)
amount = amount.substr(amount.length - 16, 16)
fees = '0000000000000000' + fees._value.toRadix(16)
fees = fees.substr(fees.length - 16, 16)
change = '0000000000000000' + new BigInteger(change.toString()).toRadix(16)
change = change.substr(change.length - 16, 16)
sizeAddress = Convert.toHexByte recipientAddress.length
pin = new ByteString(charsResponse.join(''), ASCII).toString(HEX)
m2faData = pin + amount + fees + change + sizeAddress + (new ByteString(recipientAddress, ASCII).toString(HEX))
padding = m2faData.length % 8
m2faData = _.str.rpad m2faData, m2faData.length + (8 - padding), '0'
# Encrypt
cipher = new JSUCrypt.cipher.DES(JSUCrypt.padder.None , JSUCrypt.cipher.MODE_CBC)
key = new JSUCrypt.key.DESKey(@_m2fa.pairingKeyHex)
cipher.init(key, JSUCrypt.cipher.MODE_ENCRYPT)
m2faData = cipher.update(m2faData)
m2faDataHex = (Convert.toHexByte(v) for v in m2faData).join('')
# Set authorizations
result.authorizationRequired = 3
result.authorizationPaired = m2faDataHex
result.indexesKeyCard = '04' + indexes.join('') + m2faDataHex
else
result.authorizationRequired = 2
result.authorizationPaired = undefined
result.indexesKeyCard = indexes.join('')
l 'result', result
l 'm2fa', @_m2fa
result
else
l 'resumeData', resumeData
# Check keycard and m2fa validity
m2faResponse = new ByteString((v.charAt(1) for v in resumeData.charsResponse.match(/.{2}/g)).join(''), ASCII).toString(HEX)
if resumeData.charsResponse isnt authorization and m2faResponse isnt authorization
_.delay (-> d.rejectWithError(Errors.WrongPinCode)), 1000
# Build raw tx
try
result = resumeData.txb.build().toHex()
catch
_.delay (-> d.rejectWithError(Errors.SignatureError)), 1000
_.delay (-> d.resolve(result)), 1000 # Dirty delay fix, odd but necessary
d.promise
splitTransaction: (input) ->
bitExt = new BitcoinExternal()
bitExt.splitTransaction(new ByteString(input.raw, HEX))
# @param [String] pubKey public key, hex encoded. # Remote screen uncompressed public key - 65 length
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve with a 32 bytes length pairing blob hex encoded. # Pairing blob : 8 bytes random nonce and (4 bytes keycard challenge + 16 bytes pairing key) encrypted by the session key # Challenge
initiateSecureScreen: (pubKey, callback=undefined) ->
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! pubKey.match(/^[0-9A-Fa-f]{130}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid pubKey : #{pubKey}")
else
###
The remote screen public key is sent to the dongle, which generates
a cleartext random 8 bytes nonce,
a 4 bytes challenge on the printed keycard
and a random 16 bytes 3DES-2 pairing key, concatenated and encrypted using 3DES CBC and the generated session key
###
# ECDH key exchange
ecdhdomain = JSUCrypt.ECFp.getEcDomainByName("secp256k1")
ecdhprivkey = new JSUCrypt.key.EcFpPrivateKey(256, ecdhdomain, @_m2fa.privKey.match(/^(\w{2})(\w{64})(01)?(\w{8})$/)[2])
ecdh = new JSUCrypt.keyagreement.ECDH_SVDP(ecdhprivkey)
aKey = pubKey.match(/^(\w{2})(\w{64})(\w{64})$/)
secret = ecdh.generate(new JSUCrypt.ECFp.AffinePoint(aKey[2], aKey[3], ecdhdomain.curve)) # 32 bytes secret is obtained
# Split into two 16 bytes components S1 and S2. S1 and S2 are XORed to produce a 16 bytes 3DES-2 session key
@_m2fa.sessionKey = (Convert.toHexByte(secret[i] ^ secret[16+i]) for i in [0...16]).join('')
# Challenge (keycard indexes) - 4 bytes
@_m2fa.keycard = ledger.keycard.generateKeycardFromSeed('<KEY>')
@_m2fa.challengeIndexes = ''
@_m2fa.challengeResponses = ''
for i in [0..3]
num = _.random(ledger.crypto.Base58.concatAlphabet().length - 1)
@_m2fa.challengeIndexes += Convert.toHexByte(ledger.crypto.Base58.concatAlphabet().charCodeAt(num) - 0x30)
@_m2fa.challengeResponses += '0' + @_m2fa.keycard[ledger.crypto.Base58.concatAlphabet().charAt(num)]
# Crypted challenge - challenheHex + PairingKeyHex - 24 bytes
blob = @_m2fa.challengeIndexes + @_m2fa.pairingKeyHex + "00000000"
cipher = new JSUCrypt.cipher.DES(JSUCrypt.padder.None, JSUCrypt.cipher.MODE_CBC)
key = new JSUCrypt.key.DESKey(@_m2fa.sessionKey)
cipher.init(key, JSUCrypt.cipher.MODE_ENCRYPT)
cryptedBlob = cipher.update(blob)
cryptedBlobHex = (Convert.toHexByte(v) for v in cryptedBlob).join('')
# 8 bytes Nonce
nonce = crypto.getRandomValues new Uint8Array(8)
@_m2fa.nonceHex = (Convert.toHexByte(v) for v in nonce).join('')
# concat Nonce + (challenge + pairingKey)
res = @_m2fa.nonceHex + cryptedBlobHex
d.resolve(res)
d.promise
# @param [String] resp challenge response, hex encoded. #Encrypted nonce and challenge response + padding - 16 length
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
confirmSecureScreen: (challengeResp, callback=undefined) ->
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! challengeResp.match(/^[0-9A-Fa-f]{32}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid challenge resp : #{challengeResp}")
else
# Decipher
cipher = new JSUCrypt.cipher.DES(JSUCrypt.padder.None, JSUCrypt.cipher.MODE_CBC)
key = new JSUCrypt.key.DESKey(@_m2fa.sessionKey)
cipher.init(key, JSUCrypt.cipher.MODE_DECRYPT)
challengeRespDecipher = cipher.update(challengeResp)
challengeRespDecipher = (Convert.toHexByte(v) for v in challengeRespDecipher).join('')
#l 'challengeRespDecipher', challengeRespDecipher
# Verify Challenge
[nonce, challenge, padding] = [challengeRespDecipher[0...16], challengeRespDecipher[16...24], challengeRespDecipher[24..-1]]
#l [nonce, challenge, padding]
if nonce is @_m2fa.nonceHex and challenge is @_m2fa.challengeResponses
@_clearPairingInfo()
d.resolve()
else
@_clearPairingInfo(yes)
d.reject('Pairing fail - Invalid status 1 - 6a80')
d.promise
getStringFirmwareVersion: ->
'1.0.1'
_generatePairingKeyHex: ->
pairingKey = <KEY>Values new Uint8Array(16)
@_m2fa.pairingKeyHex = (Convert.toHexByte(v) for v in pairingKey).join('')
_clearPairingInfo: (isErr) ->
if isErr
@_m2fa = _.omit(@_m2fa, ['challengeIndexes', 'sessionKey', 'nonceHex', 'challengeIndexes', 'challengeResponses', 'keycard', 'pairingKeyHex'])
else
@_m2fa = _.omit(@_m2fa, ['challengeIndexes', 'sessionKey', 'nonceHex', 'challengeIndexes', 'challengeResponses', 'keycard'])
# Get PubKeyHash from base58
_getPubKeyHashFromBase58: (addr) ->
arr = ledger.crypto.Base58.decode(addr)
buffer = JSUCrypt.utils.byteArrayToHexStr(arr)
x = new ByteString(buffer, HEX)
pubKeyHash = x.bytes(0, x.length - 4).bytes(1) # remove network 1 byte at the beginning, remove checksum 4 bytes at the end
pubKeyHash
_setState: (newState, args...) ->
[@state, oldState] = [newState, @state]
@emit "state:#{@state}", @state, args...
@emit 'state:changed', @state
_setup: (pin, restoreSeed, isPowerCycle, callback=undefined) ->
d = ledger.defer(callback)
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
[restoreSeed, callback] = [callback, restoreSeed] if ! callback && typeof restoreSeed == 'function'
Throw new Error('Setup need a seed') if not restoreSeed?
@_pin = pin
@_masterNode = bitcoin.HDNode.fromSeedHex restoreSeed, ledger.config.network.bitcoinjs
# Validate seed
if restoreSeed?
bytesSeed = new ByteString(restoreSeed, HEX)
if bytesSeed.length != 64
e('Invalid seed :', restoreSeed)
if isPowerCycle then @_setState States.LOCKED else _.defer => @_setState States.DISCONNECTED
d.resolve()
return d.promise
_getNodeFromPath: (path) ->
path = path.split('/')
node = @_masterNode
for item in path
[index, hardened] = item.split "'"
node = if hardened? then node.deriveHardened parseInt(index) else node = node.derive index
node
# Set appropriate state, and return corresponding Error
# @param [String] errorCode
# @return [Error]
_handleErrorCode: (errorCode) ->
if errorCode.match("6982") # Pin required
@_setState(States.LOCKED)
error = Errors.new(Errors.DongleLocked, errorCode)
else if errorCode.match("6985") # Error ?
@_setState(States.BLANK)
error = Errors.new(Errors.BlankDongle, errorCode)
else if errorCode.match("6faa")
@_setState(States.ERROR)
error = Errors.new(Errors.UnknowError, errorCode)
else if errorCode.match(/63c\d/)
error = Errors.new(Errors.WrongPinCode, errorCode)
error.retryCount = parseInt(errorCode.substr(-1))
if error.retryCount == 0
@_setState(States.BLANK)
error.code = Errors.DongleLocked
else
@_setState(States.ERROR)
else
@_setState(States.UnknowError)
error = Errors.new(Errors.UnknowError, errorCode)
l 'ERROR', error
return error | true |
States =
# Dongle juste created, not initialized.
UNDEFINED: undefined
# PIN required.
LOCKED: 'locked'
# PIN has been verified.
UNLOCKED: 'unlocked'
# No seed present, dongle must be setup.
BLANK: 'blank'
# Dongle has been unplugged.
DISCONNECTED: 'disconnected'
# An error appended, user must unplug/replug dongle.
ERROR: 'error'
Errors = @ledger.errors
class ledger.dongle.MockDongle extends EventEmitter
_xpubs: []
_remainingPinAttempt: 2
# M2FA
_m2fa:
pubKey: "PI:KEY:<KEY>END_PI"PI:KEY:<KEY>END_PI"PI:KEY:<KEY>END_PI"
privKey: "PI:KEY:<KEY>END_PI"PI:KEY:<KEY>END_PI"+"PI:KEY:<KEY>END_PI"
sessionKey: ''
pairingKeyHex: ''
nonceHex: ''
challengeIndexes: ''
challengeResponses: ''
keycard: ''
constructor: (pin, seed, pairingKeyHex = undefined, isInBootloaderMode = no) ->
super
@_m2fa = _.clone(@_m2fa)
@_m2fa.pairingKeyHex = pairingKeyHex
@_isInBootloaderMode = isInBootloaderMode
@state = States.UNDEFINED
@_setState(States.BLANK)
@_setup(pin, seed, yes) if pin? and seed?
isInBootloaderMode: -> @_isInBootloaderMode
disconnect: () ->
@emit 'disconnected', @
@_setState(States.DISCONNECTED)
connect: () ->
@emit 'connected', @
@_setState(States.LOCKED)
# Return asynchronosly state. Wait until a state is set.
# @param [Function] callback Optional argument
# @return [Q.Promise]
getState: (callback=undefined) -> ledger.defer(callback).resolve(@state).promise
# @return [Integer] Firmware version, 0x20010000010f for example.
getIntFirmwareVersion: ->
parseInt(0x0001040d.toString(HEX), 16)
###
Gets the raw version {ByteString} of the dongle.
@param [Boolean] isInBootLoaderMode Must be true if the current dongle is in bootloader mode.
@param [Boolean] forceBl Force the call in BootLoader mode
@param [Function] callback Called once the version is retrieved. The callback must be prototyped like size `(version, error) ->`
@return [Q.Promise]
###
getRawFirmwareVersion: (isInBootLoaderMode, forceBl=no, checkHiddenReloader = no, callback=undefined) ->
d = ledger.defer(callback)
try
d.resolve ['00000020', '00010001']
catch
d.rejectWithError(ledger.errors.UnknowError, error)
console.error("Fail to getRawFirmwareVersion :", error)
d.promise
# @param [String] pin ASCII encoded
# @param [Function] callback Optional argument
# @return [Q.Promise]
unlockWithPinCode: (pin, callback=undefined) ->
Errors.throw(Errors.DongleAlreadyUnlock) if @state isnt States.LOCKED
d = ledger.defer(callback)
if pin is @_pin
@_setState(States.UNLOCKED)
@_remainingPinAttempt = 3
d.resolve()
else
console.error("Fail to unlockWithPinCode 1 :", '63c' + @_remainingPinAttempt)
error = @_handleErrorCode('63c' + @_remainingPinAttempt)
@_remainingPinAttempt -= 1
d.reject(error)
d.promise
lock: () ->
if @state isnt ledger.dongle.States.BLANK and @state?
@_setState(States.LOCKED)
# @return [Q.Promise] resolve with a Number, reject with a ledger Error.
getRemainingPinAttempt: (callback=undefined) ->
d = ledger.defer(callback)
if @_remainingPinAttempt < 0
d.resolve(@_remainingPinAttempt)
else
d.reject(@_handleErrorCode('6985'))
d.promise
setup: (pin, restoreSeed, callback=undefined) ->
@_setup(pin, restoreSeed, no, callback)
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise]
getPublicAddress: (path, callback=undefined) ->
d = ledger.defer(callback)
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED && @state isnt States.UNDEFINED
res = @getPublicAddressSync(path)
_.defer -> d.resolve(res)
return d.promise
getPublicAddressSync: (path) ->
node = @_getNodeFromPath(path)
bitcoinAddress: new ByteString node.getAddress().toString(), ASCII
chainCode: new ByteString (Convert.toHexByte(n) for n in node.chainCode).join(''), HEX
publicKey: new ByteString do (->
node.pubKey.compressed = false
node.pubKey.toHex()
)
, HEX
signMessage: (message, {path, pubKey}, callback=undefined) ->
d = ledger.defer(callback)
node = @_getNodeFromPath(path)
d.resolve bitcoin.Message.sign(node.privKey, message).toString('base64')
d.promise
getBitIdAddress: (subpath=undefined, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state isnt States.UNLOCKED
[subpath, callback] = [callback, subpath] if ! callback && typeof subpath == 'function'
path = ledger.dongle.BitIdRootPath
path += "/#{subpath}" if subpath?
@getPublicAddress(path, callback)
# @param [String] path
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
getExtendedPublicKey: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
d = ledger.defer(callback)
return d.resolve(@_xpubs[path]).promise if @_xpubs[path]?
xpub = new ledger.wallet.ExtendedPublicKey(@, path)
xpub.initialize () =>
@_xpubs[path] = xpub
d.resolve(xpub)
d.promise
isCertified: (callback=undefined) ->
d = ledger.defer(callback)
d.resolve(@)
d.promise
isBetaCertified: (callback=undefined) ->
d = ledger.defer(callback)
d.resolve(@)
d.promise
# @return [Q.Promise]
isFirmwareUpdateAvailable: (callback=undefined) -> ledger.defer(callback).resolve(false).promise
###
@param [Array<Object>] inputs
@param [Array] associatedKeysets
@param changePath
@param [String] recipientAddress
@param [Amount] amount
@param [Amount] fee
@param [Integer] lockTime
@param [Integer] sighashType
@param [String] authorization hex encoded
@param [Object] resumeData
@return [Q.Promise] Resolve with resumeData
###
createPaymentTransaction: (inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData, network) ->
d = ledger.defer()
result = {}
if _.isEmpty resumeData
txb = new bitcoin.TransactionBuilder()
# Create rawTxs from inputs
rawTxs = for input in inputs
[splittedTx, outputIndex] = input
rawTxBuffer = splittedTx.version
rawTxBuffer = rawTxBuffer.concat(new ByteString(Convert.toHexByte(splittedTx.inputs.length), HEX))
for input in splittedTx.inputs
rawTxBuffer = rawTxBuffer.concat(input.prevout).concat(new ByteString(Convert.toHexByte(input.script.length), HEX)).concat(input.script).concat(input.sequence)
rawTxBuffer = rawTxBuffer.concat(new ByteString(Convert.toHexByte(splittedTx.outputs.length), HEX))
for output in splittedTx.outputs
rawTxBuffer = rawTxBuffer.concat(output.amount).concat(new ByteString(Convert.toHexByte(output.script.length), HEX)).concat(output.script)
rawTxBuffer = rawTxBuffer.concat(splittedTx.locktime)
[rawTxBuffer, outputIndex]
values = []
balance = Bitcoin.BigInteger.valueOf(0)
# Add Input
for [rawTx, outputIndex] in rawTxs
tx = bitcoin.Transaction.fromHex(rawTx.toString())
txb.addInput(tx, outputIndex)
values.push(tx.outs[outputIndex].value)
# Create balance
for val, i in values
balance = balance.add Bitcoin.BigInteger.valueOf(val)
# Create change
change = (balance.toString() - fees.toSatoshiNumber()) - amount.toSatoshiNumber()
# Create scriptPubKey
scriptPubKeyStart = Convert.toHexByte(bitcoin.opcodes.OP_DUP) + Convert.toHexByte(bitcoin.opcodes.OP_HASH160) + 14
scriptPubKeyEnd = Convert.toHexByte(bitcoin.opcodes.OP_EQUALVERIFY) + Convert.toHexByte(bitcoin.opcodes.OP_CHECKSIG)
# recipient addr
scriptPubKey = bitcoin.Script.fromHex(scriptPubKeyStart + @_getPubKeyHashFromBase58(recipientAddress).toString() + scriptPubKeyEnd)
txb.addOutput(scriptPubKey, amount.toSatoshiNumber())
# change addr
scriptPubKey = bitcoin.Script.fromHex(scriptPubKeyStart + @_getPubKeyHashFromBase58(@_getNodeFromPath(changePath).getAddress().toString()).toString() + scriptPubKeyEnd)
if change isnt 0
txb.addOutput(scriptPubKey, change)
# Signature
for path, index in associatedKeysets
txb.sign(index, @_getNodeFromPath(associatedKeysets[index]).privKey)
# Keycard
keycard = ledger.keycard.generateKeycardFromSeed('PI:KEY:<KEY>END_PI')
charsQuestion = []
indexes = [] # charQuestion indexes of recipient address
charsResponse = []
for i in [0..3]
randomNum = _.random recipientAddress.length - 1
charsQuestion.push recipientAddress.charAt randomNum
charsResponse.push keycard[charsQuestion[i]]
indexes.push Convert.toHexByte randomNum
result.authorizationReference = indexes.join('')
result.publicKeys = []
result.publicKeys.push recipientAddress
result.txb = txb
result.charsResponse = "0" + charsResponse.join('0')
# M2fa
if @_m2fa.pairingKeyHex?
amount = '0000000000000000' + amount._value.toRadix(16)
amount = amount.substr(amount.length - 16, 16)
fees = '0000000000000000' + fees._value.toRadix(16)
fees = fees.substr(fees.length - 16, 16)
change = '0000000000000000' + new BigInteger(change.toString()).toRadix(16)
change = change.substr(change.length - 16, 16)
sizeAddress = Convert.toHexByte recipientAddress.length
pin = new ByteString(charsResponse.join(''), ASCII).toString(HEX)
m2faData = pin + amount + fees + change + sizeAddress + (new ByteString(recipientAddress, ASCII).toString(HEX))
padding = m2faData.length % 8
m2faData = _.str.rpad m2faData, m2faData.length + (8 - padding), '0'
# Encrypt
cipher = new JSUCrypt.cipher.DES(JSUCrypt.padder.None , JSUCrypt.cipher.MODE_CBC)
key = new JSUCrypt.key.DESKey(@_m2fa.pairingKeyHex)
cipher.init(key, JSUCrypt.cipher.MODE_ENCRYPT)
m2faData = cipher.update(m2faData)
m2faDataHex = (Convert.toHexByte(v) for v in m2faData).join('')
# Set authorizations
result.authorizationRequired = 3
result.authorizationPaired = m2faDataHex
result.indexesKeyCard = '04' + indexes.join('') + m2faDataHex
else
result.authorizationRequired = 2
result.authorizationPaired = undefined
result.indexesKeyCard = indexes.join('')
l 'result', result
l 'm2fa', @_m2fa
result
else
l 'resumeData', resumeData
# Check keycard and m2fa validity
m2faResponse = new ByteString((v.charAt(1) for v in resumeData.charsResponse.match(/.{2}/g)).join(''), ASCII).toString(HEX)
if resumeData.charsResponse isnt authorization and m2faResponse isnt authorization
_.delay (-> d.rejectWithError(Errors.WrongPinCode)), 1000
# Build raw tx
try
result = resumeData.txb.build().toHex()
catch
_.delay (-> d.rejectWithError(Errors.SignatureError)), 1000
_.delay (-> d.resolve(result)), 1000 # Dirty delay fix, odd but necessary
d.promise
splitTransaction: (input) ->
bitExt = new BitcoinExternal()
bitExt.splitTransaction(new ByteString(input.raw, HEX))
# @param [String] pubKey public key, hex encoded. # Remote screen uncompressed public key - 65 length
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve with a 32 bytes length pairing blob hex encoded. # Pairing blob : 8 bytes random nonce and (4 bytes keycard challenge + 16 bytes pairing key) encrypted by the session key # Challenge
initiateSecureScreen: (pubKey, callback=undefined) ->
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! pubKey.match(/^[0-9A-Fa-f]{130}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid pubKey : #{pubKey}")
else
###
The remote screen public key is sent to the dongle, which generates
a cleartext random 8 bytes nonce,
a 4 bytes challenge on the printed keycard
and a random 16 bytes 3DES-2 pairing key, concatenated and encrypted using 3DES CBC and the generated session key
###
# ECDH key exchange
ecdhdomain = JSUCrypt.ECFp.getEcDomainByName("secp256k1")
ecdhprivkey = new JSUCrypt.key.EcFpPrivateKey(256, ecdhdomain, @_m2fa.privKey.match(/^(\w{2})(\w{64})(01)?(\w{8})$/)[2])
ecdh = new JSUCrypt.keyagreement.ECDH_SVDP(ecdhprivkey)
aKey = pubKey.match(/^(\w{2})(\w{64})(\w{64})$/)
secret = ecdh.generate(new JSUCrypt.ECFp.AffinePoint(aKey[2], aKey[3], ecdhdomain.curve)) # 32 bytes secret is obtained
# Split into two 16 bytes components S1 and S2. S1 and S2 are XORed to produce a 16 bytes 3DES-2 session key
@_m2fa.sessionKey = (Convert.toHexByte(secret[i] ^ secret[16+i]) for i in [0...16]).join('')
# Challenge (keycard indexes) - 4 bytes
@_m2fa.keycard = ledger.keycard.generateKeycardFromSeed('PI:KEY:<KEY>END_PI')
@_m2fa.challengeIndexes = ''
@_m2fa.challengeResponses = ''
for i in [0..3]
num = _.random(ledger.crypto.Base58.concatAlphabet().length - 1)
@_m2fa.challengeIndexes += Convert.toHexByte(ledger.crypto.Base58.concatAlphabet().charCodeAt(num) - 0x30)
@_m2fa.challengeResponses += '0' + @_m2fa.keycard[ledger.crypto.Base58.concatAlphabet().charAt(num)]
# Crypted challenge - challenheHex + PairingKeyHex - 24 bytes
blob = @_m2fa.challengeIndexes + @_m2fa.pairingKeyHex + "00000000"
cipher = new JSUCrypt.cipher.DES(JSUCrypt.padder.None, JSUCrypt.cipher.MODE_CBC)
key = new JSUCrypt.key.DESKey(@_m2fa.sessionKey)
cipher.init(key, JSUCrypt.cipher.MODE_ENCRYPT)
cryptedBlob = cipher.update(blob)
cryptedBlobHex = (Convert.toHexByte(v) for v in cryptedBlob).join('')
# 8 bytes Nonce
nonce = crypto.getRandomValues new Uint8Array(8)
@_m2fa.nonceHex = (Convert.toHexByte(v) for v in nonce).join('')
# concat Nonce + (challenge + pairingKey)
res = @_m2fa.nonceHex + cryptedBlobHex
d.resolve(res)
d.promise
# @param [String] resp challenge response, hex encoded. #Encrypted nonce and challenge response + padding - 16 length
# @param [Function] callback Optional argument
# @return [Q.Promise] Resolve if pairing is successful.
confirmSecureScreen: (challengeResp, callback=undefined) ->
d = ledger.defer(callback)
if @state != States.UNLOCKED
d.rejectWithError(Errors.DongleLocked)
else if ! challengeResp.match(/^[0-9A-Fa-f]{32}$/)?
d.rejectWithError(Errors.InvalidArgument, "Invalid challenge resp : #{challengeResp}")
else
# Decipher
cipher = new JSUCrypt.cipher.DES(JSUCrypt.padder.None, JSUCrypt.cipher.MODE_CBC)
key = new JSUCrypt.key.DESKey(@_m2fa.sessionKey)
cipher.init(key, JSUCrypt.cipher.MODE_DECRYPT)
challengeRespDecipher = cipher.update(challengeResp)
challengeRespDecipher = (Convert.toHexByte(v) for v in challengeRespDecipher).join('')
#l 'challengeRespDecipher', challengeRespDecipher
# Verify Challenge
[nonce, challenge, padding] = [challengeRespDecipher[0...16], challengeRespDecipher[16...24], challengeRespDecipher[24..-1]]
#l [nonce, challenge, padding]
if nonce is @_m2fa.nonceHex and challenge is @_m2fa.challengeResponses
@_clearPairingInfo()
d.resolve()
else
@_clearPairingInfo(yes)
d.reject('Pairing fail - Invalid status 1 - 6a80')
d.promise
getStringFirmwareVersion: ->
'1.0.1'
_generatePairingKeyHex: ->
pairingKey = PI:KEY:<KEY>END_PIValues new Uint8Array(16)
@_m2fa.pairingKeyHex = (Convert.toHexByte(v) for v in pairingKey).join('')
_clearPairingInfo: (isErr) ->
if isErr
@_m2fa = _.omit(@_m2fa, ['challengeIndexes', 'sessionKey', 'nonceHex', 'challengeIndexes', 'challengeResponses', 'keycard', 'pairingKeyHex'])
else
@_m2fa = _.omit(@_m2fa, ['challengeIndexes', 'sessionKey', 'nonceHex', 'challengeIndexes', 'challengeResponses', 'keycard'])
# Get PubKeyHash from base58
_getPubKeyHashFromBase58: (addr) ->
arr = ledger.crypto.Base58.decode(addr)
buffer = JSUCrypt.utils.byteArrayToHexStr(arr)
x = new ByteString(buffer, HEX)
pubKeyHash = x.bytes(0, x.length - 4).bytes(1) # remove network 1 byte at the beginning, remove checksum 4 bytes at the end
pubKeyHash
_setState: (newState, args...) ->
[@state, oldState] = [newState, @state]
@emit "state:#{@state}", @state, args...
@emit 'state:changed', @state
_setup: (pin, restoreSeed, isPowerCycle, callback=undefined) ->
d = ledger.defer(callback)
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
[restoreSeed, callback] = [callback, restoreSeed] if ! callback && typeof restoreSeed == 'function'
Throw new Error('Setup need a seed') if not restoreSeed?
@_pin = pin
@_masterNode = bitcoin.HDNode.fromSeedHex restoreSeed, ledger.config.network.bitcoinjs
# Validate seed
if restoreSeed?
bytesSeed = new ByteString(restoreSeed, HEX)
if bytesSeed.length != 64
e('Invalid seed :', restoreSeed)
if isPowerCycle then @_setState States.LOCKED else _.defer => @_setState States.DISCONNECTED
d.resolve()
return d.promise
_getNodeFromPath: (path) ->
path = path.split('/')
node = @_masterNode
for item in path
[index, hardened] = item.split "'"
node = if hardened? then node.deriveHardened parseInt(index) else node = node.derive index
node
# Set appropriate state, and return corresponding Error
# @param [String] errorCode
# @return [Error]
_handleErrorCode: (errorCode) ->
if errorCode.match("6982") # Pin required
@_setState(States.LOCKED)
error = Errors.new(Errors.DongleLocked, errorCode)
else if errorCode.match("6985") # Error ?
@_setState(States.BLANK)
error = Errors.new(Errors.BlankDongle, errorCode)
else if errorCode.match("6faa")
@_setState(States.ERROR)
error = Errors.new(Errors.UnknowError, errorCode)
else if errorCode.match(/63c\d/)
error = Errors.new(Errors.WrongPinCode, errorCode)
error.retryCount = parseInt(errorCode.substr(-1))
if error.retryCount == 0
@_setState(States.BLANK)
error.code = Errors.DongleLocked
else
@_setState(States.ERROR)
else
@_setState(States.UnknowError)
error = Errors.new(Errors.UnknowError, errorCode)
l 'ERROR', error
return error |
[
{
"context": "# Adejair Júnior <adejair.junioroulook@gmail.com>\n\nSafadao = requi",
"end": 16,
"score": 0.9998952746391296,
"start": 2,
"tag": "NAME",
"value": "Adejair Júnior"
},
{
"context": "# Adejair Júnior <adejair.junioroulook@gmail.com>\n\nSafadao = require \"./wesley_safadao... | coffeescript/wesley_safadao_test.coffee | mabrasil/safadometro | 128 | # Adejair Júnior <adejair.junioroulook@gmail.com>
Safadao = require "./wesley_safadao"
adejair = new Safadao(4,8,69)
adejair.vai_safadao()
| 211448 | # <NAME> <<EMAIL>>
Safadao = require "./wesley_safadao"
adejair = new Safadao(4,8,69)
adejair.vai_safadao()
| true | # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Safadao = require "./wesley_safadao"
adejair = new Safadao(4,8,69)
adejair.vai_safadao()
|
[
{
"context": "ffee'\n assets_head: '/assets'\n session_secret: '1234567'\n rainbow:\n controllers: '/controllers/'\n ",
"end": 142,
"score": 0.9941781163215637,
"start": 135,
"tag": "KEY",
"value": "1234567"
}
] | config.coffee | nasawz/tumojs | 0 | config =
port: 8080
restApiRoot: '/api'
base_path: __dirname
script_ext: '.coffee'
assets_head: '/assets'
session_secret: '1234567'
rainbow:
controllers: '/controllers/'
filters: '/filters/'
template: '/views/'
module.exports = config
| 69047 | config =
port: 8080
restApiRoot: '/api'
base_path: __dirname
script_ext: '.coffee'
assets_head: '/assets'
session_secret: '<KEY>'
rainbow:
controllers: '/controllers/'
filters: '/filters/'
template: '/views/'
module.exports = config
| true | config =
port: 8080
restApiRoot: '/api'
base_path: __dirname
script_ext: '.coffee'
assets_head: '/assets'
session_secret: 'PI:KEY:<KEY>END_PI'
rainbow:
controllers: '/controllers/'
filters: '/filters/'
template: '/views/'
module.exports = config
|
[
{
"context": "###\nbookCtrl.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.com>\n\nDistributed under terms of t",
"end": 47,
"score": 0.9996843338012695,
"start": 39,
"tag": "NAME",
"value": "ender xu"
},
{
"context": "###\nbookCtrl.coffee\nCopyright (C) 2014 ender xu <xuender@gm... | src/note/booksCtrl.coffee | xuender/mindfulness | 0 | ###
bookCtrl.coffee
Copyright (C) 2014 ender xu <xuender@gmail.com>
Distributed under terms of the MIT license.
###
BooksCtrl = ($scope, $http, $log, $modal, ngTableParams, $filter, $q)->
$scope.$parent.name = 'book'
$log.debug 'xxx'
$scope.status=
new: '新建'
publish: '发布'
$scope.selectStatus = ->
# 状态列表
def = $q.defer()
ret = []
for k of $scope.status
$log.debug k
ret.push(
id:k
title: $scope.status[k]
)
def.resolve(ret)
def
$scope.new = ->
$modal.open(
templateUrl: 'partials/note/book.html?8.html'
controller: BookCtrl
backdrop: 'static'
size: 'lg'
resolve:
book: ->
publish: false
del: ->
false
status: ->
$scope.status
).result.then((b)->
$http.post('/note/book', b).success((data)->
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
,->
$log.info '取消'
)
$scope.update = (book)->
$modal.open(
templateUrl: 'partials/note/book.html?8.html'
controller: BookCtrl
backdrop: 'static'
size: 'lg'
resolve:
book: ->
book
del: ->
true
status: ->
$scope.status
).result.then((b)->
$log.debug b
if angular.isString(b)
$http.delete('/note/book/' + b).success((data)->
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
else
$http.put('/note/book', b).success((data)->
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
,->
$log.info '取消'
)
$scope.tableParams = new ngTableParams(
page: 1
count: 10
sorting:
ca: 'desc'
,
getData: ($defer, params)->
# 过滤
$http.post('/note/books',
Page: params.page()
Count: params.count()
Sorting: params.orderBy()
Filter: params.filter()
).success((data)->
$log.debug data
params.total(data.count)
$defer.resolve(data.data)
)
)
BooksCtrl.$inject = [
'$scope'
'$http'
'$log'
'$modal'
'ngTableParams'
'$filter'
'$q'
]
| 155751 | ###
bookCtrl.coffee
Copyright (C) 2014 <NAME> <<EMAIL>>
Distributed under terms of the MIT license.
###
BooksCtrl = ($scope, $http, $log, $modal, ngTableParams, $filter, $q)->
$scope.$parent.name = 'book'
$log.debug 'xxx'
$scope.status=
new: '新建'
publish: '发布'
$scope.selectStatus = ->
# 状态列表
def = $q.defer()
ret = []
for k of $scope.status
$log.debug k
ret.push(
id:k
title: $scope.status[k]
)
def.resolve(ret)
def
$scope.new = ->
$modal.open(
templateUrl: 'partials/note/book.html?8.html'
controller: BookCtrl
backdrop: 'static'
size: 'lg'
resolve:
book: ->
publish: false
del: ->
false
status: ->
$scope.status
).result.then((b)->
$http.post('/note/book', b).success((data)->
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
,->
$log.info '取消'
)
$scope.update = (book)->
$modal.open(
templateUrl: 'partials/note/book.html?8.html'
controller: BookCtrl
backdrop: 'static'
size: 'lg'
resolve:
book: ->
book
del: ->
true
status: ->
$scope.status
).result.then((b)->
$log.debug b
if angular.isString(b)
$http.delete('/note/book/' + b).success((data)->
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
else
$http.put('/note/book', b).success((data)->
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
,->
$log.info '取消'
)
$scope.tableParams = new ngTableParams(
page: 1
count: 10
sorting:
ca: 'desc'
,
getData: ($defer, params)->
# 过滤
$http.post('/note/books',
Page: params.page()
Count: params.count()
Sorting: params.orderBy()
Filter: params.filter()
).success((data)->
$log.debug data
params.total(data.count)
$defer.resolve(data.data)
)
)
BooksCtrl.$inject = [
'$scope'
'$http'
'$log'
'$modal'
'ngTableParams'
'$filter'
'$q'
]
| true | ###
bookCtrl.coffee
Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Distributed under terms of the MIT license.
###
BooksCtrl = ($scope, $http, $log, $modal, ngTableParams, $filter, $q)->
$scope.$parent.name = 'book'
$log.debug 'xxx'
$scope.status=
new: '新建'
publish: '发布'
$scope.selectStatus = ->
# 状态列表
def = $q.defer()
ret = []
for k of $scope.status
$log.debug k
ret.push(
id:k
title: $scope.status[k]
)
def.resolve(ret)
def
$scope.new = ->
$modal.open(
templateUrl: 'partials/note/book.html?8.html'
controller: BookCtrl
backdrop: 'static'
size: 'lg'
resolve:
book: ->
publish: false
del: ->
false
status: ->
$scope.status
).result.then((b)->
$http.post('/note/book', b).success((data)->
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
,->
$log.info '取消'
)
$scope.update = (book)->
$modal.open(
templateUrl: 'partials/note/book.html?8.html'
controller: BookCtrl
backdrop: 'static'
size: 'lg'
resolve:
book: ->
book
del: ->
true
status: ->
$scope.status
).result.then((b)->
$log.debug b
if angular.isString(b)
$http.delete('/note/book/' + b).success((data)->
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
else
$http.put('/note/book', b).success((data)->
if data.ok
$scope.tableParams.reload()
else
alert(data.err)
)
,->
$log.info '取消'
)
$scope.tableParams = new ngTableParams(
page: 1
count: 10
sorting:
ca: 'desc'
,
getData: ($defer, params)->
# 过滤
$http.post('/note/books',
Page: params.page()
Count: params.count()
Sorting: params.orderBy()
Filter: params.filter()
).success((data)->
$log.debug data
params.total(data.count)
$defer.resolve(data.data)
)
)
BooksCtrl.$inject = [
'$scope'
'$http'
'$log'
'$modal'
'ngTableParams'
'$filter'
'$q'
]
|
[
{
"context": "nit/helpers\n\noccasionsThatDoNotAffectShaharit = [\"HataratNedarim\", \"ErubTabshilin\", \"Regel\", \"ShabbatHaGadol\", \"Ma",
"end": 102,
"score": 0.9981122016906738,
"start": 88,
"tag": "NAME",
"value": "HataratNedarim"
},
{
"context": "ionsThatDoNotAffectShaharit = ... | source/javascripts/qunit/site/shaharitTest.js.coffee | betesh/nahar-shalom-schedule | 0 | #= require site/shaharit
#= require qunit/helpers
occasionsThatDoNotAffectShaharit = ["HataratNedarim", "ErubTabshilin", "Regel", "ShabbatHaGadol", "MaharHodesh", "ShabbatMevarechim", "ErebYomTob"]
assertTimeEqual = QunitHelpers.assertTimeEqual
shaharitTest = (gregorianDate, expected, sofZmanKeriatShemaMinute = 31) ->
hebrewDate = new HebrewDate(gregorianDate)
sunrise = moment(gregorianDate).hour(6).minute(8).seconds(8)
sofZmanKeriatShema = moment(gregorianDate).hour(9).minute(sofZmanKeriatShemaMinute).seconds(9)
events = hebrewDate.occasions().filter((e) -> (-1 == occasionsThatDoNotAffectShaharit.indexOf(e))).join(" / ")
QUnit.test "When sunrise is at #{sunrise.format("hh:mm:ss A")} and Sof Zman Keriat Shema is at #{sofZmanKeriatShema.format("hh:mm:ss A")} on #{events}", (assert) ->
shaharit = new Shaharit(hebrewDate, sunrise, sofZmanKeriatShema)
if expected.selihot?
assertTimeEqual assert, shaharit.selihot(), expected.selihot, "Selihot"
else
assert.equal shaharit.selihot(), null, "Shaharit.selihot() does not return a time"
assert.equal shaharit.korbanot().length, expected.korbanot.length, "There are #{expected.korbanot.length} times for Korbanot"
for i in [0...(expected.korbanot.length)]
assertTimeEqual assert, shaharit.korbanot()[i], expected.korbanot[i], "Korbanot ##{i}"
assert.equal shaharit.hodu().length, expected.hodu.length, "There are #{expected.korbanot.length} times for Hodu"
for i in [0...(expected.hodu.length)]
assertTimeEqual assert, shaharit.hodu()[i], expected.hodu[i], "Hodu ##{i}"
if expected.nishmat?
assertTimeEqual assert, shaharit.nishmat(), expected.nishmat, "Nishmat"
else
assert.equal shaharit.nishmat(), null, "Shaharit.nishmat() does not return a time"
assertTimeEqual assert, shaharit.yishtabach(), expected.yishtabach,"Yishtabach"
assertTimeEqual assert, shaharit.amidah(), expected.amidah,"Amidah"
shaharitPesachTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(11), moment(date).hours(8).minutes(45)],
hodu: [moment(date).hours(5).minutes(26), moment(date).hours(9).minutes(0)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitShabuotTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(2)],
hodu: [moment(date).hours(5).minutes(17)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitYomKippurTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(4).minutes(58), moment(date).hours(7).minutes(0)],
hodu: [moment(date).hours(5).minutes(13), moment(date).hours(7).minutes(15)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitWeekdayTest = (date, selihot) ->
shaharitTest date,
selihot: selihot,
korbanot: [moment(date).hours(5).minutes(32)],
hodu: [moment(date).hours(5).minutes(48)],
yishtabach: moment(date).hours(5).minutes(59),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitShabbatTest815 = (date, yomTob = false) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(if yomTob then 11 else 13), moment(date).hours(8).minutes(15)],
hodu: [moment(date).hours(5).minutes(if yomTob then 26 else 28), moment(date).hours(8).minutes(30)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitShabbatTest745 = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(13), moment(date).hours(7).minutes(45)],
hodu: [moment(date).hours(5).minutes(28), moment(date).hours(8).minutes(0)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8),
13
shaharitShabbatTest845 = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(11), moment(date).hours(8).minutes(30)],
hodu: [moment(date).hours(5).minutes(26), moment(date).hours(8).minutes(45)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8),
13
shaharitHolHaMoedTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(30)],
hodu: [moment(date).hours(5).minutes(46)],
yishtabach: moment(date).hours(5).minutes(59),
amidah: moment(date).hours(6).minutes(8).seconds(8)
$ ->
# 1st Day of Pesach
shaharitPesachTest(new Date(2017,3,11))
# 2nd Day of Pesach
shaharitPesachTest(new Date(2017,3,12))
# Holl Hamoed
shaharitHolHaMoedTest(new Date(2017,3,16))
# 7th Day of Pesach
shaharitShabbatTest815(new Date(2017,3,17), true)
# 8th Day of Pesach
shaharitShabbatTest815(new Date(2017,3,18), true)
# 1st Day of Shabuot
shaharitShabuotTest(new Date(2021,4,17))
# 2nd Day of Shabuot
shaharitShabbatTest845(new Date(2021,4,18), true)
# 1st Day of Rosh Hashana
shaharitShabbatTest815(new Date(2016,9,3), true)
# Rosh Hodesh Elul
shaharitWeekdayTest(new Date(2016,8,4))
# Elul
erebRoshHashana = new Date(2016,9,2)
shaharitWeekdayTest(erebRoshHashana, moment(erebRoshHashana).hours(4).minutes(42))
# Aseret Yemei Teshubat
erebKippur = new Date(2016,9,11)
shaharitWeekdayTest(erebKippur, moment(erebKippur).hours(4).minutes(36))
# Yom Kippur
shaharitYomKippurTest(new Date(2016,9,12))
# Shabbat (7:45)
shaharitShabbatTest745(new Date(2016,2,12))
# Shabbat (8:15)
shaharitShabbatTest815(new Date(2016,2,19))
# Shabbat Shubah
shaharitShabbatTest815(new Date(2016,9,8))
# Weekday
shaharitWeekdayTest(new Date(2016,4,9))
| 132964 | #= require site/shaharit
#= require qunit/helpers
occasionsThatDoNotAffectShaharit = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"]
assertTimeEqual = QunitHelpers.assertTimeEqual
shaharitTest = (gregorianDate, expected, sofZmanKeriatShemaMinute = 31) ->
hebrewDate = new HebrewDate(gregorianDate)
sunrise = moment(gregorianDate).hour(6).minute(8).seconds(8)
sofZmanKeriatShema = moment(gregorianDate).hour(9).minute(sofZmanKeriatShemaMinute).seconds(9)
events = hebrewDate.occasions().filter((e) -> (-1 == occasionsThatDoNotAffectShaharit.indexOf(e))).join(" / ")
QUnit.test "When sunrise is at #{sunrise.format("hh:mm:ss A")} and Sof Zman Keriat Shema is at #{sofZmanKeriatShema.format("hh:mm:ss A")} on #{events}", (assert) ->
shaharit = new Shaharit(hebrewDate, sunrise, sofZmanKeriatShema)
if expected.selihot?
assertTimeEqual assert, shaharit.selihot(), expected.selihot, "Selihot"
else
assert.equal shaharit.selihot(), null, "Shaharit.selihot() does not return a time"
assert.equal shaharit.korbanot().length, expected.korbanot.length, "There are #{expected.korbanot.length} times for Korbanot"
for i in [0...(expected.korbanot.length)]
assertTimeEqual assert, shaharit.korbanot()[i], expected.korbanot[i], "Korbanot ##{i}"
assert.equal shaharit.hodu().length, expected.hodu.length, "There are #{expected.korbanot.length} times for Hodu"
for i in [0...(expected.hodu.length)]
assertTimeEqual assert, shaharit.hodu()[i], expected.hodu[i], "Hodu ##{i}"
if expected.nishmat?
assertTimeEqual assert, shaharit.nishmat(), expected.nishmat, "Nishmat"
else
assert.equal shaharit.nishmat(), null, "Shaharit.nishmat() does not return a time"
assertTimeEqual assert, shaharit.yishtabach(), expected.yishtabach,"Yishtabach"
assertTimeEqual assert, shaharit.amidah(), expected.amidah,"Amidah"
shaharitPesachTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(11), moment(date).hours(8).minutes(45)],
hodu: [moment(date).hours(5).minutes(26), moment(date).hours(9).minutes(0)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitShabuotTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(2)],
hodu: [moment(date).hours(5).minutes(17)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitYomKippurTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(4).minutes(58), moment(date).hours(7).minutes(0)],
hodu: [moment(date).hours(5).minutes(13), moment(date).hours(7).minutes(15)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitWeekdayTest = (date, selihot) ->
shaharitTest date,
selihot: selihot,
korbanot: [moment(date).hours(5).minutes(32)],
hodu: [moment(date).hours(5).minutes(48)],
yishtabach: moment(date).hours(5).minutes(59),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitShabbatTest815 = (date, yomTob = false) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(if yomTob then 11 else 13), moment(date).hours(8).minutes(15)],
hodu: [moment(date).hours(5).minutes(if yomTob then 26 else 28), moment(date).hours(8).minutes(30)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitShabbatTest745 = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(13), moment(date).hours(7).minutes(45)],
hodu: [moment(date).hours(5).minutes(28), moment(date).hours(8).minutes(0)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8),
13
shaharitShabbatTest845 = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(11), moment(date).hours(8).minutes(30)],
hodu: [moment(date).hours(5).minutes(26), moment(date).hours(8).minutes(45)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8),
13
shaharitHolHaMoedTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(30)],
hodu: [moment(date).hours(5).minutes(46)],
yishtabach: moment(date).hours(5).minutes(59),
amidah: moment(date).hours(6).minutes(8).seconds(8)
$ ->
# 1st Day of Pesach
shaharitPesachTest(new Date(2017,3,11))
# 2nd Day of Pesach
shaharitPesachTest(new Date(2017,3,12))
# <NAME>
shaharitHolHaMoedTest(new Date(2017,3,16))
# 7th Day of Pesach
shaharitShabbatTest815(new Date(2017,3,17), true)
# 8th Day of Pesach
shaharitShabbatTest815(new Date(2017,3,18), true)
# 1st Day of Shabuot
shaharitShabuotTest(new Date(2021,4,17))
# 2nd Day of Shabuot
shaharitShabbatTest845(new Date(2021,4,18), true)
# 1st Day of <NAME>
shaharitShabbatTest815(new Date(2016,9,3), true)
# <NAME>
shaharitWeekdayTest(new Date(2016,8,4))
# <NAME>
erebRoshHashana = new Date(2016,9,2)
shaharitWeekdayTest(erebRoshHashana, moment(erebRoshHashana).hours(4).minutes(42))
# <NAME>
erebKippur = new Date(2016,9,11)
shaharitWeekdayTest(erebKippur, moment(erebKippur).hours(4).minutes(36))
# <NAME>
shaharitYomKippurTest(new Date(2016,9,12))
# Shabbat (7:45)
shaharitShabbatTest745(new Date(2016,2,12))
# Shabbat (8:15)
shaharitShabbatTest815(new Date(2016,2,19))
# Shabbat Shubah
shaharitShabbatTest815(new Date(2016,9,8))
# Weekday
shaharitWeekdayTest(new Date(2016,4,9))
| true | #= require site/shaharit
#= require qunit/helpers
occasionsThatDoNotAffectShaharit = ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"]
assertTimeEqual = QunitHelpers.assertTimeEqual
shaharitTest = (gregorianDate, expected, sofZmanKeriatShemaMinute = 31) ->
hebrewDate = new HebrewDate(gregorianDate)
sunrise = moment(gregorianDate).hour(6).minute(8).seconds(8)
sofZmanKeriatShema = moment(gregorianDate).hour(9).minute(sofZmanKeriatShemaMinute).seconds(9)
events = hebrewDate.occasions().filter((e) -> (-1 == occasionsThatDoNotAffectShaharit.indexOf(e))).join(" / ")
QUnit.test "When sunrise is at #{sunrise.format("hh:mm:ss A")} and Sof Zman Keriat Shema is at #{sofZmanKeriatShema.format("hh:mm:ss A")} on #{events}", (assert) ->
shaharit = new Shaharit(hebrewDate, sunrise, sofZmanKeriatShema)
if expected.selihot?
assertTimeEqual assert, shaharit.selihot(), expected.selihot, "Selihot"
else
assert.equal shaharit.selihot(), null, "Shaharit.selihot() does not return a time"
assert.equal shaharit.korbanot().length, expected.korbanot.length, "There are #{expected.korbanot.length} times for Korbanot"
for i in [0...(expected.korbanot.length)]
assertTimeEqual assert, shaharit.korbanot()[i], expected.korbanot[i], "Korbanot ##{i}"
assert.equal shaharit.hodu().length, expected.hodu.length, "There are #{expected.korbanot.length} times for Hodu"
for i in [0...(expected.hodu.length)]
assertTimeEqual assert, shaharit.hodu()[i], expected.hodu[i], "Hodu ##{i}"
if expected.nishmat?
assertTimeEqual assert, shaharit.nishmat(), expected.nishmat, "Nishmat"
else
assert.equal shaharit.nishmat(), null, "Shaharit.nishmat() does not return a time"
assertTimeEqual assert, shaharit.yishtabach(), expected.yishtabach,"Yishtabach"
assertTimeEqual assert, shaharit.amidah(), expected.amidah,"Amidah"
shaharitPesachTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(11), moment(date).hours(8).minutes(45)],
hodu: [moment(date).hours(5).minutes(26), moment(date).hours(9).minutes(0)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitShabuotTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(2)],
hodu: [moment(date).hours(5).minutes(17)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitYomKippurTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(4).minutes(58), moment(date).hours(7).minutes(0)],
hodu: [moment(date).hours(5).minutes(13), moment(date).hours(7).minutes(15)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitWeekdayTest = (date, selihot) ->
shaharitTest date,
selihot: selihot,
korbanot: [moment(date).hours(5).minutes(32)],
hodu: [moment(date).hours(5).minutes(48)],
yishtabach: moment(date).hours(5).minutes(59),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitShabbatTest815 = (date, yomTob = false) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(if yomTob then 11 else 13), moment(date).hours(8).minutes(15)],
hodu: [moment(date).hours(5).minutes(if yomTob then 26 else 28), moment(date).hours(8).minutes(30)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8)
shaharitShabbatTest745 = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(13), moment(date).hours(7).minutes(45)],
hodu: [moment(date).hours(5).minutes(28), moment(date).hours(8).minutes(0)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8),
13
shaharitShabbatTest845 = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(11), moment(date).hours(8).minutes(30)],
hodu: [moment(date).hours(5).minutes(26), moment(date).hours(8).minutes(45)],
nishmat: moment(date).hours(5).minutes(51),
yishtabach: moment(date).hours(5).minutes(55),
amidah: moment(date).hours(6).minutes(8).seconds(8),
13
shaharitHolHaMoedTest = (date) ->
shaharitTest date,
selihot: null,
korbanot: [moment(date).hours(5).minutes(30)],
hodu: [moment(date).hours(5).minutes(46)],
yishtabach: moment(date).hours(5).minutes(59),
amidah: moment(date).hours(6).minutes(8).seconds(8)
$ ->
# 1st Day of Pesach
shaharitPesachTest(new Date(2017,3,11))
# 2nd Day of Pesach
shaharitPesachTest(new Date(2017,3,12))
# PI:NAME:<NAME>END_PI
shaharitHolHaMoedTest(new Date(2017,3,16))
# 7th Day of Pesach
shaharitShabbatTest815(new Date(2017,3,17), true)
# 8th Day of Pesach
shaharitShabbatTest815(new Date(2017,3,18), true)
# 1st Day of Shabuot
shaharitShabuotTest(new Date(2021,4,17))
# 2nd Day of Shabuot
shaharitShabbatTest845(new Date(2021,4,18), true)
# 1st Day of PI:NAME:<NAME>END_PI
shaharitShabbatTest815(new Date(2016,9,3), true)
# PI:NAME:<NAME>END_PI
shaharitWeekdayTest(new Date(2016,8,4))
# PI:NAME:<NAME>END_PI
erebRoshHashana = new Date(2016,9,2)
shaharitWeekdayTest(erebRoshHashana, moment(erebRoshHashana).hours(4).minutes(42))
# PI:NAME:<NAME>END_PI
erebKippur = new Date(2016,9,11)
shaharitWeekdayTest(erebKippur, moment(erebKippur).hours(4).minutes(36))
# PI:NAME:<NAME>END_PI
shaharitYomKippurTest(new Date(2016,9,12))
# Shabbat (7:45)
shaharitShabbatTest745(new Date(2016,2,12))
# Shabbat (8:15)
shaharitShabbatTest815(new Date(2016,2,19))
# Shabbat Shubah
shaharitShabbatTest815(new Date(2016,9,8))
# Weekday
shaharitWeekdayTest(new Date(2016,4,9))
|
[
{
"context": "ts = true\n if exists is false\n if key is 'ms-sql'\n apps.push {\"key\": key, \"name\": name, \"in",
"end": 3428,
"score": 0.9984743595123291,
"start": 3422,
"tag": "KEY",
"value": "ms-sql"
}
] | source/js/app/models/ServerModel.coffee | CenturyLinkCloud/PriceEstimator | 9 | ServerModel = Backbone.Model.extend
HOURS_PER_DAY: "hours_per_day"
HOURS_PER_WEEK: "hours_per_week"
HOURS_PER_MONTH: "hours_per_month"
PERCENTAGE_OF_MONTH: "percentage_of_month"
HOURS_IN_MONTH: 720
DAYS_IN_MONTH: 30.41666667
WEEKS_IN_MONTH: 4.345238095
defaults:
type: "standard"
os: "linux"
cpu: 1
memory: 1
storage: 1
quantity: 1
usagePeriod: "percentage_of_month"
usage: 100
managed: false
managedApps: []
initialize: ->
@initPricing()
@.set("managedApps", [])
parse: (data) ->
return data
initPricing: ->
pricing = @.get("pricingMap").attributes.options
@.set("pricing", pricing)
updatePricing: (pricingMap) ->
@.set("pricingMap", pricingMap)
pricing = @.get("pricingMap").attributes.options
@.set("pricing", pricing)
totalCpuPerHour: ->
price = @.get("cpu") * @.get("pricing").cpu
return price
totalMemoryPerHour: ->
@.get("memory") * @.get("pricing").memory
totalOSPerHour: ->
os = @.get("os")
# os = "#{os}-managed" if @.get("managed")
@.get("pricing").os[os] * @.get("cpu")
managedBasePricePerHour: ->
if @.get("managed")
os = @.get("os")
osPrice = @.get("pricing").os["#{os}-managed"]
return osPrice
else
return 0
managedBasePricePerMonth: ->
return @priceForMonth(@managedBasePricePerHour())
utilityPricePerHourPerInstance: ->
@totalCpuPerHour() + @totalMemoryPerHour() + @totalOSPerHour() + @managedBasePricePerHour()
utilityPricePerHourTotal: ->
@utilityPricePerHourPerInstance() * @.get("quantity")
storagePricePerMonth: ->
type = @.get("type")
@.get("storage") * @.get("pricing").storage[type] * @.get("quantity")
managedAppPricePerMonth: (managedAppKey, instances, softwareId) ->
softwarePricing = @.get('pricing').software
software_selection = _.findWhere(softwarePricing, {name: softwareId})
appSoftwareHourlyPrice = if software_selection? then software_selection.price else 0
appSoftwareHourlyPrice *= @.get("cpu") || 1
appPerHour = @.get("pricing")[managedAppKey]
return ((@priceForMonth(appPerHour) + @priceForMonth(appSoftwareHourlyPrice)) * @.get("quantity")) * instances
managedAppsPricePerMonth: ->
apps = @.get("managedApps")
total = 0
_.each apps, (app) =>
total += @managedAppPricePerMonth(app.key, app.instances, app.softwareId)
return total
totalOSPricePerMonth: ->
@priceForMonth(@totalOSPerHour()) * @.get("quantity")
totalPricePerMonth: ->
utilityPerMonth = 0
utilityPerMonth = @priceForMonth(@utilityPricePerHourTotal())
total = utilityPerMonth + @storagePricePerMonth()
return total
totalPricePerMonthWithApps: ->
total = @totalPricePerMonth + @managedAppsPricePerMonth()
return total
priceForMonth: (hourlyPrice) ->
switch @.get("usagePeriod")
when @HOURS_PER_DAY
return hourlyPrice * @.get("usage") * @DAYS_IN_MONTH
when @HOURS_PER_WEEK
return hourlyPrice * @.get("usage") * @WEEKS_IN_MONTH
when @HOURS_PER_MONTH
return hourlyPrice * @.get("usage")
when @PERCENTAGE_OF_MONTH
return @.get("usage") / 100 * @HOURS_IN_MONTH * hourlyPrice
addManagedApp: (key, name) ->
apps = @.get("managedApps")
exists = false
_.each apps, (app) ->
if app.key is key
exists = true
if exists is false
if key is 'ms-sql'
apps.push {"key": key, "name": name, "instances": 1, "softwareId": "Microsoft SQL Server Standard Edition"}
else
apps.push {"key": key, "name": name, "instances": 1, "softwareId": ""}
@.set("managedApps", apps)
@.trigger "change", @
@.trigger "change:managedApps", @
updateManagedAppIntances: (key, quantity, softwareId) ->
apps = @.get("managedApps")
_.each apps, (app) ->
if app.key is key
app.instances = quantity
app.softwareId = softwareId
@.set("managedApps", apps)
@.trigger "change:managedApps", @
module.exports = ServerModel
| 50251 | ServerModel = Backbone.Model.extend
HOURS_PER_DAY: "hours_per_day"
HOURS_PER_WEEK: "hours_per_week"
HOURS_PER_MONTH: "hours_per_month"
PERCENTAGE_OF_MONTH: "percentage_of_month"
HOURS_IN_MONTH: 720
DAYS_IN_MONTH: 30.41666667
WEEKS_IN_MONTH: 4.345238095
defaults:
type: "standard"
os: "linux"
cpu: 1
memory: 1
storage: 1
quantity: 1
usagePeriod: "percentage_of_month"
usage: 100
managed: false
managedApps: []
initialize: ->
@initPricing()
@.set("managedApps", [])
parse: (data) ->
return data
initPricing: ->
pricing = @.get("pricingMap").attributes.options
@.set("pricing", pricing)
updatePricing: (pricingMap) ->
@.set("pricingMap", pricingMap)
pricing = @.get("pricingMap").attributes.options
@.set("pricing", pricing)
totalCpuPerHour: ->
price = @.get("cpu") * @.get("pricing").cpu
return price
totalMemoryPerHour: ->
@.get("memory") * @.get("pricing").memory
totalOSPerHour: ->
os = @.get("os")
# os = "#{os}-managed" if @.get("managed")
@.get("pricing").os[os] * @.get("cpu")
managedBasePricePerHour: ->
if @.get("managed")
os = @.get("os")
osPrice = @.get("pricing").os["#{os}-managed"]
return osPrice
else
return 0
managedBasePricePerMonth: ->
return @priceForMonth(@managedBasePricePerHour())
utilityPricePerHourPerInstance: ->
@totalCpuPerHour() + @totalMemoryPerHour() + @totalOSPerHour() + @managedBasePricePerHour()
utilityPricePerHourTotal: ->
@utilityPricePerHourPerInstance() * @.get("quantity")
storagePricePerMonth: ->
type = @.get("type")
@.get("storage") * @.get("pricing").storage[type] * @.get("quantity")
managedAppPricePerMonth: (managedAppKey, instances, softwareId) ->
softwarePricing = @.get('pricing').software
software_selection = _.findWhere(softwarePricing, {name: softwareId})
appSoftwareHourlyPrice = if software_selection? then software_selection.price else 0
appSoftwareHourlyPrice *= @.get("cpu") || 1
appPerHour = @.get("pricing")[managedAppKey]
return ((@priceForMonth(appPerHour) + @priceForMonth(appSoftwareHourlyPrice)) * @.get("quantity")) * instances
managedAppsPricePerMonth: ->
apps = @.get("managedApps")
total = 0
_.each apps, (app) =>
total += @managedAppPricePerMonth(app.key, app.instances, app.softwareId)
return total
totalOSPricePerMonth: ->
@priceForMonth(@totalOSPerHour()) * @.get("quantity")
totalPricePerMonth: ->
utilityPerMonth = 0
utilityPerMonth = @priceForMonth(@utilityPricePerHourTotal())
total = utilityPerMonth + @storagePricePerMonth()
return total
totalPricePerMonthWithApps: ->
total = @totalPricePerMonth + @managedAppsPricePerMonth()
return total
priceForMonth: (hourlyPrice) ->
switch @.get("usagePeriod")
when @HOURS_PER_DAY
return hourlyPrice * @.get("usage") * @DAYS_IN_MONTH
when @HOURS_PER_WEEK
return hourlyPrice * @.get("usage") * @WEEKS_IN_MONTH
when @HOURS_PER_MONTH
return hourlyPrice * @.get("usage")
when @PERCENTAGE_OF_MONTH
return @.get("usage") / 100 * @HOURS_IN_MONTH * hourlyPrice
addManagedApp: (key, name) ->
apps = @.get("managedApps")
exists = false
_.each apps, (app) ->
if app.key is key
exists = true
if exists is false
if key is '<KEY>'
apps.push {"key": key, "name": name, "instances": 1, "softwareId": "Microsoft SQL Server Standard Edition"}
else
apps.push {"key": key, "name": name, "instances": 1, "softwareId": ""}
@.set("managedApps", apps)
@.trigger "change", @
@.trigger "change:managedApps", @
updateManagedAppIntances: (key, quantity, softwareId) ->
apps = @.get("managedApps")
_.each apps, (app) ->
if app.key is key
app.instances = quantity
app.softwareId = softwareId
@.set("managedApps", apps)
@.trigger "change:managedApps", @
module.exports = ServerModel
| true | ServerModel = Backbone.Model.extend
HOURS_PER_DAY: "hours_per_day"
HOURS_PER_WEEK: "hours_per_week"
HOURS_PER_MONTH: "hours_per_month"
PERCENTAGE_OF_MONTH: "percentage_of_month"
HOURS_IN_MONTH: 720
DAYS_IN_MONTH: 30.41666667
WEEKS_IN_MONTH: 4.345238095
defaults:
type: "standard"
os: "linux"
cpu: 1
memory: 1
storage: 1
quantity: 1
usagePeriod: "percentage_of_month"
usage: 100
managed: false
managedApps: []
initialize: ->
@initPricing()
@.set("managedApps", [])
parse: (data) ->
return data
initPricing: ->
pricing = @.get("pricingMap").attributes.options
@.set("pricing", pricing)
updatePricing: (pricingMap) ->
@.set("pricingMap", pricingMap)
pricing = @.get("pricingMap").attributes.options
@.set("pricing", pricing)
totalCpuPerHour: ->
price = @.get("cpu") * @.get("pricing").cpu
return price
totalMemoryPerHour: ->
@.get("memory") * @.get("pricing").memory
totalOSPerHour: ->
os = @.get("os")
# os = "#{os}-managed" if @.get("managed")
@.get("pricing").os[os] * @.get("cpu")
managedBasePricePerHour: ->
if @.get("managed")
os = @.get("os")
osPrice = @.get("pricing").os["#{os}-managed"]
return osPrice
else
return 0
managedBasePricePerMonth: ->
return @priceForMonth(@managedBasePricePerHour())
utilityPricePerHourPerInstance: ->
@totalCpuPerHour() + @totalMemoryPerHour() + @totalOSPerHour() + @managedBasePricePerHour()
utilityPricePerHourTotal: ->
@utilityPricePerHourPerInstance() * @.get("quantity")
storagePricePerMonth: ->
type = @.get("type")
@.get("storage") * @.get("pricing").storage[type] * @.get("quantity")
managedAppPricePerMonth: (managedAppKey, instances, softwareId) ->
softwarePricing = @.get('pricing').software
software_selection = _.findWhere(softwarePricing, {name: softwareId})
appSoftwareHourlyPrice = if software_selection? then software_selection.price else 0
appSoftwareHourlyPrice *= @.get("cpu") || 1
appPerHour = @.get("pricing")[managedAppKey]
return ((@priceForMonth(appPerHour) + @priceForMonth(appSoftwareHourlyPrice)) * @.get("quantity")) * instances
managedAppsPricePerMonth: ->
apps = @.get("managedApps")
total = 0
_.each apps, (app) =>
total += @managedAppPricePerMonth(app.key, app.instances, app.softwareId)
return total
totalOSPricePerMonth: ->
@priceForMonth(@totalOSPerHour()) * @.get("quantity")
totalPricePerMonth: ->
utilityPerMonth = 0
utilityPerMonth = @priceForMonth(@utilityPricePerHourTotal())
total = utilityPerMonth + @storagePricePerMonth()
return total
totalPricePerMonthWithApps: ->
total = @totalPricePerMonth + @managedAppsPricePerMonth()
return total
priceForMonth: (hourlyPrice) ->
switch @.get("usagePeriod")
when @HOURS_PER_DAY
return hourlyPrice * @.get("usage") * @DAYS_IN_MONTH
when @HOURS_PER_WEEK
return hourlyPrice * @.get("usage") * @WEEKS_IN_MONTH
when @HOURS_PER_MONTH
return hourlyPrice * @.get("usage")
when @PERCENTAGE_OF_MONTH
return @.get("usage") / 100 * @HOURS_IN_MONTH * hourlyPrice
addManagedApp: (key, name) ->
apps = @.get("managedApps")
exists = false
_.each apps, (app) ->
if app.key is key
exists = true
if exists is false
if key is 'PI:KEY:<KEY>END_PI'
apps.push {"key": key, "name": name, "instances": 1, "softwareId": "Microsoft SQL Server Standard Edition"}
else
apps.push {"key": key, "name": name, "instances": 1, "softwareId": ""}
@.set("managedApps", apps)
@.trigger "change", @
@.trigger "change:managedApps", @
updateManagedAppIntances: (key, quantity, softwareId) ->
apps = @.get("managedApps")
_.each apps, (app) ->
if app.key is key
app.instances = quantity
app.softwareId = softwareId
@.set("managedApps", apps)
@.trigger "change:managedApps", @
module.exports = ServerModel
|
[
{
"context": "rvice', ->\n\n ID = '1234-abcd-5678-efgh'\n KEY = 'key-key-key'\n\n _.each [\n {name: 'BaseService', service: B",
"end": 1895,
"score": 0.8169090151786804,
"start": 1884,
"tag": "KEY",
"value": "key-key-key"
},
{
"context": " headers:\n Authorizatio... | src/spec/client/services/base.spec.coffee | commercetools/sphere-node-sdk | 13 | _ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{TaskQueue} = require '../../../lib/main'
BaseService = require '../../../lib/services/base'
CartDiscountService = require '../../../lib/services/cart-discounts'
CartService = require '../../../lib/services/carts'
CategoryService = require '../../../lib/services/categories'
ChannelService = require '../../../lib/services/channels'
CustomObjectService = require '../../../lib/services/custom-objects'
CustomerService = require '../../../lib/services/customers'
CustomerGroupService = require '../../../lib/services/customer-groups'
DiscountCodeService = require '../../../lib/services/discount-codes'
InventoryEntryService = require '../../../lib/services/inventory-entries'
MessageService = require '../../../lib/services/messages'
OrderService = require '../../../lib/services/orders'
PaymentService = require '../../../lib/services/payments'
ProductService = require '../../../lib/services/products'
ProductDiscountService = require '../../../lib/services/product-discounts'
ProductProjectionService = require '../../../lib/services/product-projections'
ProductTypeService = require '../../../lib/services/product-types'
ProjectService = require '../../../lib/services/project'
ReviewService = require '../../../lib/services/reviews'
ShippingMethodService = require '../../../lib/services/shipping-methods'
StateService = require '../../../lib/services/states'
TaxCategoryService = require '../../../lib/services/tax-categories'
TypeService = require '../../../lib/services/types'
ZoneService = require '../../../lib/services/zones'
describe 'Service', ->
ID = '1234-abcd-5678-efgh'
KEY = 'key-key-key'
_.each [
{name: 'BaseService', service: BaseService, path: '', blacklist: ['byKey']}
{name: 'CartDiscountService', service: CartDiscountService, path: '/cart-discounts', blacklist: ['byKey']}
{name: 'CartService', service: CartService, path: '/carts', blacklist: ['byKey']}
{name: 'CategoryService', service: CategoryService, path: '/categories', blacklist: ['byKey']}
{name: 'ChannelService', service: ChannelService, path: '/channels', blacklist: ['byKey']}
{name: 'CustomObjectService', service: CustomObjectService, path: '/custom-objects', blacklist: ['byKey']}
{name: 'CustomerService', service: CustomerService, path: '/customers', blacklist: ['byKey']}
{name: 'CustomerGroupService', service: CustomerGroupService, path: '/customer-groups', blacklist: ['byKey']}
{name: 'DiscountCodeService', service: DiscountCodeService, path: '/discount-codes', blacklist: ['byKey']}
{name: 'InventoryEntryService', service: InventoryEntryService, path: '/inventory', blacklist: ['byKey']}
{name: 'MessageService', service: MessageService, path: '/messages', blacklist: ['byKey', 'save', 'create', 'update', 'delete']}
{name: 'OrderService', service: OrderService, path: '/orders', blacklist: ['byKey', 'delete']}
{name: 'PaymentService', service: PaymentService, path: '/payments', blacklist: ['byKey']}
{name: 'ProductService', service: ProductService, path: '/products', blacklist: ['byKey']}
{name: 'ProductDiscountService', service: ProductDiscountService, path: '/product-discounts', blacklist: ['byKey']}
{name: 'ProductProjectionService', service: ProductProjectionService, path: '/product-projections', blacklist: ['byKey', 'save', 'create', 'update', 'delete']}
{name: 'ProductTypeService', service: ProductTypeService, path: '/product-types', blacklist: []}
{name: 'ProjectService', service: ProjectService, path: '', blacklist: ['byKey', 'save', 'create', 'update', 'delete']}
{name: 'ReviewService', service: ReviewService, path: '/reviews', blacklist: ['byKey', 'delete']}
{name: 'ShippingMethodService', service: ShippingMethodService, path: '/shipping-methods', blacklist: ['byKey']}
{name: 'StateService', service: StateService, path: '/states', blacklist: ['byKey']}
{name: 'TaxCategoryService', service: TaxCategoryService, path: '/tax-categories', blacklist: ['byKey']}
{name: 'TypeService', service: TypeService, path: '/types', blacklist: []}
{name: 'ZoneService', service: ZoneService, path: '/zones', blacklist: ['byKey']}
], (o) ->
describe ":: #{o.name}", ->
beforeEach ->
@restMock =
config: {}
GET: (endpoint, callback) ->
POST: -> (endpoint, payload, callback) ->
PUT: ->
DELETE: -> (endpoint, callback) ->
PAGED: -> (endpoint, callback) ->
_preRequest: ->
_doRequest: ->
@task = new TaskQueue
@service = new o.service
_rest: @restMock,
_task: @task
_stats:
includeHeaders: false
maskSensitiveHeaderData: false
afterEach ->
@service = null
@restMock = null
@task = null
it 'should have constants defined', ->
expect(o.service.baseResourceEndpoint).toBe o.path
it 'should not share variables between instances', ->
base1 = new o.service @restMock
base1._currentEndpoint = '/foo/1'
base2 = new o.service @restMock
expect(base2._currentEndpoint).toBe o.path
it 'should initialize with Rest client', ->
expect(@service).toBeDefined()
expect(@service._currentEndpoint).toBe o.path
it 'should reset default params', ->
expect(@service._params.query.where).toEqual []
expect(@service._params.query.operator).toBe 'and'
expect(@service._params.query.sort).toEqual []
expect(@service._params.query.expand).toEqual []
it 'should build endpoint with id', ->
@service.byId(ID)
expect(@service._currentEndpoint).toBe "#{o.path}/#{ID}"
it 'should throw if endpoint is already built with key', ->
expect(=> @service.byKey(KEY).byId(ID)).toThrow()
_.each [
['byId', '1234567890']
['where', 'key = "foo"']
['whereOperator', 'and']
['page', 2]
['perPage', 5]
['sort', 'createdAt']
], (f) ->
it "should chain '#{f[0]}'", ->
clazz = @service[f[0]](f[1])
expect(clazz).toEqual @service
promise = @service[f[0]](f[1]).fetch()
expect(promise.isPending()).toBe true
it 'should add where predicates to query', ->
@service.where('name(en="Foo")')
expect(@service._params.query.where).toEqual ['name(en%3D%22Foo%22)']
@service.where('variants is empty')
expect(@service._params.query.where).toEqual ['name(en%3D%22Foo%22)', 'variants%20is%20empty']
it 'should not add undefined where predicates', ->
@service.where()
expect(@service._params.query.where).toEqual []
it 'should set query logical operator', ->
@service.whereOperator('or')
expect(@service._params.query.operator).toBe 'or'
@service.whereOperator()
expect(@service._params.query.operator).toBe 'and'
@service.whereOperator('foo')
expect(@service._params.query.operator).toBe 'and'
_.each ['30s', '15m', '12h', '7d', '2w'], (type) ->
it "should allow to query for last #{type}", ->
@service.last(type)
expect(@service._params.query.where[0]).toMatch /lastModifiedAt%20%3E%20%2220\d\d-\d\d-\d\dT\d\d%3A\d\d%3A\d\d.\d\d\dZ%22/
it 'should throw an exception when the period for last can not be parsed', ->
expect(=> @service.last('30')).toThrow new Error "Cannot parse period '30'"
expect(=> @service.last('-1h')).toThrow new Error "Cannot parse period '-1h'"
it 'should do nothing for 0 as input', ->
@service.last('0m')
expect(_.size @service._params.query.where).toBe 0
it 'should add page number', ->
@service.page(5)
expect(@service._params.query.page).toBe 5
it 'should throw if page < 1', ->
expect(=> @service.page(0)).toThrow new Error 'Page must be a number >= 1'
it 'should add perPage number', ->
@service.perPage(50)
expect(@service._params.query.perPage).toBe 50
it 'should throw if perPage < 0', ->
expect(=> @service.perPage(-1)).toThrow new Error 'PerPage (limit) must be a number >= 0'
it 'should set flag for \'all\'', ->
@service.all()
expect(@service._fetchAll).toBe(true)
it 'should build query string', ->
queryString = @service
.where 'name(en = "Foo")'
.where 'id = "1234567890"'
.whereOperator 'or'
.page 3
.perPage 25
.sort 'attrib', false
.sort 'createdAt'
.expand 'lineItems[*].state[*].state'
._queryString()
expect(queryString).toBe 'where=name(en%20%3D%20%22Foo%22)%20or%20id%20%3D%20%221234567890%22&limit=25&offset=50&sort=attrib%20desc&sort=createdAt%20asc&expand=lineItems%5B*%5D.state%5B*%5D.state'
it 'should use given queryString, when building it', ->
queryString = @service
.where 'name(en = "Foo")'
.perPage 25
.expand 'lineItems[*].state[*].state'
.byQueryString('foo=bar')._queryString()
expect(queryString).toBe 'foo=bar'
it 'should set queryString, if given', ->
@service.byQueryString('where=name(en = "Foo")&limit=10&staged=true&sort=name asc&expand=foo.bar1&expand=foo.bar2')
expect(@service._params.queryString).toEqual 'where=name(en%20%3D%20%22Foo%22)&limit=10&staged=true&sort=name%20asc&expand=foo.bar1&expand=foo.bar2'
it 'should set queryString, if given (already encoding)', ->
@service.byQueryString('where=name(en%20%3D%20%22Foo%22)&limit=10&staged=true&sort=name%20asc&expand=foo.bar1&expand=foo.bar2', true)
expect(@service._params.queryString).toEqual 'where=name(en%20%3D%20%22Foo%22)&limit=10&staged=true&sort=name%20asc&expand=foo.bar1&expand=foo.bar2'
it 'should not use PAGED request when queryString is set', ->
spyOn(@restMock, 'PAGED')
spyOn(@restMock, 'GET')
@service.byQueryString('limit=10').all().fetch()
expect(@restMock.PAGED).not.toHaveBeenCalled()
expect(@restMock.GET).toHaveBeenCalledWith "#{o.path}?limit=10", jasmine.any(Function)
_.each [
['fetch']
['save', {foo: 'bar'}]
['delete', 2]
], (f) ->
if not _.contains(o.blacklist, f[0])
it "should reset params after creating a promise for #{f[0]}", ->
_service = @service.byId('123-abc').where('name = "foo"').page(2).perPage(10).sort('id').expand('foo.bar')
expect(@service._params.id).toBe '123-abc'
expect(@service._params.query.where).toEqual [encodeURIComponent('name = "foo"')]
expect(@service._params.query.operator).toBe 'and'
expect(@service._params.query.sort).toEqual [encodeURIComponent('id asc')]
expect(@service._params.query.page).toBe 2
expect(@service._params.query.perPage).toBe 10
expect(@service._params.query.expand).toEqual [encodeURIComponent('foo.bar')]
if f[1]
_service[f[0]](f[1])
else
_service[f[0]]()
expect(@service._params.query.where).toEqual []
expect(@service._params.query.operator).toBe 'and'
expect(@service._params.query.sort).toEqual []
expect(@service._params.query.expand).toEqual []
if not _.contains(o.blacklist, 'byKey')
it 'should build endpoint with key', ->
@service.byKey(KEY)
expect(@service._currentEndpoint).toBe "#{o.path}/key=#{KEY}"
it 'should throw if endpoint is already built with id', ->
expect(=> @service.byId(ID).byKey(KEY)).toThrow()
if not _.contains(o.blacklist, 'save')
it 'should censor authorization headers in case of a timeout', (done) ->
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback new Error('timeout'), null, null
@service._rest._options =
headers:
Authorization: 'Bearer 9y1cbq8y34cnq9yap8enxrfgyqp934ncgp9'
@service._stats.maskSensitiveHeaderData = true
@service._stats.includeHeaders = true
@service.save({foo: 'bar'})
.then -> done('Should not happen')
.catch (error) ->
expect(error.body).toEqual
message: 'timeout'
originalRequest:
options:
headers:
Authorization: 'Bearer **********'
endpoint: o.path
payload:
foo: 'bar'
done()
.done()
it 'should censor authorization headers', (done) ->
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback null, {
statusCode: 400,
req: {
_header: 'Authorization: Bearer 9y1cbq8y34cnq9yap8enxrfgyqp934ncgp9'
},
request: {
headers: {
Authorization: 'Bearer 9y1cbq8y34cnq9yap8enxrfgyqp934ncgp9'
}
},
headers: {
Authorization: 'Bearer 9y1cbq8y34cnq9yap8enxrfgyqp934ncgp9'
}
}, {statusCode: 400, message: 'Oops, something went wrong'}
@service._rest._options =
headers:
Authorization: 'Bearer 9y1cbq8y34cnq9yap8enxrfgyqp934ncgp9'
@service._stats.maskSensitiveHeaderData = true
@service._stats.includeHeaders = true
@service.save({foo: 'bar'})
.then -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'BadRequest'
expect(error.body).toEqual
http:
request:
method: undefined
httpVersion: undefined
uri: undefined
header: 'Authorization: Bearer **********'
headers:
Authorization: 'Bearer **********'
response:
headers:
Authorization: 'Bearer **********'
statusCode: 400
message: 'Oops, something went wrong'
originalRequest:
options:
headers:
Authorization: 'Bearer **********'
endpoint: o.path
payload:
foo: 'bar'
done()
.done()
it 'should pass original request to failed response', (done) ->
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback null, {statusCode: 400}, {statusCode: 400, message: 'Oops, something went wrong'}
@service.save({foo: 'bar'})
.then -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'BadRequest'
expect(error.body).toEqual
statusCode: 400
message: 'Oops, something went wrong'
originalRequest:
options: {}
endpoint: o.path
payload:
foo: 'bar'
done()
.done()
it 'should pass headers info', (done) ->
@service._stats.includeHeaders = true
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback null,
statusCode: 200
httpVersion: '1.1'
request:
method: 'POST'
uri: {}
headers: {}
req:
_header: 'POST /foo HTTP/1.1'
headers: {}
, {foo: 'bar'}
@service.save({foo: 'bar'})
.then (result) ->
expect(result).toEqual
http:
request:
method: 'POST'
httpVersion: '1.1'
uri: {}
header: 'POST /foo HTTP/1.1'
headers: {}
response:
headers: {}
statusCode: 200
body:
foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
.done()
describe ':: process', ->
it 'should return promise', ->
promise = @service.process( -> )
expect(promise.isPending()).toBe true
it 'should call process function for one page', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {
count: 1
offset: 0
results: []
})
fn = (payload) -> Promise.resolve 'done'
@service.process(fn)
.then (result) ->
expect(result).toEqual ['done']
done()
.catch (error) -> done(_.prettify(error))
it 'should call process function for several pages (default sorting)', (done) ->
offset = -20
count = 20
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 10 else count
offset: offset
results: _.map (if offset is 40 then [1..10] else [1..20]), (i) -> {id: "id_#{i}", endpoint}
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.page(3).perPage(count).process(fn)
.then (result) ->
expect(_.size result).toBe 3
expect(result[0].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&withTotal=false$/
expect(result[1].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&withTotal=false&where=id%20%3E%20%22id_20%22$/
expect(result[2].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&withTotal=false&where=id%20%3E%20%22id_20%22$/
done()
.catch (error) -> done(_.prettify(error))
it 'should call process function for several pages (given sorting)', (done) ->
offset = -20
count = 20
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 10 else count
offset: offset
results: _.map (if offset is 40 then [1..10] else [1..20]), (i) -> {id: "id_#{i}", endpoint}
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.page(3).perPage(count).sort('foo').process(fn)
.then (result) ->
expect(_.size result).toBe 3
expect(result[0].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&sort=foo%20asc&withTotal=false$/
expect(result[1].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&sort=foo%20asc&withTotal=false&where=id%20%3E%20%22id_20%22$/
expect(result[2].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&sort=foo%20asc&withTotal=false&where=id%20%3E%20%22id_20%22$/
done()
.catch (error) -> done(_.prettify(error))
it 'should fail if the process functions rejects', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {total: 100})
fn = (payload) ->
Promise.reject 'bad luck'
@service.process(fn)
.then (result) -> done 'not expected!'
.catch (error) ->
expect(error).toBe 'bad luck'
done()
it 'should call each page with the same query', (done) ->
offset = -20
count = 20
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 10 else count
offset: offset
results: _.map (if offset is 40 then [1..10] else [1..20]), (i) -> {id: "id_#{i}", endpoint}
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.sort('name', false)
.where('foo=bar')
.where('hello=world')
.whereOperator('or')
.process(fn)
.then (result) ->
expect(_.size result).toBe 3
expect(result[0].endpoint).toMatch /\?sort=id%20asc&where=foo%3Dbar%20or%20hello%3Dworld&sort=name%20desc&withTotal=false$/
expect(result[1].endpoint).toMatch /\?sort=id%20asc&where=foo%3Dbar%20or%20hello%3Dworld&sort=name%20desc&withTotal=false&where=id%20%3E%20%22id_20%22$/
expect(result[2].endpoint).toMatch /\?sort=id%20asc&where=foo%3Dbar%20or%20hello%3Dworld&sort=name%20desc&withTotal=false&where=id%20%3E%20%22id_20%22$/
done()
.catch (error) -> done(_.prettify(error))
it 'should throw error if function is missing', ->
spyOn(@restMock, 'GET')
expect(=> @service.process()).toThrow new Error 'Please provide a function to process the elements'
expect(@restMock.GET).not.toHaveBeenCalled()
it 'should set the limit to 20 if it is 0', ->
spyOn(@restMock, 'GET')
@service._params.query.perPage = 0
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.process(fn)
.then () ->
actual = @service._params.query.limit
expected = 20
expect(actual).toEqual(expected)
done()
.catch (error) -> done(_.prettify(error))
it 'should not accumulate results if explicitly set', (done) ->
offset = -20
count = 1
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 0 else count
offset: offset
results: if offset is 40 then [] else [{id: '123', endpoint}]
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.perPage(1).process(fn, accumulate: false)
.then (result) ->
expect(result).toEqual []
done()
.catch (error) -> done(_.prettify(error))
describe ':: fetch', ->
it 'should return promise on fetch', ->
promise = @service.fetch()
expect(promise.isPending()).toBe true
it 'should resolve the promise on fetch', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
@service.fetch().then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on fetch (404)', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: o.path
done()
it 'should return error message for endpoint not found with query', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service
.where()
.page(1)
.perPage()
.fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: o.path
done()
it 'should reject the promise on fetch', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback('foo', null, null)
@service.fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: o.path
done()
it 'should send request with id, if provided', ->
spyOn(@restMock, 'GET')
@service.byId(ID).fetch()
expect(@restMock.GET).toHaveBeenCalledWith "#{o.path}/#{ID}", jasmine.any(Function)
it 'should not do a paged request if perPage is 0', ->
spyOn(@restMock, 'PAGED')
spyOn(@restMock, 'GET')
@service.byId(ID).sort('createdAt', true).perPage(0).fetch()
expect(@restMock.PAGED).not.toHaveBeenCalled()
expect(@restMock.GET).toHaveBeenCalledWith "#{o.path}/#{ID}?limit=0&sort=createdAt%20asc", jasmine.any(Function)
it 'should do a paged request if all() was used before fetch', ->
spyOn(@restMock, 'PAGED')
spyOn(@restMock, 'GET')
@service.byId(ID).sort('createdAt', true).all().fetch()
expect(@restMock.PAGED).toHaveBeenCalledWith "#{o.path}/#{ID}?sort=createdAt%20asc", jasmine.any(Function)
expect(@restMock.GET).not.toHaveBeenCalled()
describe ':: paged', ->
it 'should resolve the promise on (paged) fetch', (done) ->
spyOn(@restMock, 'PAGED').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {total: 1, results: [{foo: 'bar'}]})
@service.all().fetch()
.then (result) ->
expect(result.statusCode).toBe 200
expect(result.body.total).toBe 1
expect(result.body.results.length).toBe 1
expect(result.body.results[0]).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on (paged) fetch (404)', (done) ->
spyOn(@restMock, 'PAGED').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.all().fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: "#{o.path}?sort=id%20asc"
done()
it 'should reject the promise on (paged) fetch', (done) ->
spyOn(@restMock, 'PAGED').andCallFake (endpoint, callback) -> callback('foo', null, null)
@service.all().fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: "#{o.path}?sort=id%20asc"
done()
it 'should set default sorting if not provided (fetching all)', ->
spyOn(@service, '_paged')
@service.all().fetch()
expect(@service._paged).toHaveBeenCalledWith "#{o.path}?sort=id%20asc"
it 'should not set default sorting if provided (fetching all)', ->
spyOn(@service, '_paged')
@service.all().sort('foo').fetch()
expect(@service._paged).toHaveBeenCalledWith "#{o.path}?sort=foo%20asc"
if not _.contains(o.blacklist, 'save')
describe ':: save', ->
it 'should return promise on save', ->
promise = @service.save {foo: 'bar'}
expect(promise.isPending()).toBe true
it 'should resolve the promise on save', (done) ->
spyOn(@restMock, 'POST').andCallFake (endpoint, payload, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
@service.save({foo: 'bar'}).then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on save (404)', (done) ->
spyOn(@restMock, 'POST').andCallFake (endpoint, payload, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.save({foo: 'bar'})
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: o.path
payload:
foo: 'bar'
done()
it 'should throw error if payload is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.save()).toThrow new Error "Body payload is required for creating a resource (endpoint: #{@service.constructor.baseResourceEndpoint})"
expect(@restMock.POST).not.toHaveBeenCalled()
it 'should reject the promise on save', (done) ->
spyOn(@restMock, 'POST').andCallFake (endpoint, payload, callback) -> callback('foo', null, null)
@service.save({foo: 'bar'})
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: o.path
payload:
foo: 'bar'
done()
it 'should send request for base endpoint', ->
spyOn(@restMock, 'POST')
@service.save({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith o.path, {foo: 'bar'}, jasmine.any(Function)
it 'should send request for base endpoint allowing expand param', ->
spyOn(@restMock, 'POST')
@service
.expand('foo.bar') # should use it
.page(1) # should discard
.save({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}?expand=foo.bar", {foo: 'bar'}, jasmine.any(Function)
if not _.contains(o.blacklist, 'create')
describe ':: create', ->
it 'should be an alias for \'save\'', ->
spyOn(@service, 'save')
@service.create foo: 'bar'
expect(@service.save).toHaveBeenCalledWith foo: 'bar'
if not _.contains(o.blacklist, 'update')
describe ':: update', ->
it 'should send request for current endpoint with Id', ->
spyOn(@restMock, 'POST')
@service.byId(ID).update({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}/#{ID}", {foo: 'bar'}, jasmine.any(Function)
if not _.contains(o.blacklist, 'byKey')
it 'should send request for current endpoint with Key', ->
spyOn(@restMock, 'POST')
@service.byKey(KEY).update({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}/key=#{KEY}", {foo: 'bar'}, jasmine.any(Function)
it 'should throw error if id and key is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.update()).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'"
expect(@restMock.POST).not.toHaveBeenCalled()
else
it 'should throw error if id is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.update()).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)'"
expect(@restMock.POST).not.toHaveBeenCalled()
it 'should throw error if payload is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.byId(ID).update()).toThrow new Error "Body payload is required for updating a resource (endpoint: #{@service._currentEndpoint}/#{ID})"
expect(@restMock.POST).not.toHaveBeenCalled()
it 'should use correct endpoints when calling update and create', ->
spyOn(@restMock, 'POST')
@service.byId(ID).update({foo: 'bar1'})
@service.create({foo: 'bar2'})
@service.byId(ID).update({foo: 'bar3'})
@service.create({foo: 'bar4'})
expect(@restMock.POST.calls.length).toBe 4
expect(@restMock.POST.calls[0].args[0]).toEqual "#{o.path}/#{ID}"
expect(@restMock.POST.calls[0].args[1]).toEqual {foo: 'bar1'}
expect(@restMock.POST.calls[1].args[0]).toEqual o.path
expect(@restMock.POST.calls[1].args[1]).toEqual {foo: 'bar2'}
expect(@restMock.POST.calls[2].args[0]).toEqual "#{o.path}/#{ID}"
expect(@restMock.POST.calls[2].args[1]).toEqual {foo: 'bar3'}
expect(@restMock.POST.calls[3].args[0]).toEqual o.path
expect(@restMock.POST.calls[3].args[1]).toEqual {foo: 'bar4'}
it 'should send request for base endpoint allowing expand param', ->
spyOn(@restMock, 'POST')
@service
.expand('foo.bar') # should use it
.page(1) # should discard
.byId(ID)
.update({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}/#{ID}?expand=foo.bar", {foo: 'bar'}, jasmine.any(Function)
if not _.contains(o.blacklist, 'delete')
describe ':: delete', ->
it 'should throw error if version is missing', ->
spyOn(@restMock, 'DELETE')
expect(=> @service.delete()).toThrow new Error "Version is required for deleting a resource (endpoint: #{@service._currentEndpoint})"
expect(@restMock.DELETE).not.toHaveBeenCalled()
if not _.contains(o.blacklist, 'byKey')
it 'should send request for current endpoint with Key', ->
spyOn(@restMock, 'DELETE')
@service.byKey(KEY).delete(1)
expect(@restMock.DELETE).toHaveBeenCalledWith "#{o.path}/key=#{KEY}?version=1", jasmine.any(Function)
it 'should throw error if id and key is missing', ->
spyOn(@restMock, 'DELETE')
expect(=> @service.delete(1)).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'"
expect(@restMock.DELETE).not.toHaveBeenCalled()
else
it 'should throw error if id is missing', ->
spyOn(@restMock, 'DELETE')
expect(=> @service.delete(1)).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)'"
expect(@restMock.DELETE).not.toHaveBeenCalled()
it 'should return promise on delete', ->
promise = @service.byId('123-abc').delete(1)
expect(promise.isPending()).toBe true
it 'should resolve the promise on delete', (done) ->
spyOn(@restMock, 'DELETE').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
@service.byId('123-abc').delete(1).then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on delete (404)', (done) ->
spyOn(@restMock, 'DELETE').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.byId('123-abc').delete(1)
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: "#{o.path}/123-abc?version=1"
done()
it 'should reject the promise on delete', (done) ->
spyOn(@restMock, 'DELETE').andCallFake (endpoint, callback) -> callback('foo', null, null)
@service.byId('123-abc').delete(1)
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: "#{o.path}/123-abc?version=1"
done()
| 35566 | _ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{TaskQueue} = require '../../../lib/main'
BaseService = require '../../../lib/services/base'
CartDiscountService = require '../../../lib/services/cart-discounts'
CartService = require '../../../lib/services/carts'
CategoryService = require '../../../lib/services/categories'
ChannelService = require '../../../lib/services/channels'
CustomObjectService = require '../../../lib/services/custom-objects'
CustomerService = require '../../../lib/services/customers'
CustomerGroupService = require '../../../lib/services/customer-groups'
DiscountCodeService = require '../../../lib/services/discount-codes'
InventoryEntryService = require '../../../lib/services/inventory-entries'
MessageService = require '../../../lib/services/messages'
OrderService = require '../../../lib/services/orders'
PaymentService = require '../../../lib/services/payments'
ProductService = require '../../../lib/services/products'
ProductDiscountService = require '../../../lib/services/product-discounts'
ProductProjectionService = require '../../../lib/services/product-projections'
ProductTypeService = require '../../../lib/services/product-types'
ProjectService = require '../../../lib/services/project'
ReviewService = require '../../../lib/services/reviews'
ShippingMethodService = require '../../../lib/services/shipping-methods'
StateService = require '../../../lib/services/states'
TaxCategoryService = require '../../../lib/services/tax-categories'
TypeService = require '../../../lib/services/types'
ZoneService = require '../../../lib/services/zones'
describe 'Service', ->
ID = '1234-abcd-5678-efgh'
KEY = '<KEY>'
_.each [
{name: 'BaseService', service: BaseService, path: '', blacklist: ['byKey']}
{name: 'CartDiscountService', service: CartDiscountService, path: '/cart-discounts', blacklist: ['byKey']}
{name: 'CartService', service: CartService, path: '/carts', blacklist: ['byKey']}
{name: 'CategoryService', service: CategoryService, path: '/categories', blacklist: ['byKey']}
{name: 'ChannelService', service: ChannelService, path: '/channels', blacklist: ['byKey']}
{name: 'CustomObjectService', service: CustomObjectService, path: '/custom-objects', blacklist: ['byKey']}
{name: 'CustomerService', service: CustomerService, path: '/customers', blacklist: ['byKey']}
{name: 'CustomerGroupService', service: CustomerGroupService, path: '/customer-groups', blacklist: ['byKey']}
{name: 'DiscountCodeService', service: DiscountCodeService, path: '/discount-codes', blacklist: ['byKey']}
{name: 'InventoryEntryService', service: InventoryEntryService, path: '/inventory', blacklist: ['byKey']}
{name: 'MessageService', service: MessageService, path: '/messages', blacklist: ['byKey', 'save', 'create', 'update', 'delete']}
{name: 'OrderService', service: OrderService, path: '/orders', blacklist: ['byKey', 'delete']}
{name: 'PaymentService', service: PaymentService, path: '/payments', blacklist: ['byKey']}
{name: 'ProductService', service: ProductService, path: '/products', blacklist: ['byKey']}
{name: 'ProductDiscountService', service: ProductDiscountService, path: '/product-discounts', blacklist: ['byKey']}
{name: 'ProductProjectionService', service: ProductProjectionService, path: '/product-projections', blacklist: ['byKey', 'save', 'create', 'update', 'delete']}
{name: 'ProductTypeService', service: ProductTypeService, path: '/product-types', blacklist: []}
{name: 'ProjectService', service: ProjectService, path: '', blacklist: ['byKey', 'save', 'create', 'update', 'delete']}
{name: 'ReviewService', service: ReviewService, path: '/reviews', blacklist: ['byKey', 'delete']}
{name: 'ShippingMethodService', service: ShippingMethodService, path: '/shipping-methods', blacklist: ['byKey']}
{name: 'StateService', service: StateService, path: '/states', blacklist: ['byKey']}
{name: 'TaxCategoryService', service: TaxCategoryService, path: '/tax-categories', blacklist: ['byKey']}
{name: 'TypeService', service: TypeService, path: '/types', blacklist: []}
{name: 'ZoneService', service: ZoneService, path: '/zones', blacklist: ['byKey']}
], (o) ->
describe ":: #{o.name}", ->
beforeEach ->
@restMock =
config: {}
GET: (endpoint, callback) ->
POST: -> (endpoint, payload, callback) ->
PUT: ->
DELETE: -> (endpoint, callback) ->
PAGED: -> (endpoint, callback) ->
_preRequest: ->
_doRequest: ->
@task = new TaskQueue
@service = new o.service
_rest: @restMock,
_task: @task
_stats:
includeHeaders: false
maskSensitiveHeaderData: false
afterEach ->
@service = null
@restMock = null
@task = null
it 'should have constants defined', ->
expect(o.service.baseResourceEndpoint).toBe o.path
it 'should not share variables between instances', ->
base1 = new o.service @restMock
base1._currentEndpoint = '/foo/1'
base2 = new o.service @restMock
expect(base2._currentEndpoint).toBe o.path
it 'should initialize with Rest client', ->
expect(@service).toBeDefined()
expect(@service._currentEndpoint).toBe o.path
it 'should reset default params', ->
expect(@service._params.query.where).toEqual []
expect(@service._params.query.operator).toBe 'and'
expect(@service._params.query.sort).toEqual []
expect(@service._params.query.expand).toEqual []
it 'should build endpoint with id', ->
@service.byId(ID)
expect(@service._currentEndpoint).toBe "#{o.path}/#{ID}"
it 'should throw if endpoint is already built with key', ->
expect(=> @service.byKey(KEY).byId(ID)).toThrow()
_.each [
['byId', '1234567890']
['where', 'key = "foo"']
['whereOperator', 'and']
['page', 2]
['perPage', 5]
['sort', 'createdAt']
], (f) ->
it "should chain '#{f[0]}'", ->
clazz = @service[f[0]](f[1])
expect(clazz).toEqual @service
promise = @service[f[0]](f[1]).fetch()
expect(promise.isPending()).toBe true
it 'should add where predicates to query', ->
@service.where('name(en="Foo")')
expect(@service._params.query.where).toEqual ['name(en%3D%22Foo%22)']
@service.where('variants is empty')
expect(@service._params.query.where).toEqual ['name(en%3D%22Foo%22)', 'variants%20is%20empty']
it 'should not add undefined where predicates', ->
@service.where()
expect(@service._params.query.where).toEqual []
it 'should set query logical operator', ->
@service.whereOperator('or')
expect(@service._params.query.operator).toBe 'or'
@service.whereOperator()
expect(@service._params.query.operator).toBe 'and'
@service.whereOperator('foo')
expect(@service._params.query.operator).toBe 'and'
_.each ['30s', '15m', '12h', '7d', '2w'], (type) ->
it "should allow to query for last #{type}", ->
@service.last(type)
expect(@service._params.query.where[0]).toMatch /lastModifiedAt%20%3E%20%2220\d\d-\d\d-\d\dT\d\d%3A\d\d%3A\d\d.\d\d\dZ%22/
it 'should throw an exception when the period for last can not be parsed', ->
expect(=> @service.last('30')).toThrow new Error "Cannot parse period '30'"
expect(=> @service.last('-1h')).toThrow new Error "Cannot parse period '-1h'"
it 'should do nothing for 0 as input', ->
@service.last('0m')
expect(_.size @service._params.query.where).toBe 0
it 'should add page number', ->
@service.page(5)
expect(@service._params.query.page).toBe 5
it 'should throw if page < 1', ->
expect(=> @service.page(0)).toThrow new Error 'Page must be a number >= 1'
it 'should add perPage number', ->
@service.perPage(50)
expect(@service._params.query.perPage).toBe 50
it 'should throw if perPage < 0', ->
expect(=> @service.perPage(-1)).toThrow new Error 'PerPage (limit) must be a number >= 0'
it 'should set flag for \'all\'', ->
@service.all()
expect(@service._fetchAll).toBe(true)
it 'should build query string', ->
queryString = @service
.where 'name(en = "Foo")'
.where 'id = "1234567890"'
.whereOperator 'or'
.page 3
.perPage 25
.sort 'attrib', false
.sort 'createdAt'
.expand 'lineItems[*].state[*].state'
._queryString()
expect(queryString).toBe 'where=name(en%20%3D%20%22Foo%22)%20or%20id%20%3D%20%221234567890%22&limit=25&offset=50&sort=attrib%20desc&sort=createdAt%20asc&expand=lineItems%5B*%5D.state%5B*%5D.state'
it 'should use given queryString, when building it', ->
queryString = @service
.where 'name(en = "Foo")'
.perPage 25
.expand 'lineItems[*].state[*].state'
.byQueryString('foo=bar')._queryString()
expect(queryString).toBe 'foo=bar'
it 'should set queryString, if given', ->
@service.byQueryString('where=name(en = "Foo")&limit=10&staged=true&sort=name asc&expand=foo.bar1&expand=foo.bar2')
expect(@service._params.queryString).toEqual 'where=name(en%20%3D%20%22Foo%22)&limit=10&staged=true&sort=name%20asc&expand=foo.bar1&expand=foo.bar2'
it 'should set queryString, if given (already encoding)', ->
@service.byQueryString('where=name(en%20%3D%20%22Foo%22)&limit=10&staged=true&sort=name%20asc&expand=foo.bar1&expand=foo.bar2', true)
expect(@service._params.queryString).toEqual 'where=name(en%20%3D%20%22Foo%22)&limit=10&staged=true&sort=name%20asc&expand=foo.bar1&expand=foo.bar2'
it 'should not use PAGED request when queryString is set', ->
spyOn(@restMock, 'PAGED')
spyOn(@restMock, 'GET')
@service.byQueryString('limit=10').all().fetch()
expect(@restMock.PAGED).not.toHaveBeenCalled()
expect(@restMock.GET).toHaveBeenCalledWith "#{o.path}?limit=10", jasmine.any(Function)
_.each [
['fetch']
['save', {foo: 'bar'}]
['delete', 2]
], (f) ->
if not _.contains(o.blacklist, f[0])
it "should reset params after creating a promise for #{f[0]}", ->
_service = @service.byId('123-abc').where('name = "foo"').page(2).perPage(10).sort('id').expand('foo.bar')
expect(@service._params.id).toBe '123-abc'
expect(@service._params.query.where).toEqual [encodeURIComponent('name = "foo"')]
expect(@service._params.query.operator).toBe 'and'
expect(@service._params.query.sort).toEqual [encodeURIComponent('id asc')]
expect(@service._params.query.page).toBe 2
expect(@service._params.query.perPage).toBe 10
expect(@service._params.query.expand).toEqual [encodeURIComponent('foo.bar')]
if f[1]
_service[f[0]](f[1])
else
_service[f[0]]()
expect(@service._params.query.where).toEqual []
expect(@service._params.query.operator).toBe 'and'
expect(@service._params.query.sort).toEqual []
expect(@service._params.query.expand).toEqual []
if not _.contains(o.blacklist, 'byKey')
it 'should build endpoint with key', ->
@service.byKey(KEY)
expect(@service._currentEndpoint).toBe "#{o.path}/key=#{KEY}"
it 'should throw if endpoint is already built with id', ->
expect(=> @service.byId(ID).byKey(KEY)).toThrow()
if not _.contains(o.blacklist, 'save')
it 'should censor authorization headers in case of a timeout', (done) ->
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback new Error('timeout'), null, null
@service._rest._options =
headers:
Authorization: 'Bearer 9<KEY>'
@service._stats.maskSensitiveHeaderData = true
@service._stats.includeHeaders = true
@service.save({foo: 'bar'})
.then -> done('Should not happen')
.catch (error) ->
expect(error.body).toEqual
message: 'timeout'
originalRequest:
options:
headers:
Authorization: 'Bearer **********'
endpoint: o.path
payload:
foo: 'bar'
done()
.done()
it 'should censor authorization headers', (done) ->
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback null, {
statusCode: 400,
req: {
_header: 'Authorization: Bearer 9<KEY>'
},
request: {
headers: {
Authorization: 'Bearer 9<KEY>'
}
},
headers: {
Authorization: 'Bearer <KEY>'
}
}, {statusCode: 400, message: 'Oops, something went wrong'}
@service._rest._options =
headers:
Authorization: 'Bearer <KEY>'
@service._stats.maskSensitiveHeaderData = true
@service._stats.includeHeaders = true
@service.save({foo: 'bar'})
.then -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'BadRequest'
expect(error.body).toEqual
http:
request:
method: undefined
httpVersion: undefined
uri: undefined
header: 'Authorization: Bearer **********'
headers:
Authorization: 'Bearer **********'
response:
headers:
Authorization: 'Bearer **********'
statusCode: 400
message: 'Oops, something went wrong'
originalRequest:
options:
headers:
Authorization: 'Bearer **********'
endpoint: o.path
payload:
foo: 'bar'
done()
.done()
it 'should pass original request to failed response', (done) ->
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback null, {statusCode: 400}, {statusCode: 400, message: 'Oops, something went wrong'}
@service.save({foo: 'bar'})
.then -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'BadRequest'
expect(error.body).toEqual
statusCode: 400
message: 'Oops, something went wrong'
originalRequest:
options: {}
endpoint: o.path
payload:
foo: 'bar'
done()
.done()
it 'should pass headers info', (done) ->
@service._stats.includeHeaders = true
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback null,
statusCode: 200
httpVersion: '1.1'
request:
method: 'POST'
uri: {}
headers: {}
req:
_header: 'POST /foo HTTP/1.1'
headers: {}
, {foo: 'bar'}
@service.save({foo: 'bar'})
.then (result) ->
expect(result).toEqual
http:
request:
method: 'POST'
httpVersion: '1.1'
uri: {}
header: 'POST /foo HTTP/1.1'
headers: {}
response:
headers: {}
statusCode: 200
body:
foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
.done()
describe ':: process', ->
it 'should return promise', ->
promise = @service.process( -> )
expect(promise.isPending()).toBe true
it 'should call process function for one page', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {
count: 1
offset: 0
results: []
})
fn = (payload) -> Promise.resolve 'done'
@service.process(fn)
.then (result) ->
expect(result).toEqual ['done']
done()
.catch (error) -> done(_.prettify(error))
it 'should call process function for several pages (default sorting)', (done) ->
offset = -20
count = 20
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 10 else count
offset: offset
results: _.map (if offset is 40 then [1..10] else [1..20]), (i) -> {id: "id_#{i}", endpoint}
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.page(3).perPage(count).process(fn)
.then (result) ->
expect(_.size result).toBe 3
expect(result[0].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&withTotal=false$/
expect(result[1].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&withTotal=false&where=id%20%3E%20%22id_20%22$/
expect(result[2].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&withTotal=false&where=id%20%3E%20%22id_20%22$/
done()
.catch (error) -> done(_.prettify(error))
it 'should call process function for several pages (given sorting)', (done) ->
offset = -20
count = 20
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 10 else count
offset: offset
results: _.map (if offset is 40 then [1..10] else [1..20]), (i) -> {id: "id_#{i}", endpoint}
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.page(3).perPage(count).sort('foo').process(fn)
.then (result) ->
expect(_.size result).toBe 3
expect(result[0].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&sort=foo%20asc&withTotal=false$/
expect(result[1].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&sort=foo%20asc&withTotal=false&where=id%20%3E%20%22id_20%22$/
expect(result[2].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&sort=foo%20asc&withTotal=false&where=id%20%3E%20%22id_20%22$/
done()
.catch (error) -> done(_.prettify(error))
it 'should fail if the process functions rejects', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {total: 100})
fn = (payload) ->
Promise.reject 'bad luck'
@service.process(fn)
.then (result) -> done 'not expected!'
.catch (error) ->
expect(error).toBe 'bad luck'
done()
it 'should call each page with the same query', (done) ->
offset = -20
count = 20
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 10 else count
offset: offset
results: _.map (if offset is 40 then [1..10] else [1..20]), (i) -> {id: "id_#{i}", endpoint}
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.sort('name', false)
.where('foo=bar')
.where('hello=world')
.whereOperator('or')
.process(fn)
.then (result) ->
expect(_.size result).toBe 3
expect(result[0].endpoint).toMatch /\?sort=id%20asc&where=foo%3Dbar%20or%20hello%3Dworld&sort=name%20desc&withTotal=false$/
expect(result[1].endpoint).toMatch /\?sort=id%20asc&where=foo%3Dbar%20or%20hello%3Dworld&sort=name%20desc&withTotal=false&where=id%20%3E%20%22id_20%22$/
expect(result[2].endpoint).toMatch /\?sort=id%20asc&where=foo%3Dbar%20or%20hello%3Dworld&sort=name%20desc&withTotal=false&where=id%20%3E%20%22id_20%22$/
done()
.catch (error) -> done(_.prettify(error))
it 'should throw error if function is missing', ->
spyOn(@restMock, 'GET')
expect(=> @service.process()).toThrow new Error 'Please provide a function to process the elements'
expect(@restMock.GET).not.toHaveBeenCalled()
it 'should set the limit to 20 if it is 0', ->
spyOn(@restMock, 'GET')
@service._params.query.perPage = 0
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.process(fn)
.then () ->
actual = @service._params.query.limit
expected = 20
expect(actual).toEqual(expected)
done()
.catch (error) -> done(_.prettify(error))
it 'should not accumulate results if explicitly set', (done) ->
offset = -20
count = 1
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 0 else count
offset: offset
results: if offset is 40 then [] else [{id: '123', endpoint}]
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.perPage(1).process(fn, accumulate: false)
.then (result) ->
expect(result).toEqual []
done()
.catch (error) -> done(_.prettify(error))
describe ':: fetch', ->
it 'should return promise on fetch', ->
promise = @service.fetch()
expect(promise.isPending()).toBe true
it 'should resolve the promise on fetch', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
@service.fetch().then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on fetch (404)', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: o.path
done()
it 'should return error message for endpoint not found with query', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service
.where()
.page(1)
.perPage()
.fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: o.path
done()
it 'should reject the promise on fetch', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback('foo', null, null)
@service.fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: o.path
done()
it 'should send request with id, if provided', ->
spyOn(@restMock, 'GET')
@service.byId(ID).fetch()
expect(@restMock.GET).toHaveBeenCalledWith "#{o.path}/#{ID}", jasmine.any(Function)
it 'should not do a paged request if perPage is 0', ->
spyOn(@restMock, 'PAGED')
spyOn(@restMock, 'GET')
@service.byId(ID).sort('createdAt', true).perPage(0).fetch()
expect(@restMock.PAGED).not.toHaveBeenCalled()
expect(@restMock.GET).toHaveBeenCalledWith "#{o.path}/#{ID}?limit=0&sort=createdAt%20asc", jasmine.any(Function)
it 'should do a paged request if all() was used before fetch', ->
spyOn(@restMock, 'PAGED')
spyOn(@restMock, 'GET')
@service.byId(ID).sort('createdAt', true).all().fetch()
expect(@restMock.PAGED).toHaveBeenCalledWith "#{o.path}/#{ID}?sort=createdAt%20asc", jasmine.any(Function)
expect(@restMock.GET).not.toHaveBeenCalled()
describe ':: paged', ->
it 'should resolve the promise on (paged) fetch', (done) ->
spyOn(@restMock, 'PAGED').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {total: 1, results: [{foo: 'bar'}]})
@service.all().fetch()
.then (result) ->
expect(result.statusCode).toBe 200
expect(result.body.total).toBe 1
expect(result.body.results.length).toBe 1
expect(result.body.results[0]).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on (paged) fetch (404)', (done) ->
spyOn(@restMock, 'PAGED').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.all().fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: "#{o.path}?sort=id%20asc"
done()
it 'should reject the promise on (paged) fetch', (done) ->
spyOn(@restMock, 'PAGED').andCallFake (endpoint, callback) -> callback('foo', null, null)
@service.all().fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: "#{o.path}?sort=id%20asc"
done()
it 'should set default sorting if not provided (fetching all)', ->
spyOn(@service, '_paged')
@service.all().fetch()
expect(@service._paged).toHaveBeenCalledWith "#{o.path}?sort=id%20asc"
it 'should not set default sorting if provided (fetching all)', ->
spyOn(@service, '_paged')
@service.all().sort('foo').fetch()
expect(@service._paged).toHaveBeenCalledWith "#{o.path}?sort=foo%20asc"
if not _.contains(o.blacklist, 'save')
describe ':: save', ->
it 'should return promise on save', ->
promise = @service.save {foo: 'bar'}
expect(promise.isPending()).toBe true
it 'should resolve the promise on save', (done) ->
spyOn(@restMock, 'POST').andCallFake (endpoint, payload, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
@service.save({foo: 'bar'}).then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on save (404)', (done) ->
spyOn(@restMock, 'POST').andCallFake (endpoint, payload, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.save({foo: 'bar'})
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: o.path
payload:
foo: 'bar'
done()
it 'should throw error if payload is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.save()).toThrow new Error "Body payload is required for creating a resource (endpoint: #{@service.constructor.baseResourceEndpoint})"
expect(@restMock.POST).not.toHaveBeenCalled()
it 'should reject the promise on save', (done) ->
spyOn(@restMock, 'POST').andCallFake (endpoint, payload, callback) -> callback('foo', null, null)
@service.save({foo: 'bar'})
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: o.path
payload:
foo: 'bar'
done()
it 'should send request for base endpoint', ->
spyOn(@restMock, 'POST')
@service.save({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith o.path, {foo: 'bar'}, jasmine.any(Function)
it 'should send request for base endpoint allowing expand param', ->
spyOn(@restMock, 'POST')
@service
.expand('foo.bar') # should use it
.page(1) # should discard
.save({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}?expand=foo.bar", {foo: 'bar'}, jasmine.any(Function)
if not _.contains(o.blacklist, 'create')
describe ':: create', ->
it 'should be an alias for \'save\'', ->
spyOn(@service, 'save')
@service.create foo: 'bar'
expect(@service.save).toHaveBeenCalledWith foo: 'bar'
if not _.contains(o.blacklist, 'update')
describe ':: update', ->
it 'should send request for current endpoint with Id', ->
spyOn(@restMock, 'POST')
@service.byId(ID).update({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}/#{ID}", {foo: 'bar'}, jasmine.any(Function)
if not _.contains(o.blacklist, 'byKey')
it 'should send request for current endpoint with Key', ->
spyOn(@restMock, 'POST')
@service.byKey(KEY).update({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}/key=#{KEY}", {foo: 'bar'}, jasmine.any(Function)
it 'should throw error if id and key is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.update()).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'"
expect(@restMock.POST).not.toHaveBeenCalled()
else
it 'should throw error if id is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.update()).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)'"
expect(@restMock.POST).not.toHaveBeenCalled()
it 'should throw error if payload is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.byId(ID).update()).toThrow new Error "Body payload is required for updating a resource (endpoint: #{@service._currentEndpoint}/#{ID})"
expect(@restMock.POST).not.toHaveBeenCalled()
it 'should use correct endpoints when calling update and create', ->
spyOn(@restMock, 'POST')
@service.byId(ID).update({foo: 'bar1'})
@service.create({foo: 'bar2'})
@service.byId(ID).update({foo: 'bar3'})
@service.create({foo: 'bar4'})
expect(@restMock.POST.calls.length).toBe 4
expect(@restMock.POST.calls[0].args[0]).toEqual "#{o.path}/#{ID}"
expect(@restMock.POST.calls[0].args[1]).toEqual {foo: 'bar1'}
expect(@restMock.POST.calls[1].args[0]).toEqual o.path
expect(@restMock.POST.calls[1].args[1]).toEqual {foo: 'bar2'}
expect(@restMock.POST.calls[2].args[0]).toEqual "#{o.path}/#{ID}"
expect(@restMock.POST.calls[2].args[1]).toEqual {foo: 'bar3'}
expect(@restMock.POST.calls[3].args[0]).toEqual o.path
expect(@restMock.POST.calls[3].args[1]).toEqual {foo: 'bar4'}
it 'should send request for base endpoint allowing expand param', ->
spyOn(@restMock, 'POST')
@service
.expand('foo.bar') # should use it
.page(1) # should discard
.byId(ID)
.update({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}/#{ID}?expand=foo.bar", {foo: 'bar'}, jasmine.any(Function)
if not _.contains(o.blacklist, 'delete')
describe ':: delete', ->
it 'should throw error if version is missing', ->
spyOn(@restMock, 'DELETE')
expect(=> @service.delete()).toThrow new Error "Version is required for deleting a resource (endpoint: #{@service._currentEndpoint})"
expect(@restMock.DELETE).not.toHaveBeenCalled()
if not _.contains(o.blacklist, 'byKey')
it 'should send request for current endpoint with Key', ->
spyOn(@restMock, 'DELETE')
@service.byKey(KEY).delete(1)
expect(@restMock.DELETE).toHaveBeenCalledWith "#{o.path}/key=#{KEY}?version=1", jasmine.any(Function)
it 'should throw error if id and key is missing', ->
spyOn(@restMock, 'DELETE')
expect(=> @service.delete(1)).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'"
expect(@restMock.DELETE).not.toHaveBeenCalled()
else
it 'should throw error if id is missing', ->
spyOn(@restMock, 'DELETE')
expect(=> @service.delete(1)).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)'"
expect(@restMock.DELETE).not.toHaveBeenCalled()
it 'should return promise on delete', ->
promise = @service.byId('123-abc').delete(1)
expect(promise.isPending()).toBe true
it 'should resolve the promise on delete', (done) ->
spyOn(@restMock, 'DELETE').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
@service.byId('123-abc').delete(1).then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on delete (404)', (done) ->
spyOn(@restMock, 'DELETE').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.byId('123-abc').delete(1)
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: "#{o.path}/123-abc?version=1"
done()
it 'should reject the promise on delete', (done) ->
spyOn(@restMock, 'DELETE').andCallFake (endpoint, callback) -> callback('foo', null, null)
@service.byId('123-abc').delete(1)
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: "#{o.path}/123-abc?version=1"
done()
| true | _ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{TaskQueue} = require '../../../lib/main'
BaseService = require '../../../lib/services/base'
CartDiscountService = require '../../../lib/services/cart-discounts'
CartService = require '../../../lib/services/carts'
CategoryService = require '../../../lib/services/categories'
ChannelService = require '../../../lib/services/channels'
CustomObjectService = require '../../../lib/services/custom-objects'
CustomerService = require '../../../lib/services/customers'
CustomerGroupService = require '../../../lib/services/customer-groups'
DiscountCodeService = require '../../../lib/services/discount-codes'
InventoryEntryService = require '../../../lib/services/inventory-entries'
MessageService = require '../../../lib/services/messages'
OrderService = require '../../../lib/services/orders'
PaymentService = require '../../../lib/services/payments'
ProductService = require '../../../lib/services/products'
ProductDiscountService = require '../../../lib/services/product-discounts'
ProductProjectionService = require '../../../lib/services/product-projections'
ProductTypeService = require '../../../lib/services/product-types'
ProjectService = require '../../../lib/services/project'
ReviewService = require '../../../lib/services/reviews'
ShippingMethodService = require '../../../lib/services/shipping-methods'
StateService = require '../../../lib/services/states'
TaxCategoryService = require '../../../lib/services/tax-categories'
TypeService = require '../../../lib/services/types'
ZoneService = require '../../../lib/services/zones'
describe 'Service', ->
ID = '1234-abcd-5678-efgh'
KEY = 'PI:KEY:<KEY>END_PI'
_.each [
{name: 'BaseService', service: BaseService, path: '', blacklist: ['byKey']}
{name: 'CartDiscountService', service: CartDiscountService, path: '/cart-discounts', blacklist: ['byKey']}
{name: 'CartService', service: CartService, path: '/carts', blacklist: ['byKey']}
{name: 'CategoryService', service: CategoryService, path: '/categories', blacklist: ['byKey']}
{name: 'ChannelService', service: ChannelService, path: '/channels', blacklist: ['byKey']}
{name: 'CustomObjectService', service: CustomObjectService, path: '/custom-objects', blacklist: ['byKey']}
{name: 'CustomerService', service: CustomerService, path: '/customers', blacklist: ['byKey']}
{name: 'CustomerGroupService', service: CustomerGroupService, path: '/customer-groups', blacklist: ['byKey']}
{name: 'DiscountCodeService', service: DiscountCodeService, path: '/discount-codes', blacklist: ['byKey']}
{name: 'InventoryEntryService', service: InventoryEntryService, path: '/inventory', blacklist: ['byKey']}
{name: 'MessageService', service: MessageService, path: '/messages', blacklist: ['byKey', 'save', 'create', 'update', 'delete']}
{name: 'OrderService', service: OrderService, path: '/orders', blacklist: ['byKey', 'delete']}
{name: 'PaymentService', service: PaymentService, path: '/payments', blacklist: ['byKey']}
{name: 'ProductService', service: ProductService, path: '/products', blacklist: ['byKey']}
{name: 'ProductDiscountService', service: ProductDiscountService, path: '/product-discounts', blacklist: ['byKey']}
{name: 'ProductProjectionService', service: ProductProjectionService, path: '/product-projections', blacklist: ['byKey', 'save', 'create', 'update', 'delete']}
{name: 'ProductTypeService', service: ProductTypeService, path: '/product-types', blacklist: []}
{name: 'ProjectService', service: ProjectService, path: '', blacklist: ['byKey', 'save', 'create', 'update', 'delete']}
{name: 'ReviewService', service: ReviewService, path: '/reviews', blacklist: ['byKey', 'delete']}
{name: 'ShippingMethodService', service: ShippingMethodService, path: '/shipping-methods', blacklist: ['byKey']}
{name: 'StateService', service: StateService, path: '/states', blacklist: ['byKey']}
{name: 'TaxCategoryService', service: TaxCategoryService, path: '/tax-categories', blacklist: ['byKey']}
{name: 'TypeService', service: TypeService, path: '/types', blacklist: []}
{name: 'ZoneService', service: ZoneService, path: '/zones', blacklist: ['byKey']}
], (o) ->
describe ":: #{o.name}", ->
beforeEach ->
@restMock =
config: {}
GET: (endpoint, callback) ->
POST: -> (endpoint, payload, callback) ->
PUT: ->
DELETE: -> (endpoint, callback) ->
PAGED: -> (endpoint, callback) ->
_preRequest: ->
_doRequest: ->
@task = new TaskQueue
@service = new o.service
_rest: @restMock,
_task: @task
_stats:
includeHeaders: false
maskSensitiveHeaderData: false
afterEach ->
@service = null
@restMock = null
@task = null
it 'should have constants defined', ->
expect(o.service.baseResourceEndpoint).toBe o.path
it 'should not share variables between instances', ->
base1 = new o.service @restMock
base1._currentEndpoint = '/foo/1'
base2 = new o.service @restMock
expect(base2._currentEndpoint).toBe o.path
it 'should initialize with Rest client', ->
expect(@service).toBeDefined()
expect(@service._currentEndpoint).toBe o.path
it 'should reset default params', ->
expect(@service._params.query.where).toEqual []
expect(@service._params.query.operator).toBe 'and'
expect(@service._params.query.sort).toEqual []
expect(@service._params.query.expand).toEqual []
it 'should build endpoint with id', ->
@service.byId(ID)
expect(@service._currentEndpoint).toBe "#{o.path}/#{ID}"
it 'should throw if endpoint is already built with key', ->
expect(=> @service.byKey(KEY).byId(ID)).toThrow()
_.each [
['byId', '1234567890']
['where', 'key = "foo"']
['whereOperator', 'and']
['page', 2]
['perPage', 5]
['sort', 'createdAt']
], (f) ->
it "should chain '#{f[0]}'", ->
clazz = @service[f[0]](f[1])
expect(clazz).toEqual @service
promise = @service[f[0]](f[1]).fetch()
expect(promise.isPending()).toBe true
it 'should add where predicates to query', ->
@service.where('name(en="Foo")')
expect(@service._params.query.where).toEqual ['name(en%3D%22Foo%22)']
@service.where('variants is empty')
expect(@service._params.query.where).toEqual ['name(en%3D%22Foo%22)', 'variants%20is%20empty']
it 'should not add undefined where predicates', ->
@service.where()
expect(@service._params.query.where).toEqual []
it 'should set query logical operator', ->
@service.whereOperator('or')
expect(@service._params.query.operator).toBe 'or'
@service.whereOperator()
expect(@service._params.query.operator).toBe 'and'
@service.whereOperator('foo')
expect(@service._params.query.operator).toBe 'and'
_.each ['30s', '15m', '12h', '7d', '2w'], (type) ->
it "should allow to query for last #{type}", ->
@service.last(type)
expect(@service._params.query.where[0]).toMatch /lastModifiedAt%20%3E%20%2220\d\d-\d\d-\d\dT\d\d%3A\d\d%3A\d\d.\d\d\dZ%22/
it 'should throw an exception when the period for last can not be parsed', ->
expect(=> @service.last('30')).toThrow new Error "Cannot parse period '30'"
expect(=> @service.last('-1h')).toThrow new Error "Cannot parse period '-1h'"
it 'should do nothing for 0 as input', ->
@service.last('0m')
expect(_.size @service._params.query.where).toBe 0
it 'should add page number', ->
@service.page(5)
expect(@service._params.query.page).toBe 5
it 'should throw if page < 1', ->
expect(=> @service.page(0)).toThrow new Error 'Page must be a number >= 1'
it 'should add perPage number', ->
@service.perPage(50)
expect(@service._params.query.perPage).toBe 50
it 'should throw if perPage < 0', ->
expect(=> @service.perPage(-1)).toThrow new Error 'PerPage (limit) must be a number >= 0'
it 'should set flag for \'all\'', ->
@service.all()
expect(@service._fetchAll).toBe(true)
it 'should build query string', ->
queryString = @service
.where 'name(en = "Foo")'
.where 'id = "1234567890"'
.whereOperator 'or'
.page 3
.perPage 25
.sort 'attrib', false
.sort 'createdAt'
.expand 'lineItems[*].state[*].state'
._queryString()
expect(queryString).toBe 'where=name(en%20%3D%20%22Foo%22)%20or%20id%20%3D%20%221234567890%22&limit=25&offset=50&sort=attrib%20desc&sort=createdAt%20asc&expand=lineItems%5B*%5D.state%5B*%5D.state'
it 'should use given queryString, when building it', ->
queryString = @service
.where 'name(en = "Foo")'
.perPage 25
.expand 'lineItems[*].state[*].state'
.byQueryString('foo=bar')._queryString()
expect(queryString).toBe 'foo=bar'
it 'should set queryString, if given', ->
@service.byQueryString('where=name(en = "Foo")&limit=10&staged=true&sort=name asc&expand=foo.bar1&expand=foo.bar2')
expect(@service._params.queryString).toEqual 'where=name(en%20%3D%20%22Foo%22)&limit=10&staged=true&sort=name%20asc&expand=foo.bar1&expand=foo.bar2'
it 'should set queryString, if given (already encoding)', ->
@service.byQueryString('where=name(en%20%3D%20%22Foo%22)&limit=10&staged=true&sort=name%20asc&expand=foo.bar1&expand=foo.bar2', true)
expect(@service._params.queryString).toEqual 'where=name(en%20%3D%20%22Foo%22)&limit=10&staged=true&sort=name%20asc&expand=foo.bar1&expand=foo.bar2'
it 'should not use PAGED request when queryString is set', ->
spyOn(@restMock, 'PAGED')
spyOn(@restMock, 'GET')
@service.byQueryString('limit=10').all().fetch()
expect(@restMock.PAGED).not.toHaveBeenCalled()
expect(@restMock.GET).toHaveBeenCalledWith "#{o.path}?limit=10", jasmine.any(Function)
_.each [
['fetch']
['save', {foo: 'bar'}]
['delete', 2]
], (f) ->
if not _.contains(o.blacklist, f[0])
it "should reset params after creating a promise for #{f[0]}", ->
_service = @service.byId('123-abc').where('name = "foo"').page(2).perPage(10).sort('id').expand('foo.bar')
expect(@service._params.id).toBe '123-abc'
expect(@service._params.query.where).toEqual [encodeURIComponent('name = "foo"')]
expect(@service._params.query.operator).toBe 'and'
expect(@service._params.query.sort).toEqual [encodeURIComponent('id asc')]
expect(@service._params.query.page).toBe 2
expect(@service._params.query.perPage).toBe 10
expect(@service._params.query.expand).toEqual [encodeURIComponent('foo.bar')]
if f[1]
_service[f[0]](f[1])
else
_service[f[0]]()
expect(@service._params.query.where).toEqual []
expect(@service._params.query.operator).toBe 'and'
expect(@service._params.query.sort).toEqual []
expect(@service._params.query.expand).toEqual []
if not _.contains(o.blacklist, 'byKey')
it 'should build endpoint with key', ->
@service.byKey(KEY)
expect(@service._currentEndpoint).toBe "#{o.path}/key=#{KEY}"
it 'should throw if endpoint is already built with id', ->
expect(=> @service.byId(ID).byKey(KEY)).toThrow()
if not _.contains(o.blacklist, 'save')
it 'should censor authorization headers in case of a timeout', (done) ->
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback new Error('timeout'), null, null
@service._rest._options =
headers:
Authorization: 'Bearer 9PI:KEY:<KEY>END_PI'
@service._stats.maskSensitiveHeaderData = true
@service._stats.includeHeaders = true
@service.save({foo: 'bar'})
.then -> done('Should not happen')
.catch (error) ->
expect(error.body).toEqual
message: 'timeout'
originalRequest:
options:
headers:
Authorization: 'Bearer **********'
endpoint: o.path
payload:
foo: 'bar'
done()
.done()
it 'should censor authorization headers', (done) ->
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback null, {
statusCode: 400,
req: {
_header: 'Authorization: Bearer 9PI:KEY:<KEY>END_PI'
},
request: {
headers: {
Authorization: 'Bearer 9PI:KEY:<KEY>END_PI'
}
},
headers: {
Authorization: 'Bearer PI:KEY:<KEY>END_PI'
}
}, {statusCode: 400, message: 'Oops, something went wrong'}
@service._rest._options =
headers:
Authorization: 'Bearer PI:KEY:<KEY>END_PI'
@service._stats.maskSensitiveHeaderData = true
@service._stats.includeHeaders = true
@service.save({foo: 'bar'})
.then -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'BadRequest'
expect(error.body).toEqual
http:
request:
method: undefined
httpVersion: undefined
uri: undefined
header: 'Authorization: Bearer **********'
headers:
Authorization: 'Bearer **********'
response:
headers:
Authorization: 'Bearer **********'
statusCode: 400
message: 'Oops, something went wrong'
originalRequest:
options:
headers:
Authorization: 'Bearer **********'
endpoint: o.path
payload:
foo: 'bar'
done()
.done()
it 'should pass original request to failed response', (done) ->
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback null, {statusCode: 400}, {statusCode: 400, message: 'Oops, something went wrong'}
@service.save({foo: 'bar'})
.then -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'BadRequest'
expect(error.body).toEqual
statusCode: 400
message: 'Oops, something went wrong'
originalRequest:
options: {}
endpoint: o.path
payload:
foo: 'bar'
done()
.done()
it 'should pass headers info', (done) ->
@service._stats.includeHeaders = true
spyOn(@service._rest, 'POST').andCallFake (endpoint, payload, callback) ->
callback null,
statusCode: 200
httpVersion: '1.1'
request:
method: 'POST'
uri: {}
headers: {}
req:
_header: 'POST /foo HTTP/1.1'
headers: {}
, {foo: 'bar'}
@service.save({foo: 'bar'})
.then (result) ->
expect(result).toEqual
http:
request:
method: 'POST'
httpVersion: '1.1'
uri: {}
header: 'POST /foo HTTP/1.1'
headers: {}
response:
headers: {}
statusCode: 200
body:
foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
.done()
describe ':: process', ->
it 'should return promise', ->
promise = @service.process( -> )
expect(promise.isPending()).toBe true
it 'should call process function for one page', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {
count: 1
offset: 0
results: []
})
fn = (payload) -> Promise.resolve 'done'
@service.process(fn)
.then (result) ->
expect(result).toEqual ['done']
done()
.catch (error) -> done(_.prettify(error))
it 'should call process function for several pages (default sorting)', (done) ->
offset = -20
count = 20
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 10 else count
offset: offset
results: _.map (if offset is 40 then [1..10] else [1..20]), (i) -> {id: "id_#{i}", endpoint}
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.page(3).perPage(count).process(fn)
.then (result) ->
expect(_.size result).toBe 3
expect(result[0].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&withTotal=false$/
expect(result[1].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&withTotal=false&where=id%20%3E%20%22id_20%22$/
expect(result[2].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&withTotal=false&where=id%20%3E%20%22id_20%22$/
done()
.catch (error) -> done(_.prettify(error))
it 'should call process function for several pages (given sorting)', (done) ->
offset = -20
count = 20
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 10 else count
offset: offset
results: _.map (if offset is 40 then [1..10] else [1..20]), (i) -> {id: "id_#{i}", endpoint}
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.page(3).perPage(count).sort('foo').process(fn)
.then (result) ->
expect(_.size result).toBe 3
expect(result[0].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&sort=foo%20asc&withTotal=false$/
expect(result[1].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&sort=foo%20asc&withTotal=false&where=id%20%3E%20%22id_20%22$/
expect(result[2].endpoint).toMatch /\?sort=id%20asc&limit=20&offset=40&sort=foo%20asc&withTotal=false&where=id%20%3E%20%22id_20%22$/
done()
.catch (error) -> done(_.prettify(error))
it 'should fail if the process functions rejects', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {total: 100})
fn = (payload) ->
Promise.reject 'bad luck'
@service.process(fn)
.then (result) -> done 'not expected!'
.catch (error) ->
expect(error).toBe 'bad luck'
done()
it 'should call each page with the same query', (done) ->
offset = -20
count = 20
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 10 else count
offset: offset
results: _.map (if offset is 40 then [1..10] else [1..20]), (i) -> {id: "id_#{i}", endpoint}
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.sort('name', false)
.where('foo=bar')
.where('hello=world')
.whereOperator('or')
.process(fn)
.then (result) ->
expect(_.size result).toBe 3
expect(result[0].endpoint).toMatch /\?sort=id%20asc&where=foo%3Dbar%20or%20hello%3Dworld&sort=name%20desc&withTotal=false$/
expect(result[1].endpoint).toMatch /\?sort=id%20asc&where=foo%3Dbar%20or%20hello%3Dworld&sort=name%20desc&withTotal=false&where=id%20%3E%20%22id_20%22$/
expect(result[2].endpoint).toMatch /\?sort=id%20asc&where=foo%3Dbar%20or%20hello%3Dworld&sort=name%20desc&withTotal=false&where=id%20%3E%20%22id_20%22$/
done()
.catch (error) -> done(_.prettify(error))
it 'should throw error if function is missing', ->
spyOn(@restMock, 'GET')
expect(=> @service.process()).toThrow new Error 'Please provide a function to process the elements'
expect(@restMock.GET).not.toHaveBeenCalled()
it 'should set the limit to 20 if it is 0', ->
spyOn(@restMock, 'GET')
@service._params.query.perPage = 0
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.process(fn)
.then () ->
actual = @service._params.query.limit
expected = 20
expect(actual).toEqual(expected)
done()
.catch (error) -> done(_.prettify(error))
it 'should not accumulate results if explicitly set', (done) ->
offset = -20
count = 1
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) ->
offset += 20
callback(null, {statusCode: 200}, {
# total: 50
count: if offset is 40 then 0 else count
offset: offset
results: if offset is 40 then [] else [{id: '123', endpoint}]
})
fn = (payload) ->
Promise.resolve payload.body.results[0]
@service.perPage(1).process(fn, accumulate: false)
.then (result) ->
expect(result).toEqual []
done()
.catch (error) -> done(_.prettify(error))
describe ':: fetch', ->
it 'should return promise on fetch', ->
promise = @service.fetch()
expect(promise.isPending()).toBe true
it 'should resolve the promise on fetch', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
@service.fetch().then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on fetch (404)', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: o.path
done()
it 'should return error message for endpoint not found with query', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service
.where()
.page(1)
.perPage()
.fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: o.path
done()
it 'should reject the promise on fetch', (done) ->
spyOn(@restMock, 'GET').andCallFake (endpoint, callback) -> callback('foo', null, null)
@service.fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: o.path
done()
it 'should send request with id, if provided', ->
spyOn(@restMock, 'GET')
@service.byId(ID).fetch()
expect(@restMock.GET).toHaveBeenCalledWith "#{o.path}/#{ID}", jasmine.any(Function)
it 'should not do a paged request if perPage is 0', ->
spyOn(@restMock, 'PAGED')
spyOn(@restMock, 'GET')
@service.byId(ID).sort('createdAt', true).perPage(0).fetch()
expect(@restMock.PAGED).not.toHaveBeenCalled()
expect(@restMock.GET).toHaveBeenCalledWith "#{o.path}/#{ID}?limit=0&sort=createdAt%20asc", jasmine.any(Function)
it 'should do a paged request if all() was used before fetch', ->
spyOn(@restMock, 'PAGED')
spyOn(@restMock, 'GET')
@service.byId(ID).sort('createdAt', true).all().fetch()
expect(@restMock.PAGED).toHaveBeenCalledWith "#{o.path}/#{ID}?sort=createdAt%20asc", jasmine.any(Function)
expect(@restMock.GET).not.toHaveBeenCalled()
describe ':: paged', ->
it 'should resolve the promise on (paged) fetch', (done) ->
spyOn(@restMock, 'PAGED').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {total: 1, results: [{foo: 'bar'}]})
@service.all().fetch()
.then (result) ->
expect(result.statusCode).toBe 200
expect(result.body.total).toBe 1
expect(result.body.results.length).toBe 1
expect(result.body.results[0]).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on (paged) fetch (404)', (done) ->
spyOn(@restMock, 'PAGED').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.all().fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: "#{o.path}?sort=id%20asc"
done()
it 'should reject the promise on (paged) fetch', (done) ->
spyOn(@restMock, 'PAGED').andCallFake (endpoint, callback) -> callback('foo', null, null)
@service.all().fetch()
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: "#{o.path}?sort=id%20asc"
done()
it 'should set default sorting if not provided (fetching all)', ->
spyOn(@service, '_paged')
@service.all().fetch()
expect(@service._paged).toHaveBeenCalledWith "#{o.path}?sort=id%20asc"
it 'should not set default sorting if provided (fetching all)', ->
spyOn(@service, '_paged')
@service.all().sort('foo').fetch()
expect(@service._paged).toHaveBeenCalledWith "#{o.path}?sort=foo%20asc"
if not _.contains(o.blacklist, 'save')
describe ':: save', ->
it 'should return promise on save', ->
promise = @service.save {foo: 'bar'}
expect(promise.isPending()).toBe true
it 'should resolve the promise on save', (done) ->
spyOn(@restMock, 'POST').andCallFake (endpoint, payload, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
@service.save({foo: 'bar'}).then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on save (404)', (done) ->
spyOn(@restMock, 'POST').andCallFake (endpoint, payload, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.save({foo: 'bar'})
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: o.path
payload:
foo: 'bar'
done()
it 'should throw error if payload is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.save()).toThrow new Error "Body payload is required for creating a resource (endpoint: #{@service.constructor.baseResourceEndpoint})"
expect(@restMock.POST).not.toHaveBeenCalled()
it 'should reject the promise on save', (done) ->
spyOn(@restMock, 'POST').andCallFake (endpoint, payload, callback) -> callback('foo', null, null)
@service.save({foo: 'bar'})
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: o.path
payload:
foo: 'bar'
done()
it 'should send request for base endpoint', ->
spyOn(@restMock, 'POST')
@service.save({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith o.path, {foo: 'bar'}, jasmine.any(Function)
it 'should send request for base endpoint allowing expand param', ->
spyOn(@restMock, 'POST')
@service
.expand('foo.bar') # should use it
.page(1) # should discard
.save({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}?expand=foo.bar", {foo: 'bar'}, jasmine.any(Function)
if not _.contains(o.blacklist, 'create')
describe ':: create', ->
it 'should be an alias for \'save\'', ->
spyOn(@service, 'save')
@service.create foo: 'bar'
expect(@service.save).toHaveBeenCalledWith foo: 'bar'
if not _.contains(o.blacklist, 'update')
describe ':: update', ->
it 'should send request for current endpoint with Id', ->
spyOn(@restMock, 'POST')
@service.byId(ID).update({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}/#{ID}", {foo: 'bar'}, jasmine.any(Function)
if not _.contains(o.blacklist, 'byKey')
it 'should send request for current endpoint with Key', ->
spyOn(@restMock, 'POST')
@service.byKey(KEY).update({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}/key=#{KEY}", {foo: 'bar'}, jasmine.any(Function)
it 'should throw error if id and key is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.update()).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'"
expect(@restMock.POST).not.toHaveBeenCalled()
else
it 'should throw error if id is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.update()).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)'"
expect(@restMock.POST).not.toHaveBeenCalled()
it 'should throw error if payload is missing', ->
spyOn(@restMock, 'POST')
expect(=> @service.byId(ID).update()).toThrow new Error "Body payload is required for updating a resource (endpoint: #{@service._currentEndpoint}/#{ID})"
expect(@restMock.POST).not.toHaveBeenCalled()
it 'should use correct endpoints when calling update and create', ->
spyOn(@restMock, 'POST')
@service.byId(ID).update({foo: 'bar1'})
@service.create({foo: 'bar2'})
@service.byId(ID).update({foo: 'bar3'})
@service.create({foo: 'bar4'})
expect(@restMock.POST.calls.length).toBe 4
expect(@restMock.POST.calls[0].args[0]).toEqual "#{o.path}/#{ID}"
expect(@restMock.POST.calls[0].args[1]).toEqual {foo: 'bar1'}
expect(@restMock.POST.calls[1].args[0]).toEqual o.path
expect(@restMock.POST.calls[1].args[1]).toEqual {foo: 'bar2'}
expect(@restMock.POST.calls[2].args[0]).toEqual "#{o.path}/#{ID}"
expect(@restMock.POST.calls[2].args[1]).toEqual {foo: 'bar3'}
expect(@restMock.POST.calls[3].args[0]).toEqual o.path
expect(@restMock.POST.calls[3].args[1]).toEqual {foo: 'bar4'}
it 'should send request for base endpoint allowing expand param', ->
spyOn(@restMock, 'POST')
@service
.expand('foo.bar') # should use it
.page(1) # should discard
.byId(ID)
.update({foo: 'bar'})
expect(@restMock.POST).toHaveBeenCalledWith "#{o.path}/#{ID}?expand=foo.bar", {foo: 'bar'}, jasmine.any(Function)
if not _.contains(o.blacklist, 'delete')
describe ':: delete', ->
it 'should throw error if version is missing', ->
spyOn(@restMock, 'DELETE')
expect(=> @service.delete()).toThrow new Error "Version is required for deleting a resource (endpoint: #{@service._currentEndpoint})"
expect(@restMock.DELETE).not.toHaveBeenCalled()
if not _.contains(o.blacklist, 'byKey')
it 'should send request for current endpoint with Key', ->
spyOn(@restMock, 'DELETE')
@service.byKey(KEY).delete(1)
expect(@restMock.DELETE).toHaveBeenCalledWith "#{o.path}/key=#{KEY}?version=1", jasmine.any(Function)
it 'should throw error if id and key is missing', ->
spyOn(@restMock, 'DELETE')
expect(=> @service.delete(1)).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)' or '.byKey(KEY)'"
expect(@restMock.DELETE).not.toHaveBeenCalled()
else
it 'should throw error if id is missing', ->
spyOn(@restMock, 'DELETE')
expect(=> @service.delete(1)).toThrow new Error "Missing resource id. You can set it by chaining '.byId(ID)'"
expect(@restMock.DELETE).not.toHaveBeenCalled()
it 'should return promise on delete', ->
promise = @service.byId('123-abc').delete(1)
expect(promise.isPending()).toBe true
it 'should resolve the promise on delete', (done) ->
spyOn(@restMock, 'DELETE').andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
@service.byId('123-abc').delete(1).then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (error) -> done(_.prettify(error))
it 'should reject the promise on delete (404)', (done) ->
spyOn(@restMock, 'DELETE').andCallFake (endpoint, callback) -> callback(null, {statusCode: 404, request: {uri: {path: '/foo'}}}, null)
@service.byId('123-abc').delete(1)
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'NotFound'
expect(error.body).toEqual
statusCode: 404
message: "Endpoint '/foo' not found."
originalRequest:
options: {}
endpoint: "#{o.path}/123-abc?version=1"
done()
it 'should reject the promise on delete', (done) ->
spyOn(@restMock, 'DELETE').andCallFake (endpoint, callback) -> callback('foo', null, null)
@service.byId('123-abc').delete(1)
.then (result) -> done('Should not happen')
.catch (error) ->
expect(error.name).toBe 'HttpError'
expect(error.body).toEqual
message: 'foo'
originalRequest:
options: {}
endpoint: "#{o.path}/123-abc?version=1"
done()
|
[
{
"context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig",
"end": 74,
"score": 0.9998793601989746,
"start": 61,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "f the Konsserto package.\n *\n * (c) Je... | node_modules/konsserto/lib/src/Konsserto/Component/Static/Crypt.coffee | konsserto/konsserto | 2 | ###
* This file is part of the Konsserto package.
*
* (c) Jessym Reziga <jessym@konsserto.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
#
# Crypt
#
# @author Jessym Reziga <jessym@konsserto.com>
#
class Crypt
@md5cycle = (x, k) ->
a = x[0]
b = x[1]
c = x[2]
d = x[3]
a = @ff(a, b, c, d, k[0], 7, -680876936)
d = @ff(d, a, b, c, k[1], 12, -389564586)
c = @ff(c, d, a, b, k[2], 17, 606105819)
b = @ff(b, c, d, a, k[3], 22, -1044525330)
a = @ff(a, b, c, d, k[4], 7, -176418897)
d = @ff(d, a, b, c, k[5], 12, 1200080426)
c = @ff(c, d, a, b, k[6], 17, -1473231341)
b = @ff(b, c, d, a, k[7], 22, -45705983)
a = @ff(a, b, c, d, k[8], 7, 1770035416)
d = @ff(d, a, b, c, k[9], 12, -1958414417)
c = @ff(c, d, a, b, k[10], 17, -42063)
b = @ff(b, c, d, a, k[11], 22, -1990404162)
a = @ff(a, b, c, d, k[12], 7, 1804603682)
d = @ff(d, a, b, c, k[13], 12, -40341101)
c = @ff(c, d, a, b, k[14], 17, -1502002290)
b = @ff(b, c, d, a, k[15], 22, 1236535329)
a = @gg(a, b, c, d, k[1], 5, -165796510)
d = @gg(d, a, b, c, k[6], 9, -1069501632)
c = @gg(c, d, a, b, k[11], 14, 643717713)
b = @gg(b, c, d, a, k[0], 20, -373897302)
a = @gg(a, b, c, d, k[5], 5, -701558691)
d = @gg(d, a, b, c, k[10], 9, 38016083)
c = @gg(c, d, a, b, k[15], 14, -660478335)
b = @gg(b, c, d, a, k[4], 20, -405537848)
a = @gg(a, b, c, d, k[9], 5, 568446438)
d = @gg(d, a, b, c, k[14], 9, -1019803690)
c = @gg(c, d, a, b, k[3], 14, -187363961)
b = @gg(b, c, d, a, k[8], 20, 1163531501)
a = @gg(a, b, c, d, k[13], 5, -1444681467)
d = @gg(d, a, b, c, k[2], 9, -51403784)
c = @gg(c, d, a, b, k[7], 14, 1735328473)
b = @gg(b, c, d, a, k[12], 20, -1926607734)
a = @hh(a, b, c, d, k[5], 4, -378558)
d = @hh(d, a, b, c, k[8], 11, -2022574463)
c = @hh(c, d, a, b, k[11], 16, 1839030562)
b = @hh(b, c, d, a, k[14], 23, -35309556)
a = @hh(a, b, c, d, k[1], 4, -1530992060)
d = @hh(d, a, b, c, k[4], 11, 1272893353)
c = @hh(c, d, a, b, k[7], 16, -155497632)
b = @hh(b, c, d, a, k[10], 23, -1094730640)
a = @hh(a, b, c, d, k[13], 4, 681279174)
d = @hh(d, a, b, c, k[0], 11, -358537222)
c = @hh(c, d, a, b, k[3], 16, -722521979)
b = @hh(b, c, d, a, k[6], 23, 76029189)
a = @hh(a, b, c, d, k[9], 4, -640364487)
d = @hh(d, a, b, c, k[12], 11, -421815835)
c = @hh(c, d, a, b, k[15], 16, 530742520)
b = @hh(b, c, d, a, k[2], 23, -995338651)
a = @ii(a, b, c, d, k[0], 6, -198630844)
d = @ii(d, a, b, c, k[7], 10, 1126891415)
c = @ii(c, d, a, b, k[14], 15, -1416354905)
b = @ii(b, c, d, a, k[5], 21, -57434055)
a = @ii(a, b, c, d, k[12], 6, 1700485571)
d = @ii(d, a, b, c, k[3], 10, -1894986606)
c = @ii(c, d, a, b, k[10], 15, -1051523)
b = @ii(b, c, d, a, k[1], 21, -2054922799)
a = @ii(a, b, c, d, k[8], 6, 1873313359)
d = @ii(d, a, b, c, k[15], 10, -30611744)
c = @ii(c, d, a, b, k[6], 15, -1560198380)
b = @ii(b, c, d, a, k[13], 21, 1309151649)
a = @ii(a, b, c, d, k[4], 6, -145523070)
d = @ii(d, a, b, c, k[11], 10, -1120210379)
c = @ii(c, d, a, b, k[2], 15, 718787259)
b = @ii(b, c, d, a, k[9], 21, -343485551)
x[0] = @add32(a, x[0])
x[1] = @add32(b, x[1])
x[2] = @add32(c, x[2])
x[3] = @add32(d, x[3])
@cmn = (q, a, b, x, s, t) ->
a = @add32(@add32(a, q), @add32(x, t))
@add32 (a << s) | (a >>> (32 - s)), b
@ff = (a, b, c, d, x, s, t) ->
@cmn (b & c) | ((~b) & d), a, b, x, s, t
@gg = (a, b, c, d, x, s, t) ->
@cmn (b & d) | (c & (~d)), a, b, x, s, t
@hh = (a, b, c, d, x, s, t) ->
@cmn b ^ c ^ d, a, b, x, s, t
@ii = (a, b, c, d, x, s, t) ->
@cmn c ^ (b | (~d)), a, b, x, s, t
@md51 = (s) ->
txt = ''
n = s.length
state = [
1732584193
-271733879
-1732584194
271733878
]
i = undefined
i = 64
while i <= s.length
@md5cycle state, @md5blk(s.substring(i - 64, i))
i += 64
s = s.substring(i - 64)
tail = [
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
]
i = 0
while i < s.length
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3)
i++
tail[i >> 2] |= 0x80 << ((i % 4) << 3)
if i > 55
@md5cycle state, tail
i = 0
while i < 16
tail[i] = 0
i++
tail[14] = n * 8
@md5cycle state, tail
state
# there needs to be support for Unicode here,
# * unless we pretend that we can redefine the MD-5
# * algorithm for multi-byte characters (perhaps
# * by adding every four 16-bit characters and
# * shortening the sum to 32 bits). Otherwise
# * I suggest performing MD-5 as if every character
# * was two bytes--e.g., 0040 0025 = @%--but then
# * how will an ordinary MD-5 sum be matched?
# * There is no way to standardize text to something
# * like UTF-8 before transformation; speed cost is
# * utterly prohibitive. The JavaScript standard
# * itself needs to look at this: it should start
# * providing access to strings as preformed UTF-8
# * 8-bit unsigned value arrays.
#
@md5blk = (s) -> # I figured global was faster.
md5blks = [] # Andy King said do it this way.
i = undefined
i = 0
while i < 64
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24)
i += 4
md5blks
@rhex = (n) ->
s = ''
j = 0
while j < 4
s += @hex_chr[(n >> (j * 8 + 4)) & 0x0F] + @hex_chr[(n >> (j * 8)) & 0x0F]
j++
s
@hex = (x) ->
i = 0
while i < x.length
x[i] = @rhex(x[i])
i++
x.join ''
@md5 = (s) ->
@hex @md51(s)
# this function is much faster,
#so if possible we use it. Some IEs
#are the only ones I know of that
#need the idiotic second function,
#generated by an if clause.
@add32 = (a, b) ->
(a + b) & 0xFFFFFFFF
@hex_chr = '0123456789abcdef'.split('');
module.exports = Crypt
| 203822 | ###
* This file is part of the Konsserto package.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
#
# Crypt
#
# @author <NAME> <<EMAIL>>
#
class Crypt
@md5cycle = (x, k) ->
a = x[0]
b = x[1]
c = x[2]
d = x[3]
a = @ff(a, b, c, d, k[0], 7, -680876936)
d = @ff(d, a, b, c, k[1], 12, -389564586)
c = @ff(c, d, a, b, k[2], 17, 606105819)
b = @ff(b, c, d, a, k[3], 22, -1044525330)
a = @ff(a, b, c, d, k[4], 7, -176418897)
d = @ff(d, a, b, c, k[5], 12, 1200080426)
c = @ff(c, d, a, b, k[6], 17, -1473231341)
b = @ff(b, c, d, a, k[7], 22, -45705983)
a = @ff(a, b, c, d, k[8], 7, 1770035416)
d = @ff(d, a, b, c, k[9], 12, -1958414417)
c = @ff(c, d, a, b, k[10], 17, -42063)
b = @ff(b, c, d, a, k[11], 22, -1990404162)
a = @ff(a, b, c, d, k[12], 7, 1804603682)
d = @ff(d, a, b, c, k[13], 12, -40341101)
c = @ff(c, d, a, b, k[14], 17, -1502002290)
b = @ff(b, c, d, a, k[15], 22, 1236535329)
a = @gg(a, b, c, d, k[1], 5, -165796510)
d = @gg(d, a, b, c, k[6], 9, -1069501632)
c = @gg(c, d, a, b, k[11], 14, 643717713)
b = @gg(b, c, d, a, k[0], 20, -373897302)
a = @gg(a, b, c, d, k[5], 5, -701558691)
d = @gg(d, a, b, c, k[10], 9, 38016083)
c = @gg(c, d, a, b, k[15], 14, -660478335)
b = @gg(b, c, d, a, k[4], 20, -405537848)
a = @gg(a, b, c, d, k[9], 5, 568446438)
d = @gg(d, a, b, c, k[14], 9, -1019803690)
c = @gg(c, d, a, b, k[3], 14, -187363961)
b = @gg(b, c, d, a, k[8], 20, 1163531501)
a = @gg(a, b, c, d, k[13], 5, -1444681467)
d = @gg(d, a, b, c, k[2], 9, -51403784)
c = @gg(c, d, a, b, k[7], 14, 1735328473)
b = @gg(b, c, d, a, k[12], 20, -1926607734)
a = @hh(a, b, c, d, k[5], 4, -378558)
d = @hh(d, a, b, c, k[8], 11, -2022574463)
c = @hh(c, d, a, b, k[11], 16, 1839030562)
b = @hh(b, c, d, a, k[14], 23, -35309556)
a = @hh(a, b, c, d, k[1], 4, -1530992060)
d = @hh(d, a, b, c, k[4], 11, 1272893353)
c = @hh(c, d, a, b, k[7], 16, -155497632)
b = @hh(b, c, d, a, k[10], 23, -1094730640)
a = @hh(a, b, c, d, k[13], 4, 681279174)
d = @hh(d, a, b, c, k[0], 11, -358537222)
c = @hh(c, d, a, b, k[3], 16, -722521979)
b = @hh(b, c, d, a, k[6], 23, 76029189)
a = @hh(a, b, c, d, k[9], 4, -640364487)
d = @hh(d, a, b, c, k[12], 11, -421815835)
c = @hh(c, d, a, b, k[15], 16, 530742520)
b = @hh(b, c, d, a, k[2], 23, -995338651)
a = @ii(a, b, c, d, k[0], 6, -198630844)
d = @ii(d, a, b, c, k[7], 10, 1126891415)
c = @ii(c, d, a, b, k[14], 15, -1416354905)
b = @ii(b, c, d, a, k[5], 21, -57434055)
a = @ii(a, b, c, d, k[12], 6, 1700485571)
d = @ii(d, a, b, c, k[3], 10, -1894986606)
c = @ii(c, d, a, b, k[10], 15, -1051523)
b = @ii(b, c, d, a, k[1], 21, -2054922799)
a = @ii(a, b, c, d, k[8], 6, 1873313359)
d = @ii(d, a, b, c, k[15], 10, -30611744)
c = @ii(c, d, a, b, k[6], 15, -1560198380)
b = @ii(b, c, d, a, k[13], 21, 1309151649)
a = @ii(a, b, c, d, k[4], 6, -145523070)
d = @ii(d, a, b, c, k[11], 10, -1120210379)
c = @ii(c, d, a, b, k[2], 15, 718787259)
b = @ii(b, c, d, a, k[9], 21, -343485551)
x[0] = @add32(a, x[0])
x[1] = @add32(b, x[1])
x[2] = @add32(c, x[2])
x[3] = @add32(d, x[3])
@cmn = (q, a, b, x, s, t) ->
a = @add32(@add32(a, q), @add32(x, t))
@add32 (a << s) | (a >>> (32 - s)), b
@ff = (a, b, c, d, x, s, t) ->
@cmn (b & c) | ((~b) & d), a, b, x, s, t
@gg = (a, b, c, d, x, s, t) ->
@cmn (b & d) | (c & (~d)), a, b, x, s, t
@hh = (a, b, c, d, x, s, t) ->
@cmn b ^ c ^ d, a, b, x, s, t
@ii = (a, b, c, d, x, s, t) ->
@cmn c ^ (b | (~d)), a, b, x, s, t
@md51 = (s) ->
txt = ''
n = s.length
state = [
1732584193
-271733879
-1732584194
271733878
]
i = undefined
i = 64
while i <= s.length
@md5cycle state, @md5blk(s.substring(i - 64, i))
i += 64
s = s.substring(i - 64)
tail = [
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
]
i = 0
while i < s.length
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3)
i++
tail[i >> 2] |= 0x80 << ((i % 4) << 3)
if i > 55
@md5cycle state, tail
i = 0
while i < 16
tail[i] = 0
i++
tail[14] = n * 8
@md5cycle state, tail
state
# there needs to be support for Unicode here,
# * unless we pretend that we can redefine the MD-5
# * algorithm for multi-byte characters (perhaps
# * by adding every four 16-bit characters and
# * shortening the sum to 32 bits). Otherwise
# * I suggest performing MD-5 as if every character
# * was two bytes--e.g., 0040 0025 = @%--but then
# * how will an ordinary MD-5 sum be matched?
# * There is no way to standardize text to something
# * like UTF-8 before transformation; speed cost is
# * utterly prohibitive. The JavaScript standard
# * itself needs to look at this: it should start
# * providing access to strings as preformed UTF-8
# * 8-bit unsigned value arrays.
#
@md5blk = (s) -> # I figured global was faster.
md5blks = [] # Andy King said do it this way.
i = undefined
i = 0
while i < 64
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24)
i += 4
md5blks
@rhex = (n) ->
s = ''
j = 0
while j < 4
s += @hex_chr[(n >> (j * 8 + 4)) & 0x0F] + @hex_chr[(n >> (j * 8)) & 0x0F]
j++
s
@hex = (x) ->
i = 0
while i < x.length
x[i] = @rhex(x[i])
i++
x.join ''
@md5 = (s) ->
@hex @md51(s)
# this function is much faster,
#so if possible we use it. Some IEs
#are the only ones I know of that
#need the idiotic second function,
#generated by an if clause.
@add32 = (a, b) ->
(a + b) & 0xFFFFFFFF
@hex_chr = '0123456789abcdef'.split('');
module.exports = Crypt
| true | ###
* This file is part of the Konsserto package.
*
* (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
#
# Crypt
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
class Crypt
@md5cycle = (x, k) ->
a = x[0]
b = x[1]
c = x[2]
d = x[3]
a = @ff(a, b, c, d, k[0], 7, -680876936)
d = @ff(d, a, b, c, k[1], 12, -389564586)
c = @ff(c, d, a, b, k[2], 17, 606105819)
b = @ff(b, c, d, a, k[3], 22, -1044525330)
a = @ff(a, b, c, d, k[4], 7, -176418897)
d = @ff(d, a, b, c, k[5], 12, 1200080426)
c = @ff(c, d, a, b, k[6], 17, -1473231341)
b = @ff(b, c, d, a, k[7], 22, -45705983)
a = @ff(a, b, c, d, k[8], 7, 1770035416)
d = @ff(d, a, b, c, k[9], 12, -1958414417)
c = @ff(c, d, a, b, k[10], 17, -42063)
b = @ff(b, c, d, a, k[11], 22, -1990404162)
a = @ff(a, b, c, d, k[12], 7, 1804603682)
d = @ff(d, a, b, c, k[13], 12, -40341101)
c = @ff(c, d, a, b, k[14], 17, -1502002290)
b = @ff(b, c, d, a, k[15], 22, 1236535329)
a = @gg(a, b, c, d, k[1], 5, -165796510)
d = @gg(d, a, b, c, k[6], 9, -1069501632)
c = @gg(c, d, a, b, k[11], 14, 643717713)
b = @gg(b, c, d, a, k[0], 20, -373897302)
a = @gg(a, b, c, d, k[5], 5, -701558691)
d = @gg(d, a, b, c, k[10], 9, 38016083)
c = @gg(c, d, a, b, k[15], 14, -660478335)
b = @gg(b, c, d, a, k[4], 20, -405537848)
a = @gg(a, b, c, d, k[9], 5, 568446438)
d = @gg(d, a, b, c, k[14], 9, -1019803690)
c = @gg(c, d, a, b, k[3], 14, -187363961)
b = @gg(b, c, d, a, k[8], 20, 1163531501)
a = @gg(a, b, c, d, k[13], 5, -1444681467)
d = @gg(d, a, b, c, k[2], 9, -51403784)
c = @gg(c, d, a, b, k[7], 14, 1735328473)
b = @gg(b, c, d, a, k[12], 20, -1926607734)
a = @hh(a, b, c, d, k[5], 4, -378558)
d = @hh(d, a, b, c, k[8], 11, -2022574463)
c = @hh(c, d, a, b, k[11], 16, 1839030562)
b = @hh(b, c, d, a, k[14], 23, -35309556)
a = @hh(a, b, c, d, k[1], 4, -1530992060)
d = @hh(d, a, b, c, k[4], 11, 1272893353)
c = @hh(c, d, a, b, k[7], 16, -155497632)
b = @hh(b, c, d, a, k[10], 23, -1094730640)
a = @hh(a, b, c, d, k[13], 4, 681279174)
d = @hh(d, a, b, c, k[0], 11, -358537222)
c = @hh(c, d, a, b, k[3], 16, -722521979)
b = @hh(b, c, d, a, k[6], 23, 76029189)
a = @hh(a, b, c, d, k[9], 4, -640364487)
d = @hh(d, a, b, c, k[12], 11, -421815835)
c = @hh(c, d, a, b, k[15], 16, 530742520)
b = @hh(b, c, d, a, k[2], 23, -995338651)
a = @ii(a, b, c, d, k[0], 6, -198630844)
d = @ii(d, a, b, c, k[7], 10, 1126891415)
c = @ii(c, d, a, b, k[14], 15, -1416354905)
b = @ii(b, c, d, a, k[5], 21, -57434055)
a = @ii(a, b, c, d, k[12], 6, 1700485571)
d = @ii(d, a, b, c, k[3], 10, -1894986606)
c = @ii(c, d, a, b, k[10], 15, -1051523)
b = @ii(b, c, d, a, k[1], 21, -2054922799)
a = @ii(a, b, c, d, k[8], 6, 1873313359)
d = @ii(d, a, b, c, k[15], 10, -30611744)
c = @ii(c, d, a, b, k[6], 15, -1560198380)
b = @ii(b, c, d, a, k[13], 21, 1309151649)
a = @ii(a, b, c, d, k[4], 6, -145523070)
d = @ii(d, a, b, c, k[11], 10, -1120210379)
c = @ii(c, d, a, b, k[2], 15, 718787259)
b = @ii(b, c, d, a, k[9], 21, -343485551)
x[0] = @add32(a, x[0])
x[1] = @add32(b, x[1])
x[2] = @add32(c, x[2])
x[3] = @add32(d, x[3])
@cmn = (q, a, b, x, s, t) ->
a = @add32(@add32(a, q), @add32(x, t))
@add32 (a << s) | (a >>> (32 - s)), b
@ff = (a, b, c, d, x, s, t) ->
@cmn (b & c) | ((~b) & d), a, b, x, s, t
@gg = (a, b, c, d, x, s, t) ->
@cmn (b & d) | (c & (~d)), a, b, x, s, t
@hh = (a, b, c, d, x, s, t) ->
@cmn b ^ c ^ d, a, b, x, s, t
@ii = (a, b, c, d, x, s, t) ->
@cmn c ^ (b | (~d)), a, b, x, s, t
@md51 = (s) ->
txt = ''
n = s.length
state = [
1732584193
-271733879
-1732584194
271733878
]
i = undefined
i = 64
while i <= s.length
@md5cycle state, @md5blk(s.substring(i - 64, i))
i += 64
s = s.substring(i - 64)
tail = [
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
]
i = 0
while i < s.length
tail[i >> 2] |= s.charCodeAt(i) << ((i % 4) << 3)
i++
tail[i >> 2] |= 0x80 << ((i % 4) << 3)
if i > 55
@md5cycle state, tail
i = 0
while i < 16
tail[i] = 0
i++
tail[14] = n * 8
@md5cycle state, tail
state
# there needs to be support for Unicode here,
# * unless we pretend that we can redefine the MD-5
# * algorithm for multi-byte characters (perhaps
# * by adding every four 16-bit characters and
# * shortening the sum to 32 bits). Otherwise
# * I suggest performing MD-5 as if every character
# * was two bytes--e.g., 0040 0025 = @%--but then
# * how will an ordinary MD-5 sum be matched?
# * There is no way to standardize text to something
# * like UTF-8 before transformation; speed cost is
# * utterly prohibitive. The JavaScript standard
# * itself needs to look at this: it should start
# * providing access to strings as preformed UTF-8
# * 8-bit unsigned value arrays.
#
@md5blk = (s) -> # I figured global was faster.
md5blks = [] # Andy King said do it this way.
i = undefined
i = 0
while i < 64
md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24)
i += 4
md5blks
@rhex = (n) ->
s = ''
j = 0
while j < 4
s += @hex_chr[(n >> (j * 8 + 4)) & 0x0F] + @hex_chr[(n >> (j * 8)) & 0x0F]
j++
s
@hex = (x) ->
i = 0
while i < x.length
x[i] = @rhex(x[i])
i++
x.join ''
@md5 = (s) ->
@hex @md51(s)
# this function is much faster,
#so if possible we use it. Some IEs
#are the only ones I know of that
#need the idiotic second function,
#generated by an if clause.
@add32 = (a, b) ->
(a + b) & 0xFFFFFFFF
@hex_chr = '0123456789abcdef'.split('');
module.exports = Crypt
|
[
{
"context": "l': 'Email'\n 'message': 'Message'\n 'name': 'Name'\n\n $.i18n.load dictionary\n\n return",
"end": 203,
"score": 0.9696592092514038,
"start": 199,
"tag": "NAME",
"value": "Name"
}
] | public/javascripts/i18n/en.js.coffee | bitaculous/webby | 0 | # This is the manifest for `en.js`.
#= require_self
@locale = 'en'
$ ->
dictionary =
'can\'t not be blank': 'can\'t not be blank.'
'email': 'Email'
'message': 'Message'
'name': 'Name'
$.i18n.load dictionary
return | 140529 | # This is the manifest for `en.js`.
#= require_self
@locale = 'en'
$ ->
dictionary =
'can\'t not be blank': 'can\'t not be blank.'
'email': 'Email'
'message': 'Message'
'name': '<NAME>'
$.i18n.load dictionary
return | true | # This is the manifest for `en.js`.
#= require_self
@locale = 'en'
$ ->
dictionary =
'can\'t not be blank': 'can\'t not be blank.'
'email': 'Email'
'message': 'Message'
'name': 'PI:NAME:<NAME>END_PI'
$.i18n.load dictionary
return |
[
{
"context": "n, you must change this please send us an email at support@koding.com.'\n name : 'url'\n disabled :",
"end": 1804,
"score": 0.9998982548713684,
"start": 1786,
"tag": "EMAIL",
"value": "support@koding.com"
}
] | client/admin/lib/views/general/groupgeneralsettingsview.coffee | ezgikaysi/koding | 1 | _ = require 'lodash'
kd = require 'kd'
KDView = kd.View
KDCustomScrollView = kd.CustomScrollView
Encoder = require 'htmlencode'
s3upload = require 'app/util/s3upload'
showError = require 'app/util/showError'
validator = require 'validator'
showError = require 'app/util/showError'
geoPattern = require 'geopattern'
KDFormView = kd.FormView
KDInputView = kd.InputView
KDButtonView = kd.ButtonView
KDCustomHTMLView = kd.CustomHTMLView
KDNotificationView = kd.NotificationView
module.exports = class GroupGeneralSettingsView extends KDCustomScrollView
constructor: (options = {}, data) ->
options.cssClass = 'general-settings-view'
super options, data
@forms = {}
@_canEditGroup = kd.singletons.groupsController.canEditGroup()
@createGeneralSettingsForm()
@createAvatarUploadForm() if @_canEditGroup
# @createDeletionForm()
createGeneralSettingsForm: ->
group = @getData()
url = if group.slug is 'koding' then '' else "#{group.slug}."
@wrapper.addSubView section = @createSection { name: 'general-settings' }
section.addSubView form = @generalSettingsForm = new KDFormView
@addInput form,
label : 'Name'
description : 'Your team name is displayed in menus and emails. It usually is (or includes) the name of your company.'
name : 'title'
cssClass : 'name'
defaultValue : Encoder.htmlDecode group.title ? ''
placeholder : 'Please enter a title here'
@addInput form,
label : 'URL'
description : 'Changing your team URL is currently not supported, if, for any reason, you must change this please send us an email at support@koding.com.'
name : 'url'
disabled : yes
defaultValue : Encoder.htmlDecode group.slug ? ''
placeholder : 'Please enter a title here'
# @addInput form,
# label : 'Default Channels'
# description : 'Your new members will automatically join to <b>#general</b> channel. Here you can specify more channels for new team members to join automatically.'
# name : 'channels'
# placeholder : 'product, design, ux, random etc'
# defaultValue : Encoder.htmlDecode group.defaultChannels?.join(', ') ? ''
# nextElement : new KDCustomHTMLView
# cssClass : 'warning-text'
# tagName : 'span'
# partial : 'Please add channel names separated by commas.'
# @addInput form,
# label : 'Allowed Domains'
# description : 'Allow anyone to sign up with an email address from a domain you specify here. If you need to enter multiple domains, please separate them by commas. e.g. acme.com, acme-inc.com'
# name : 'domains'
# placeholder : 'domain.com, other.edu'
# defaultValue : Encoder.htmlDecode group.allowedDomains?.join(', ') ? ''
if @_canEditGroup
form.addSubView new KDButtonView
title : 'Save Changes'
type : 'submit'
cssClass : 'solid medium green'
callback : @bound 'update'
createAvatarUploadForm: ->
@wrapper.addSubView @uploadSection = section = @createSection
name : 'avatar-upload'
section.addSubView @avatar = new KDCustomHTMLView
cssClass : 'avatar'
section.addSubView @uploadButton = new KDButtonView
cssClass : 'compact solid green upload'
title : 'UPLOAD LOGO'
loader : yes
section.addSubView @removeLogoButton = new KDButtonView
cssClass : 'compact solid black remove'
title : 'REMOVE LOGO'
loader : yes
callback : @bound 'removeLogo'
section.addSubView @uploadInput = new KDInputView
type : 'file'
cssClass : 'upload-input'
attributes : { accept : 'image/*' }
change : @bound 'handleUpload'
logo = @getData().customize?.logo
if logo then @showLogo logo else @showPattern()
handleUpload: ->
@uploadButton.showLoader()
[file] = @uploadInput.getElement().files
return @uploadButton.hideLoader() unless file
reader = new FileReader
reader.onload = (event) =>
options =
mimeType : file.type
content : file
@uploadAvatar options, => @uploadAvatarBtn.hideLoader()
reader.readAsDataURL file
uploadAvatar: (fileOptions, callback) ->
{ mimeType, content } = fileOptions
group = kd.singletons.groupsController.getCurrentGroup()
name = "#{group.slug}-logo-#{Date.now()}.png"
timeout = 3e4
s3upload { name, content, mimeType, timeout }, (err, url) =>
@uploadButton.hideLoader()
return showError err if err
group.modify { 'customize.logo': url }, => @showLogo url
showLogo: (url) ->
@avatar.getElement().style.backgroundImage = "url(#{url})"
@uploadSection.setClass 'with-logo'
showPattern: ->
avatarEl = @avatar.getElement()
pattern = geoPattern.generate @getData().slug, { generator: 'plusSigns' }
avatarEl.style.backgroundImage = pattern.toDataUrl()
@uploadSection.unsetClass 'with-logo'
removeLogo: ->
@getData().modify { 'customize.logo': '' }, =>
@showPattern()
@removeLogoButton.hideLoader()
@uploadInput.setValue ''
createDeletionForm: ->
@wrapper.addSubView section = @createSection
name : 'deletion'
description : 'If Koding is no use to your team anymore, you can delete your team page here.'
section.addSubView form = new KDFormView
@addInput form,
itemClass : KDButtonView
cssClass : 'solid medium red'
description : 'Note: Don\'t delete your team if you just want to change your team\'s name or URL. You also might want to export your data before deleting your team.'
title : 'DELETE TEAM'
separateCommas: (value) ->
# split from comma then trim spaces then filter empty values
return value.split ','
.map (i) -> return i.trim()
.filter (i) -> return i
update: ->
# { channels, domains } = @generalSettingsForm.getFormData()
{ domains } = @generalSettingsForm.getFormData()
formData = @generalSettingsForm.getFormData()
jGroup = @getData()
# newChannels = @separateCommas channels
# newDomains = @separateCommas domains
dataToUpdate = {}
unless formData.title is jGroup.title
dataToUpdate.title = formData.title
# unless _.isEqual newChannels, jGroup.defaultChannels
# dataToUpdate.defaultChannels = newChannels
# unless _.isEqual newDomains, jGroup.allowedDomains
# for domain in newDomains when not validator.isURL domain
# return @notify 'Please check allowed domains again'
# dataToUpdate.allowedDomains = newDomains
return if _.isEmpty dataToUpdate
jGroup.modify dataToUpdate, (err, result) =>
message = 'Group settings has been successfully updated.'
if err
message = 'Couldn\'t update group settings. Please try again'
kd.warn err
@notify message
createSection: (options = {}) ->
{ name, title, description } = options
section = new KDCustomHTMLView
tagName : 'section'
cssClass : kd.utils.curry 'AppModal-section', name
section.addSubView desc = new KDCustomHTMLView
tagName : 'p'
cssClass : 'AppModal-sectionDescription'
partial : description
return section
addInput: (form, options) ->
{ name, label, description, itemClass, nextElement } = options
itemClass or= KDInputView
form.inputs ?= {}
form.addSubView field = new KDCustomHTMLView { tagName : 'fieldset' }
if label
field.addSubView labelView = new KDCustomHTMLView
tagName : 'label'
for : name
partial : label
options.label = labelView
field.addSubView form.inputs[name] = input = new itemClass options
field.addSubView new KDCustomHTMLView { tagName : 'p', partial : description } if description
field.addSubView nextElement if nextElement and nextElement instanceof KDView
return input
notify: (title, duration = 5000) ->
new KDNotificationView { title, duration }
| 103441 | _ = require 'lodash'
kd = require 'kd'
KDView = kd.View
KDCustomScrollView = kd.CustomScrollView
Encoder = require 'htmlencode'
s3upload = require 'app/util/s3upload'
showError = require 'app/util/showError'
validator = require 'validator'
showError = require 'app/util/showError'
geoPattern = require 'geopattern'
KDFormView = kd.FormView
KDInputView = kd.InputView
KDButtonView = kd.ButtonView
KDCustomHTMLView = kd.CustomHTMLView
KDNotificationView = kd.NotificationView
module.exports = class GroupGeneralSettingsView extends KDCustomScrollView
constructor: (options = {}, data) ->
options.cssClass = 'general-settings-view'
super options, data
@forms = {}
@_canEditGroup = kd.singletons.groupsController.canEditGroup()
@createGeneralSettingsForm()
@createAvatarUploadForm() if @_canEditGroup
# @createDeletionForm()
createGeneralSettingsForm: ->
group = @getData()
url = if group.slug is 'koding' then '' else "#{group.slug}."
@wrapper.addSubView section = @createSection { name: 'general-settings' }
section.addSubView form = @generalSettingsForm = new KDFormView
@addInput form,
label : 'Name'
description : 'Your team name is displayed in menus and emails. It usually is (or includes) the name of your company.'
name : 'title'
cssClass : 'name'
defaultValue : Encoder.htmlDecode group.title ? ''
placeholder : 'Please enter a title here'
@addInput form,
label : 'URL'
description : 'Changing your team URL is currently not supported, if, for any reason, you must change this please send us an email at <EMAIL>.'
name : 'url'
disabled : yes
defaultValue : Encoder.htmlDecode group.slug ? ''
placeholder : 'Please enter a title here'
# @addInput form,
# label : 'Default Channels'
# description : 'Your new members will automatically join to <b>#general</b> channel. Here you can specify more channels for new team members to join automatically.'
# name : 'channels'
# placeholder : 'product, design, ux, random etc'
# defaultValue : Encoder.htmlDecode group.defaultChannels?.join(', ') ? ''
# nextElement : new KDCustomHTMLView
# cssClass : 'warning-text'
# tagName : 'span'
# partial : 'Please add channel names separated by commas.'
# @addInput form,
# label : 'Allowed Domains'
# description : 'Allow anyone to sign up with an email address from a domain you specify here. If you need to enter multiple domains, please separate them by commas. e.g. acme.com, acme-inc.com'
# name : 'domains'
# placeholder : 'domain.com, other.edu'
# defaultValue : Encoder.htmlDecode group.allowedDomains?.join(', ') ? ''
if @_canEditGroup
form.addSubView new KDButtonView
title : 'Save Changes'
type : 'submit'
cssClass : 'solid medium green'
callback : @bound 'update'
createAvatarUploadForm: ->
@wrapper.addSubView @uploadSection = section = @createSection
name : 'avatar-upload'
section.addSubView @avatar = new KDCustomHTMLView
cssClass : 'avatar'
section.addSubView @uploadButton = new KDButtonView
cssClass : 'compact solid green upload'
title : 'UPLOAD LOGO'
loader : yes
section.addSubView @removeLogoButton = new KDButtonView
cssClass : 'compact solid black remove'
title : 'REMOVE LOGO'
loader : yes
callback : @bound 'removeLogo'
section.addSubView @uploadInput = new KDInputView
type : 'file'
cssClass : 'upload-input'
attributes : { accept : 'image/*' }
change : @bound 'handleUpload'
logo = @getData().customize?.logo
if logo then @showLogo logo else @showPattern()
handleUpload: ->
@uploadButton.showLoader()
[file] = @uploadInput.getElement().files
return @uploadButton.hideLoader() unless file
reader = new FileReader
reader.onload = (event) =>
options =
mimeType : file.type
content : file
@uploadAvatar options, => @uploadAvatarBtn.hideLoader()
reader.readAsDataURL file
uploadAvatar: (fileOptions, callback) ->
{ mimeType, content } = fileOptions
group = kd.singletons.groupsController.getCurrentGroup()
name = "#{group.slug}-logo-#{Date.now()}.png"
timeout = 3e4
s3upload { name, content, mimeType, timeout }, (err, url) =>
@uploadButton.hideLoader()
return showError err if err
group.modify { 'customize.logo': url }, => @showLogo url
showLogo: (url) ->
@avatar.getElement().style.backgroundImage = "url(#{url})"
@uploadSection.setClass 'with-logo'
showPattern: ->
avatarEl = @avatar.getElement()
pattern = geoPattern.generate @getData().slug, { generator: 'plusSigns' }
avatarEl.style.backgroundImage = pattern.toDataUrl()
@uploadSection.unsetClass 'with-logo'
removeLogo: ->
@getData().modify { 'customize.logo': '' }, =>
@showPattern()
@removeLogoButton.hideLoader()
@uploadInput.setValue ''
createDeletionForm: ->
@wrapper.addSubView section = @createSection
name : 'deletion'
description : 'If Koding is no use to your team anymore, you can delete your team page here.'
section.addSubView form = new KDFormView
@addInput form,
itemClass : KDButtonView
cssClass : 'solid medium red'
description : 'Note: Don\'t delete your team if you just want to change your team\'s name or URL. You also might want to export your data before deleting your team.'
title : 'DELETE TEAM'
separateCommas: (value) ->
# split from comma then trim spaces then filter empty values
return value.split ','
.map (i) -> return i.trim()
.filter (i) -> return i
update: ->
# { channels, domains } = @generalSettingsForm.getFormData()
{ domains } = @generalSettingsForm.getFormData()
formData = @generalSettingsForm.getFormData()
jGroup = @getData()
# newChannels = @separateCommas channels
# newDomains = @separateCommas domains
dataToUpdate = {}
unless formData.title is jGroup.title
dataToUpdate.title = formData.title
# unless _.isEqual newChannels, jGroup.defaultChannels
# dataToUpdate.defaultChannels = newChannels
# unless _.isEqual newDomains, jGroup.allowedDomains
# for domain in newDomains when not validator.isURL domain
# return @notify 'Please check allowed domains again'
# dataToUpdate.allowedDomains = newDomains
return if _.isEmpty dataToUpdate
jGroup.modify dataToUpdate, (err, result) =>
message = 'Group settings has been successfully updated.'
if err
message = 'Couldn\'t update group settings. Please try again'
kd.warn err
@notify message
createSection: (options = {}) ->
{ name, title, description } = options
section = new KDCustomHTMLView
tagName : 'section'
cssClass : kd.utils.curry 'AppModal-section', name
section.addSubView desc = new KDCustomHTMLView
tagName : 'p'
cssClass : 'AppModal-sectionDescription'
partial : description
return section
addInput: (form, options) ->
{ name, label, description, itemClass, nextElement } = options
itemClass or= KDInputView
form.inputs ?= {}
form.addSubView field = new KDCustomHTMLView { tagName : 'fieldset' }
if label
field.addSubView labelView = new KDCustomHTMLView
tagName : 'label'
for : name
partial : label
options.label = labelView
field.addSubView form.inputs[name] = input = new itemClass options
field.addSubView new KDCustomHTMLView { tagName : 'p', partial : description } if description
field.addSubView nextElement if nextElement and nextElement instanceof KDView
return input
notify: (title, duration = 5000) ->
new KDNotificationView { title, duration }
| true | _ = require 'lodash'
kd = require 'kd'
KDView = kd.View
KDCustomScrollView = kd.CustomScrollView
Encoder = require 'htmlencode'
s3upload = require 'app/util/s3upload'
showError = require 'app/util/showError'
validator = require 'validator'
showError = require 'app/util/showError'
geoPattern = require 'geopattern'
KDFormView = kd.FormView
KDInputView = kd.InputView
KDButtonView = kd.ButtonView
KDCustomHTMLView = kd.CustomHTMLView
KDNotificationView = kd.NotificationView
module.exports = class GroupGeneralSettingsView extends KDCustomScrollView
constructor: (options = {}, data) ->
options.cssClass = 'general-settings-view'
super options, data
@forms = {}
@_canEditGroup = kd.singletons.groupsController.canEditGroup()
@createGeneralSettingsForm()
@createAvatarUploadForm() if @_canEditGroup
# @createDeletionForm()
createGeneralSettingsForm: ->
group = @getData()
url = if group.slug is 'koding' then '' else "#{group.slug}."
@wrapper.addSubView section = @createSection { name: 'general-settings' }
section.addSubView form = @generalSettingsForm = new KDFormView
@addInput form,
label : 'Name'
description : 'Your team name is displayed in menus and emails. It usually is (or includes) the name of your company.'
name : 'title'
cssClass : 'name'
defaultValue : Encoder.htmlDecode group.title ? ''
placeholder : 'Please enter a title here'
@addInput form,
label : 'URL'
description : 'Changing your team URL is currently not supported, if, for any reason, you must change this please send us an email at PI:EMAIL:<EMAIL>END_PI.'
name : 'url'
disabled : yes
defaultValue : Encoder.htmlDecode group.slug ? ''
placeholder : 'Please enter a title here'
# @addInput form,
# label : 'Default Channels'
# description : 'Your new members will automatically join to <b>#general</b> channel. Here you can specify more channels for new team members to join automatically.'
# name : 'channels'
# placeholder : 'product, design, ux, random etc'
# defaultValue : Encoder.htmlDecode group.defaultChannels?.join(', ') ? ''
# nextElement : new KDCustomHTMLView
# cssClass : 'warning-text'
# tagName : 'span'
# partial : 'Please add channel names separated by commas.'
# @addInput form,
# label : 'Allowed Domains'
# description : 'Allow anyone to sign up with an email address from a domain you specify here. If you need to enter multiple domains, please separate them by commas. e.g. acme.com, acme-inc.com'
# name : 'domains'
# placeholder : 'domain.com, other.edu'
# defaultValue : Encoder.htmlDecode group.allowedDomains?.join(', ') ? ''
if @_canEditGroup
form.addSubView new KDButtonView
title : 'Save Changes'
type : 'submit'
cssClass : 'solid medium green'
callback : @bound 'update'
createAvatarUploadForm: ->
@wrapper.addSubView @uploadSection = section = @createSection
name : 'avatar-upload'
section.addSubView @avatar = new KDCustomHTMLView
cssClass : 'avatar'
section.addSubView @uploadButton = new KDButtonView
cssClass : 'compact solid green upload'
title : 'UPLOAD LOGO'
loader : yes
section.addSubView @removeLogoButton = new KDButtonView
cssClass : 'compact solid black remove'
title : 'REMOVE LOGO'
loader : yes
callback : @bound 'removeLogo'
section.addSubView @uploadInput = new KDInputView
type : 'file'
cssClass : 'upload-input'
attributes : { accept : 'image/*' }
change : @bound 'handleUpload'
logo = @getData().customize?.logo
if logo then @showLogo logo else @showPattern()
handleUpload: ->
@uploadButton.showLoader()
[file] = @uploadInput.getElement().files
return @uploadButton.hideLoader() unless file
reader = new FileReader
reader.onload = (event) =>
options =
mimeType : file.type
content : file
@uploadAvatar options, => @uploadAvatarBtn.hideLoader()
reader.readAsDataURL file
uploadAvatar: (fileOptions, callback) ->
{ mimeType, content } = fileOptions
group = kd.singletons.groupsController.getCurrentGroup()
name = "#{group.slug}-logo-#{Date.now()}.png"
timeout = 3e4
s3upload { name, content, mimeType, timeout }, (err, url) =>
@uploadButton.hideLoader()
return showError err if err
group.modify { 'customize.logo': url }, => @showLogo url
showLogo: (url) ->
@avatar.getElement().style.backgroundImage = "url(#{url})"
@uploadSection.setClass 'with-logo'
showPattern: ->
avatarEl = @avatar.getElement()
pattern = geoPattern.generate @getData().slug, { generator: 'plusSigns' }
avatarEl.style.backgroundImage = pattern.toDataUrl()
@uploadSection.unsetClass 'with-logo'
removeLogo: ->
@getData().modify { 'customize.logo': '' }, =>
@showPattern()
@removeLogoButton.hideLoader()
@uploadInput.setValue ''
createDeletionForm: ->
@wrapper.addSubView section = @createSection
name : 'deletion'
description : 'If Koding is no use to your team anymore, you can delete your team page here.'
section.addSubView form = new KDFormView
@addInput form,
itemClass : KDButtonView
cssClass : 'solid medium red'
description : 'Note: Don\'t delete your team if you just want to change your team\'s name or URL. You also might want to export your data before deleting your team.'
title : 'DELETE TEAM'
separateCommas: (value) ->
# split from comma then trim spaces then filter empty values
return value.split ','
.map (i) -> return i.trim()
.filter (i) -> return i
update: ->
# { channels, domains } = @generalSettingsForm.getFormData()
{ domains } = @generalSettingsForm.getFormData()
formData = @generalSettingsForm.getFormData()
jGroup = @getData()
# newChannels = @separateCommas channels
# newDomains = @separateCommas domains
dataToUpdate = {}
unless formData.title is jGroup.title
dataToUpdate.title = formData.title
# unless _.isEqual newChannels, jGroup.defaultChannels
# dataToUpdate.defaultChannels = newChannels
# unless _.isEqual newDomains, jGroup.allowedDomains
# for domain in newDomains when not validator.isURL domain
# return @notify 'Please check allowed domains again'
# dataToUpdate.allowedDomains = newDomains
return if _.isEmpty dataToUpdate
jGroup.modify dataToUpdate, (err, result) =>
message = 'Group settings has been successfully updated.'
if err
message = 'Couldn\'t update group settings. Please try again'
kd.warn err
@notify message
createSection: (options = {}) ->
{ name, title, description } = options
section = new KDCustomHTMLView
tagName : 'section'
cssClass : kd.utils.curry 'AppModal-section', name
section.addSubView desc = new KDCustomHTMLView
tagName : 'p'
cssClass : 'AppModal-sectionDescription'
partial : description
return section
addInput: (form, options) ->
{ name, label, description, itemClass, nextElement } = options
itemClass or= KDInputView
form.inputs ?= {}
form.addSubView field = new KDCustomHTMLView { tagName : 'fieldset' }
if label
field.addSubView labelView = new KDCustomHTMLView
tagName : 'label'
for : name
partial : label
options.label = labelView
field.addSubView form.inputs[name] = input = new itemClass options
field.addSubView new KDCustomHTMLView { tagName : 'p', partial : description } if description
field.addSubView nextElement if nextElement and nextElement instanceof KDView
return input
notify: (title, duration = 5000) ->
new KDNotificationView { title, duration }
|
[
{
"context": "ind location associated with an IP\n#\n# Author:\n# Scott J Roberts - @sroberts\n\nRHODEY_IP = process.env.RHODEY_IP\nRH",
"end": 233,
"score": 0.9998523592948914,
"start": 218,
"tag": "NAME",
"value": "Scott J Roberts"
},
{
"context": "iated with an IP\n#\n# Author:\... | src/scripts/rhodey-geo-maxmind.coffee | 3ch01c/hubot-vtr-scripts | 47 | # Description:
# Geolocate an IP using Maxmind through Rhodey
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot maxmind <ip> - Gets MaxMind location associated with an IP
#
# Author:
# Scott J Roberts - @sroberts
RHODEY_IP = process.env.RHODEY_IP
RHODEY_PORT = process.env.RHODEY_PORT
module.exports = (robot) ->
robot.respond /maxmind (.*)/i, (msg) ->
ip = msg.match[1]
console.log("trying to get: #{RHODEY_IP}:#{RHODEY_PORT}" + "/ip/#{ip}/geo/maxmind.json")
robot.http("http://#{RHODEY_IP}:#{RHODEY_PORT}" + "/ip/#{ip}/geo/maxmind.json")
.get() (err, res, body) ->
if res.statusCode is 200
ipinfo_json = JSON.parse body
msg.send "According to MaxMind I'm pretty sure #{ip} is in #{ipinfo_json['city']}, #{ipinfo_json['region']}, #{ipinfo_json['country_name']}."
else
msg.send "I couldn't access Rhodey(#{RHODEY_IP}:#{RHODEY_PORT}). Maybe this tells you something? Error Message: #{err}. Status Code: #{res.statusCode}"
| 150909 | # Description:
# Geolocate an IP using Maxmind through Rhodey
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot maxmind <ip> - Gets MaxMind location associated with an IP
#
# Author:
# <NAME> - @sroberts
RHODEY_IP = process.env.RHODEY_IP
RHODEY_PORT = process.env.RHODEY_PORT
module.exports = (robot) ->
robot.respond /maxmind (.*)/i, (msg) ->
ip = msg.match[1]
console.log("trying to get: #{RHODEY_IP}:#{RHODEY_PORT}" + "/ip/#{ip}/geo/maxmind.json")
robot.http("http://#{RHODEY_IP}:#{RHODEY_PORT}" + "/ip/#{ip}/geo/maxmind.json")
.get() (err, res, body) ->
if res.statusCode is 200
ipinfo_json = JSON.parse body
msg.send "According to MaxMind I'm pretty sure #{ip} is in #{ipinfo_json['city']}, #{ipinfo_json['region']}, #{ipinfo_json['country_name']}."
else
msg.send "I couldn't access Rhodey(#{RHODEY_IP}:#{RHODEY_PORT}). Maybe this tells you something? Error Message: #{err}. Status Code: #{res.statusCode}"
| true | # Description:
# Geolocate an IP using Maxmind through Rhodey
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot maxmind <ip> - Gets MaxMind location associated with an IP
#
# Author:
# PI:NAME:<NAME>END_PI - @sroberts
RHODEY_IP = process.env.RHODEY_IP
RHODEY_PORT = process.env.RHODEY_PORT
module.exports = (robot) ->
robot.respond /maxmind (.*)/i, (msg) ->
ip = msg.match[1]
console.log("trying to get: #{RHODEY_IP}:#{RHODEY_PORT}" + "/ip/#{ip}/geo/maxmind.json")
robot.http("http://#{RHODEY_IP}:#{RHODEY_PORT}" + "/ip/#{ip}/geo/maxmind.json")
.get() (err, res, body) ->
if res.statusCode is 200
ipinfo_json = JSON.parse body
msg.send "According to MaxMind I'm pretty sure #{ip} is in #{ipinfo_json['city']}, #{ipinfo_json['region']}, #{ipinfo_json['country_name']}."
else
msg.send "I couldn't access Rhodey(#{RHODEY_IP}:#{RHODEY_PORT}). Maybe this tells you something? Error Message: #{err}. Status Code: #{res.statusCode}"
|
[
{
"context": "shedUrl = \"https://docs.google.com/spreadsheets/d/1vyPu1EtzU1DvGXfthjrR-blJ8mGe75TL4BFNWtFMm0I/pubhtml\"\n @key = \"1vyPu1EtzU1DvGXfthjrR-blJ8mG",
"end": 197,
"score": 0.9768465161323547,
"start": 153,
"tag": "KEY",
"value": "1vyPu1EtzU1DvGXfthjrR-blJ8mGe75TL4BFNWtFMm0I"
... | spec/googleSpreadsheetsParserSpec.coffee | tanakaworld/google-spreadsheets-parser | 4 | #require 'jasmine-collection-matchers'
describe GoogleSpreadsheetsParser, ->
beforeAll ->
@publishedUrl = "https://docs.google.com/spreadsheets/d/1vyPu1EtzU1DvGXfthjrR-blJ8mGe75TL4BFNWtFMm0I/pubhtml"
@key = "1vyPu1EtzU1DvGXfthjrR-blJ8mGe75TL4BFNWtFMm0I"
@firstWorksheetId = "od6"
describe '.toJson', ->
beforeEach ->
jasmine.Ajax.install()
afterEach ->
jasmine.Ajax.uninstall()
describe 'should got json', ->
beforeEach ->
# mock for basic
mockedSampleDataBasicJson = window.__fixtures__['spec/fixtures/sampleDataBasic']
requestUrl = "https://spreadsheets.google.com/feeds/worksheets/#{@key}/public/basic?alt=json"
jasmine.Ajax.stubRequest(requestUrl).andReturn
status: 200
responseText: JSON.stringify(mockedSampleDataBasicJson)
# mock for feed
mockedSampleDataFeedJson = window.__fixtures__['spec/fixtures/sampleDataFeed']
requestUrl = "https://spreadsheets.google.com/feeds/cells/#{@key}/#{@firstWorksheetId}/public/values?alt=json"
jasmine.Ajax.stubRequest(requestUrl).andReturn
status: 200
responseText: JSON.stringify(mockedSampleDataFeedJson)
it 'should got feeds', ->
gss = new GoogleSpreadsheetsParser(@publishedUrl, {sheetTitle: 'Sample', hasTitle: true})
expect(gss.toJson()).toBe('[{"ID":"1","Name":"Mike","Age":"24"},{"ID":"2","Name":"Chris","Age":"28"},{"ID":"3","Name":"Doug","Age":"34"},{"ID":"4","Name":"Vlade","Age":"21"},{"ID":"5","Name":"Peja","Age":"37"}]')
| 133139 | #require 'jasmine-collection-matchers'
describe GoogleSpreadsheetsParser, ->
beforeAll ->
@publishedUrl = "https://docs.google.com/spreadsheets/d/<KEY>/pubhtml"
@key = "<KEY>"
@firstWorksheetId = "od6"
describe '.toJson', ->
beforeEach ->
jasmine.Ajax.install()
afterEach ->
jasmine.Ajax.uninstall()
describe 'should got json', ->
beforeEach ->
# mock for basic
mockedSampleDataBasicJson = window.__fixtures__['spec/fixtures/sampleDataBasic']
requestUrl = "https://spreadsheets.google.com/feeds/worksheets/#{@key}/public/basic?alt=json"
jasmine.Ajax.stubRequest(requestUrl).andReturn
status: 200
responseText: JSON.stringify(mockedSampleDataBasicJson)
# mock for feed
mockedSampleDataFeedJson = window.__fixtures__['spec/fixtures/sampleDataFeed']
requestUrl = "https://spreadsheets.google.com/feeds/cells/#{@key}/#{@firstWorksheetId}/public/values?alt=json"
jasmine.Ajax.stubRequest(requestUrl).andReturn
status: 200
responseText: JSON.stringify(mockedSampleDataFeedJson)
it 'should got feeds', ->
gss = new GoogleSpreadsheetsParser(@publishedUrl, {sheetTitle: 'Sample', hasTitle: true})
expect(gss.toJson()).toBe('[{"ID":"1","Name":"<NAME>","Age":"24"},{"ID":"2","Name":"<NAME>","Age":"28"},{"ID":"3","Name":"<NAME>","Age":"34"},{"ID":"4","Name":"<NAME>","Age":"21"},{"ID":"5","Name":"<NAME>","Age":"37"}]')
| true | #require 'jasmine-collection-matchers'
describe GoogleSpreadsheetsParser, ->
beforeAll ->
@publishedUrl = "https://docs.google.com/spreadsheets/d/PI:KEY:<KEY>END_PI/pubhtml"
@key = "PI:KEY:<KEY>END_PI"
@firstWorksheetId = "od6"
describe '.toJson', ->
beforeEach ->
jasmine.Ajax.install()
afterEach ->
jasmine.Ajax.uninstall()
describe 'should got json', ->
beforeEach ->
# mock for basic
mockedSampleDataBasicJson = window.__fixtures__['spec/fixtures/sampleDataBasic']
requestUrl = "https://spreadsheets.google.com/feeds/worksheets/#{@key}/public/basic?alt=json"
jasmine.Ajax.stubRequest(requestUrl).andReturn
status: 200
responseText: JSON.stringify(mockedSampleDataBasicJson)
# mock for feed
mockedSampleDataFeedJson = window.__fixtures__['spec/fixtures/sampleDataFeed']
requestUrl = "https://spreadsheets.google.com/feeds/cells/#{@key}/#{@firstWorksheetId}/public/values?alt=json"
jasmine.Ajax.stubRequest(requestUrl).andReturn
status: 200
responseText: JSON.stringify(mockedSampleDataFeedJson)
it 'should got feeds', ->
gss = new GoogleSpreadsheetsParser(@publishedUrl, {sheetTitle: 'Sample', hasTitle: true})
expect(gss.toJson()).toBe('[{"ID":"1","Name":"PI:NAME:<NAME>END_PI","Age":"24"},{"ID":"2","Name":"PI:NAME:<NAME>END_PI","Age":"28"},{"ID":"3","Name":"PI:NAME:<NAME>END_PI","Age":"34"},{"ID":"4","Name":"PI:NAME:<NAME>END_PI","Age":"21"},{"ID":"5","Name":"PI:NAME:<NAME>END_PI","Age":"37"}]')
|
[
{
"context": "\n###\nTest CSV - Copyright David Worms <open@adaltas.com> (BSD Licensed)\n###\n\nfs = requi",
"end": 37,
"score": 0.999826967716217,
"start": 26,
"tag": "NAME",
"value": "David Worms"
},
{
"context": "\n###\nTest CSV - Copyright David Worms <open@adaltas.com> (BSD Lice... | servers/nodejs/node_modules/restify/node_modules/csv/test/header.coffee | HyperNexus/crashdumper | 186 |
###
Test CSV - Copyright David Worms <open@adaltas.com> (BSD Licensed)
###
fs = require 'fs'
should = require 'should'
csv = if process.env.CSV_COV then require '../lib-cov' else require '../src'
describe 'header', ->
it 'should print headers with defined write columns', (next) ->
csv()
.from.string("""
20322051544,1979,8.8017226E7,ABC,45,2000-01-01
28392898392,1974,8.8392926E7,DEF,23,2050-11-27
""")
.on 'end', (count) ->
count.should.eql 2
.to.string( (result) ->
result.should.eql """
FIELD_1,FIELD_2
20322051544,1979
28392898392,1974
"""
next()
, header: true, columns: ["FIELD_1", "FIELD_2"] )
it 'should print headers with true read columns and defined write columns', (next) ->
csv()
.from.string("""
FIELD_1,FIELD_2,FIELD_3,FIELD_4,FIELD_5,FIELD_6
20322051544,1979,8.8017226E7,ABC,45,2000-01-01
28392898392,1974,8.8392926E7,DEF,23,2050-11-27
""", columns: true)
.to.string( (result) ->
result.should.eql """
FIELD_1,FIELD_2
20322051544,1979
28392898392,1974
"""
next()
, header: true, columns: ["FIELD_1", "FIELD_2"] )
it 'should print headers if no records to parse', (next) ->
csv()
.from.array([])
.to.string((data) ->
data.should.eql 'some,headers'
, header: true, columns: ['some', 'headers'])
.on 'end', (count) ->
count.should.eql 0
next()
| 2722 |
###
Test CSV - Copyright <NAME> <<EMAIL>> (BSD Licensed)
###
fs = require 'fs'
should = require 'should'
csv = if process.env.CSV_COV then require '../lib-cov' else require '../src'
describe 'header', ->
it 'should print headers with defined write columns', (next) ->
csv()
.from.string("""
20322051544,1979,8.8017226E7,ABC,45,2000-01-01
28392898392,1974,8.8392926E7,DEF,23,2050-11-27
""")
.on 'end', (count) ->
count.should.eql 2
.to.string( (result) ->
result.should.eql """
FIELD_1,FIELD_2
20322051544,1979
28392898392,1974
"""
next()
, header: true, columns: ["FIELD_1", "FIELD_2"] )
it 'should print headers with true read columns and defined write columns', (next) ->
csv()
.from.string("""
FIELD_1,FIELD_2,FIELD_3,FIELD_4,FIELD_5,FIELD_6
20322051544,1979,8.8017226E7,ABC,45,2000-01-01
28392898392,1974,8.8392926E7,DEF,23,2050-11-27
""", columns: true)
.to.string( (result) ->
result.should.eql """
FIELD_1,FIELD_2
20322051544,1979
28392898392,1974
"""
next()
, header: true, columns: ["FIELD_1", "FIELD_2"] )
it 'should print headers if no records to parse', (next) ->
csv()
.from.array([])
.to.string((data) ->
data.should.eql 'some,headers'
, header: true, columns: ['some', 'headers'])
.on 'end', (count) ->
count.should.eql 0
next()
| true |
###
Test CSV - Copyright PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (BSD Licensed)
###
fs = require 'fs'
should = require 'should'
csv = if process.env.CSV_COV then require '../lib-cov' else require '../src'
describe 'header', ->
it 'should print headers with defined write columns', (next) ->
csv()
.from.string("""
20322051544,1979,8.8017226E7,ABC,45,2000-01-01
28392898392,1974,8.8392926E7,DEF,23,2050-11-27
""")
.on 'end', (count) ->
count.should.eql 2
.to.string( (result) ->
result.should.eql """
FIELD_1,FIELD_2
20322051544,1979
28392898392,1974
"""
next()
, header: true, columns: ["FIELD_1", "FIELD_2"] )
it 'should print headers with true read columns and defined write columns', (next) ->
csv()
.from.string("""
FIELD_1,FIELD_2,FIELD_3,FIELD_4,FIELD_5,FIELD_6
20322051544,1979,8.8017226E7,ABC,45,2000-01-01
28392898392,1974,8.8392926E7,DEF,23,2050-11-27
""", columns: true)
.to.string( (result) ->
result.should.eql """
FIELD_1,FIELD_2
20322051544,1979
28392898392,1974
"""
next()
, header: true, columns: ["FIELD_1", "FIELD_2"] )
it 'should print headers if no records to parse', (next) ->
csv()
.from.array([])
.to.string((data) ->
data.should.eql 'some,headers'
, header: true, columns: ['some', 'headers'])
.on 'end', (count) ->
count.should.eql 0
next()
|
[
{
"context": "onMixin\n\n import test.output.dir.gregor1 as gregor1\n import test.output.dir.keybase1 as keybas",
"end": 1988,
"score": 0.9777029752731323,
"start": 1981,
"tag": "USERNAME",
"value": "gregor1"
},
{
"context": " record = {\n type: \"record\"\n ... | src/py_emit.test.iced | samkenxstream/node-avdl-compiler | 7 | {PythonEmitter} = require("./py_emit")
pkg = require '../package.json'
describe "PythonEmitter", () ->
emitter = null
beforeEach () ->
emitter = new PythonEmitter
describe "output_doc", () ->
it "should output a Python docstring", () ->
emitter.output_doc "This is a test comment with\na new line."
code = emitter._code.join "\n"
expect(code).toBe("""
\"\"\"
This is a test comment with
a new line.
\"\"\"
""")
return
return
describe "emit_preface", () ->
it "Should emit a preface", () ->
emitter.emit_preface ["./my_test_file.avdl"], {namespace: "chat1"}
code = emitter._code.join "\n"
expect(code).toBe("""
\"\"\"chat1
Auto-generated to Python types by #{pkg.name} v#{pkg.version} (#{pkg.homepage})
Input files:
- my_test_file.avdl
\"\"\"\n
""")
return
return
describe "emit_imports", () ->
it "should output all imports used by the file", () ->
imports = [
{
path: "../gregor1"
type: "idl"
import_as: "gregor1"
},
{
path: "../keybase1"
type: "idl",
import_as: "keybase1"
},
{
path: "common.avdl"
type: "idl"
},
{
path: "chat_ui.avdl"
type: "idl"
},
{
path: "unfurl.avdl"
type: "idl"
},
{
path: "commands.avdl"
type: "idl"
}
]
emitter.emit_imports {imports}, "test/output/dir/name/__init__.py"
code = emitter._code.join "\n"
expect(code).toBe("""
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
from typing_extensions import Literal
from dataclasses_json import config, DataClassJsonMixin
import test.output.dir.gregor1 as gregor1
import test.output.dir.keybase1 as keybase1\n
""")
return
return
describe "emit_typedef", () ->
it "Should emit a string typedef", () ->
type = {
type: "record"
name: "BuildPaymentID"
fields: []
typedef: "string"
}
emitter.emit_typedef type
code = emitter._code.join "\n"
expect(code).toBe("""
BuildPaymentID = str
""")
return
return
describe "emit_record", () ->
it "should emit an object with primative value keys", () ->
record = {
type: "record"
name: "TestRecord"
fields: [
{
type: "string",
name: "statusDescription"
},
{
type: "boolean"
name: "isValidThing"
},
{
type: "long",
name: "longInt"
},
{
type: "double",
name: "doubleOrNothin"
},
{
type: "bytes",
name: "takeAByteOfThisApple"
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class TestRecord(DataClassJsonMixin):
status_description: str = field(metadata=config(field_name='statusDescription'))
is_valid_thing: bool = field(metadata=config(field_name='isValidThing'))
long_int: int = field(metadata=config(field_name='longInt'))
double_or_nothin: float = field(metadata=config(field_name='doubleOrNothin'))
take_a_byte_of_this_apple: str = field(metadata=config(field_name='takeAByteOfThisApple'))\n
""")
return
it "Should support custom types as fields", () ->
record = {
type: "record"
name: "TestRecord"
fields: [
{
type: "MySuperCoolCustomType",
name: "superCool"
},
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class TestRecord(DataClassJsonMixin):
super_cool: MySuperCoolCustomType = field(metadata=config(field_name='superCool'))\n
""")
return
it "should support optional types, and have non-optionals be declared first", () ->
record = {
"type": "record",
"name": "MsgSender",
"fields": [
{
"type": "string",
"name": "uid",
"jsonkey": "uid"
},
{
"type": "string",
"name": "username",
"jsonkey": "username",
"optional": true
},
{
"type": "string",
"name": "deviceID",
"jsonkey": "device_id"
},
{
"type": "string",
"name": "deviceName",
"jsonkey": "device_name",
"optional": true
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class MsgSender(DataClassJsonMixin):
uid: str = field(metadata=config(field_name='uid'))
device_id: str = field(metadata=config(field_name='device_id'))
username: Optional[str] = field(default=None, metadata=config(field_name='username'))
device_name: Optional[str] = field(default=None, metadata=config(field_name='device_name'))\n
""")
return
it "Should support optional arrays", () ->
record = {
type: "record",
name: "Thread",
fields: [
{
type: {
type: "array",
items: "Message"
},
name: "messages",
jsonkey: "messages"
},
{
type: [
null,
"Pagination"
],
name: "pagination",
jsonkey: "pagination"
},
{
type: "boolean",
name: "offline",
jsonkey: "offline",
optional: true
},
{
type: {
"type": "array",
"items": "keybase1.TLFIdentifyFailure"
},
name: "identifyFailures",
jsonkey: "identify_failures",
optional: true
},
{
type: {
"type": "array",
"items": "RateLimitRes"
},
name: "rateLimits",
jsonkey: "ratelimits",
optional: true
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class Thread(DataClassJsonMixin):
messages: Optional[List[Message]] = field(default=None, metadata=config(field_name='messages'))
pagination: Optional[Pagination] = field(default=None, metadata=config(field_name='pagination'))
offline: Optional[bool] = field(default=None, metadata=config(field_name='offline'))
identify_failures: Optional[List[keybase1.TLFIdentifyFailure]] = field(default=None, metadata=config(field_name='identify_failures'))
rate_limits: Optional[List[RateLimitRes]] = field(default=None, metadata=config(field_name='ratelimits'))\n
""")
return
it "Should emit a struct with a map type", () ->
record = {
type: "record"
name: "StellarServerDefinitions"
fields: [
{
type: "int",
name: "revision"
},
{
type: {
type: "map"
values: "OutsideCurrencyDefinition"
keys: "OutsideCurrencyCode"
}
name: "currencies"
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class StellarServerDefinitions(DataClassJsonMixin):
revision: int = field(metadata=config(field_name='revision'))
currencies: Dict[str, OutsideCurrencyDefinition] = field(metadata=config(field_name='currencies'))\n
""")
return
return
describe "emit_fixed", () ->
it "should emit a string", () ->
emitter.emit_fixed { name: "FunHash", size: 32 }
code = emitter._code.join "\n"
expect(code).toBe("""
FunHash = Optional[str]
""")
return
return
describe "emit_enum", () ->
it "should emit both an int and string enum", () ->
test_enum = {
type: "enum",
name: "AuditVersion",
symbols: [
"V0_0",
"V1_1",
"V2_2",
"V3_3"
]
"doc": "This is a docstring\nhi"
}
emitter.emit_enum test_enum
code = emitter._code.join "\n"
expect(code).toBe("""
class AuditVersion(Enum):
\"\"\"
This is a docstring
hi
\"\"\"
V0 = 0
V1 = 1
V2 = 2
V3 = 3
class AuditVersionStrings(Enum):
V0 = 'v0'
V1 = 'v1'
V2 = 'v2'
V3 = 'v3'\n\n
""")
return
return
describe "emit_variant", () ->
it "should emit a variant", () ->
variant =
type: "variant",
name: "MyVariant",
switch: {
type: "InboxResType",
name: "rtype"
},
cases: [
{
label: {
name: "VERSIONHIT",
def: false
},
body: null
},
{
label: {
name: "FULL",
def: false
},
body: "InboxViewFull"
},
{
label: {
name: "HELLO",
def: false
},
body: "bool"
},
{
label: {
name: "BLAH",
def: true
},
body: "int"
},
{
label: {
name: "DECK",
def: false
},
body: {
type: "array",
items: "int"
}
}
]
emitter.emit_variant variant
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class MyVariant__VERSIONHIT(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.VERSIONHIT]
VERSIONHIT: None
@dataclass
class MyVariant__FULL(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.FULL]
FULL: Optional[InboxViewFull]
@dataclass
class MyVariant__HELLO(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.HELLO]
HELLO: Optional[bool]
@dataclass
class MyVariant__DECK(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.DECK]
DECK: Optional[List[int]]
MyVariant = Union[MyVariant__VERSIONHIT, MyVariant__FULL, MyVariant__HELLO, MyVariant__DECK]\n
""")
return
return
return
| 118723 | {PythonEmitter} = require("./py_emit")
pkg = require '../package.json'
describe "PythonEmitter", () ->
emitter = null
beforeEach () ->
emitter = new PythonEmitter
describe "output_doc", () ->
it "should output a Python docstring", () ->
emitter.output_doc "This is a test comment with\na new line."
code = emitter._code.join "\n"
expect(code).toBe("""
\"\"\"
This is a test comment with
a new line.
\"\"\"
""")
return
return
describe "emit_preface", () ->
it "Should emit a preface", () ->
emitter.emit_preface ["./my_test_file.avdl"], {namespace: "chat1"}
code = emitter._code.join "\n"
expect(code).toBe("""
\"\"\"chat1
Auto-generated to Python types by #{pkg.name} v#{pkg.version} (#{pkg.homepage})
Input files:
- my_test_file.avdl
\"\"\"\n
""")
return
return
describe "emit_imports", () ->
it "should output all imports used by the file", () ->
imports = [
{
path: "../gregor1"
type: "idl"
import_as: "gregor1"
},
{
path: "../keybase1"
type: "idl",
import_as: "keybase1"
},
{
path: "common.avdl"
type: "idl"
},
{
path: "chat_ui.avdl"
type: "idl"
},
{
path: "unfurl.avdl"
type: "idl"
},
{
path: "commands.avdl"
type: "idl"
}
]
emitter.emit_imports {imports}, "test/output/dir/name/__init__.py"
code = emitter._code.join "\n"
expect(code).toBe("""
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
from typing_extensions import Literal
from dataclasses_json import config, DataClassJsonMixin
import test.output.dir.gregor1 as gregor1
import test.output.dir.keybase1 as keybase1\n
""")
return
return
describe "emit_typedef", () ->
it "Should emit a string typedef", () ->
type = {
type: "record"
name: "BuildPaymentID"
fields: []
typedef: "string"
}
emitter.emit_typedef type
code = emitter._code.join "\n"
expect(code).toBe("""
BuildPaymentID = str
""")
return
return
describe "emit_record", () ->
it "should emit an object with primative value keys", () ->
record = {
type: "record"
name: "<NAME>"
fields: [
{
type: "string",
name: "statusDescription"
},
{
type: "boolean"
name: "isValidThing"
},
{
type: "long",
name: "longInt"
},
{
type: "double",
name: "doubleOrNothin"
},
{
type: "bytes",
name: "takeAByteOfThisApple"
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class TestRecord(DataClassJsonMixin):
status_description: str = field(metadata=config(field_name='statusDescription'))
is_valid_thing: bool = field(metadata=config(field_name='isValidThing'))
long_int: int = field(metadata=config(field_name='longInt'))
double_or_nothin: float = field(metadata=config(field_name='doubleOrNothin'))
take_a_byte_of_this_apple: str = field(metadata=config(field_name='takeAByteOfThisApple'))\n
""")
return
it "Should support custom types as fields", () ->
record = {
type: "record"
name: "<NAME>"
fields: [
{
type: "MySuperCoolCustomType",
name: "<NAME>Cool"
},
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class TestRecord(DataClassJsonMixin):
super_cool: MySuperCoolCustomType = field(metadata=config(field_name='superCool'))\n
""")
return
it "should support optional types, and have non-optionals be declared first", () ->
record = {
"type": "record",
"name": "<NAME>Sender",
"fields": [
{
"type": "string",
"name": "uid",
"jsonkey": "uid"
},
{
"type": "string",
"name": "username",
"jsonkey": "username",
"optional": true
},
{
"type": "string",
"name": "deviceID",
"jsonkey": "device_id"
},
{
"type": "string",
"name": "deviceName",
"jsonkey": "device_name",
"optional": true
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class MsgSender(DataClassJsonMixin):
uid: str = field(metadata=config(field_name='uid'))
device_id: str = field(metadata=config(field_name='device_id'))
username: Optional[str] = field(default=None, metadata=config(field_name='username'))
device_name: Optional[str] = field(default=None, metadata=config(field_name='device_name'))\n
""")
return
it "Should support optional arrays", () ->
record = {
type: "record",
name: "Thread",
fields: [
{
type: {
type: "array",
items: "Message"
},
name: "messages",
jsonkey: "messages"
},
{
type: [
null,
"Pagination"
],
name: "pagination",
jsonkey: "pagination"
},
{
type: "boolean",
name: "offline",
jsonkey: "offline",
optional: true
},
{
type: {
"type": "array",
"items": "keybase1.TLFIdentifyFailure"
},
name: "identifyFailures",
jsonkey: "identify_failures",
optional: true
},
{
type: {
"type": "array",
"items": "RateLimitRes"
},
name: "rateLimits",
jsonkey: "<KEY>limits",
optional: true
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class Thread(DataClassJsonMixin):
messages: Optional[List[Message]] = field(default=None, metadata=config(field_name='messages'))
pagination: Optional[Pagination] = field(default=None, metadata=config(field_name='pagination'))
offline: Optional[bool] = field(default=None, metadata=config(field_name='offline'))
identify_failures: Optional[List[keybase1.TLFIdentifyFailure]] = field(default=None, metadata=config(field_name='identify_failures'))
rate_limits: Optional[List[RateLimitRes]] = field(default=None, metadata=config(field_name='ratelimits'))\n
""")
return
it "Should emit a struct with a map type", () ->
record = {
type: "record"
name: "StellarServerDefinitions"
fields: [
{
type: "int",
name: "revision"
},
{
type: {
type: "map"
values: "OutsideCurrencyDefinition"
keys: "OutsideCurrencyCode"
}
name: "currencies"
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class StellarServerDefinitions(DataClassJsonMixin):
revision: int = field(metadata=config(field_name='revision'))
currencies: Dict[str, OutsideCurrencyDefinition] = field(metadata=config(field_name='currencies'))\n
""")
return
return
describe "emit_fixed", () ->
it "should emit a string", () ->
emitter.emit_fixed { name: "FunHash", size: 32 }
code = emitter._code.join "\n"
expect(code).toBe("""
FunHash = Optional[str]
""")
return
return
describe "emit_enum", () ->
it "should emit both an int and string enum", () ->
test_enum = {
type: "enum",
name: "AuditVersion",
symbols: [
"V0_0",
"V1_1",
"V2_2",
"V3_3"
]
"doc": "This is a docstring\nhi"
}
emitter.emit_enum test_enum
code = emitter._code.join "\n"
expect(code).toBe("""
class AuditVersion(Enum):
\"\"\"
This is a docstring
hi
\"\"\"
V0 = 0
V1 = 1
V2 = 2
V3 = 3
class AuditVersionStrings(Enum):
V0 = 'v0'
V1 = 'v1'
V2 = 'v2'
V3 = 'v3'\n\n
""")
return
return
describe "emit_variant", () ->
it "should emit a variant", () ->
variant =
type: "variant",
name: "<NAME>Variant",
switch: {
type: "InboxResType",
name: "rtype"
},
cases: [
{
label: {
name: "VERSIONHIT",
def: false
},
body: null
},
{
label: {
name: "FULL",
def: false
},
body: "InboxViewFull"
},
{
label: {
name: "<NAME>LO",
def: false
},
body: "bool"
},
{
label: {
name: "<NAME>AH",
def: true
},
body: "int"
},
{
label: {
name: "DECK",
def: false
},
body: {
type: "array",
items: "int"
}
}
]
emitter.emit_variant variant
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class MyVariant__VERSIONHIT(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.VERSIONHIT]
VERSIONHIT: None
@dataclass
class MyVariant__FULL(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.FULL]
FULL: Optional[InboxViewFull]
@dataclass
class MyVariant__HELLO(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.HELLO]
HELLO: Optional[bool]
@dataclass
class MyVariant__DECK(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.DECK]
DECK: Optional[List[int]]
MyVariant = Union[MyVariant__VERSIONHIT, MyVariant__FULL, MyVariant__HELLO, MyVariant__DECK]\n
""")
return
return
return
| true | {PythonEmitter} = require("./py_emit")
pkg = require '../package.json'
describe "PythonEmitter", () ->
emitter = null
beforeEach () ->
emitter = new PythonEmitter
describe "output_doc", () ->
it "should output a Python docstring", () ->
emitter.output_doc "This is a test comment with\na new line."
code = emitter._code.join "\n"
expect(code).toBe("""
\"\"\"
This is a test comment with
a new line.
\"\"\"
""")
return
return
describe "emit_preface", () ->
it "Should emit a preface", () ->
emitter.emit_preface ["./my_test_file.avdl"], {namespace: "chat1"}
code = emitter._code.join "\n"
expect(code).toBe("""
\"\"\"chat1
Auto-generated to Python types by #{pkg.name} v#{pkg.version} (#{pkg.homepage})
Input files:
- my_test_file.avdl
\"\"\"\n
""")
return
return
describe "emit_imports", () ->
it "should output all imports used by the file", () ->
imports = [
{
path: "../gregor1"
type: "idl"
import_as: "gregor1"
},
{
path: "../keybase1"
type: "idl",
import_as: "keybase1"
},
{
path: "common.avdl"
type: "idl"
},
{
path: "chat_ui.avdl"
type: "idl"
},
{
path: "unfurl.avdl"
type: "idl"
},
{
path: "commands.avdl"
type: "idl"
}
]
emitter.emit_imports {imports}, "test/output/dir/name/__init__.py"
code = emitter._code.join "\n"
expect(code).toBe("""
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union
from typing_extensions import Literal
from dataclasses_json import config, DataClassJsonMixin
import test.output.dir.gregor1 as gregor1
import test.output.dir.keybase1 as keybase1\n
""")
return
return
describe "emit_typedef", () ->
it "Should emit a string typedef", () ->
type = {
type: "record"
name: "BuildPaymentID"
fields: []
typedef: "string"
}
emitter.emit_typedef type
code = emitter._code.join "\n"
expect(code).toBe("""
BuildPaymentID = str
""")
return
return
describe "emit_record", () ->
it "should emit an object with primative value keys", () ->
record = {
type: "record"
name: "PI:NAME:<NAME>END_PI"
fields: [
{
type: "string",
name: "statusDescription"
},
{
type: "boolean"
name: "isValidThing"
},
{
type: "long",
name: "longInt"
},
{
type: "double",
name: "doubleOrNothin"
},
{
type: "bytes",
name: "takeAByteOfThisApple"
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class TestRecord(DataClassJsonMixin):
status_description: str = field(metadata=config(field_name='statusDescription'))
is_valid_thing: bool = field(metadata=config(field_name='isValidThing'))
long_int: int = field(metadata=config(field_name='longInt'))
double_or_nothin: float = field(metadata=config(field_name='doubleOrNothin'))
take_a_byte_of_this_apple: str = field(metadata=config(field_name='takeAByteOfThisApple'))\n
""")
return
it "Should support custom types as fields", () ->
record = {
type: "record"
name: "PI:NAME:<NAME>END_PI"
fields: [
{
type: "MySuperCoolCustomType",
name: "PI:NAME:<NAME>END_PICool"
},
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class TestRecord(DataClassJsonMixin):
super_cool: MySuperCoolCustomType = field(metadata=config(field_name='superCool'))\n
""")
return
it "should support optional types, and have non-optionals be declared first", () ->
record = {
"type": "record",
"name": "PI:NAME:<NAME>END_PISender",
"fields": [
{
"type": "string",
"name": "uid",
"jsonkey": "uid"
},
{
"type": "string",
"name": "username",
"jsonkey": "username",
"optional": true
},
{
"type": "string",
"name": "deviceID",
"jsonkey": "device_id"
},
{
"type": "string",
"name": "deviceName",
"jsonkey": "device_name",
"optional": true
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class MsgSender(DataClassJsonMixin):
uid: str = field(metadata=config(field_name='uid'))
device_id: str = field(metadata=config(field_name='device_id'))
username: Optional[str] = field(default=None, metadata=config(field_name='username'))
device_name: Optional[str] = field(default=None, metadata=config(field_name='device_name'))\n
""")
return
it "Should support optional arrays", () ->
record = {
type: "record",
name: "Thread",
fields: [
{
type: {
type: "array",
items: "Message"
},
name: "messages",
jsonkey: "messages"
},
{
type: [
null,
"Pagination"
],
name: "pagination",
jsonkey: "pagination"
},
{
type: "boolean",
name: "offline",
jsonkey: "offline",
optional: true
},
{
type: {
"type": "array",
"items": "keybase1.TLFIdentifyFailure"
},
name: "identifyFailures",
jsonkey: "identify_failures",
optional: true
},
{
type: {
"type": "array",
"items": "RateLimitRes"
},
name: "rateLimits",
jsonkey: "PI:KEY:<KEY>END_PIlimits",
optional: true
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class Thread(DataClassJsonMixin):
messages: Optional[List[Message]] = field(default=None, metadata=config(field_name='messages'))
pagination: Optional[Pagination] = field(default=None, metadata=config(field_name='pagination'))
offline: Optional[bool] = field(default=None, metadata=config(field_name='offline'))
identify_failures: Optional[List[keybase1.TLFIdentifyFailure]] = field(default=None, metadata=config(field_name='identify_failures'))
rate_limits: Optional[List[RateLimitRes]] = field(default=None, metadata=config(field_name='ratelimits'))\n
""")
return
it "Should emit a struct with a map type", () ->
record = {
type: "record"
name: "StellarServerDefinitions"
fields: [
{
type: "int",
name: "revision"
},
{
type: {
type: "map"
values: "OutsideCurrencyDefinition"
keys: "OutsideCurrencyCode"
}
name: "currencies"
}
]
}
emitter.emit_record record
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class StellarServerDefinitions(DataClassJsonMixin):
revision: int = field(metadata=config(field_name='revision'))
currencies: Dict[str, OutsideCurrencyDefinition] = field(metadata=config(field_name='currencies'))\n
""")
return
return
describe "emit_fixed", () ->
it "should emit a string", () ->
emitter.emit_fixed { name: "FunHash", size: 32 }
code = emitter._code.join "\n"
expect(code).toBe("""
FunHash = Optional[str]
""")
return
return
describe "emit_enum", () ->
it "should emit both an int and string enum", () ->
test_enum = {
type: "enum",
name: "AuditVersion",
symbols: [
"V0_0",
"V1_1",
"V2_2",
"V3_3"
]
"doc": "This is a docstring\nhi"
}
emitter.emit_enum test_enum
code = emitter._code.join "\n"
expect(code).toBe("""
class AuditVersion(Enum):
\"\"\"
This is a docstring
hi
\"\"\"
V0 = 0
V1 = 1
V2 = 2
V3 = 3
class AuditVersionStrings(Enum):
V0 = 'v0'
V1 = 'v1'
V2 = 'v2'
V3 = 'v3'\n\n
""")
return
return
describe "emit_variant", () ->
it "should emit a variant", () ->
variant =
type: "variant",
name: "PI:NAME:<NAME>END_PIVariant",
switch: {
type: "InboxResType",
name: "rtype"
},
cases: [
{
label: {
name: "VERSIONHIT",
def: false
},
body: null
},
{
label: {
name: "FULL",
def: false
},
body: "InboxViewFull"
},
{
label: {
name: "PI:NAME:<NAME>END_PILO",
def: false
},
body: "bool"
},
{
label: {
name: "PI:NAME:<NAME>END_PIAH",
def: true
},
body: "int"
},
{
label: {
name: "DECK",
def: false
},
body: {
type: "array",
items: "int"
}
}
]
emitter.emit_variant variant
code = emitter._code.join "\n"
expect(code).toBe("""
@dataclass
class MyVariant__VERSIONHIT(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.VERSIONHIT]
VERSIONHIT: None
@dataclass
class MyVariant__FULL(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.FULL]
FULL: Optional[InboxViewFull]
@dataclass
class MyVariant__HELLO(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.HELLO]
HELLO: Optional[bool]
@dataclass
class MyVariant__DECK(DataClassJsonMixin):
rtype: Literal[InboxResTypeStrings.DECK]
DECK: Optional[List[int]]
MyVariant = Union[MyVariant__VERSIONHIT, MyVariant__FULL, MyVariant__HELLO, MyVariant__DECK]\n
""")
return
return
return
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999109506607056,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/_components/tracklist.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div, table, thead, tbody, tr, th } from 'react-dom-factories'
import { TracklistTrack } from 'tracklist-track'
el = React.createElement
export class Tracklist extends React.Component
render: ->
return null unless @props.tracks.length > 0
tracks = @props.tracks.map (track) =>
el TracklistTrack,
key: track.id,
track: track,
div className: 'tracklist',
table className: 'tracklist__table',
thead {},
tr className: 'tracklist__row--header',
th className: 'tracklist__col tracklist__col--preview', ''
th className: 'tracklist__col tracklist__col--title', osu.trans('artist.tracklist.title')
th className: 'tracklist__col tracklist__col--length', osu.trans('artist.tracklist.length')
th className: 'tracklist__col tracklist__col--bpm', osu.trans('artist.tracklist.bpm')
th className: 'tracklist__col tracklist__col--genre', osu.trans('artist.tracklist.genre')
th className: 'tracklist__col tracklist__col--dl',
tbody {}, tracks
| 192414 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div, table, thead, tbody, tr, th } from 'react-dom-factories'
import { TracklistTrack } from 'tracklist-track'
el = React.createElement
export class Tracklist extends React.Component
render: ->
return null unless @props.tracks.length > 0
tracks = @props.tracks.map (track) =>
el TracklistTrack,
key: track.id,
track: track,
div className: 'tracklist',
table className: 'tracklist__table',
thead {},
tr className: 'tracklist__row--header',
th className: 'tracklist__col tracklist__col--preview', ''
th className: 'tracklist__col tracklist__col--title', osu.trans('artist.tracklist.title')
th className: 'tracklist__col tracklist__col--length', osu.trans('artist.tracklist.length')
th className: 'tracklist__col tracklist__col--bpm', osu.trans('artist.tracklist.bpm')
th className: 'tracklist__col tracklist__col--genre', osu.trans('artist.tracklist.genre')
th className: 'tracklist__col tracklist__col--dl',
tbody {}, tracks
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import * as React from 'react'
import { div, table, thead, tbody, tr, th } from 'react-dom-factories'
import { TracklistTrack } from 'tracklist-track'
el = React.createElement
export class Tracklist extends React.Component
render: ->
return null unless @props.tracks.length > 0
tracks = @props.tracks.map (track) =>
el TracklistTrack,
key: track.id,
track: track,
div className: 'tracklist',
table className: 'tracklist__table',
thead {},
tr className: 'tracklist__row--header',
th className: 'tracklist__col tracklist__col--preview', ''
th className: 'tracklist__col tracklist__col--title', osu.trans('artist.tracklist.title')
th className: 'tracklist__col tracklist__col--length', osu.trans('artist.tracklist.length')
th className: 'tracklist__col tracklist__col--bpm', osu.trans('artist.tracklist.bpm')
th className: 'tracklist__col tracklist__col--genre', osu.trans('artist.tracklist.genre')
th className: 'tracklist__col tracklist__col--dl',
tbody {}, tracks
|
[
{
"context": "lit('-')\n stamp = parts.pop()\n key = parts.join('-')\n files[key] ?= []\n files[key].push ",
"end": 5855,
"score": 0.9740497469902039,
"start": 5840,
"tag": "KEY",
"value": "parts.join('-')"
}
] | lib/atom-io-client.coffee | luna/atom-settings-view | 0 | fs = require 'fs-plus'
path = require 'path'
{remote} = require 'electron'
glob = require 'glob'
request = require 'request'
module.exports =
class AtomIoClient
constructor: (@packageManager, @baseURL) ->
@baseURL ?= 'https://atom.io/api/'
# 12 hour expiry
@expiry = 1000 * 60 * 60 * 12
@createAvatarCache()
@expireAvatarCache()
# Public: Get an avatar image from the filesystem, fetching it first if necessary
avatar: (login, callback) ->
@cachedAvatar login, (err, cached) =>
stale = Date.now() - parseInt(cached.split('-').pop()) > @expiry if cached
if cached and (not stale or not @online())
callback null, cached
else
@fetchAndCacheAvatar(login, callback)
# Public: get a package from the atom.io API, with the appropriate level of
# caching.
package: (name, callback) ->
packagePath = "packages/#{name}"
@fetchFromCache packagePath, {}, (err, data) =>
if data
callback(null, data)
else
@request(packagePath, callback)
featuredPackages: (callback) ->
# TODO clean up caching copypasta
@fetchFromCache 'packages/featured', {}, (err, data) =>
if data
callback(null, data)
else
@getFeatured(false, callback)
featuredThemes: (callback) ->
# TODO clean up caching copypasta
@fetchFromCache 'themes/featured', {}, (err, data) =>
if data
callback(null, data)
else
@getFeatured(true, callback)
getFeatured: (loadThemes, callback) ->
# apm already does this, might as well use it instead of request i guess? The
# downside is that I need to repeat caching logic here.
@packageManager.getFeatured(loadThemes)
.then (packages) =>
# copypasta from below
key = if loadThemes then 'themes/featured' else 'packages/featured'
cached =
data: packages
createdOn: Date.now()
localStorage.setItem(@cacheKeyForPath(key), JSON.stringify(cached))
# end copypasta
callback(null, packages)
.catch (error) ->
callback(error, null)
request: (path, callback) ->
options = {
url: "#{@baseURL}#{path}"
headers: {'User-Agent': navigator.userAgent}
}
request options, (err, res, body) =>
try
data = JSON.parse(body)
catch error
return callback(error)
delete data.versions
cached =
data: data
createdOn: Date.now()
localStorage.setItem(@cacheKeyForPath(path), JSON.stringify(cached))
callback(err, cached.data)
cacheKeyForPath: (path) ->
"settings-view:#{path}"
online: ->
navigator.onLine
# This could use a better name, since it checks whether it's appropriate to return
# the cached data and pretends it's null if it's stale and we're online
fetchFromCache: (packagePath, options, callback) ->
unless callback
callback = options
options = {}
unless options.force
# Set `force` to true if we can't reach the network.
options.force = not @online()
cached = localStorage.getItem(@cacheKeyForPath(packagePath))
cached = if cached then JSON.parse(cached)
if cached? and (not @online() or options.force or (Date.now() - cached.createdOn < @expiry))
cached ?= data: {}
callback(null, cached.data)
else if not cached? and not @online()
# The user hasn't requested this resource before and there's no way for us
# to get it to them so just hand back an empty object so callers don't crash
callback(null, {})
else
# falsy data means "try to hit the network"
callback(null, null)
createAvatarCache: ->
fs.makeTree(@getCachePath())
avatarPath: (login) ->
path.join @getCachePath(), "#{login}-#{Date.now()}"
cachedAvatar: (login, callback) ->
glob @avatarGlob(login), (err, files) =>
return callback(err) if err
files.sort().reverse()
for imagePath in files
filename = path.basename(imagePath)
[..., createdOn] = filename.split('-')
if Date.now() - parseInt(createdOn) < @expiry
return callback(null, imagePath)
callback(null, null)
avatarGlob: (login) ->
path.join @getCachePath(), "#{login}-*([0-9])"
fetchAndCacheAvatar: (login, callback) ->
if not @online()
callback(null, null)
else
imagePath = @avatarPath login
requestObject = {
url: "https://avatars.githubusercontent.com/#{login}"
headers: {'User-Agent': navigator.userAgent}
}
request.head requestObject, (error, response, body) ->
if error? or response.statusCode isnt 200 or not response.headers['content-type'].startsWith('image/')
callback(error)
else
writeStream = fs.createWriteStream imagePath
writeStream.on 'finish', -> callback(null, imagePath)
writeStream.on 'error', (error) ->
writeStream.close()
try
fs.unlinkSync imagePath if fs.existsSync imagePath
callback(error)
request(requestObject).pipe(writeStream)
# The cache expiry doesn't need to be clever, or even compare dates, it just
# needs to always keep around the newest item, and that item only. The localStorage
# cache updates in place, so it doesn't need to be purged.
expireAvatarCache: ->
deleteAvatar = (child) =>
avatarPath = path.join(@getCachePath(), child)
fs.unlink avatarPath, (error) ->
if error and error.code isnt 'ENOENT' # Ignore cache paths that don't exist
console.warn("Error deleting avatar (#{error.code}): #{avatarPath}")
fs.readdir @getCachePath(), (error, _files) ->
_files ?= []
files = {}
for filename in _files
parts = filename.split('-')
stamp = parts.pop()
key = parts.join('-')
files[key] ?= []
files[key].push "#{key}-#{stamp}"
for key, children of files
children.sort()
children.pop() # keep
# Right now a bunch of clients might be instantiated at once, so
# we can just ignore attempts to unlink files that have already been removed
# - this should be fixed with a singleton client
children.forEach(deleteAvatar)
getCachePath: ->
@cachePath ?= path.join(remote.app.getPath('userData'), 'Cache', 'settings-view')
| 224536 | fs = require 'fs-plus'
path = require 'path'
{remote} = require 'electron'
glob = require 'glob'
request = require 'request'
module.exports =
class AtomIoClient
constructor: (@packageManager, @baseURL) ->
@baseURL ?= 'https://atom.io/api/'
# 12 hour expiry
@expiry = 1000 * 60 * 60 * 12
@createAvatarCache()
@expireAvatarCache()
# Public: Get an avatar image from the filesystem, fetching it first if necessary
avatar: (login, callback) ->
@cachedAvatar login, (err, cached) =>
stale = Date.now() - parseInt(cached.split('-').pop()) > @expiry if cached
if cached and (not stale or not @online())
callback null, cached
else
@fetchAndCacheAvatar(login, callback)
# Public: get a package from the atom.io API, with the appropriate level of
# caching.
package: (name, callback) ->
packagePath = "packages/#{name}"
@fetchFromCache packagePath, {}, (err, data) =>
if data
callback(null, data)
else
@request(packagePath, callback)
featuredPackages: (callback) ->
# TODO clean up caching copypasta
@fetchFromCache 'packages/featured', {}, (err, data) =>
if data
callback(null, data)
else
@getFeatured(false, callback)
featuredThemes: (callback) ->
# TODO clean up caching copypasta
@fetchFromCache 'themes/featured', {}, (err, data) =>
if data
callback(null, data)
else
@getFeatured(true, callback)
getFeatured: (loadThemes, callback) ->
# apm already does this, might as well use it instead of request i guess? The
# downside is that I need to repeat caching logic here.
@packageManager.getFeatured(loadThemes)
.then (packages) =>
# copypasta from below
key = if loadThemes then 'themes/featured' else 'packages/featured'
cached =
data: packages
createdOn: Date.now()
localStorage.setItem(@cacheKeyForPath(key), JSON.stringify(cached))
# end copypasta
callback(null, packages)
.catch (error) ->
callback(error, null)
request: (path, callback) ->
options = {
url: "#{@baseURL}#{path}"
headers: {'User-Agent': navigator.userAgent}
}
request options, (err, res, body) =>
try
data = JSON.parse(body)
catch error
return callback(error)
delete data.versions
cached =
data: data
createdOn: Date.now()
localStorage.setItem(@cacheKeyForPath(path), JSON.stringify(cached))
callback(err, cached.data)
cacheKeyForPath: (path) ->
"settings-view:#{path}"
online: ->
navigator.onLine
# This could use a better name, since it checks whether it's appropriate to return
# the cached data and pretends it's null if it's stale and we're online
fetchFromCache: (packagePath, options, callback) ->
unless callback
callback = options
options = {}
unless options.force
# Set `force` to true if we can't reach the network.
options.force = not @online()
cached = localStorage.getItem(@cacheKeyForPath(packagePath))
cached = if cached then JSON.parse(cached)
if cached? and (not @online() or options.force or (Date.now() - cached.createdOn < @expiry))
cached ?= data: {}
callback(null, cached.data)
else if not cached? and not @online()
# The user hasn't requested this resource before and there's no way for us
# to get it to them so just hand back an empty object so callers don't crash
callback(null, {})
else
# falsy data means "try to hit the network"
callback(null, null)
createAvatarCache: ->
fs.makeTree(@getCachePath())
avatarPath: (login) ->
path.join @getCachePath(), "#{login}-#{Date.now()}"
cachedAvatar: (login, callback) ->
glob @avatarGlob(login), (err, files) =>
return callback(err) if err
files.sort().reverse()
for imagePath in files
filename = path.basename(imagePath)
[..., createdOn] = filename.split('-')
if Date.now() - parseInt(createdOn) < @expiry
return callback(null, imagePath)
callback(null, null)
avatarGlob: (login) ->
path.join @getCachePath(), "#{login}-*([0-9])"
fetchAndCacheAvatar: (login, callback) ->
if not @online()
callback(null, null)
else
imagePath = @avatarPath login
requestObject = {
url: "https://avatars.githubusercontent.com/#{login}"
headers: {'User-Agent': navigator.userAgent}
}
request.head requestObject, (error, response, body) ->
if error? or response.statusCode isnt 200 or not response.headers['content-type'].startsWith('image/')
callback(error)
else
writeStream = fs.createWriteStream imagePath
writeStream.on 'finish', -> callback(null, imagePath)
writeStream.on 'error', (error) ->
writeStream.close()
try
fs.unlinkSync imagePath if fs.existsSync imagePath
callback(error)
request(requestObject).pipe(writeStream)
# The cache expiry doesn't need to be clever, or even compare dates, it just
# needs to always keep around the newest item, and that item only. The localStorage
# cache updates in place, so it doesn't need to be purged.
expireAvatarCache: ->
deleteAvatar = (child) =>
avatarPath = path.join(@getCachePath(), child)
fs.unlink avatarPath, (error) ->
if error and error.code isnt 'ENOENT' # Ignore cache paths that don't exist
console.warn("Error deleting avatar (#{error.code}): #{avatarPath}")
fs.readdir @getCachePath(), (error, _files) ->
_files ?= []
files = {}
for filename in _files
parts = filename.split('-')
stamp = parts.pop()
key = <KEY>
files[key] ?= []
files[key].push "#{key}-#{stamp}"
for key, children of files
children.sort()
children.pop() # keep
# Right now a bunch of clients might be instantiated at once, so
# we can just ignore attempts to unlink files that have already been removed
# - this should be fixed with a singleton client
children.forEach(deleteAvatar)
getCachePath: ->
@cachePath ?= path.join(remote.app.getPath('userData'), 'Cache', 'settings-view')
| true | fs = require 'fs-plus'
path = require 'path'
{remote} = require 'electron'
glob = require 'glob'
request = require 'request'
module.exports =
class AtomIoClient
constructor: (@packageManager, @baseURL) ->
@baseURL ?= 'https://atom.io/api/'
# 12 hour expiry
@expiry = 1000 * 60 * 60 * 12
@createAvatarCache()
@expireAvatarCache()
# Public: Get an avatar image from the filesystem, fetching it first if necessary
avatar: (login, callback) ->
@cachedAvatar login, (err, cached) =>
stale = Date.now() - parseInt(cached.split('-').pop()) > @expiry if cached
if cached and (not stale or not @online())
callback null, cached
else
@fetchAndCacheAvatar(login, callback)
# Public: get a package from the atom.io API, with the appropriate level of
# caching.
package: (name, callback) ->
packagePath = "packages/#{name}"
@fetchFromCache packagePath, {}, (err, data) =>
if data
callback(null, data)
else
@request(packagePath, callback)
featuredPackages: (callback) ->
# TODO clean up caching copypasta
@fetchFromCache 'packages/featured', {}, (err, data) =>
if data
callback(null, data)
else
@getFeatured(false, callback)
featuredThemes: (callback) ->
# TODO clean up caching copypasta
@fetchFromCache 'themes/featured', {}, (err, data) =>
if data
callback(null, data)
else
@getFeatured(true, callback)
getFeatured: (loadThemes, callback) ->
# apm already does this, might as well use it instead of request i guess? The
# downside is that I need to repeat caching logic here.
@packageManager.getFeatured(loadThemes)
.then (packages) =>
# copypasta from below
key = if loadThemes then 'themes/featured' else 'packages/featured'
cached =
data: packages
createdOn: Date.now()
localStorage.setItem(@cacheKeyForPath(key), JSON.stringify(cached))
# end copypasta
callback(null, packages)
.catch (error) ->
callback(error, null)
request: (path, callback) ->
options = {
url: "#{@baseURL}#{path}"
headers: {'User-Agent': navigator.userAgent}
}
request options, (err, res, body) =>
try
data = JSON.parse(body)
catch error
return callback(error)
delete data.versions
cached =
data: data
createdOn: Date.now()
localStorage.setItem(@cacheKeyForPath(path), JSON.stringify(cached))
callback(err, cached.data)
cacheKeyForPath: (path) ->
"settings-view:#{path}"
online: ->
navigator.onLine
# This could use a better name, since it checks whether it's appropriate to return
# the cached data and pretends it's null if it's stale and we're online
fetchFromCache: (packagePath, options, callback) ->
unless callback
callback = options
options = {}
unless options.force
# Set `force` to true if we can't reach the network.
options.force = not @online()
cached = localStorage.getItem(@cacheKeyForPath(packagePath))
cached = if cached then JSON.parse(cached)
if cached? and (not @online() or options.force or (Date.now() - cached.createdOn < @expiry))
cached ?= data: {}
callback(null, cached.data)
else if not cached? and not @online()
# The user hasn't requested this resource before and there's no way for us
# to get it to them so just hand back an empty object so callers don't crash
callback(null, {})
else
# falsy data means "try to hit the network"
callback(null, null)
createAvatarCache: ->
fs.makeTree(@getCachePath())
avatarPath: (login) ->
path.join @getCachePath(), "#{login}-#{Date.now()}"
cachedAvatar: (login, callback) ->
glob @avatarGlob(login), (err, files) =>
return callback(err) if err
files.sort().reverse()
for imagePath in files
filename = path.basename(imagePath)
[..., createdOn] = filename.split('-')
if Date.now() - parseInt(createdOn) < @expiry
return callback(null, imagePath)
callback(null, null)
avatarGlob: (login) ->
path.join @getCachePath(), "#{login}-*([0-9])"
fetchAndCacheAvatar: (login, callback) ->
if not @online()
callback(null, null)
else
imagePath = @avatarPath login
requestObject = {
url: "https://avatars.githubusercontent.com/#{login}"
headers: {'User-Agent': navigator.userAgent}
}
request.head requestObject, (error, response, body) ->
if error? or response.statusCode isnt 200 or not response.headers['content-type'].startsWith('image/')
callback(error)
else
writeStream = fs.createWriteStream imagePath
writeStream.on 'finish', -> callback(null, imagePath)
writeStream.on 'error', (error) ->
writeStream.close()
try
fs.unlinkSync imagePath if fs.existsSync imagePath
callback(error)
request(requestObject).pipe(writeStream)
# The cache expiry doesn't need to be clever, or even compare dates, it just
# needs to always keep around the newest item, and that item only. The localStorage
# cache updates in place, so it doesn't need to be purged.
expireAvatarCache: ->
deleteAvatar = (child) =>
avatarPath = path.join(@getCachePath(), child)
fs.unlink avatarPath, (error) ->
if error and error.code isnt 'ENOENT' # Ignore cache paths that don't exist
console.warn("Error deleting avatar (#{error.code}): #{avatarPath}")
fs.readdir @getCachePath(), (error, _files) ->
_files ?= []
files = {}
for filename in _files
parts = filename.split('-')
stamp = parts.pop()
key = PI:KEY:<KEY>END_PI
files[key] ?= []
files[key].push "#{key}-#{stamp}"
for key, children of files
children.sort()
children.pop() # keep
# Right now a bunch of clients might be instantiated at once, so
# we can just ignore attempts to unlink files that have already been removed
# - this should be fixed with a singleton client
children.forEach(deleteAvatar)
getCachePath: ->
@cachePath ?= path.join(remote.app.getPath('userData'), 'Cache', 'settings-view')
|
[
{
"context": "ation\": \"Inscrição de Administrador\"\n \"Name\": \"Nome\"\n \"Entername\": \"(Escrever Nome)\"\n \"Professi",
"end": 3633,
"score": 0.9709747433662415,
"start": 3629,
"tag": "NAME",
"value": "Nome"
},
{
"context": "nascimento\"\n \"Question\":\"Pergunta\"... | _attachments/i18n/pt_PT.coffee | chrisekelley/coconut-kiwi-demo | 0 | polyglot = new Polyglot()
polyglot.extend({
"Home": "Início"
"Sync": "Sinc"
"Scanner": "Scan"
"verifyAdmin": "Para começar, favor de verificar Identidade do Administrador: meter o polegar no digitalizador e fazer click no butão 'Scan'."
"scan": "Scan"
"cannotId": "O sistema não podia identificar a esta pessoa."
"scanAgain": "Fazer 'Scan' de novo."
"clickEnroll": "Clique 'Cadastrar' para registrar a sua impressão digital no servidor Simprints."
"enroll": "Cadastrar"
"idConfirmed":"Identidade Confirmado"
"registered": "Você está inscrito para utilizar este aparelho. "
"doYouwant": "Você quer:"
"registerIndividualButton": "Cadastrar um indivíduo"
"enterNewReport": "Fazer Relatório Novo"
"newReport": "Relatório Novo"
"ClickFormName": "Seleciona a forma desejada:"
"trichiasisSurgery": "Cirurgia triquíase"
"Trichiasis Surgery": "Cirurgia triquíase"
"postOperativeFollowup": "Visita de acompanhamento pos-cirurgia"
"postOperativeFollowupAbbrev": "Visita pos-cirurgia"
"Post-Operative Followup": "Visita de acompanhamento pos-cirurgia"
"DateTime": "Data / Hora"
"RefusedSurgery": "Cirurgia Recusada"
"ProvidedEpilationConsultation": "Forneceu consulta sobre depilação"
"Lefteye": "Olho esquerdo"
"TypeofOperationL": "Tipo de operação"
"TypeofOperationL::BTRP": "BTRP"
"TypeofOperationL::Trabut": "Trabut"
"SutureTypeL": "Tipo de Sutura"
"SutureTypeL::Silk": "Seda"
"SutureTypeL::Absorbable": "Absorvível"
"ClampusedL": "Tipo de braçadeira Usado"
"ComplicationsL": "Complicações"
"ExcessbleedingL": "Sangramento excessivo"
"MarginfragmantseveredL": "Fragmento da margem cortada"
"GlobePunctureL": "Punção de globo ocular "
"ComplicationsReferralL": "Complicações referidas ao Hospital"
"ReferralHospitalL": "Nome do hospital"
"Righteye": "Olho direito"
"TypeofOperationR": "Tipo de operação"
"TypeofOperationR::BTRP": "BTRP"
"TypeofOperationR::Trabut": "Trabut"
"SutureTypeR": "Tipo de Sutura"
"SutureTypeR::Silk": "Seda"
"SutureTypeR::Absorbable": "Absorvível"
"ClampusedR": "Tipo de braçadeira Usado"
"ComplicationsR": "Complicações"
"ExcessbleedingR": "Sangramento excessivo"
"MarginfragmantseveredR": "Fragmento da margem cortada"
"GlobePunctureR": "Punção de globo ocular "
"ComplicationsReferralR": "Complicações referidas ao Hospital"
"ReferralHospitalR": "Nome do hospital"
"PostSurgicalTreatments": "Tratamento pos-cirurgia"
"azithromycinR": "Azitromicina"
"tetracyclineEyeOintmentR": "Pomada ocular de Tetraciclina"
"Submit": "Enviar"
"Post-OperativeFollowup": "Visita de acompanhamento pos-cirurgia"
"Nameofprocedurebeingfollowed": "Tipo de procedimento acompanhado"
"Nameofprocedurebeingfollowed::Hydrocele":"Hydrocele"
"Nameofprocedurebeingfollowed::Trichiasis":"Trichiasis"
"SelectOne": "Escolhe Um(a)"
"Hydrocele": "hidrocele"
"TrichiasisSurgery": "Cirurgia triquíase"
"Followupdate": "Data de Visita de Acompanhamento"
"Followupdate::1 week": "1 semana"
"Followupdate::2 weeks": "2 semanas"
"Followupdate::1 month": "1 mês"
"Followupdate::6 months": "6 mêses"
"Followupdate::1 year": "1 ano"
"Recurrence": "Retorno"
"Complicationsrefertoclinichospital": "Complicações - manda para clínica / hospital"
"Continuemonitoring": "Continuar acompanhamento"
"Complete": "Completo"
"Submit": "Enviar"
"AdminRegistration": "Inscrição de Administrador"
"Admin Registration": "Inscrição de Administrador"
"Name": "Nome"
"Entername": "(Escrever Nome)"
"Profession": "Ocupação"
"Association": "Associação"
"District": "Distrito"
"Individualregistration": "Inscrição Individual"
"Individual Registration": "Inscrição Individual"
"Gender": "Sexo"
"Gender::Male": "Homem"
"Gender::Female": "Mulher"
"Male": "Homem"
"Female": "Mulher"
"DOB": "Data de nascimento"
"clientInstructions":"Leia ao cliente: "
"clientText":"Nós queremos que o Sr / a Sra entenda que a sua impressão digital vai servir só para confirmar a sua identidade. Junto com a sua impressão digital, apenas escrevemos aqui que o Sr / a Sra é homem ou mulher, e a sua idade. Aparte disto, não vou pôr aqui qualquer outra informacão sobre a sua identidade."
"consentQuestion":"O Sr / a Sra permite que fazermos um scan da sua impressão digital?"
"consentProceed":"Se o cliente aceitou, favor de continuar."
"scanInstructions":"Para identicar ou cadastrar uma pessoa, colocar o polegar no aparelho e clique 'Scan'."
"sendData":"Enviar dados"
"replicationLog":"Arquivo de replicações"
"replicationLogDescription":"O arquivo de replicações contém os resultados de comunicações com o servidor principal."
"refreshLog":"Recargar Arquivo"
"PatientRecordListing":"Arquivo de pacientes"
"Male":"Homem"
"Female":"Mulher"
"dateOfBirth":"Data de nascimento"
"Question":"Pergunta"
"User":"Utilizador"
"dateModified":"Data Modificada"
"scanFailed":"Erro no Scan: Não foi possível ler a impressão digital. Favor de fechar o pacote no 'Task Manager' e renicie novamente."
"server":"Servidor"
"Instructions":"Instruções"
"RegistrationComplete":"Inscrição completo"
"NoClientLoaded":"Nenhum cliente é identificado"
"Error":"Erro"
"Enter":"Escrever"
"email": "Email"
"deviceError": "Erro: ou um digitalizador não está ligada ou o digitalizador conectado não é suportado. Favor de fechar o pacote no 'Task Manager', conecte o digitalizador, e renicie novamente."
"version": "Versão"
"updateForms": "Atualize as formas"
"sendLogs": "Enviar Logs"
"Login": "Login"
"PatientEncounters": "Patient Encounters"
"SetLanguage": "Set Language"
"LangChoice": "Language set to: "
"Settings": "Settings"
})
Handlebars.registerHelper 'polyglot', (phrase)->
polyglot.t(phrase)
| 58891 | polyglot = new Polyglot()
polyglot.extend({
"Home": "Início"
"Sync": "Sinc"
"Scanner": "Scan"
"verifyAdmin": "Para começar, favor de verificar Identidade do Administrador: meter o polegar no digitalizador e fazer click no butão 'Scan'."
"scan": "Scan"
"cannotId": "O sistema não podia identificar a esta pessoa."
"scanAgain": "Fazer 'Scan' de novo."
"clickEnroll": "Clique 'Cadastrar' para registrar a sua impressão digital no servidor Simprints."
"enroll": "Cadastrar"
"idConfirmed":"Identidade Confirmado"
"registered": "Você está inscrito para utilizar este aparelho. "
"doYouwant": "Você quer:"
"registerIndividualButton": "Cadastrar um indivíduo"
"enterNewReport": "Fazer Relatório Novo"
"newReport": "Relatório Novo"
"ClickFormName": "Seleciona a forma desejada:"
"trichiasisSurgery": "Cirurgia triquíase"
"Trichiasis Surgery": "Cirurgia triquíase"
"postOperativeFollowup": "Visita de acompanhamento pos-cirurgia"
"postOperativeFollowupAbbrev": "Visita pos-cirurgia"
"Post-Operative Followup": "Visita de acompanhamento pos-cirurgia"
"DateTime": "Data / Hora"
"RefusedSurgery": "Cirurgia Recusada"
"ProvidedEpilationConsultation": "Forneceu consulta sobre depilação"
"Lefteye": "Olho esquerdo"
"TypeofOperationL": "Tipo de operação"
"TypeofOperationL::BTRP": "BTRP"
"TypeofOperationL::Trabut": "Trabut"
"SutureTypeL": "Tipo de Sutura"
"SutureTypeL::Silk": "Seda"
"SutureTypeL::Absorbable": "Absorvível"
"ClampusedL": "Tipo de braçadeira Usado"
"ComplicationsL": "Complicações"
"ExcessbleedingL": "Sangramento excessivo"
"MarginfragmantseveredL": "Fragmento da margem cortada"
"GlobePunctureL": "Punção de globo ocular "
"ComplicationsReferralL": "Complicações referidas ao Hospital"
"ReferralHospitalL": "Nome do hospital"
"Righteye": "Olho direito"
"TypeofOperationR": "Tipo de operação"
"TypeofOperationR::BTRP": "BTRP"
"TypeofOperationR::Trabut": "Trabut"
"SutureTypeR": "Tipo de Sutura"
"SutureTypeR::Silk": "Seda"
"SutureTypeR::Absorbable": "Absorvível"
"ClampusedR": "Tipo de braçadeira Usado"
"ComplicationsR": "Complicações"
"ExcessbleedingR": "Sangramento excessivo"
"MarginfragmantseveredR": "Fragmento da margem cortada"
"GlobePunctureR": "Punção de globo ocular "
"ComplicationsReferralR": "Complicações referidas ao Hospital"
"ReferralHospitalR": "Nome do hospital"
"PostSurgicalTreatments": "Tratamento pos-cirurgia"
"azithromycinR": "Azitromicina"
"tetracyclineEyeOintmentR": "Pomada ocular de Tetraciclina"
"Submit": "Enviar"
"Post-OperativeFollowup": "Visita de acompanhamento pos-cirurgia"
"Nameofprocedurebeingfollowed": "Tipo de procedimento acompanhado"
"Nameofprocedurebeingfollowed::Hydrocele":"Hydrocele"
"Nameofprocedurebeingfollowed::Trichiasis":"Trichiasis"
"SelectOne": "Escolhe Um(a)"
"Hydrocele": "hidrocele"
"TrichiasisSurgery": "Cirurgia triquíase"
"Followupdate": "Data de Visita de Acompanhamento"
"Followupdate::1 week": "1 semana"
"Followupdate::2 weeks": "2 semanas"
"Followupdate::1 month": "1 mês"
"Followupdate::6 months": "6 mêses"
"Followupdate::1 year": "1 ano"
"Recurrence": "Retorno"
"Complicationsrefertoclinichospital": "Complicações - manda para clínica / hospital"
"Continuemonitoring": "Continuar acompanhamento"
"Complete": "Completo"
"Submit": "Enviar"
"AdminRegistration": "Inscrição de Administrador"
"Admin Registration": "Inscrição de Administrador"
"Name": "<NAME>"
"Entername": "(Escrever Nome)"
"Profession": "Ocupação"
"Association": "Associação"
"District": "Distrito"
"Individualregistration": "Inscrição Individual"
"Individual Registration": "Inscrição Individual"
"Gender": "Sexo"
"Gender::Male": "Homem"
"Gender::Female": "Mulher"
"Male": "Homem"
"Female": "Mulher"
"DOB": "Data de nascimento"
"clientInstructions":"Leia ao cliente: "
"clientText":"Nós queremos que o Sr / a Sra entenda que a sua impressão digital vai servir só para confirmar a sua identidade. Junto com a sua impressão digital, apenas escrevemos aqui que o Sr / a Sra é homem ou mulher, e a sua idade. Aparte disto, não vou pôr aqui qualquer outra informacão sobre a sua identidade."
"consentQuestion":"O Sr / a Sra permite que fazermos um scan da sua impressão digital?"
"consentProceed":"Se o cliente aceitou, favor de continuar."
"scanInstructions":"Para identicar ou cadastrar uma pessoa, colocar o polegar no aparelho e clique 'Scan'."
"sendData":"Enviar dados"
"replicationLog":"Arquivo de replicações"
"replicationLogDescription":"O arquivo de replicações contém os resultados de comunicações com o servidor principal."
"refreshLog":"Recargar Arquivo"
"PatientRecordListing":"Arquivo de pacientes"
"Male":"Homem"
"Female":"Mulher"
"dateOfBirth":"Data de nascimento"
"Question":"Pergunta"
"User":"Utilizador"
"dateModified":"Data Modificada"
"scanFailed":"Erro no Scan: Não foi possível ler a impressão digital. Favor de fechar o pacote no 'Task Manager' e renicie novamente."
"server":"Servidor"
"Instructions":"Instruções"
"RegistrationComplete":"Inscrição completo"
"NoClientLoaded":"Nenhum cliente é identificado"
"Error":"Erro"
"Enter":"Escrever"
"email": "Email"
"deviceError": "Erro: ou um digitalizador não está ligada ou o digitalizador conectado não é suportado. Favor de fechar o pacote no 'Task Manager', conecte o digitalizador, e renicie novamente."
"version": "Versão"
"updateForms": "Atualize as formas"
"sendLogs": "Enviar Logs"
"Login": "Login"
"PatientEncounters": "Patient Encounters"
"SetLanguage": "Set Language"
"LangChoice": "Language set to: "
"Settings": "Settings"
})
Handlebars.registerHelper 'polyglot', (phrase)->
polyglot.t(phrase)
| true | polyglot = new Polyglot()
polyglot.extend({
"Home": "Início"
"Sync": "Sinc"
"Scanner": "Scan"
"verifyAdmin": "Para começar, favor de verificar Identidade do Administrador: meter o polegar no digitalizador e fazer click no butão 'Scan'."
"scan": "Scan"
"cannotId": "O sistema não podia identificar a esta pessoa."
"scanAgain": "Fazer 'Scan' de novo."
"clickEnroll": "Clique 'Cadastrar' para registrar a sua impressão digital no servidor Simprints."
"enroll": "Cadastrar"
"idConfirmed":"Identidade Confirmado"
"registered": "Você está inscrito para utilizar este aparelho. "
"doYouwant": "Você quer:"
"registerIndividualButton": "Cadastrar um indivíduo"
"enterNewReport": "Fazer Relatório Novo"
"newReport": "Relatório Novo"
"ClickFormName": "Seleciona a forma desejada:"
"trichiasisSurgery": "Cirurgia triquíase"
"Trichiasis Surgery": "Cirurgia triquíase"
"postOperativeFollowup": "Visita de acompanhamento pos-cirurgia"
"postOperativeFollowupAbbrev": "Visita pos-cirurgia"
"Post-Operative Followup": "Visita de acompanhamento pos-cirurgia"
"DateTime": "Data / Hora"
"RefusedSurgery": "Cirurgia Recusada"
"ProvidedEpilationConsultation": "Forneceu consulta sobre depilação"
"Lefteye": "Olho esquerdo"
"TypeofOperationL": "Tipo de operação"
"TypeofOperationL::BTRP": "BTRP"
"TypeofOperationL::Trabut": "Trabut"
"SutureTypeL": "Tipo de Sutura"
"SutureTypeL::Silk": "Seda"
"SutureTypeL::Absorbable": "Absorvível"
"ClampusedL": "Tipo de braçadeira Usado"
"ComplicationsL": "Complicações"
"ExcessbleedingL": "Sangramento excessivo"
"MarginfragmantseveredL": "Fragmento da margem cortada"
"GlobePunctureL": "Punção de globo ocular "
"ComplicationsReferralL": "Complicações referidas ao Hospital"
"ReferralHospitalL": "Nome do hospital"
"Righteye": "Olho direito"
"TypeofOperationR": "Tipo de operação"
"TypeofOperationR::BTRP": "BTRP"
"TypeofOperationR::Trabut": "Trabut"
"SutureTypeR": "Tipo de Sutura"
"SutureTypeR::Silk": "Seda"
"SutureTypeR::Absorbable": "Absorvível"
"ClampusedR": "Tipo de braçadeira Usado"
"ComplicationsR": "Complicações"
"ExcessbleedingR": "Sangramento excessivo"
"MarginfragmantseveredR": "Fragmento da margem cortada"
"GlobePunctureR": "Punção de globo ocular "
"ComplicationsReferralR": "Complicações referidas ao Hospital"
"ReferralHospitalR": "Nome do hospital"
"PostSurgicalTreatments": "Tratamento pos-cirurgia"
"azithromycinR": "Azitromicina"
"tetracyclineEyeOintmentR": "Pomada ocular de Tetraciclina"
"Submit": "Enviar"
"Post-OperativeFollowup": "Visita de acompanhamento pos-cirurgia"
"Nameofprocedurebeingfollowed": "Tipo de procedimento acompanhado"
"Nameofprocedurebeingfollowed::Hydrocele":"Hydrocele"
"Nameofprocedurebeingfollowed::Trichiasis":"Trichiasis"
"SelectOne": "Escolhe Um(a)"
"Hydrocele": "hidrocele"
"TrichiasisSurgery": "Cirurgia triquíase"
"Followupdate": "Data de Visita de Acompanhamento"
"Followupdate::1 week": "1 semana"
"Followupdate::2 weeks": "2 semanas"
"Followupdate::1 month": "1 mês"
"Followupdate::6 months": "6 mêses"
"Followupdate::1 year": "1 ano"
"Recurrence": "Retorno"
"Complicationsrefertoclinichospital": "Complicações - manda para clínica / hospital"
"Continuemonitoring": "Continuar acompanhamento"
"Complete": "Completo"
"Submit": "Enviar"
"AdminRegistration": "Inscrição de Administrador"
"Admin Registration": "Inscrição de Administrador"
"Name": "PI:NAME:<NAME>END_PI"
"Entername": "(Escrever Nome)"
"Profession": "Ocupação"
"Association": "Associação"
"District": "Distrito"
"Individualregistration": "Inscrição Individual"
"Individual Registration": "Inscrição Individual"
"Gender": "Sexo"
"Gender::Male": "Homem"
"Gender::Female": "Mulher"
"Male": "Homem"
"Female": "Mulher"
"DOB": "Data de nascimento"
"clientInstructions":"Leia ao cliente: "
"clientText":"Nós queremos que o Sr / a Sra entenda que a sua impressão digital vai servir só para confirmar a sua identidade. Junto com a sua impressão digital, apenas escrevemos aqui que o Sr / a Sra é homem ou mulher, e a sua idade. Aparte disto, não vou pôr aqui qualquer outra informacão sobre a sua identidade."
"consentQuestion":"O Sr / a Sra permite que fazermos um scan da sua impressão digital?"
"consentProceed":"Se o cliente aceitou, favor de continuar."
"scanInstructions":"Para identicar ou cadastrar uma pessoa, colocar o polegar no aparelho e clique 'Scan'."
"sendData":"Enviar dados"
"replicationLog":"Arquivo de replicações"
"replicationLogDescription":"O arquivo de replicações contém os resultados de comunicações com o servidor principal."
"refreshLog":"Recargar Arquivo"
"PatientRecordListing":"Arquivo de pacientes"
"Male":"Homem"
"Female":"Mulher"
"dateOfBirth":"Data de nascimento"
"Question":"Pergunta"
"User":"Utilizador"
"dateModified":"Data Modificada"
"scanFailed":"Erro no Scan: Não foi possível ler a impressão digital. Favor de fechar o pacote no 'Task Manager' e renicie novamente."
"server":"Servidor"
"Instructions":"Instruções"
"RegistrationComplete":"Inscrição completo"
"NoClientLoaded":"Nenhum cliente é identificado"
"Error":"Erro"
"Enter":"Escrever"
"email": "Email"
"deviceError": "Erro: ou um digitalizador não está ligada ou o digitalizador conectado não é suportado. Favor de fechar o pacote no 'Task Manager', conecte o digitalizador, e renicie novamente."
"version": "Versão"
"updateForms": "Atualize as formas"
"sendLogs": "Enviar Logs"
"Login": "Login"
"PatientEncounters": "Patient Encounters"
"SetLanguage": "Set Language"
"LangChoice": "Language set to: "
"Settings": "Settings"
})
Handlebars.registerHelper 'polyglot', (phrase)->
polyglot.t(phrase)
|
[
{
"context": "af8-11e4-9001-b7f689b1ce71'\nJADES_IPHONE_TOKEN = '0po2feq55q4a38frifxyfwkkue42huxr'\n\nROYS_PHONE_UUID = 'ecbbe3d1-2970-11e4-b860-af35",
"end": 426,
"score": 0.982057511806488,
"start": 394,
"tag": "PASSWORD",
"value": "0po2feq55q4a38frifxyfwkkue42huxr"
},
{
"context":... | location-monitor/server.coffee | octoblu/lm-hackathon | 0 | Meshblu = require './src/meshblu'
Device = require './src/device'
{spawn} = require 'child_process'
_ = require 'lodash'
device_uuid = process.env.DEVICE_UUID
device_token = process.env.DEVICE_TOKEN
payload_only = process.env.PAYLOAD_ONLY
meshblu_uri = process.env.MESHBLU_URI || 'wss://meshblu.octoblu.com'
JADES_IPHONE_UUID = '2a901861-2af8-11e4-9001-b7f689b1ce71'
JADES_IPHONE_TOKEN = '0po2feq55q4a38frifxyfwkkue42huxr'
ROYS_PHONE_UUID = 'ecbbe3d1-2970-11e4-b860-af35e34d021f'
ROYS_PHONE_TOKEN = '0p0xi0dde59kep14ijbrjcwis7d86w29'
RALLYFIGHTER_UUID = 'c43462d1-1cea-11e4-861d-89322229e557/3c701ab0-2a69-11e4-ba29-b7d9779a4387'
GATEWAY_UUID = 'cfe8372a-7ec1-4517-a6c3-843490c21567'
KIT_GATEWAY_UUID = '9dc9031b-ce6e-40f7-a0d7-3e3aca24471d'
DEFAULT_GEO = {heading: 0, latitude: 0, longitude: 0}
UUIDS = {}
UUIDS[JADES_IPHONE_UUID] = 'jade'
UUIDS[ROYS_PHONE_UUID] = 'roy'
GEOS = {}
meshblu = new Meshblu device_uuid, device_token, meshblu_uri, =>
unlock = =>
sendMessage 'unlock'
sendMessage 'headlightson'
sendAlljoyn 'Unlocked the car'
sendLifx()
sendBlinkyTape()
lock = =>
sendMessage 'lock'
sendAlljoyn 'Locked the car'
turnOffLifex()
turnOffBlinkyTape()
sendMessage = (m) =>
msg =
devices : RALLYFIGHTER_UUID
payload:
m: m
console.log msg
meshblu.connection.message msg
sendAlljoyn = (m) =>
msg =
devices: GATEWAY_UUID,
subdevice: "alljoyn",
payload:
method:"notify",
message: m
console.log msg
meshblu.connection.message msg
turnOffBlinkyTape = =>
msg =
devices: KIT_GATEWAY_UUID,
subdevice: "blinky-tape",
payload: 's0'
console.log msg
meshblu.connection.message msg
sendBlinkyTape = =>
msg =
devices: KIT_GATEWAY_UUID,
subdevice: "blinky-tape",
payload: 'k9'
console.log msg
meshblu.connection.message msg
turnOffLifex = =>
msg =
devices: GATEWAY_UUID
subdevice: 'lifx'
payload:
setState:
on: false
console.log msg
meshblu.connection.message msg
sendLifx = (m) =>
setTimeout =>
msg =
devices: GATEWAY_UUID
subdevice: 'lifx'
payload:
setState:
on: true
console.log msg
meshblu.connection.message msg
, 1500
setTimeout =>
msg =
devices: GATEWAY_UUID
subdevice: 'lifx'
payload:
setState:
hue: 0x1111
sat: 0xffff
white: 5000
lum: 0x8000
console.log msg
meshblu.connection.message msg
, 2000
lock()
device = new Device meshblu
device.onMessage (message) =>
key = UUIDS[message.fromUuid] || 'unknown'
GEOS[key] ?= {}
geo = GEOS[key]
coords = message.payload?.sensorData?.data?.coords
magneticHeading = message.payload?.sensorData?.data?.magneticHeading
if coords?
geo.latitude = coords.latitude
geo.longitude = coords.longitude
if magneticHeading?
geo.heading = magneticHeading
if geo.heading > 10 and geo.heading < 60
unlock()
setTimeout(process.exit, 3000)
_.each GEOS, (values, name) =>
console.log name, JSON.stringify(values)
meshblu.connection.subscribe
uuid: JADES_IPHONE_UUID,
token: JADES_IPHONE_TOKEN
meshblu.connection.subscribe
uuid: ROYS_PHONE_UUID
token: ROYS_PHONE_TOKEN
| 68221 | Meshblu = require './src/meshblu'
Device = require './src/device'
{spawn} = require 'child_process'
_ = require 'lodash'
device_uuid = process.env.DEVICE_UUID
device_token = process.env.DEVICE_TOKEN
payload_only = process.env.PAYLOAD_ONLY
meshblu_uri = process.env.MESHBLU_URI || 'wss://meshblu.octoblu.com'
JADES_IPHONE_UUID = '2a901861-2af8-11e4-9001-b7f689b1ce71'
JADES_IPHONE_TOKEN = '<PASSWORD>'
ROYS_PHONE_UUID = 'ecbbe3d1-2970-11e4-b860-af35e34d021f'
ROYS_PHONE_TOKEN = '<PASSWORD>'
RALLYFIGHTER_UUID = 'c43462d1-1cea-11e4-861d-89322229e557/3c701ab0-2a69-11e4-ba29-b7d9779a4387'
GATEWAY_UUID = 'cfe8372a-7ec1-4517-a6c3-843490c21567'
KIT_GATEWAY_UUID = '9dc9031b-ce6e-40f7-a0d7-3e3aca24471d'
DEFAULT_GEO = {heading: 0, latitude: 0, longitude: 0}
UUIDS = {}
UUIDS[JADES_IPHONE_UUID] = 'jade'
UUIDS[ROYS_PHONE_UUID] = 'roy'
GEOS = {}
meshblu = new Meshblu device_uuid, device_token, meshblu_uri, =>
unlock = =>
sendMessage 'unlock'
sendMessage 'headlightson'
sendAlljoyn 'Unlocked the car'
sendLifx()
sendBlinkyTape()
lock = =>
sendMessage 'lock'
sendAlljoyn 'Locked the car'
turnOffLifex()
turnOffBlinkyTape()
sendMessage = (m) =>
msg =
devices : RALLYFIGHTER_UUID
payload:
m: m
console.log msg
meshblu.connection.message msg
sendAlljoyn = (m) =>
msg =
devices: GATEWAY_UUID,
subdevice: "alljoyn",
payload:
method:"notify",
message: m
console.log msg
meshblu.connection.message msg
turnOffBlinkyTape = =>
msg =
devices: KIT_GATEWAY_UUID,
subdevice: "blinky-tape",
payload: 's0'
console.log msg
meshblu.connection.message msg
sendBlinkyTape = =>
msg =
devices: KIT_GATEWAY_UUID,
subdevice: "blinky-tape",
payload: 'k9'
console.log msg
meshblu.connection.message msg
turnOffLifex = =>
msg =
devices: GATEWAY_UUID
subdevice: 'lifx'
payload:
setState:
on: false
console.log msg
meshblu.connection.message msg
sendLifx = (m) =>
setTimeout =>
msg =
devices: GATEWAY_UUID
subdevice: 'lifx'
payload:
setState:
on: true
console.log msg
meshblu.connection.message msg
, 1500
setTimeout =>
msg =
devices: GATEWAY_UUID
subdevice: 'lifx'
payload:
setState:
hue: 0x1111
sat: 0xffff
white: 5000
lum: 0x8000
console.log msg
meshblu.connection.message msg
, 2000
lock()
device = new Device meshblu
device.onMessage (message) =>
key = UUIDS[message.fromUuid] || 'unknown'
GEOS[key] ?= {}
geo = GEOS[key]
coords = message.payload?.sensorData?.data?.coords
magneticHeading = message.payload?.sensorData?.data?.magneticHeading
if coords?
geo.latitude = coords.latitude
geo.longitude = coords.longitude
if magneticHeading?
geo.heading = magneticHeading
if geo.heading > 10 and geo.heading < 60
unlock()
setTimeout(process.exit, 3000)
_.each GEOS, (values, name) =>
console.log name, JSON.stringify(values)
meshblu.connection.subscribe
uuid: JADES_IPHONE_UUID,
token: JADES_IPHONE_TOKEN
meshblu.connection.subscribe
uuid: ROYS_PHONE_UUID
token: ROYS_PHONE_TOKEN
| true | Meshblu = require './src/meshblu'
Device = require './src/device'
{spawn} = require 'child_process'
_ = require 'lodash'
device_uuid = process.env.DEVICE_UUID
device_token = process.env.DEVICE_TOKEN
payload_only = process.env.PAYLOAD_ONLY
meshblu_uri = process.env.MESHBLU_URI || 'wss://meshblu.octoblu.com'
JADES_IPHONE_UUID = '2a901861-2af8-11e4-9001-b7f689b1ce71'
JADES_IPHONE_TOKEN = 'PI:PASSWORD:<PASSWORD>END_PI'
ROYS_PHONE_UUID = 'ecbbe3d1-2970-11e4-b860-af35e34d021f'
ROYS_PHONE_TOKEN = 'PI:PASSWORD:<PASSWORD>END_PI'
RALLYFIGHTER_UUID = 'c43462d1-1cea-11e4-861d-89322229e557/3c701ab0-2a69-11e4-ba29-b7d9779a4387'
GATEWAY_UUID = 'cfe8372a-7ec1-4517-a6c3-843490c21567'
KIT_GATEWAY_UUID = '9dc9031b-ce6e-40f7-a0d7-3e3aca24471d'
DEFAULT_GEO = {heading: 0, latitude: 0, longitude: 0}
UUIDS = {}
UUIDS[JADES_IPHONE_UUID] = 'jade'
UUIDS[ROYS_PHONE_UUID] = 'roy'
GEOS = {}
meshblu = new Meshblu device_uuid, device_token, meshblu_uri, =>
unlock = =>
sendMessage 'unlock'
sendMessage 'headlightson'
sendAlljoyn 'Unlocked the car'
sendLifx()
sendBlinkyTape()
lock = =>
sendMessage 'lock'
sendAlljoyn 'Locked the car'
turnOffLifex()
turnOffBlinkyTape()
sendMessage = (m) =>
msg =
devices : RALLYFIGHTER_UUID
payload:
m: m
console.log msg
meshblu.connection.message msg
sendAlljoyn = (m) =>
msg =
devices: GATEWAY_UUID,
subdevice: "alljoyn",
payload:
method:"notify",
message: m
console.log msg
meshblu.connection.message msg
turnOffBlinkyTape = =>
msg =
devices: KIT_GATEWAY_UUID,
subdevice: "blinky-tape",
payload: 's0'
console.log msg
meshblu.connection.message msg
sendBlinkyTape = =>
msg =
devices: KIT_GATEWAY_UUID,
subdevice: "blinky-tape",
payload: 'k9'
console.log msg
meshblu.connection.message msg
turnOffLifex = =>
msg =
devices: GATEWAY_UUID
subdevice: 'lifx'
payload:
setState:
on: false
console.log msg
meshblu.connection.message msg
sendLifx = (m) =>
setTimeout =>
msg =
devices: GATEWAY_UUID
subdevice: 'lifx'
payload:
setState:
on: true
console.log msg
meshblu.connection.message msg
, 1500
setTimeout =>
msg =
devices: GATEWAY_UUID
subdevice: 'lifx'
payload:
setState:
hue: 0x1111
sat: 0xffff
white: 5000
lum: 0x8000
console.log msg
meshblu.connection.message msg
, 2000
lock()
device = new Device meshblu
device.onMessage (message) =>
key = UUIDS[message.fromUuid] || 'unknown'
GEOS[key] ?= {}
geo = GEOS[key]
coords = message.payload?.sensorData?.data?.coords
magneticHeading = message.payload?.sensorData?.data?.magneticHeading
if coords?
geo.latitude = coords.latitude
geo.longitude = coords.longitude
if magneticHeading?
geo.heading = magneticHeading
if geo.heading > 10 and geo.heading < 60
unlock()
setTimeout(process.exit, 3000)
_.each GEOS, (values, name) =>
console.log name, JSON.stringify(values)
meshblu.connection.subscribe
uuid: JADES_IPHONE_UUID,
token: JADES_IPHONE_TOKEN
meshblu.connection.subscribe
uuid: ROYS_PHONE_UUID
token: ROYS_PHONE_TOKEN
|
[
{
"context": "esome: \"No Opinion\",\n people: [\n { name: \"George Clooney\", like: true },\n { name: \"Bill Murray\", like",
"end": 1081,
"score": 0.9997357726097107,
"start": 1067,
"tag": "NAME",
"value": "George Clooney"
},
{
"context": "e: \"George Clooney\", like: ... | source/assets/js/app.coffee | headcanon/mandrill-angular | 6 | angular.module('mandrill',['ngResource'])
.factory('Mandrill', ($resource) ->
Mandrill = $resource(
'https://mandrillapp.com/api/1.0/:category/:call.json',
{},
{
sendMessage: {
method: "POST",
isArray: true,
params: {
category: "messages",
call: "send"
}
}
ping: {
method: "POST",
params: {
category: "users",
call:"ping"
}
}
}
)
)
angular.module('sender', ['mandrill'])
.config(($routeProvider) ->
$routeProvider.
when('/', {controller: SenderCtrl, templateUrl: 'partials/senderForm.html'}))
.config(($httpProvider) -> delete $httpProvider.defaults.headers.common["X-Requested-With"])
SenderCtrl = ($scope, Mandrill) ->
$scope.setup = {
apiKey: "", # Initialize this with your api key if you don't want to have to fill it in every time
toEmail: "" # same with your email
}
$scope.sender = {
name: "",
email: "",
phone: "",
awesome: "No Opinion",
people: [
{ name: "George Clooney", like: true },
{ name: "Bill Murray", like: true },
{ name: "Paris Hilton", like: false },
{ name: "Snooki", like: false },
{ name: "Ghandi", like: true }
],
randomtext: ""
}
@constructMessage = (sender) ->
peopleILike = ((people) ->
return "Nobody" if people.length is 0
return "#{person.name for person in people}"
)(person for person in sender.people when person.like is true)
"<h2>Hello.</h2>
<p>I just got sent from the Mandrill angular proof of concept
at <a href='http://www.github.com'>www.github.com</a>.</p>
<h3>Info:</h3>
<ul>
<li>Name: #{sender.name}</li>
<li>Email: #{sender.email}</li>
<li>Phone: #{sender.phone}</li>
</ul>
<h3>How awesome am I?</h3>
<p>#{sender.awesome}</p>
<h3>Who do I like?</h3>
<p>#{peopleILike}</p>
<h3>Anything Else?</h3>
<p>#{sender.randomtext}</p>"
$scope.checkSetup = () ->
Mandrill.ping(
{"key": $scope.setup.apiKey},
((data,status,headers,config)->
$scope.apiStatusClass = "alert alert-success"
$scope.apiStatusContent = "API key looks good. Go ahead and fill out the rest of the form."),
((data,status,headers,config)->
$scope.apiStatusClass = "alert alert-error"
$scope.apiStatusContent = "Doesn't seem to be valid.")
)
$scope.send = () =>
$scope.messageText = @constructMessage($scope.sender)
Mandrill.sendMessage(
{
key: $scope.setup.apiKey,
message: {
html: $scope.messageText,
subject: "sent from Angular Mandrill proof-of-concept",
from_email: $scope.sender.email,
to: [{email: $scope.setup.toEmail}]
}
},
((data,status,headers,config) ->
$scope.messageStatusClass = "alert alert-success"
$scope.messageStatusContent = "Congratulations! The message should appear soon at #{$scope.setup.toEmail}"
$scope.messageStatusJson = data
),
((data,status,headers,config) ->
$scope.messageStatusClass = "alert alert-error"
$scope.messageStatusContent = "Hmm. Doesn't look like it went through. Check your API key."
$scope.messageStatusJson = data
)
)
| 121386 | angular.module('mandrill',['ngResource'])
.factory('Mandrill', ($resource) ->
Mandrill = $resource(
'https://mandrillapp.com/api/1.0/:category/:call.json',
{},
{
sendMessage: {
method: "POST",
isArray: true,
params: {
category: "messages",
call: "send"
}
}
ping: {
method: "POST",
params: {
category: "users",
call:"ping"
}
}
}
)
)
angular.module('sender', ['mandrill'])
.config(($routeProvider) ->
$routeProvider.
when('/', {controller: SenderCtrl, templateUrl: 'partials/senderForm.html'}))
.config(($httpProvider) -> delete $httpProvider.defaults.headers.common["X-Requested-With"])
SenderCtrl = ($scope, Mandrill) ->
$scope.setup = {
apiKey: "", # Initialize this with your api key if you don't want to have to fill it in every time
toEmail: "" # same with your email
}
$scope.sender = {
name: "",
email: "",
phone: "",
awesome: "No Opinion",
people: [
{ name: "<NAME>", like: true },
{ name: "<NAME>", like: true },
{ name: "<NAME>", like: false },
{ name: "<NAME>", like: false },
{ name: "<NAME>", like: true }
],
randomtext: ""
}
@constructMessage = (sender) ->
peopleILike = ((people) ->
return "Nobody" if people.length is 0
return "#{person.name for person in people}"
)(person for person in sender.people when person.like is true)
"<h2>Hello.</h2>
<p>I just got sent from the Mandrill angular proof of concept
at <a href='http://www.github.com'>www.github.com</a>.</p>
<h3>Info:</h3>
<ul>
<li>Name: #{sender.name}</li>
<li>Email: #{sender.email}</li>
<li>Phone: #{sender.phone}</li>
</ul>
<h3>How awesome am I?</h3>
<p>#{sender.awesome}</p>
<h3>Who do I like?</h3>
<p>#{peopleILike}</p>
<h3>Anything Else?</h3>
<p>#{sender.randomtext}</p>"
$scope.checkSetup = () ->
Mandrill.ping(
{"key": $scope.setup.apiKey},
((data,status,headers,config)->
$scope.apiStatusClass = "alert alert-success"
$scope.apiStatusContent = "API key looks good. Go ahead and fill out the rest of the form."),
((data,status,headers,config)->
$scope.apiStatusClass = "alert alert-error"
$scope.apiStatusContent = "Doesn't seem to be valid.")
)
$scope.send = () =>
$scope.messageText = @constructMessage($scope.sender)
Mandrill.sendMessage(
{
key: $scope.setup.apiKey,
message: {
html: $scope.messageText,
subject: "sent from Angular Mandrill proof-of-concept",
from_email: $scope.sender.email,
to: [{email: $scope.setup.toEmail}]
}
},
((data,status,headers,config) ->
$scope.messageStatusClass = "alert alert-success"
$scope.messageStatusContent = "Congratulations! The message should appear soon at #{$scope.setup.toEmail}"
$scope.messageStatusJson = data
),
((data,status,headers,config) ->
$scope.messageStatusClass = "alert alert-error"
$scope.messageStatusContent = "Hmm. Doesn't look like it went through. Check your API key."
$scope.messageStatusJson = data
)
)
| true | angular.module('mandrill',['ngResource'])
.factory('Mandrill', ($resource) ->
Mandrill = $resource(
'https://mandrillapp.com/api/1.0/:category/:call.json',
{},
{
sendMessage: {
method: "POST",
isArray: true,
params: {
category: "messages",
call: "send"
}
}
ping: {
method: "POST",
params: {
category: "users",
call:"ping"
}
}
}
)
)
angular.module('sender', ['mandrill'])
.config(($routeProvider) ->
$routeProvider.
when('/', {controller: SenderCtrl, templateUrl: 'partials/senderForm.html'}))
.config(($httpProvider) -> delete $httpProvider.defaults.headers.common["X-Requested-With"])
SenderCtrl = ($scope, Mandrill) ->
$scope.setup = {
apiKey: "", # Initialize this with your api key if you don't want to have to fill it in every time
toEmail: "" # same with your email
}
$scope.sender = {
name: "",
email: "",
phone: "",
awesome: "No Opinion",
people: [
{ name: "PI:NAME:<NAME>END_PI", like: true },
{ name: "PI:NAME:<NAME>END_PI", like: true },
{ name: "PI:NAME:<NAME>END_PI", like: false },
{ name: "PI:NAME:<NAME>END_PI", like: false },
{ name: "PI:NAME:<NAME>END_PI", like: true }
],
randomtext: ""
}
@constructMessage = (sender) ->
peopleILike = ((people) ->
return "Nobody" if people.length is 0
return "#{person.name for person in people}"
)(person for person in sender.people when person.like is true)
"<h2>Hello.</h2>
<p>I just got sent from the Mandrill angular proof of concept
at <a href='http://www.github.com'>www.github.com</a>.</p>
<h3>Info:</h3>
<ul>
<li>Name: #{sender.name}</li>
<li>Email: #{sender.email}</li>
<li>Phone: #{sender.phone}</li>
</ul>
<h3>How awesome am I?</h3>
<p>#{sender.awesome}</p>
<h3>Who do I like?</h3>
<p>#{peopleILike}</p>
<h3>Anything Else?</h3>
<p>#{sender.randomtext}</p>"
$scope.checkSetup = () ->
Mandrill.ping(
{"key": $scope.setup.apiKey},
((data,status,headers,config)->
$scope.apiStatusClass = "alert alert-success"
$scope.apiStatusContent = "API key looks good. Go ahead and fill out the rest of the form."),
((data,status,headers,config)->
$scope.apiStatusClass = "alert alert-error"
$scope.apiStatusContent = "Doesn't seem to be valid.")
)
$scope.send = () =>
$scope.messageText = @constructMessage($scope.sender)
Mandrill.sendMessage(
{
key: $scope.setup.apiKey,
message: {
html: $scope.messageText,
subject: "sent from Angular Mandrill proof-of-concept",
from_email: $scope.sender.email,
to: [{email: $scope.setup.toEmail}]
}
},
((data,status,headers,config) ->
$scope.messageStatusClass = "alert alert-success"
$scope.messageStatusContent = "Congratulations! The message should appear soon at #{$scope.setup.toEmail}"
$scope.messageStatusJson = data
),
((data,status,headers,config) ->
$scope.messageStatusClass = "alert alert-error"
$scope.messageStatusContent = "Hmm. Doesn't look like it went through. Check your API key."
$scope.messageStatusJson = data
)
)
|
[
{
"context": "veCommentBox\n\n defaults: {\n csrfToken: \"csrf_token\",\n target: \"#post_url\"\n }\n\n construc",
"end": 111,
"score": 0.9892842173576355,
"start": 101,
"tag": "PASSWORD",
"value": "csrf_token"
}
] | spirit/core/static/spirit/scripts/src/move_comments.coffee | Ke-xueting/Spirit | 974 | ###
Move comments to other topic
###
class MoveCommentBox
defaults: {
csrfToken: "csrf_token",
target: "#post_url"
}
constructor: (options) ->
@el = document.querySelector('.js-move-comments-form')
@options = Object.assign({}, @defaults, options)
@setUp()
setUp: ->
@el
.querySelector('.js-move-comments-button')
.addEventListener('click', @moveComments)
moveComments: (e) =>
e.preventDefault()
e.stopPropagation()
formElm = document.createElement('form')
formElm.className = 'js-move-comment-form'
formElm.action = @options.target
formElm.method = 'POST'
formElm.style.display = 'none'
document.body.appendChild(formElm)
inputCSRFElm = document.createElement('input')
inputCSRFElm.name = 'csrfmiddlewaretoken'
inputCSRFElm.type = 'hidden'
inputCSRFElm.value = @options.csrfToken
formElm.appendChild(inputCSRFElm)
inputTopicIdElm = document.createElement('input')
inputTopicIdElm.name = 'topic'
inputTopicIdElm.type = 'text'
inputTopicIdElm.value = @el.querySelector('#id_move_comments_topic').value
formElm.appendChild(inputTopicIdElm)
# Append all selection inputs
Array.from(document.querySelectorAll('.js-move-comment-checkbox')).forEach((elm) ->
formElm.appendChild(elm.cloneNode(false))
)
formElm.submit()
return
isHidden: =>
return @el.style.display == 'none'
show: =>
@el.style.display = 'block'
return
class MoveComment
#TODO: prefix classes with js-
constructor: (el, box) ->
@el = el
@box = box
@setUp()
setUp: ->
@el.addEventListener('click', @showMoveComments)
showMoveComments: (e) =>
e.preventDefault()
e.stopPropagation()
if @box.isHidden()
@box.show()
@addCommentSelection()
return
addCommentSelection: =>
Array.from(document.querySelectorAll('.js-move-comment-checkbox-list')).forEach((elm) ->
liElm = document.createElement('li')
elm.appendChild(liElm)
inputCheckboxElm = document.createElement('input')
inputCheckboxElm.className = 'js-move-comment-checkbox'
inputCheckboxElm.name = 'comments'
inputCheckboxElm.type = 'checkbox'
inputCheckboxElm.value = elm.closest('.js-comment').dataset.pk
liElm.appendChild(inputCheckboxElm)
return
)
stModules.moveComments = (elms, options) ->
box = new MoveCommentBox(options)
return Array.from(elms).map((elm) -> new MoveComment(elm, box))
stModules.MoveCommentBox = MoveCommentBox
stModules.MoveComment = MoveComment
| 15340 | ###
Move comments to other topic
###
class MoveCommentBox
defaults: {
csrfToken: "<PASSWORD>",
target: "#post_url"
}
constructor: (options) ->
@el = document.querySelector('.js-move-comments-form')
@options = Object.assign({}, @defaults, options)
@setUp()
setUp: ->
@el
.querySelector('.js-move-comments-button')
.addEventListener('click', @moveComments)
moveComments: (e) =>
e.preventDefault()
e.stopPropagation()
formElm = document.createElement('form')
formElm.className = 'js-move-comment-form'
formElm.action = @options.target
formElm.method = 'POST'
formElm.style.display = 'none'
document.body.appendChild(formElm)
inputCSRFElm = document.createElement('input')
inputCSRFElm.name = 'csrfmiddlewaretoken'
inputCSRFElm.type = 'hidden'
inputCSRFElm.value = @options.csrfToken
formElm.appendChild(inputCSRFElm)
inputTopicIdElm = document.createElement('input')
inputTopicIdElm.name = 'topic'
inputTopicIdElm.type = 'text'
inputTopicIdElm.value = @el.querySelector('#id_move_comments_topic').value
formElm.appendChild(inputTopicIdElm)
# Append all selection inputs
Array.from(document.querySelectorAll('.js-move-comment-checkbox')).forEach((elm) ->
formElm.appendChild(elm.cloneNode(false))
)
formElm.submit()
return
isHidden: =>
return @el.style.display == 'none'
show: =>
@el.style.display = 'block'
return
class MoveComment
#TODO: prefix classes with js-
constructor: (el, box) ->
@el = el
@box = box
@setUp()
setUp: ->
@el.addEventListener('click', @showMoveComments)
showMoveComments: (e) =>
e.preventDefault()
e.stopPropagation()
if @box.isHidden()
@box.show()
@addCommentSelection()
return
addCommentSelection: =>
Array.from(document.querySelectorAll('.js-move-comment-checkbox-list')).forEach((elm) ->
liElm = document.createElement('li')
elm.appendChild(liElm)
inputCheckboxElm = document.createElement('input')
inputCheckboxElm.className = 'js-move-comment-checkbox'
inputCheckboxElm.name = 'comments'
inputCheckboxElm.type = 'checkbox'
inputCheckboxElm.value = elm.closest('.js-comment').dataset.pk
liElm.appendChild(inputCheckboxElm)
return
)
stModules.moveComments = (elms, options) ->
box = new MoveCommentBox(options)
return Array.from(elms).map((elm) -> new MoveComment(elm, box))
stModules.MoveCommentBox = MoveCommentBox
stModules.MoveComment = MoveComment
| true | ###
Move comments to other topic
###
class MoveCommentBox
defaults: {
csrfToken: "PI:PASSWORD:<PASSWORD>END_PI",
target: "#post_url"
}
constructor: (options) ->
@el = document.querySelector('.js-move-comments-form')
@options = Object.assign({}, @defaults, options)
@setUp()
setUp: ->
@el
.querySelector('.js-move-comments-button')
.addEventListener('click', @moveComments)
moveComments: (e) =>
e.preventDefault()
e.stopPropagation()
formElm = document.createElement('form')
formElm.className = 'js-move-comment-form'
formElm.action = @options.target
formElm.method = 'POST'
formElm.style.display = 'none'
document.body.appendChild(formElm)
inputCSRFElm = document.createElement('input')
inputCSRFElm.name = 'csrfmiddlewaretoken'
inputCSRFElm.type = 'hidden'
inputCSRFElm.value = @options.csrfToken
formElm.appendChild(inputCSRFElm)
inputTopicIdElm = document.createElement('input')
inputTopicIdElm.name = 'topic'
inputTopicIdElm.type = 'text'
inputTopicIdElm.value = @el.querySelector('#id_move_comments_topic').value
formElm.appendChild(inputTopicIdElm)
# Append all selection inputs
Array.from(document.querySelectorAll('.js-move-comment-checkbox')).forEach((elm) ->
formElm.appendChild(elm.cloneNode(false))
)
formElm.submit()
return
isHidden: =>
return @el.style.display == 'none'
show: =>
@el.style.display = 'block'
return
class MoveComment
#TODO: prefix classes with js-
constructor: (el, box) ->
@el = el
@box = box
@setUp()
setUp: ->
@el.addEventListener('click', @showMoveComments)
showMoveComments: (e) =>
e.preventDefault()
e.stopPropagation()
if @box.isHidden()
@box.show()
@addCommentSelection()
return
addCommentSelection: =>
Array.from(document.querySelectorAll('.js-move-comment-checkbox-list')).forEach((elm) ->
liElm = document.createElement('li')
elm.appendChild(liElm)
inputCheckboxElm = document.createElement('input')
inputCheckboxElm.className = 'js-move-comment-checkbox'
inputCheckboxElm.name = 'comments'
inputCheckboxElm.type = 'checkbox'
inputCheckboxElm.value = elm.closest('.js-comment').dataset.pk
liElm.appendChild(inputCheckboxElm)
return
)
stModules.moveComments = (elms, options) ->
box = new MoveCommentBox(options)
return Array.from(elms).map((elm) -> new MoveComment(elm, box))
stModules.MoveCommentBox = MoveCommentBox
stModules.MoveComment = MoveComment
|
[
{
"context": "()\n\n translations:\n oPaginate:\n sFirst: \"Pirmais\"\n sLast: \"Pēdējais\"\n sNext: \"Nākošie\"\n ",
"end": 233,
"score": 0.9736288189888,
"start": 226,
"tag": "NAME",
"value": "Pirmais"
},
{
"context": " oPaginate:\n sFirst: \"Pirmais\"\n ... | app/assets/javascripts/views/declarations_view.js.coffee | opendata-latvia/vad | 2 | class VAD.DeclarationsDatatableView extends Backbone.View
events:
"keyup thead th input" : "columnFilterChanged"
initialize: (options = {}) ->
@initializeDataTable()
translations:
oPaginate:
sFirst: "Pirmais"
sLast: "Pēdējais"
sNext: "Nākošie"
sPrevious: "Iepriekšējie"
sEmptyTable: "Nav pieejami dati"
sInfo: "Attēloti _START_ - _END_ no _TOTAL_ ierakstiem"
sInfoEmpty: "Attēloti 0 - 0 no 0 ierakstiem"
sInfoFiltered: "<br/>(atfiltrēti no _MAX_ ierakstiem)"
sLengthMenu: "Parādīt _MENU_ ierakstus"
sLoadingRecords: "Ielādē..."
sProcessing: "Apstrādā..."
sSearch: "Meklēt visās kolonnās:"
sZeroRecords: "Nav atrasts neviens ieraksts"
initializeDataTable: ->
@columnFilterValues = []
$dataTable = @$(".table")
# bind to click event on individual input elements
# to prevent default th click behaviour
$dataTable.find("thead th input").click @clickHeadInput
$.extend $.fn.dataTableExt.oStdClasses,
"sSortAsc": "header headerSortDown"
"sSortDesc": "header headerSortUp"
"sSortable": "header"
@dataTable = $dataTable.dataTable
# sDom: "<'row-fluid'<'span4'l><'span8'f>r>t<'row-fluid'<'span5'i><'span7'p>>"
sDom: "<'row-fluid'<'span4'l>r>t<'row-fluid'<'span5'i><'span7'p>>"
# sScrollX: "100%"
bProcessing: true
bServerSide: true
sAjaxSource: $dataTable.data "source"
fnServerData: @fnServerData
sPaginationType: "bootstrap"
oLanguage: @translations
@fixedHeader = new FixedHeader @dataTable,
top: true
left: true
offsetTop: $(".navbar-fixed-top").height()
# do not focus on table headers when moving with tabs between column filters
@$("thead th").attr "tabindex", "-1"
# override standard DataTebles implementation to add processing of additional returned query parameter
fnServerData: (sUrl, aoData, fnCallback, oSettings) =>
oSettings.jqXHR = $.ajax
url: sUrl
data: aoData
success: (json) =>
# console.log "fnServerData success", json
@updateDownloadLinks(json.queryParams)
$(oSettings.oInstance).trigger('xhr', oSettings)
fnCallback(json)
dataType: "json"
cache: false
type: oSettings.sServerMethod
error: (xhr, error, thrown) ->
if error == "parsererror"
oSettings.oApi._fnLog( oSettings, 0, "DataTables warning: JSON data from " +
"server could not be parsed. This is caused by a JSON formatting error." )
updateDownloadLinks: (params) ->
delete params.q unless params.q
allPagesParams = _.clone params
delete allPagesParams.page
delete allPagesParams.per_page
# delete allPagesParams.sort
# delete allPagesParams.sort_direction
@$("a[data-download-path]").each ->
$this = $(this)
# urlParams = $.param(if $this.data("currentPage") then params else allPagesParams)
urlParams = $.param allPagesParams
url = $this.data("downloadPath")
url += "?" + urlParams if urlParams
$this.attr "href", url
@$(".download-data").show()
clickHeadInput: (e) =>
# ignore click to prevent sorting
false
columnFilterChanged: (e) ->
$target = $(e.currentTarget)
inputIndex = $target.closest("tr").find("input").index($target)
@columnFilterValues[inputIndex] ?= ""
if (value = $target.val()) isnt @columnFilterValues[inputIndex]
@columnFilterValues[inputIndex] = value
@dataTable.fnFilter value, inputIndex
| 189727 | class VAD.DeclarationsDatatableView extends Backbone.View
events:
"keyup thead th input" : "columnFilterChanged"
initialize: (options = {}) ->
@initializeDataTable()
translations:
oPaginate:
sFirst: "<NAME>"
sLast: "<NAME>"
sNext: "Nākošie"
sPrevious: "Iepriekšējie"
sEmptyTable: "Nav pieejami dati"
sInfo: "Attēloti _START_ - _END_ no _TOTAL_ ierakstiem"
sInfoEmpty: "Attēloti 0 - 0 no 0 ierakstiem"
sInfoFiltered: "<br/>(atfiltrēti no _MAX_ ierakstiem)"
sLengthMenu: "Parādīt _MENU_ ierakstus"
sLoadingRecords: "Ielādē..."
sProcessing: "Apstrādā..."
sSearch: "Meklēt visās kolonnās:"
sZeroRecords: "Nav atrasts neviens ieraksts"
initializeDataTable: ->
@columnFilterValues = []
$dataTable = @$(".table")
# bind to click event on individual input elements
# to prevent default th click behaviour
$dataTable.find("thead th input").click @clickHeadInput
$.extend $.fn.dataTableExt.oStdClasses,
"sSortAsc": "header headerSortDown"
"sSortDesc": "header headerSortUp"
"sSortable": "header"
@dataTable = $dataTable.dataTable
# sDom: "<'row-fluid'<'span4'l><'span8'f>r>t<'row-fluid'<'span5'i><'span7'p>>"
sDom: "<'row-fluid'<'span4'l>r>t<'row-fluid'<'span5'i><'span7'p>>"
# sScrollX: "100%"
bProcessing: true
bServerSide: true
sAjaxSource: $dataTable.data "source"
fnServerData: @fnServerData
sPaginationType: "bootstrap"
oLanguage: @translations
@fixedHeader = new FixedHeader @dataTable,
top: true
left: true
offsetTop: $(".navbar-fixed-top").height()
# do not focus on table headers when moving with tabs between column filters
@$("thead th").attr "tabindex", "-1"
# override standard DataTebles implementation to add processing of additional returned query parameter
fnServerData: (sUrl, aoData, fnCallback, oSettings) =>
oSettings.jqXHR = $.ajax
url: sUrl
data: aoData
success: (json) =>
# console.log "fnServerData success", json
@updateDownloadLinks(json.queryParams)
$(oSettings.oInstance).trigger('xhr', oSettings)
fnCallback(json)
dataType: "json"
cache: false
type: oSettings.sServerMethod
error: (xhr, error, thrown) ->
if error == "parsererror"
oSettings.oApi._fnLog( oSettings, 0, "DataTables warning: JSON data from " +
"server could not be parsed. This is caused by a JSON formatting error." )
updateDownloadLinks: (params) ->
delete params.q unless params.q
allPagesParams = _.clone params
delete allPagesParams.page
delete allPagesParams.per_page
# delete allPagesParams.sort
# delete allPagesParams.sort_direction
@$("a[data-download-path]").each ->
$this = $(this)
# urlParams = $.param(if $this.data("currentPage") then params else allPagesParams)
urlParams = $.param allPagesParams
url = $this.data("downloadPath")
url += "?" + urlParams if urlParams
$this.attr "href", url
@$(".download-data").show()
clickHeadInput: (e) =>
# ignore click to prevent sorting
false
columnFilterChanged: (e) ->
$target = $(e.currentTarget)
inputIndex = $target.closest("tr").find("input").index($target)
@columnFilterValues[inputIndex] ?= ""
if (value = $target.val()) isnt @columnFilterValues[inputIndex]
@columnFilterValues[inputIndex] = value
@dataTable.fnFilter value, inputIndex
| true | class VAD.DeclarationsDatatableView extends Backbone.View
events:
"keyup thead th input" : "columnFilterChanged"
initialize: (options = {}) ->
@initializeDataTable()
translations:
oPaginate:
sFirst: "PI:NAME:<NAME>END_PI"
sLast: "PI:NAME:<NAME>END_PI"
sNext: "Nākošie"
sPrevious: "Iepriekšējie"
sEmptyTable: "Nav pieejami dati"
sInfo: "Attēloti _START_ - _END_ no _TOTAL_ ierakstiem"
sInfoEmpty: "Attēloti 0 - 0 no 0 ierakstiem"
sInfoFiltered: "<br/>(atfiltrēti no _MAX_ ierakstiem)"
sLengthMenu: "Parādīt _MENU_ ierakstus"
sLoadingRecords: "Ielādē..."
sProcessing: "Apstrādā..."
sSearch: "Meklēt visās kolonnās:"
sZeroRecords: "Nav atrasts neviens ieraksts"
initializeDataTable: ->
@columnFilterValues = []
$dataTable = @$(".table")
# bind to click event on individual input elements
# to prevent default th click behaviour
$dataTable.find("thead th input").click @clickHeadInput
$.extend $.fn.dataTableExt.oStdClasses,
"sSortAsc": "header headerSortDown"
"sSortDesc": "header headerSortUp"
"sSortable": "header"
@dataTable = $dataTable.dataTable
# sDom: "<'row-fluid'<'span4'l><'span8'f>r>t<'row-fluid'<'span5'i><'span7'p>>"
sDom: "<'row-fluid'<'span4'l>r>t<'row-fluid'<'span5'i><'span7'p>>"
# sScrollX: "100%"
bProcessing: true
bServerSide: true
sAjaxSource: $dataTable.data "source"
fnServerData: @fnServerData
sPaginationType: "bootstrap"
oLanguage: @translations
@fixedHeader = new FixedHeader @dataTable,
top: true
left: true
offsetTop: $(".navbar-fixed-top").height()
# do not focus on table headers when moving with tabs between column filters
@$("thead th").attr "tabindex", "-1"
# override standard DataTebles implementation to add processing of additional returned query parameter
fnServerData: (sUrl, aoData, fnCallback, oSettings) =>
oSettings.jqXHR = $.ajax
url: sUrl
data: aoData
success: (json) =>
# console.log "fnServerData success", json
@updateDownloadLinks(json.queryParams)
$(oSettings.oInstance).trigger('xhr', oSettings)
fnCallback(json)
dataType: "json"
cache: false
type: oSettings.sServerMethod
error: (xhr, error, thrown) ->
if error == "parsererror"
oSettings.oApi._fnLog( oSettings, 0, "DataTables warning: JSON data from " +
"server could not be parsed. This is caused by a JSON formatting error." )
updateDownloadLinks: (params) ->
delete params.q unless params.q
allPagesParams = _.clone params
delete allPagesParams.page
delete allPagesParams.per_page
# delete allPagesParams.sort
# delete allPagesParams.sort_direction
@$("a[data-download-path]").each ->
$this = $(this)
# urlParams = $.param(if $this.data("currentPage") then params else allPagesParams)
urlParams = $.param allPagesParams
url = $this.data("downloadPath")
url += "?" + urlParams if urlParams
$this.attr "href", url
@$(".download-data").show()
clickHeadInput: (e) =>
# ignore click to prevent sorting
false
columnFilterChanged: (e) ->
$target = $(e.currentTarget)
inputIndex = $target.closest("tr").find("input").index($target)
@columnFilterValues[inputIndex] ?= ""
if (value = $target.val()) isnt @columnFilterValues[inputIndex]
@columnFilterValues[inputIndex] = value
@dataTable.fnFilter value, inputIndex
|
[
{
"context": "ateTeam = ->\n [ Factory(\"Magikarp\")\n Factory(\"Gyarados\")\n Factory('Hitmonchan')\n Factory(\"Celebi\")",
"end": 296,
"score": 0.6362925171852112,
"start": 288,
"tag": "NAME",
"value": "Gyarados"
},
{
"context": "agikarp\")\n Factory(\"Gyarados\")\n ... | test/server/conditions/species_clause_spec.coffee | sarenji/pokebattle-sim | 5 | require '../../helpers'
{BattleServer} = require('../../../server/server')
{User} = require('../../../server/user')
{Conditions} = require '../../../shared/conditions'
{Factory} = require '../../factory'
should = require('should')
generateTeam = ->
[ Factory("Magikarp")
Factory("Gyarados")
Factory('Hitmonchan')
Factory("Celebi")
Factory("Blissey")
Factory("Alakazam") ]
describe 'Validations: Species Clause', ->
it "returns an error if the team has more than one of the same species", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Rotom", forme: "wash")
team[1] = Factory("Rotom", forme: "heat")
conditions = [ Conditions.SPECIES_CLAUSE ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns no error if the team shares no species", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
conditions = [ Conditions.SPECIES_CLAUSE ]
server.validateTeam(team, format, conditions).should.be.empty
| 75088 | require '../../helpers'
{BattleServer} = require('../../../server/server')
{User} = require('../../../server/user')
{Conditions} = require '../../../shared/conditions'
{Factory} = require '../../factory'
should = require('should')
generateTeam = ->
[ Factory("Magikarp")
Factory("<NAME>")
Factory('Hit<NAME>')
Factory("Celebi")
Factory("Blissey")
Factory("Alakazam") ]
describe 'Validations: Species Clause', ->
it "returns an error if the team has more than one of the same species", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Rotom", forme: "wash")
team[1] = Factory("Rotom", forme: "heat")
conditions = [ Conditions.SPECIES_CLAUSE ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns no error if the team shares no species", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
conditions = [ Conditions.SPECIES_CLAUSE ]
server.validateTeam(team, format, conditions).should.be.empty
| true | require '../../helpers'
{BattleServer} = require('../../../server/server')
{User} = require('../../../server/user')
{Conditions} = require '../../../shared/conditions'
{Factory} = require '../../factory'
should = require('should')
generateTeam = ->
[ Factory("Magikarp")
Factory("PI:NAME:<NAME>END_PI")
Factory('HitPI:NAME:<NAME>END_PI')
Factory("Celebi")
Factory("Blissey")
Factory("Alakazam") ]
describe 'Validations: Species Clause', ->
it "returns an error if the team has more than one of the same species", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
team[0] = Factory("Rotom", forme: "wash")
team[1] = Factory("Rotom", forme: "heat")
conditions = [ Conditions.SPECIES_CLAUSE ]
server.validateTeam(team, format, conditions).should.not.be.empty
it "returns no error if the team shares no species", ->
server = new BattleServer()
format = 'xy1000'
team = generateTeam()
conditions = [ Conditions.SPECIES_CLAUSE ]
server.validateTeam(team, format, conditions).should.be.empty
|
[
{
"context": "###\n@authors\nNicholas McCready - https://twitter.com/nmccready\n###\nangular.modul",
"end": 30,
"score": 0.999894380569458,
"start": 13,
"tag": "NAME",
"value": "Nicholas McCready"
},
{
"context": "\n@authors\nNicholas McCready - https://twitter.com/nmccready\n###\nan... | SafetyNet_Mobile/www/lib/angular-google-maps-master/src/coffee/directives/drag-zoom.coffee | donh/pheonix | 1 | ###
@authors
Nicholas McCready - https://twitter.com/nmccready
###
angular.module('uiGmapgoogle-maps')
.directive 'uiGmapDragZoom', [ 'uiGmapDragZoom', (DragZoom) -> DragZoom ]
| 220402 | ###
@authors
<NAME> - https://twitter.com/nmccready
###
angular.module('uiGmapgoogle-maps')
.directive 'uiGmapDragZoom', [ 'uiGmapDragZoom', (DragZoom) -> DragZoom ]
| true | ###
@authors
PI:NAME:<NAME>END_PI - https://twitter.com/nmccready
###
angular.module('uiGmapgoogle-maps')
.directive 'uiGmapDragZoom', [ 'uiGmapDragZoom', (DragZoom) -> DragZoom ]
|
[
{
"context": " \n#\thubot website - Aquas website \n#\n# Author:\n# Josh King\n\nwipetime = \"every Tuesday\"\ntwitter = \"https://tw",
"end": 455,
"score": 0.9998659491539001,
"start": 446,
"tag": "NAME",
"value": "Josh King"
},
{
"context": " = \"every Tuesday\"\ntwitter = \"http... | scripts/chat.coffee | Josh5K/AquaFPS-Discord-Bot | 0 | # Description:
# Basic chat commands for discord
#
# Commands:
# hubot twitch - Aquas twitch channel
# hubot youtube - Aquas youtube channel
# hubot wipe - The Aquarium wipe information
# hubot about - About Aqua Bot
# hubot server - The Aquarium information
# hubot merch - Cool Clothes
# hubot report - The Aquarium report informations
# hubot twitter - Aquas twitter account
# hubot website - Aquas website
#
# Author:
# Josh King
wipetime = "every Tuesday"
twitter = "https://twitter.com/aquafpsgaming"
twitch = "https://www.twitch.tv/aquafpsgaming"
youtube ="https://www.youtube.com/user/macaws7"
github = "https://github.com/Josh5K/AquaFPS-Discord-Bot"
merch = "https://teespring.com/stores/aquafps"
website = "http://www.AquaFPS.com/"
module.exports = (robot) ->
console.log "User sent a message."
robot.hear /@Aqua Bot twitch/i, (res) ->
res.send "#{twitch}"
console.log "A user has executed a twitch command"
robot.hear /@Aqua Bot youtube/i, (res) ->
res.send "#{youtube}"
console.log "A user has executed a youtube command"
robot.hear /@Aqua Bot wipe/i, (res) ->
res.send "The Aquarium wipes #{wipetime}.\nPlease refrain from bothering moderators. It is out of their control."
console.log "A user has executed a wipe command"
robot.hear /@Aqua Bot about/i, (res) ->
res.send "Aqua Bot is a community made discord chat bot. Wanna help develop Aqua Bot? You can find the repository here - #{github} We encourage everyone to add something new!"
console.log "A user has executed a about command"
robot.hear /@Aqua Bot server/i, (res) ->
res.send "The Aquarium Vanilla 1.5x ODD\nConnect to server using \"client.connect 142.44.177.154:28015\" In your Rust F1 console.\nhttps://rustops.com/ Server Information, FAQ, Rules and Donation infomation.\nFor support help or report go to their discord https://discord.gg/yzwyk5M"
console.log "A user has executed a server command"
robot.hear /@Aqua Bot merch/i, (res) ->
res.send "Do you wanna wear cool clothes?\nWell you can get some from #{merch}\nIf you want."
console.log "A user has executed a merch command"
robot.hear /@Aqua Bot report/i, (res) ->
res.send "Reports for The Aquarium Server are done in https://discord.gg/yzwyk5M"
console.log "A user has executed a report command"
robot.hear /@Aqua Bot twitter/i, (res) ->
res.send "#{twitter}"
console.log "A user has executed a twitter command"
robot.hear /@Aqua Bot website/i, (res) ->
res.send "#{website}"
console.log "A user has executed a website command"
robot.hear /405517910774382592/i, (res) ->
res.send "BANG! 🔫"
console.log "BANG! 🔫" | 17429 | # Description:
# Basic chat commands for discord
#
# Commands:
# hubot twitch - Aquas twitch channel
# hubot youtube - Aquas youtube channel
# hubot wipe - The Aquarium wipe information
# hubot about - About Aqua Bot
# hubot server - The Aquarium information
# hubot merch - Cool Clothes
# hubot report - The Aquarium report informations
# hubot twitter - Aquas twitter account
# hubot website - Aquas website
#
# Author:
# <NAME>
wipetime = "every Tuesday"
twitter = "https://twitter.com/aquafpsgaming"
twitch = "https://www.twitch.tv/aquafpsgaming"
youtube ="https://www.youtube.com/user/macaws7"
github = "https://github.com/Josh5K/AquaFPS-Discord-Bot"
merch = "https://teespring.com/stores/aquafps"
website = "http://www.AquaFPS.com/"
module.exports = (robot) ->
console.log "User sent a message."
robot.hear /@Aqua Bot twitch/i, (res) ->
res.send "#{twitch}"
console.log "A user has executed a twitch command"
robot.hear /@Aqua Bot youtube/i, (res) ->
res.send "#{youtube}"
console.log "A user has executed a youtube command"
robot.hear /@Aqua Bot wipe/i, (res) ->
res.send "The Aquarium wipes #{wipetime}.\nPlease refrain from bothering moderators. It is out of their control."
console.log "A user has executed a wipe command"
robot.hear /@Aqua Bot about/i, (res) ->
res.send "Aqua Bot is a community made discord chat bot. Wanna help develop Aqua Bot? You can find the repository here - #{github} We encourage everyone to add something new!"
console.log "A user has executed a about command"
robot.hear /@Aqua Bot server/i, (res) ->
res.send "The Aquarium Vanilla 1.5x ODD\nConnect to server using \"client.connect 172.16.31.10:28015\" In your Rust F1 console.\nhttps://rustops.com/ Server Information, FAQ, Rules and Donation infomation.\nFor support help or report go to their discord https://discord.gg/yzwyk5M"
console.log "A user has executed a server command"
robot.hear /@Aqua Bot merch/i, (res) ->
res.send "Do you wanna wear cool clothes?\nWell you can get some from #{merch}\nIf you want."
console.log "A user has executed a merch command"
robot.hear /@Aqua Bot report/i, (res) ->
res.send "Reports for The Aquarium Server are done in https://discord.gg/yzwyk5M"
console.log "A user has executed a report command"
robot.hear /@Aqua Bot twitter/i, (res) ->
res.send "#{twitter}"
console.log "A user has executed a twitter command"
robot.hear /@Aqua Bot website/i, (res) ->
res.send "#{website}"
console.log "A user has executed a website command"
robot.hear /405517910774382592/i, (res) ->
res.send "BANG! 🔫"
console.log "BANG! 🔫" | true | # Description:
# Basic chat commands for discord
#
# Commands:
# hubot twitch - Aquas twitch channel
# hubot youtube - Aquas youtube channel
# hubot wipe - The Aquarium wipe information
# hubot about - About Aqua Bot
# hubot server - The Aquarium information
# hubot merch - Cool Clothes
# hubot report - The Aquarium report informations
# hubot twitter - Aquas twitter account
# hubot website - Aquas website
#
# Author:
# PI:NAME:<NAME>END_PI
wipetime = "every Tuesday"
twitter = "https://twitter.com/aquafpsgaming"
twitch = "https://www.twitch.tv/aquafpsgaming"
youtube ="https://www.youtube.com/user/macaws7"
github = "https://github.com/Josh5K/AquaFPS-Discord-Bot"
merch = "https://teespring.com/stores/aquafps"
website = "http://www.AquaFPS.com/"
module.exports = (robot) ->
console.log "User sent a message."
robot.hear /@Aqua Bot twitch/i, (res) ->
res.send "#{twitch}"
console.log "A user has executed a twitch command"
robot.hear /@Aqua Bot youtube/i, (res) ->
res.send "#{youtube}"
console.log "A user has executed a youtube command"
robot.hear /@Aqua Bot wipe/i, (res) ->
res.send "The Aquarium wipes #{wipetime}.\nPlease refrain from bothering moderators. It is out of their control."
console.log "A user has executed a wipe command"
robot.hear /@Aqua Bot about/i, (res) ->
res.send "Aqua Bot is a community made discord chat bot. Wanna help develop Aqua Bot? You can find the repository here - #{github} We encourage everyone to add something new!"
console.log "A user has executed a about command"
robot.hear /@Aqua Bot server/i, (res) ->
res.send "The Aquarium Vanilla 1.5x ODD\nConnect to server using \"client.connect PI:IP_ADDRESS:172.16.31.10END_PI:28015\" In your Rust F1 console.\nhttps://rustops.com/ Server Information, FAQ, Rules and Donation infomation.\nFor support help or report go to their discord https://discord.gg/yzwyk5M"
console.log "A user has executed a server command"
robot.hear /@Aqua Bot merch/i, (res) ->
res.send "Do you wanna wear cool clothes?\nWell you can get some from #{merch}\nIf you want."
console.log "A user has executed a merch command"
robot.hear /@Aqua Bot report/i, (res) ->
res.send "Reports for The Aquarium Server are done in https://discord.gg/yzwyk5M"
console.log "A user has executed a report command"
robot.hear /@Aqua Bot twitter/i, (res) ->
res.send "#{twitter}"
console.log "A user has executed a twitter command"
robot.hear /@Aqua Bot website/i, (res) ->
res.send "#{website}"
console.log "A user has executed a website command"
robot.hear /405517910774382592/i, (res) ->
res.send "BANG! 🔫"
console.log "BANG! 🔫" |
[
{
"context": "(\"Don't talk so much\")\n .updateInfo(\"My name is albert\")\n .updateInfo(\"My name is joan\")\n .endLine",
"end": 4026,
"score": 0.9996923804283142,
"start": 4020,
"tag": "NAME",
"value": "albert"
},
{
"context": "o(\"My name is albert\")\n .updateInfo(\"... | src/scripts/tests/logger.coffee | albertsgrc/q-mspacman | 3 | _ = require 'lodash'
{ clearLine, cursorTo } = require 'readline'
{ inspect } = require 'util'
utils = require './utils'
styler = require './styler'
# Alias
{ stdout, stderr } = process
# Constants
MINIMUM_COLS_FOR_LINEBREAK = 15
TAG_INDICATOR = ': '
[ INFO, WARN, ERROR, VERBOSE ] = TAGS = [ "INFO", "WARN", "ERROR", "VERBS" ]
LEFT_MARGIN = _.maxBy(TAGS, _.size).length + 1
LEFT_PADSTRING_LONG_LINES = _.repeat(" ", LEFT_MARGIN + TAG_INDICATOR.length)
MAX_COLS_PER_LINE = (stdout.columns ? Number.MAX_VALUE) - 1 # HACK: Assumes application won't last long
# Private methods
tag = (txt, style, tagString) -> style(_.padEnd(txt, LEFT_MARGIN)) + tagString
fold = (string, leftPad = LEFT_PADSTRING_LONG_LINES) ->
cols = Math.max MINIMUM_COLS_FOR_LINEBREAK, MAX_COLS_PER_LINE - leftPad.length
chunks = string.split("\n")
foldImm = (str) ->
nonOcuppyingLength = utils.getNonOcuppyingLength(str)
if str.length - nonOcuppyingLength <= cols # Base case
str
else # Recursive case
cutString = str[...cols + nonOcuppyingLength]
lastSpace = cutString.lastIndexOf(' ')
# This if-else is in order to avoid cutting a word in half in case it's possible
if lastSpace >= 0
cutString[...lastSpace] + "\n" + leftPad + fold(str[lastSpace+1..])
else # Quite strange there's no space in 70 character string...
cutString[...-1] + "-\n" + leftPad + fold(str[cutString.length-1..])
[prefix..., last] = chunks.map foldImm
# The last endline (if exists, that's what this condition is for),
# should not be followed by the padString
if prefix.length
prefix.join("\n" + leftPad) + "\n" + last
else
last
createWriter = (txt, styler, { stream = stdout, tagString = TAG_INDICATOR } = {}) =>
(msg, { endline = on, margin = off } = {}) =>
msg = inspect msg unless _.isString msg
msg += "\n" if endline is on
if margin
stream.write "\n " + tag(txt, styler, tagString) +
fold(msg, LEFT_PADSTRING_LONG_LINES + " ") + "\n"
else
stream.write tag(txt, styler, tagString) + fold(msg)
@
# Exposed methods
@write = (str, stream = stdout) => stream.write str; @
@space = (stream = stdout) => stream.write ' '; @
@endLine = (stream = stdout) => stream.write "\n"; @openUpdate = no; @
@eraseLine = (stream = stdout) => clearLine(stream); cursorTo(stream, 0); @
@verbose = @v = do =>
verboseWriter = createWriter VERBOSE, styler.verbose
(args...) =>
verboseWriter args... if global.cli?.verbose?
@
@noTag = @n = createWriter "", _.identity, { tagString: _.repeat(" ", TAG_INDICATOR.length) }
@info = @i = createWriter INFO, styler.info
@updateInfo = (msg) => @eraseLine(); @info(msg, endline: off); @
@warn = @w = createWriter WARN, styler.warn
@error = @e = do ->
errorWriter = createWriter ERROR, styler.error, { stream: stderr }
(msg, { margin = off, exit = no, exitCode = 1, printStack = exit } = {}) ->
if printStack
stack = (new Error).stack.split("\n")[2..].join("\n")
msg = msg + "\n#{_.trimEnd stack, '\n'}"
ret = errorWriter msg, margin: margin, endline: on
process.exit exitCode if exit is yes
ret
# Testing Code
###
this
.i("Thisisastrangelongsentencewithnospacesa#{styler.id 'nditshould'}becutwithahyphenbecause\
theresnospaceanditcannotbereadcorrectlyiftheterminalistoonarrow.")
.w("This is a normal sentence which has a lot of columns, so it should be
cut cause it's too long to be read correctly in the terminal.")
.e("This sentence is also too long. But note that it has a endline,\nso
it shouldn't be cut because it already fits in the screen.")
.i(9)
.i({ hello: 'world' })
.warn("This is a warning")
.error("An error occurred", margin: on )
.info("Be informed")
.verbose("Don't talk so much")
.updateInfo("My name is albert")
.updateInfo("My name is joan")
.endLine()
stdout.write "Shouldn't appear"; @eraseLine()
@error("This ends with error code 2", exit: yes, exitCode: 2)
@info("Should'nt be printed")
###
| 163248 | _ = require 'lodash'
{ clearLine, cursorTo } = require 'readline'
{ inspect } = require 'util'
utils = require './utils'
styler = require './styler'
# Alias
{ stdout, stderr } = process
# Constants
MINIMUM_COLS_FOR_LINEBREAK = 15
TAG_INDICATOR = ': '
[ INFO, WARN, ERROR, VERBOSE ] = TAGS = [ "INFO", "WARN", "ERROR", "VERBS" ]
LEFT_MARGIN = _.maxBy(TAGS, _.size).length + 1
LEFT_PADSTRING_LONG_LINES = _.repeat(" ", LEFT_MARGIN + TAG_INDICATOR.length)
MAX_COLS_PER_LINE = (stdout.columns ? Number.MAX_VALUE) - 1 # HACK: Assumes application won't last long
# Private methods
tag = (txt, style, tagString) -> style(_.padEnd(txt, LEFT_MARGIN)) + tagString
fold = (string, leftPad = LEFT_PADSTRING_LONG_LINES) ->
cols = Math.max MINIMUM_COLS_FOR_LINEBREAK, MAX_COLS_PER_LINE - leftPad.length
chunks = string.split("\n")
foldImm = (str) ->
nonOcuppyingLength = utils.getNonOcuppyingLength(str)
if str.length - nonOcuppyingLength <= cols # Base case
str
else # Recursive case
cutString = str[...cols + nonOcuppyingLength]
lastSpace = cutString.lastIndexOf(' ')
# This if-else is in order to avoid cutting a word in half in case it's possible
if lastSpace >= 0
cutString[...lastSpace] + "\n" + leftPad + fold(str[lastSpace+1..])
else # Quite strange there's no space in 70 character string...
cutString[...-1] + "-\n" + leftPad + fold(str[cutString.length-1..])
[prefix..., last] = chunks.map foldImm
# The last endline (if exists, that's what this condition is for),
# should not be followed by the padString
if prefix.length
prefix.join("\n" + leftPad) + "\n" + last
else
last
createWriter = (txt, styler, { stream = stdout, tagString = TAG_INDICATOR } = {}) =>
(msg, { endline = on, margin = off } = {}) =>
msg = inspect msg unless _.isString msg
msg += "\n" if endline is on
if margin
stream.write "\n " + tag(txt, styler, tagString) +
fold(msg, LEFT_PADSTRING_LONG_LINES + " ") + "\n"
else
stream.write tag(txt, styler, tagString) + fold(msg)
@
# Exposed methods
@write = (str, stream = stdout) => stream.write str; @
@space = (stream = stdout) => stream.write ' '; @
@endLine = (stream = stdout) => stream.write "\n"; @openUpdate = no; @
@eraseLine = (stream = stdout) => clearLine(stream); cursorTo(stream, 0); @
@verbose = @v = do =>
verboseWriter = createWriter VERBOSE, styler.verbose
(args...) =>
verboseWriter args... if global.cli?.verbose?
@
@noTag = @n = createWriter "", _.identity, { tagString: _.repeat(" ", TAG_INDICATOR.length) }
@info = @i = createWriter INFO, styler.info
@updateInfo = (msg) => @eraseLine(); @info(msg, endline: off); @
@warn = @w = createWriter WARN, styler.warn
@error = @e = do ->
errorWriter = createWriter ERROR, styler.error, { stream: stderr }
(msg, { margin = off, exit = no, exitCode = 1, printStack = exit } = {}) ->
if printStack
stack = (new Error).stack.split("\n")[2..].join("\n")
msg = msg + "\n#{_.trimEnd stack, '\n'}"
ret = errorWriter msg, margin: margin, endline: on
process.exit exitCode if exit is yes
ret
# Testing Code
###
this
.i("Thisisastrangelongsentencewithnospacesa#{styler.id 'nditshould'}becutwithahyphenbecause\
theresnospaceanditcannotbereadcorrectlyiftheterminalistoonarrow.")
.w("This is a normal sentence which has a lot of columns, so it should be
cut cause it's too long to be read correctly in the terminal.")
.e("This sentence is also too long. But note that it has a endline,\nso
it shouldn't be cut because it already fits in the screen.")
.i(9)
.i({ hello: 'world' })
.warn("This is a warning")
.error("An error occurred", margin: on )
.info("Be informed")
.verbose("Don't talk so much")
.updateInfo("My name is <NAME>")
.updateInfo("My name is <NAME>")
.endLine()
stdout.write "Shouldn't appear"; @eraseLine()
@error("This ends with error code 2", exit: yes, exitCode: 2)
@info("Should'nt be printed")
###
| true | _ = require 'lodash'
{ clearLine, cursorTo } = require 'readline'
{ inspect } = require 'util'
utils = require './utils'
styler = require './styler'
# Alias
{ stdout, stderr } = process
# Constants
MINIMUM_COLS_FOR_LINEBREAK = 15
TAG_INDICATOR = ': '
[ INFO, WARN, ERROR, VERBOSE ] = TAGS = [ "INFO", "WARN", "ERROR", "VERBS" ]
LEFT_MARGIN = _.maxBy(TAGS, _.size).length + 1
LEFT_PADSTRING_LONG_LINES = _.repeat(" ", LEFT_MARGIN + TAG_INDICATOR.length)
MAX_COLS_PER_LINE = (stdout.columns ? Number.MAX_VALUE) - 1 # HACK: Assumes application won't last long
# Private methods
tag = (txt, style, tagString) -> style(_.padEnd(txt, LEFT_MARGIN)) + tagString
fold = (string, leftPad = LEFT_PADSTRING_LONG_LINES) ->
cols = Math.max MINIMUM_COLS_FOR_LINEBREAK, MAX_COLS_PER_LINE - leftPad.length
chunks = string.split("\n")
foldImm = (str) ->
nonOcuppyingLength = utils.getNonOcuppyingLength(str)
if str.length - nonOcuppyingLength <= cols # Base case
str
else # Recursive case
cutString = str[...cols + nonOcuppyingLength]
lastSpace = cutString.lastIndexOf(' ')
# This if-else is in order to avoid cutting a word in half in case it's possible
if lastSpace >= 0
cutString[...lastSpace] + "\n" + leftPad + fold(str[lastSpace+1..])
else # Quite strange there's no space in 70 character string...
cutString[...-1] + "-\n" + leftPad + fold(str[cutString.length-1..])
[prefix..., last] = chunks.map foldImm
# The last endline (if exists, that's what this condition is for),
# should not be followed by the padString
if prefix.length
prefix.join("\n" + leftPad) + "\n" + last
else
last
createWriter = (txt, styler, { stream = stdout, tagString = TAG_INDICATOR } = {}) =>
(msg, { endline = on, margin = off } = {}) =>
msg = inspect msg unless _.isString msg
msg += "\n" if endline is on
if margin
stream.write "\n " + tag(txt, styler, tagString) +
fold(msg, LEFT_PADSTRING_LONG_LINES + " ") + "\n"
else
stream.write tag(txt, styler, tagString) + fold(msg)
@
# Exposed methods
@write = (str, stream = stdout) => stream.write str; @
@space = (stream = stdout) => stream.write ' '; @
@endLine = (stream = stdout) => stream.write "\n"; @openUpdate = no; @
@eraseLine = (stream = stdout) => clearLine(stream); cursorTo(stream, 0); @
@verbose = @v = do =>
verboseWriter = createWriter VERBOSE, styler.verbose
(args...) =>
verboseWriter args... if global.cli?.verbose?
@
@noTag = @n = createWriter "", _.identity, { tagString: _.repeat(" ", TAG_INDICATOR.length) }
@info = @i = createWriter INFO, styler.info
@updateInfo = (msg) => @eraseLine(); @info(msg, endline: off); @
@warn = @w = createWriter WARN, styler.warn
@error = @e = do ->
errorWriter = createWriter ERROR, styler.error, { stream: stderr }
(msg, { margin = off, exit = no, exitCode = 1, printStack = exit } = {}) ->
if printStack
stack = (new Error).stack.split("\n")[2..].join("\n")
msg = msg + "\n#{_.trimEnd stack, '\n'}"
ret = errorWriter msg, margin: margin, endline: on
process.exit exitCode if exit is yes
ret
# Testing Code
###
this
.i("Thisisastrangelongsentencewithnospacesa#{styler.id 'nditshould'}becutwithahyphenbecause\
theresnospaceanditcannotbereadcorrectlyiftheterminalistoonarrow.")
.w("This is a normal sentence which has a lot of columns, so it should be
cut cause it's too long to be read correctly in the terminal.")
.e("This sentence is also too long. But note that it has a endline,\nso
it shouldn't be cut because it already fits in the screen.")
.i(9)
.i({ hello: 'world' })
.warn("This is a warning")
.error("An error occurred", margin: on )
.info("Be informed")
.verbose("Don't talk so much")
.updateInfo("My name is PI:NAME:<NAME>END_PI")
.updateInfo("My name is PI:NAME:<NAME>END_PI")
.endLine()
stdout.write "Shouldn't appear"; @eraseLine()
@error("This ends with error code 2", exit: yes, exitCode: 2)
@info("Should'nt be printed")
###
|
[
{
"context": "or questions about press contact: <a href=\"mailto:press@artsy.net\">press@artsy.net</a>'\n html.should.containEql ",
"end": 1455,
"score": 0.9999136924743652,
"start": 1440,
"tag": "EMAIL",
"value": "press@artsy.net"
},
{
"context": "t press contact: <a href=\"mailt... | desktop/components/feedback_modal/tests/index.coffee | dblock/force | 1 | benv = require 'benv'
sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
openFeedbackModal = rewire '../index'
openFeedbackModal.__set__
views:
how_can_we_help: benv.requireWithJadeify require.resolve('../views/how_can_we_help'), ['template']
press: benv.requireWithJadeify require.resolve('../views/press'), ['template']
openMultiPageModal: openMultiPageModal = sinon.stub()
openFeedback: openFeedback = sinon.stub()
describe 'openFeedbackModal', ->
before (done) ->
benv.setup ->
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
Backbone.$ = $
$.support.transition = end: 'transitionend'
$.fn.emulateTransitionEnd = -> @trigger $.support.transition.end
done()
after ->
benv.teardown()
beforeEach ->
@modal = openFeedbackModal()
it 'renders the multiple choice menu', ->
$('.fm-multiple-choice > a')
.map -> $(this).text()
.get()
.should.eql [
"I have an auction-related question."
'I’m an artist interested in listing my work.'
'I’m an individual interested in selling artwork.'
'I have a press inquiry.'
'I have another question.'
]
it 'moves to the next step when "press" is chosen', ->
$('[data-answer="press"]').click()
html = $('body').html()
html.should.containEql 'For questions about press contact: <a href="mailto:press@artsy.net">press@artsy.net</a>'
html.should.containEql 'For pitches and story ideas contact: <a href="mailto:storyideas@artsy.net">storyideas@artsy.net</a>'
it 'opens the artist FAQ', (done) ->
openMultiPageModal.called.should.be.false()
$('[data-answer="artist"]').click()
@modal.view.on 'closed', ->
openMultiPageModal.called.should.be.true()
openMultiPageModal.args[0][0].should.equal 'artist-faqs'
done()
it 'opens the feedback form', (done) ->
openFeedback.called.should.be.false()
$('[data-answer="feedback"]').click()
@modal.view.on 'closed', ->
openFeedback.called.should.be.true()
done()
| 216743 | benv = require 'benv'
sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
openFeedbackModal = rewire '../index'
openFeedbackModal.__set__
views:
how_can_we_help: benv.requireWithJadeify require.resolve('../views/how_can_we_help'), ['template']
press: benv.requireWithJadeify require.resolve('../views/press'), ['template']
openMultiPageModal: openMultiPageModal = sinon.stub()
openFeedback: openFeedback = sinon.stub()
describe 'openFeedbackModal', ->
before (done) ->
benv.setup ->
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
Backbone.$ = $
$.support.transition = end: 'transitionend'
$.fn.emulateTransitionEnd = -> @trigger $.support.transition.end
done()
after ->
benv.teardown()
beforeEach ->
@modal = openFeedbackModal()
it 'renders the multiple choice menu', ->
$('.fm-multiple-choice > a')
.map -> $(this).text()
.get()
.should.eql [
"I have an auction-related question."
'I’m an artist interested in listing my work.'
'I’m an individual interested in selling artwork.'
'I have a press inquiry.'
'I have another question.'
]
it 'moves to the next step when "press" is chosen', ->
$('[data-answer="press"]').click()
html = $('body').html()
html.should.containEql 'For questions about press contact: <a href="mailto:<EMAIL>"><EMAIL></a>'
html.should.containEql 'For pitches and story ideas contact: <a href="mailto:<EMAIL>"><EMAIL></a>'
it 'opens the artist FAQ', (done) ->
openMultiPageModal.called.should.be.false()
$('[data-answer="artist"]').click()
@modal.view.on 'closed', ->
openMultiPageModal.called.should.be.true()
openMultiPageModal.args[0][0].should.equal 'artist-faqs'
done()
it 'opens the feedback form', (done) ->
openFeedback.called.should.be.false()
$('[data-answer="feedback"]').click()
@modal.view.on 'closed', ->
openFeedback.called.should.be.true()
done()
| true | benv = require 'benv'
sinon = require 'sinon'
rewire = require 'rewire'
Backbone = require 'backbone'
openFeedbackModal = rewire '../index'
openFeedbackModal.__set__
views:
how_can_we_help: benv.requireWithJadeify require.resolve('../views/how_can_we_help'), ['template']
press: benv.requireWithJadeify require.resolve('../views/press'), ['template']
openMultiPageModal: openMultiPageModal = sinon.stub()
openFeedback: openFeedback = sinon.stub()
describe 'openFeedbackModal', ->
before (done) ->
benv.setup ->
benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery')
Backbone.$ = $
$.support.transition = end: 'transitionend'
$.fn.emulateTransitionEnd = -> @trigger $.support.transition.end
done()
after ->
benv.teardown()
beforeEach ->
@modal = openFeedbackModal()
it 'renders the multiple choice menu', ->
$('.fm-multiple-choice > a')
.map -> $(this).text()
.get()
.should.eql [
"I have an auction-related question."
'I’m an artist interested in listing my work.'
'I’m an individual interested in selling artwork.'
'I have a press inquiry.'
'I have another question.'
]
it 'moves to the next step when "press" is chosen', ->
$('[data-answer="press"]').click()
html = $('body').html()
html.should.containEql 'For questions about press contact: <a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
html.should.containEql 'For pitches and story ideas contact: <a href="mailto:PI:EMAIL:<EMAIL>END_PI">PI:EMAIL:<EMAIL>END_PI</a>'
it 'opens the artist FAQ', (done) ->
openMultiPageModal.called.should.be.false()
$('[data-answer="artist"]').click()
@modal.view.on 'closed', ->
openMultiPageModal.called.should.be.true()
openMultiPageModal.args[0][0].should.equal 'artist-faqs'
done()
it 'opens the feedback form', (done) ->
openFeedback.called.should.be.false()
$('[data-answer="feedback"]').click()
@modal.view.on 'closed', ->
openFeedback.called.should.be.true()
done()
|
[
{
"context": "###\n turing-machine.coffee\n Fionan Haralddottir\n Spring 2015\n This program is published under t",
"end": 49,
"score": 0.9998816847801208,
"start": 30,
"tag": "NAME",
"value": "Fionan Haralddottir"
}
] | src/turing-machine.coffee | Lokidottir/coffeescript-turing-machine | 0 | ###
turing-machine.coffee
Fionan Haralddottir
Spring 2015
This program is published under the MIT licence
###
{isHaltingState} = require "./turing-program"
MOVE = {
GRADUAL: 0
INSTANT: 1
}
DECISION = {
WRITE: 0
MOVE: 1
GOTO: 2
}
class TuringMachine
program: null # Program the turing machine is running
statenum: 0 # The number of the state that the turning machine is executing
decisionState: DECISION.WRITE # The Decision state of the turing machine (write/move/goto)
symbolRead: 0 # The decsition mode of the turing machine ()
tapeIndex: 0 # The index of the turing machine's head on the tape is acting on
halted: false # If the machine is at a halting state, this is true
moveMode: MOVE.GRADUAL # The movement state of the machine
inMotion: false # Is the machine in motion
movesMade: 0 # The number of moves made
constructor: (@program) ->
step: (tape, doOutput = false, log = console.log) ->
if @halted or isHaltingState(@statenum) then return
switch @decisionState
when DECISION.WRITE
@symbolRead = tape.read(@tapeIndex)
tape.write(@tapeIndex, @program.getDecision(@).write)
@decisionState = DECISION.MOVE
when DECISION.MOVE
if @moveMode == MOVE.INSTANT
@tapeIndex += parseInt(@program.getDecision(@).move)
@decisionState = DECISION.GOTO
else
movesNeeded = Math.abs(@program.getDecision(@).move)
if movesNeeded > 0
@tapeIndex += parseInt(@program.getDecision(@).move/movesNeeded)
@movesMade++
if @movesMade > movesNeeded
@movesMade = 0
@decisionState = DECISION.GOTO
when DECISION.GOTO
@statenum = @program.getDecision(@).goto
@halted = isHaltingState(@statenum)
@decisionState = DECISION.WRITE
log("""
symbol: #{@symbolRead}
decision: #{@decisionState}
statenum: #{@statenum}
moves: #{@movesMade}
index: #{@tapeIndex}
""") if doOutput
@decisionState
superstep: (tape, doOutput = false, log = console.log) ->
if @halted then return
else if @decisionState == DECISION.WITE
@step(tape, doOutput, log)
@superstep(tape, doOutput, log)
else
@step(tape, doOutput, log) while not halted and @decisionState != DECISION.WRITE
return
module.exports = {TuringMachine}
| 188790 | ###
turing-machine.coffee
<NAME>
Spring 2015
This program is published under the MIT licence
###
{isHaltingState} = require "./turing-program"
MOVE = {
GRADUAL: 0
INSTANT: 1
}
DECISION = {
WRITE: 0
MOVE: 1
GOTO: 2
}
class TuringMachine
program: null # Program the turing machine is running
statenum: 0 # The number of the state that the turning machine is executing
decisionState: DECISION.WRITE # The Decision state of the turing machine (write/move/goto)
symbolRead: 0 # The decsition mode of the turing machine ()
tapeIndex: 0 # The index of the turing machine's head on the tape is acting on
halted: false # If the machine is at a halting state, this is true
moveMode: MOVE.GRADUAL # The movement state of the machine
inMotion: false # Is the machine in motion
movesMade: 0 # The number of moves made
constructor: (@program) ->
step: (tape, doOutput = false, log = console.log) ->
if @halted or isHaltingState(@statenum) then return
switch @decisionState
when DECISION.WRITE
@symbolRead = tape.read(@tapeIndex)
tape.write(@tapeIndex, @program.getDecision(@).write)
@decisionState = DECISION.MOVE
when DECISION.MOVE
if @moveMode == MOVE.INSTANT
@tapeIndex += parseInt(@program.getDecision(@).move)
@decisionState = DECISION.GOTO
else
movesNeeded = Math.abs(@program.getDecision(@).move)
if movesNeeded > 0
@tapeIndex += parseInt(@program.getDecision(@).move/movesNeeded)
@movesMade++
if @movesMade > movesNeeded
@movesMade = 0
@decisionState = DECISION.GOTO
when DECISION.GOTO
@statenum = @program.getDecision(@).goto
@halted = isHaltingState(@statenum)
@decisionState = DECISION.WRITE
log("""
symbol: #{@symbolRead}
decision: #{@decisionState}
statenum: #{@statenum}
moves: #{@movesMade}
index: #{@tapeIndex}
""") if doOutput
@decisionState
superstep: (tape, doOutput = false, log = console.log) ->
if @halted then return
else if @decisionState == DECISION.WITE
@step(tape, doOutput, log)
@superstep(tape, doOutput, log)
else
@step(tape, doOutput, log) while not halted and @decisionState != DECISION.WRITE
return
module.exports = {TuringMachine}
| true | ###
turing-machine.coffee
PI:NAME:<NAME>END_PI
Spring 2015
This program is published under the MIT licence
###
{isHaltingState} = require "./turing-program"
MOVE = {
GRADUAL: 0
INSTANT: 1
}
DECISION = {
WRITE: 0
MOVE: 1
GOTO: 2
}
class TuringMachine
program: null # Program the turing machine is running
statenum: 0 # The number of the state that the turning machine is executing
decisionState: DECISION.WRITE # The Decision state of the turing machine (write/move/goto)
symbolRead: 0 # The decsition mode of the turing machine ()
tapeIndex: 0 # The index of the turing machine's head on the tape is acting on
halted: false # If the machine is at a halting state, this is true
moveMode: MOVE.GRADUAL # The movement state of the machine
inMotion: false # Is the machine in motion
movesMade: 0 # The number of moves made
constructor: (@program) ->
step: (tape, doOutput = false, log = console.log) ->
if @halted or isHaltingState(@statenum) then return
switch @decisionState
when DECISION.WRITE
@symbolRead = tape.read(@tapeIndex)
tape.write(@tapeIndex, @program.getDecision(@).write)
@decisionState = DECISION.MOVE
when DECISION.MOVE
if @moveMode == MOVE.INSTANT
@tapeIndex += parseInt(@program.getDecision(@).move)
@decisionState = DECISION.GOTO
else
movesNeeded = Math.abs(@program.getDecision(@).move)
if movesNeeded > 0
@tapeIndex += parseInt(@program.getDecision(@).move/movesNeeded)
@movesMade++
if @movesMade > movesNeeded
@movesMade = 0
@decisionState = DECISION.GOTO
when DECISION.GOTO
@statenum = @program.getDecision(@).goto
@halted = isHaltingState(@statenum)
@decisionState = DECISION.WRITE
log("""
symbol: #{@symbolRead}
decision: #{@decisionState}
statenum: #{@statenum}
moves: #{@movesMade}
index: #{@tapeIndex}
""") if doOutput
@decisionState
superstep: (tape, doOutput = false, log = console.log) ->
if @halted then return
else if @decisionState == DECISION.WITE
@step(tape, doOutput, log)
@superstep(tape, doOutput, log)
else
@step(tape, doOutput, log) while not halted and @decisionState != DECISION.WRITE
return
module.exports = {TuringMachine}
|
[
{
"context": "# Copyright (c) 2015 naymspace software (Dennis Nissen)\n#\n# Licensed under the Apache License, Version 2",
"end": 54,
"score": 0.9998658299446106,
"start": 41,
"tag": "NAME",
"value": "Dennis Nissen"
}
] | src/app/components/services/NotificationService.coffee | ogumi/client | 0 | # Copyright (c) 2015 naymspace software (Dennis Nissen)
#
# Licensed 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.
angular.module "webClient"
.service 'NotificationService', ($rootScope, $translate) ->
@flash = (opts) ->
opts = _.extend
additionalInfo: ''
info: ''
head: ''
type: 'success'
, opts
$translate([opts.head, opts.info, opts.link]).then (t) ->
info = t[opts.info] + opts.additionalInfo
if opts.link?
info += '<br/><a href="#/'+opts.linkUrl+'">'+t[opts.link]+'</a>'
$rootScope.$emit 'showAlert',
type: opts.type
head: t[opts.head]
info: info
if opts.callback?
setTimeout opts.callback, 1500
return
@error = (opts) ->
opts = _.extend
additionalInfo: ''
info: 'messages.server_error'
head: 'messages.error_head'
type: 'danger'
, opts
@flash opts
return
return
| 112814 | # Copyright (c) 2015 naymspace software (<NAME>)
#
# Licensed 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.
angular.module "webClient"
.service 'NotificationService', ($rootScope, $translate) ->
@flash = (opts) ->
opts = _.extend
additionalInfo: ''
info: ''
head: ''
type: 'success'
, opts
$translate([opts.head, opts.info, opts.link]).then (t) ->
info = t[opts.info] + opts.additionalInfo
if opts.link?
info += '<br/><a href="#/'+opts.linkUrl+'">'+t[opts.link]+'</a>'
$rootScope.$emit 'showAlert',
type: opts.type
head: t[opts.head]
info: info
if opts.callback?
setTimeout opts.callback, 1500
return
@error = (opts) ->
opts = _.extend
additionalInfo: ''
info: 'messages.server_error'
head: 'messages.error_head'
type: 'danger'
, opts
@flash opts
return
return
| true | # Copyright (c) 2015 naymspace software (PI:NAME:<NAME>END_PI)
#
# Licensed 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.
angular.module "webClient"
.service 'NotificationService', ($rootScope, $translate) ->
@flash = (opts) ->
opts = _.extend
additionalInfo: ''
info: ''
head: ''
type: 'success'
, opts
$translate([opts.head, opts.info, opts.link]).then (t) ->
info = t[opts.info] + opts.additionalInfo
if opts.link?
info += '<br/><a href="#/'+opts.linkUrl+'">'+t[opts.link]+'</a>'
$rootScope.$emit 'showAlert',
type: opts.type
head: t[opts.head]
info: info
if opts.callback?
setTimeout opts.callback, 1500
return
@error = (opts) ->
opts = _.extend
additionalInfo: ''
info: 'messages.server_error'
head: 'messages.error_head'
type: 'danger'
, opts
@flash opts
return
return
|
[
{
"context": "/src/index'\n\ndo =>\n for ip_port in [\n \"[2001:0db8::0001]:422\"\n \"[2001:0db8::0001]\"\n \"[2000:0000:000",
"end": 150,
"score": 0.8079261183738708,
"start": 141,
"tag": "IP_ADDRESS",
"value": "db8::0001"
},
{
"context": "port in [\n \"[2001:0db8::0001... | test/index.coffee | rmw-lib/ip_port_bin | 0 | #!/usr/bin/env coffee
import {ip_port_str, str_ip_port, ip_port_bin, bin_ip_port} from '../src/index'
do =>
for ip_port in [
"[2001:0db8::0001]:422"
"[2001:0db8::0001]"
"[2000:0000:0000:0000:0001:2345:6789:abcd]:61232"
"127.0.0.1:80"
"245.14.12.232"
]
[ip, port] = str_ip_port ip_port
bin = ip_port_bin(ip, port)
console.log ip , port or '', "=", ip_port_str ...bin_ip_port(bin)
console.log ip_port.length, ">", bin.length+"\n"
| 111335 | #!/usr/bin/env coffee
import {ip_port_str, str_ip_port, ip_port_bin, bin_ip_port} from '../src/index'
do =>
for ip_port in [
"[2001:0fc00:e968:6179::de52:7100]:422"
"[2001:0db8::0001]"
"[2000:0000:0000:0000:0001:2345:6789:abcd]:61232"
"127.0.0.1:80"
"245.14.12.232"
]
[ip, port] = str_ip_port ip_port
bin = ip_port_bin(ip, port)
console.log ip , port or '', "=", ip_port_str ...bin_ip_port(bin)
console.log ip_port.length, ">", bin.length+"\n"
| true | #!/usr/bin/env coffee
import {ip_port_str, str_ip_port, ip_port_bin, bin_ip_port} from '../src/index'
do =>
for ip_port in [
"[2001:0PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI]:422"
"[2001:0db8::0001]"
"[2000:0000:0000:0000:0001:2345:6789:abcd]:61232"
"127.0.0.1:80"
"245.14.12.232"
]
[ip, port] = str_ip_port ip_port
bin = ip_port_bin(ip, port)
console.log ip , port or '', "=", ip_port_str ...bin_ip_port(bin)
console.log ip_port.length, ">", bin.length+"\n"
|
[
{
"context": "c, GitHubSearchCode\n) ->\n $scope.spec = { user: '3scale', repo: 'no500-brainslug' }\n\n $scope.search = ->",
"end": 2144,
"score": 0.9994438886642456,
"start": 2138,
"tag": "USERNAME",
"value": "3scale"
},
{
"context": "eSpec, $location, GitHub\n) ->\n\n GitHub.use... | app/assets/javascripts/controllers/middleware_specs.coffee | rrampage/monitor | 114 | angular.module('slug.middleware_specs', ['ui.router'])
.config ($stateProvider) ->
$stateProvider
.state 'specs',
abstract: true
url: '/middlewares'
views:
"":
controller: 'MiddlewareSpecCtrl'
template: '<ui-view name="main"></ui-view>'
.state 'specs.list',
url: '/'
views:
main:
templateUrl: '/middleware_specs/index.html'
controller: 'MiddlewareSpecsListCtrl'
.state 'spec.new',
parent: 'specs'
url: '/new'
views:
main:
templateUrl: '/middleware_specs/new.html'
controller: 'MiddlewareSpecNewCtrl'
.state 'spec',
parent: 'specs'
url: '/:middlewareSpecId'
views:
main:
templateUrl: '/middleware_specs/show.html'
controller: 'MiddlewareSpecShowCtrl'
.state 'spec.share',
parent: 'spec.new'
url: '/:middlewareUuid'
views:
"main@specs":
templateUrl: '/middleware_specs/new.html'
controller: 'MiddlewareSpecNewFromCtrl'
.state 'spec.edit',
parent: 'spec'
url: '/edit'
views:
"main@specs":
templateUrl: '/middleware_specs/edit.html'
controller: 'MiddlewareSpecEditCtrl'
.state 'spec.github',
parent: 'spec'
url: '/github'
views:
"main@specs":
templateUrl: '/middleware_specs/github.html'
controller: 'MiddlewareSpecGithubCtrl'
.factory 'DefaultMiddlewareCode', ->
"""
return function(request, next_middleware)
-- every middleware has to call next_middleware,
-- so others have chance to process the request/response
-- deal with request
local response = next_middleware()
send.notification({msg=response.status, level='info'})
-- deal with response
return response
end
"""
.factory 'MiddlewareSpec', ($resource) ->
$resource '/api/middleware_specs/:id', id: '@_id'
.controller 'MiddlewareSubscriptionCtrl', (
$scope, GitHubSpec, GitHubSearchCode
) ->
$scope.spec = { user: '3scale', repo: 'no500-brainslug' }
$scope.search = ->
query =
[$scope.query,
'language:json', 'in:file', 'path:brainslug.json'].join(' ')
GitHubSearchCode.get q: query, (results) ->
$scope.results = for item in results.items
GitHubSpec.get(
user: item.repository.owner.login, repo: item.repository.name
)
$scope.load = ->
$scope.results = []
GitHubSpec.get $scope.spec, (result) -> $scope.results.push(result)
GitHubSpec.get $scope.spec, (result) -> $scope.results.push(result)
GitHubSpec.get $scope.spec, (result) -> $scope.results.push(result)
.controller 'MiddlewareSpecCtrl', ($scope, $state, $stateParams, flash) ->
$scope.save = (spec) ->
spec.$save ->
flash.success = "Middleware Spec #{spec.name} saved"
$state.transitionTo('specs.list')
.controller 'MiddlewareSpecsListCtrl', (
$scope, MiddlewareSpec, $location, GitHub
) ->
GitHub.user ||= 'mikz'
GitHub.token.set('60b6f9b60278b86a843d34f52558df7f016f0399')
$scope.github = GitHub
$scope.specs = MiddlewareSpec.query()
# extract both these to directives
$scope.badges = (spec) ->
spec.badges ||= [
{ icon: 'icon-hdd', name: 'local' }
{ icon: 'icon-github', name: 'GitHub' }
{ icon: 'icon-code-fork', name: 'fork' }
{ icon: 'icon-code-unlock', name: 'public' }
]
$scope.rating = (spec) ->
return spec.rating if spec.rating
rating = Math.ceil(Math.random() * 5)
stars = []
for i in [1 .. rating] by 1
stars.push({ icon: 'icon-heart' })
for i in [rating + 1 .. 5] by 1
stars.push({icon: 'icon-heart-empty'})
spec.rating = stars
.controller 'MiddlewareSpecNewCtrl', ($scope, MiddlewareSpec) ->
$scope.spec = new MiddlewareSpec()
.controller 'MiddlewareSpecShowCtrl', (
$scope, $stateParams, MiddlewareSpec, flash
) ->
$scope.spec = MiddlewareSpec.get(id: $stateParams.middlewareSpecId)
$scope.save = (spec = $scope.spec) ->
spec.$save ->
flash.success = "Middleware Spec #{spec.name} saved"
.controller 'MiddlewareSpecEditCtrl', ($scope, $stateParams, MiddlewareSpec) ->
$scope.spec = MiddlewareSpec.get(id: $stateParams.middlewareSpecId)
$scope.spec.author ||= {}
.controller 'MiddlewareSpecNewFromCtrl', (
$scope, $stateParams, Middleware, MiddlewareSpec
) ->
$scope.spec ||= new MiddlewareSpec()
$scope.middleware =
Middleware.get uuid: $stateParams.middlewareUuid, (middleware) ->
attributes =
code: middleware.code,
name: middleware.name,
description: middleware.description
angular.extend($scope.spec, attributes)
.controller 'MiddlewareSpecGithubCtrl', (
$scope, $stateParams, MiddlewareSpec, flash, GitHub, GitHubIntegrator,
GitHubMessages, GitHubToken, GitHubValidator
) ->
# FIXME: this does not smell bad, this stinks!
$scope.spec ||= $scope.$parent.spec
github = $scope.github = angular.copy($scope.spec?.github) || {}
github.owner ||= GitHub.user
github.repo ||= GitHub.repoSuggestion($scope.spec)
GitHubToken.set('60b6f9b60278b86a843d34f52558df7f016f0399')
$scope.save = (spec = $scope.spec) ->
spec.github = github
spec.$save ->
flash.success = "Middleware GitHub integration saved"
$scope.form.$setPristine()
$scope.validate = ->
$scope.messages = new GitHubMessages($scope.spec, github)
$scope.valid = false
success = ->
$scope.valid = true
failure = ->
$scope
GitHubValidator($scope.messages).then(success, failure)
$scope.setUpIntegration = ->
success = ->
console.log('success')
failure = ->
console.log('failure')
GitHubIntegrator($scope.messages).then(success, failure)
#Aight Michal, from this line till the end, if it's hurting your eyes too much,
# just get rif of it :D
.controller 'MiddlewareSpecWizardCtrl', (
$scope, $stateParams, $location, Middleware, DefaultMiddlewareCode,
MiddlewareSpec, flash, $state
) ->
$scope.spec = new MiddlewareSpec(code: DefaultMiddlewareCode)
if uuid = $stateParams.middlewareUuid?
$scope.middleware = Middleware.get uuid: uuid, (middleware) ->
attributes = _(middleware).pick('code', 'name', 'description')
angular.extend($scope.spec, attributes)
$scope.current_step ||= 0
$scope.steps = ["General Info", "Author" , "Middleware"]
$scope.next = ->
if step = nextStep()
template(step)
else
$scope.save()
$scope.goTo = (index) ->
template(index + 1)
nextStep = () ->
steps = $scope.steps.length
current = $scope.current_step
if current < steps
$scope.current_step = ++current
template = (step) ->
direction = $scope.current_step < step
[enter, leave] = if direction
[ 'fadeInLeftBig', 'fadeOutRightBig' ]
else
[ 'fadeInRightBig', 'fadeOutLeftBig' ]
$scope.slideAnimation =
enter: "animated enter #{enter}",
leave: "animated leave #{leave}"
$scope.last_step = step == $scope.steps.length
$scope.current_template = "/middleware_specs/wizard/#{step}.html"
$scope.next()
$scope.stepState = (index) ->
current = $scope.current_step
step = ++index
if step > current
'future'
else if step == current
'current'
else if step < current
'past'
$scope.save = (spec = $scope.spec) ->
spec.$save ->
flash.success = "Middleware Spec #{spec.name} saved"
$state.transitionTo('specs.list')
| 192693 | angular.module('slug.middleware_specs', ['ui.router'])
.config ($stateProvider) ->
$stateProvider
.state 'specs',
abstract: true
url: '/middlewares'
views:
"":
controller: 'MiddlewareSpecCtrl'
template: '<ui-view name="main"></ui-view>'
.state 'specs.list',
url: '/'
views:
main:
templateUrl: '/middleware_specs/index.html'
controller: 'MiddlewareSpecsListCtrl'
.state 'spec.new',
parent: 'specs'
url: '/new'
views:
main:
templateUrl: '/middleware_specs/new.html'
controller: 'MiddlewareSpecNewCtrl'
.state 'spec',
parent: 'specs'
url: '/:middlewareSpecId'
views:
main:
templateUrl: '/middleware_specs/show.html'
controller: 'MiddlewareSpecShowCtrl'
.state 'spec.share',
parent: 'spec.new'
url: '/:middlewareUuid'
views:
"main@specs":
templateUrl: '/middleware_specs/new.html'
controller: 'MiddlewareSpecNewFromCtrl'
.state 'spec.edit',
parent: 'spec'
url: '/edit'
views:
"main@specs":
templateUrl: '/middleware_specs/edit.html'
controller: 'MiddlewareSpecEditCtrl'
.state 'spec.github',
parent: 'spec'
url: '/github'
views:
"main@specs":
templateUrl: '/middleware_specs/github.html'
controller: 'MiddlewareSpecGithubCtrl'
.factory 'DefaultMiddlewareCode', ->
"""
return function(request, next_middleware)
-- every middleware has to call next_middleware,
-- so others have chance to process the request/response
-- deal with request
local response = next_middleware()
send.notification({msg=response.status, level='info'})
-- deal with response
return response
end
"""
.factory 'MiddlewareSpec', ($resource) ->
$resource '/api/middleware_specs/:id', id: '@_id'
.controller 'MiddlewareSubscriptionCtrl', (
$scope, GitHubSpec, GitHubSearchCode
) ->
$scope.spec = { user: '3scale', repo: 'no500-brainslug' }
$scope.search = ->
query =
[$scope.query,
'language:json', 'in:file', 'path:brainslug.json'].join(' ')
GitHubSearchCode.get q: query, (results) ->
$scope.results = for item in results.items
GitHubSpec.get(
user: item.repository.owner.login, repo: item.repository.name
)
$scope.load = ->
$scope.results = []
GitHubSpec.get $scope.spec, (result) -> $scope.results.push(result)
GitHubSpec.get $scope.spec, (result) -> $scope.results.push(result)
GitHubSpec.get $scope.spec, (result) -> $scope.results.push(result)
.controller 'MiddlewareSpecCtrl', ($scope, $state, $stateParams, flash) ->
$scope.save = (spec) ->
spec.$save ->
flash.success = "Middleware Spec #{spec.name} saved"
$state.transitionTo('specs.list')
.controller 'MiddlewareSpecsListCtrl', (
$scope, MiddlewareSpec, $location, GitHub
) ->
GitHub.user ||= 'mikz'
GitHub.token.set('<KEY>')
$scope.github = GitHub
$scope.specs = MiddlewareSpec.query()
# extract both these to directives
$scope.badges = (spec) ->
spec.badges ||= [
{ icon: 'icon-hdd', name: 'local' }
{ icon: 'icon-github', name: 'GitHub' }
{ icon: 'icon-code-fork', name: 'fork' }
{ icon: 'icon-code-unlock', name: 'public' }
]
$scope.rating = (spec) ->
return spec.rating if spec.rating
rating = Math.ceil(Math.random() * 5)
stars = []
for i in [1 .. rating] by 1
stars.push({ icon: 'icon-heart' })
for i in [rating + 1 .. 5] by 1
stars.push({icon: 'icon-heart-empty'})
spec.rating = stars
.controller 'MiddlewareSpecNewCtrl', ($scope, MiddlewareSpec) ->
$scope.spec = new MiddlewareSpec()
.controller 'MiddlewareSpecShowCtrl', (
$scope, $stateParams, MiddlewareSpec, flash
) ->
$scope.spec = MiddlewareSpec.get(id: $stateParams.middlewareSpecId)
$scope.save = (spec = $scope.spec) ->
spec.$save ->
flash.success = "Middleware Spec #{spec.name} saved"
.controller 'MiddlewareSpecEditCtrl', ($scope, $stateParams, MiddlewareSpec) ->
$scope.spec = MiddlewareSpec.get(id: $stateParams.middlewareSpecId)
$scope.spec.author ||= {}
.controller 'MiddlewareSpecNewFromCtrl', (
$scope, $stateParams, Middleware, MiddlewareSpec
) ->
$scope.spec ||= new MiddlewareSpec()
$scope.middleware =
Middleware.get uuid: $stateParams.middlewareUuid, (middleware) ->
attributes =
code: middleware.code,
name: middleware.name,
description: middleware.description
angular.extend($scope.spec, attributes)
.controller 'MiddlewareSpecGithubCtrl', (
$scope, $stateParams, MiddlewareSpec, flash, GitHub, GitHubIntegrator,
GitHubMessages, GitHubToken, GitHubValidator
) ->
# FIXME: this does not smell bad, this stinks!
$scope.spec ||= $scope.$parent.spec
github = $scope.github = angular.copy($scope.spec?.github) || {}
github.owner ||= GitHub.user
github.repo ||= GitHub.repoSuggestion($scope.spec)
GitHubToken.set('<KEY>')
$scope.save = (spec = $scope.spec) ->
spec.github = github
spec.$save ->
flash.success = "Middleware GitHub integration saved"
$scope.form.$setPristine()
$scope.validate = ->
$scope.messages = new GitHubMessages($scope.spec, github)
$scope.valid = false
success = ->
$scope.valid = true
failure = ->
$scope
GitHubValidator($scope.messages).then(success, failure)
$scope.setUpIntegration = ->
success = ->
console.log('success')
failure = ->
console.log('failure')
GitHubIntegrator($scope.messages).then(success, failure)
#<NAME>, from this line till the end, if it's hurting your eyes too much,
# just get rif of it :D
.controller 'MiddlewareSpecWizardCtrl', (
$scope, $stateParams, $location, Middleware, DefaultMiddlewareCode,
MiddlewareSpec, flash, $state
) ->
$scope.spec = new MiddlewareSpec(code: DefaultMiddlewareCode)
if uuid = $stateParams.middlewareUuid?
$scope.middleware = Middleware.get uuid: uuid, (middleware) ->
attributes = _(middleware).pick('code', 'name', 'description')
angular.extend($scope.spec, attributes)
$scope.current_step ||= 0
$scope.steps = ["General Info", "Author" , "Middleware"]
$scope.next = ->
if step = nextStep()
template(step)
else
$scope.save()
$scope.goTo = (index) ->
template(index + 1)
nextStep = () ->
steps = $scope.steps.length
current = $scope.current_step
if current < steps
$scope.current_step = ++current
template = (step) ->
direction = $scope.current_step < step
[enter, leave] = if direction
[ 'fadeInLeftBig', 'fadeOutRightBig' ]
else
[ 'fadeInRightBig', 'fadeOutLeftBig' ]
$scope.slideAnimation =
enter: "animated enter #{enter}",
leave: "animated leave #{leave}"
$scope.last_step = step == $scope.steps.length
$scope.current_template = "/middleware_specs/wizard/#{step}.html"
$scope.next()
$scope.stepState = (index) ->
current = $scope.current_step
step = ++index
if step > current
'future'
else if step == current
'current'
else if step < current
'past'
$scope.save = (spec = $scope.spec) ->
spec.$save ->
flash.success = "Middleware Spec #{spec.name} saved"
$state.transitionTo('specs.list')
| true | angular.module('slug.middleware_specs', ['ui.router'])
.config ($stateProvider) ->
$stateProvider
.state 'specs',
abstract: true
url: '/middlewares'
views:
"":
controller: 'MiddlewareSpecCtrl'
template: '<ui-view name="main"></ui-view>'
.state 'specs.list',
url: '/'
views:
main:
templateUrl: '/middleware_specs/index.html'
controller: 'MiddlewareSpecsListCtrl'
.state 'spec.new',
parent: 'specs'
url: '/new'
views:
main:
templateUrl: '/middleware_specs/new.html'
controller: 'MiddlewareSpecNewCtrl'
.state 'spec',
parent: 'specs'
url: '/:middlewareSpecId'
views:
main:
templateUrl: '/middleware_specs/show.html'
controller: 'MiddlewareSpecShowCtrl'
.state 'spec.share',
parent: 'spec.new'
url: '/:middlewareUuid'
views:
"main@specs":
templateUrl: '/middleware_specs/new.html'
controller: 'MiddlewareSpecNewFromCtrl'
.state 'spec.edit',
parent: 'spec'
url: '/edit'
views:
"main@specs":
templateUrl: '/middleware_specs/edit.html'
controller: 'MiddlewareSpecEditCtrl'
.state 'spec.github',
parent: 'spec'
url: '/github'
views:
"main@specs":
templateUrl: '/middleware_specs/github.html'
controller: 'MiddlewareSpecGithubCtrl'
.factory 'DefaultMiddlewareCode', ->
"""
return function(request, next_middleware)
-- every middleware has to call next_middleware,
-- so others have chance to process the request/response
-- deal with request
local response = next_middleware()
send.notification({msg=response.status, level='info'})
-- deal with response
return response
end
"""
.factory 'MiddlewareSpec', ($resource) ->
$resource '/api/middleware_specs/:id', id: '@_id'
.controller 'MiddlewareSubscriptionCtrl', (
$scope, GitHubSpec, GitHubSearchCode
) ->
$scope.spec = { user: '3scale', repo: 'no500-brainslug' }
$scope.search = ->
query =
[$scope.query,
'language:json', 'in:file', 'path:brainslug.json'].join(' ')
GitHubSearchCode.get q: query, (results) ->
$scope.results = for item in results.items
GitHubSpec.get(
user: item.repository.owner.login, repo: item.repository.name
)
$scope.load = ->
$scope.results = []
GitHubSpec.get $scope.spec, (result) -> $scope.results.push(result)
GitHubSpec.get $scope.spec, (result) -> $scope.results.push(result)
GitHubSpec.get $scope.spec, (result) -> $scope.results.push(result)
.controller 'MiddlewareSpecCtrl', ($scope, $state, $stateParams, flash) ->
$scope.save = (spec) ->
spec.$save ->
flash.success = "Middleware Spec #{spec.name} saved"
$state.transitionTo('specs.list')
.controller 'MiddlewareSpecsListCtrl', (
$scope, MiddlewareSpec, $location, GitHub
) ->
GitHub.user ||= 'mikz'
GitHub.token.set('PI:KEY:<KEY>END_PI')
$scope.github = GitHub
$scope.specs = MiddlewareSpec.query()
# extract both these to directives
$scope.badges = (spec) ->
spec.badges ||= [
{ icon: 'icon-hdd', name: 'local' }
{ icon: 'icon-github', name: 'GitHub' }
{ icon: 'icon-code-fork', name: 'fork' }
{ icon: 'icon-code-unlock', name: 'public' }
]
$scope.rating = (spec) ->
return spec.rating if spec.rating
rating = Math.ceil(Math.random() * 5)
stars = []
for i in [1 .. rating] by 1
stars.push({ icon: 'icon-heart' })
for i in [rating + 1 .. 5] by 1
stars.push({icon: 'icon-heart-empty'})
spec.rating = stars
.controller 'MiddlewareSpecNewCtrl', ($scope, MiddlewareSpec) ->
$scope.spec = new MiddlewareSpec()
.controller 'MiddlewareSpecShowCtrl', (
$scope, $stateParams, MiddlewareSpec, flash
) ->
$scope.spec = MiddlewareSpec.get(id: $stateParams.middlewareSpecId)
$scope.save = (spec = $scope.spec) ->
spec.$save ->
flash.success = "Middleware Spec #{spec.name} saved"
.controller 'MiddlewareSpecEditCtrl', ($scope, $stateParams, MiddlewareSpec) ->
$scope.spec = MiddlewareSpec.get(id: $stateParams.middlewareSpecId)
$scope.spec.author ||= {}
.controller 'MiddlewareSpecNewFromCtrl', (
$scope, $stateParams, Middleware, MiddlewareSpec
) ->
$scope.spec ||= new MiddlewareSpec()
$scope.middleware =
Middleware.get uuid: $stateParams.middlewareUuid, (middleware) ->
attributes =
code: middleware.code,
name: middleware.name,
description: middleware.description
angular.extend($scope.spec, attributes)
.controller 'MiddlewareSpecGithubCtrl', (
$scope, $stateParams, MiddlewareSpec, flash, GitHub, GitHubIntegrator,
GitHubMessages, GitHubToken, GitHubValidator
) ->
# FIXME: this does not smell bad, this stinks!
$scope.spec ||= $scope.$parent.spec
github = $scope.github = angular.copy($scope.spec?.github) || {}
github.owner ||= GitHub.user
github.repo ||= GitHub.repoSuggestion($scope.spec)
GitHubToken.set('PI:KEY:<KEY>END_PI')
$scope.save = (spec = $scope.spec) ->
spec.github = github
spec.$save ->
flash.success = "Middleware GitHub integration saved"
$scope.form.$setPristine()
$scope.validate = ->
$scope.messages = new GitHubMessages($scope.spec, github)
$scope.valid = false
success = ->
$scope.valid = true
failure = ->
$scope
GitHubValidator($scope.messages).then(success, failure)
$scope.setUpIntegration = ->
success = ->
console.log('success')
failure = ->
console.log('failure')
GitHubIntegrator($scope.messages).then(success, failure)
#PI:NAME:<NAME>END_PI, from this line till the end, if it's hurting your eyes too much,
# just get rif of it :D
.controller 'MiddlewareSpecWizardCtrl', (
$scope, $stateParams, $location, Middleware, DefaultMiddlewareCode,
MiddlewareSpec, flash, $state
) ->
$scope.spec = new MiddlewareSpec(code: DefaultMiddlewareCode)
if uuid = $stateParams.middlewareUuid?
$scope.middleware = Middleware.get uuid: uuid, (middleware) ->
attributes = _(middleware).pick('code', 'name', 'description')
angular.extend($scope.spec, attributes)
$scope.current_step ||= 0
$scope.steps = ["General Info", "Author" , "Middleware"]
$scope.next = ->
if step = nextStep()
template(step)
else
$scope.save()
$scope.goTo = (index) ->
template(index + 1)
nextStep = () ->
steps = $scope.steps.length
current = $scope.current_step
if current < steps
$scope.current_step = ++current
template = (step) ->
direction = $scope.current_step < step
[enter, leave] = if direction
[ 'fadeInLeftBig', 'fadeOutRightBig' ]
else
[ 'fadeInRightBig', 'fadeOutLeftBig' ]
$scope.slideAnimation =
enter: "animated enter #{enter}",
leave: "animated leave #{leave}"
$scope.last_step = step == $scope.steps.length
$scope.current_template = "/middleware_specs/wizard/#{step}.html"
$scope.next()
$scope.stepState = (index) ->
current = $scope.current_step
step = ++index
if step > current
'future'
else if step == current
'current'
else if step < current
'past'
$scope.save = (spec = $scope.spec) ->
spec.$save ->
flash.success = "Middleware Spec #{spec.name} saved"
$state.transitionTo('specs.list')
|
[
{
"context": "#\n# user structure\n# {\n# name: 'liona',\n# created_at: ...,\n# updated_at: ...,\n# l",
"end": 39,
"score": 0.9966557621955872,
"start": 34,
"tag": "NAME",
"value": "liona"
},
{
"context": "eted_at: ...\n# }\n#\n\nclass UserRepository\n KEY = 'user-settings'\... | support/user_repository.coffee | lawsonjt/liona | 9 | #
# user structure
# {
# name: 'liona',
# created_at: ...,
# updated_at: ...,
# lang: 'Flanders',
# last_greeted_at: ...
# }
#
class UserRepository
KEY = 'user-settings'
constructor: (@brain) ->
@cache = []
@brain.on 'loaded', =>
braindata = brain.data._private[KEY]
@cache = braindata if braindata
find: (user) ->
@all().filter((u) -> u.name.toLowerCase() is user.toLowerCase())?[0]
save: (data, name) ->
data = {name: name} if !data?
data.updated_at = Date.now()
@cache = @all data.name
@cache.push data
@set @cache
data
findOrNew: (name) ->
@find(name) || @new(name)
new: (name) ->
name: name, created_at: Date.now()
remove: (name) ->
@set @all name
all: (without) ->
without && (@cache.filter (u) -> u.name.toLowerCase() isnt without.toLowerCase()) || @cache
set: (data) ->
@brain.set KEY, data
module.exports = UserRepository
| 219329 | #
# user structure
# {
# name: '<NAME>',
# created_at: ...,
# updated_at: ...,
# lang: 'Flanders',
# last_greeted_at: ...
# }
#
class UserRepository
KEY = '<KEY>'
constructor: (@brain) ->
@cache = []
@brain.on 'loaded', =>
braindata = brain.data._private[KEY]
@cache = braindata if braindata
find: (user) ->
@all().filter((u) -> u.name.toLowerCase() is user.toLowerCase())?[0]
save: (data, name) ->
data = {name: name} if !data?
data.updated_at = Date.now()
@cache = @all data.name
@cache.push data
@set @cache
data
findOrNew: (name) ->
@find(name) || @new(name)
new: (name) ->
name: name, created_at: Date.now()
remove: (name) ->
@set @all name
all: (without) ->
without && (@cache.filter (u) -> u.name.toLowerCase() isnt without.toLowerCase()) || @cache
set: (data) ->
@brain.set KEY, data
module.exports = UserRepository
| true | #
# user structure
# {
# name: 'PI:NAME:<NAME>END_PI',
# created_at: ...,
# updated_at: ...,
# lang: 'Flanders',
# last_greeted_at: ...
# }
#
class UserRepository
KEY = 'PI:KEY:<KEY>END_PI'
constructor: (@brain) ->
@cache = []
@brain.on 'loaded', =>
braindata = brain.data._private[KEY]
@cache = braindata if braindata
find: (user) ->
@all().filter((u) -> u.name.toLowerCase() is user.toLowerCase())?[0]
save: (data, name) ->
data = {name: name} if !data?
data.updated_at = Date.now()
@cache = @all data.name
@cache.push data
@set @cache
data
findOrNew: (name) ->
@find(name) || @new(name)
new: (name) ->
name: name, created_at: Date.now()
remove: (name) ->
@set @all name
all: (without) ->
without && (@cache.filter (u) -> u.name.toLowerCase() isnt without.toLowerCase()) || @cache
set: (data) ->
@brain.set KEY, data
module.exports = UserRepository
|
[
{
"context": "der.sendEmail.callsArgWith(1)\n\n\t\t\topts =\n\t\t\t\tto: \"bob@bob.com\"\n\t\t\t@EmailHandler.sendEmail \"welcome\", opts, =>\n\t",
"end": 860,
"score": 0.9999059438705444,
"start": 849,
"tag": "EMAIL",
"value": "bob@bob.com"
},
{
"context": "mail.callsArgWith(1, \"er... | test/UnitTests/coffee/Email/EmailHandlerTests.coffee | mickaobrien/web-sharelatex | 1 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Email/EmailHandler"
expect = require("chai").expect
describe "EmailHandler", ->
beforeEach ->
@settings =
email:{}
@EmailBuilder =
buildEmail:sinon.stub()
@EmailSender =
sendEmail:sinon.stub()
@EmailHandler = SandboxedModule.require modulePath, requires:
"./EmailBuilder":@EmailBuilder
"./EmailSender":@EmailSender
"settings-sharelatex":@settings
"logger-sharelatex": log:->
@html = "<html>hello</html>"
describe "send email", ->
it "should use the correct options", (done)->
@EmailBuilder.buildEmail.returns({html:@html})
@EmailSender.sendEmail.callsArgWith(1)
opts =
to: "bob@bob.com"
@EmailHandler.sendEmail "welcome", opts, =>
args = @EmailSender.sendEmail.args[0][0]
args.html.should.equal @html
done()
it "should return the erroor", (done)->
@EmailBuilder.buildEmail.returns({html:@html})
@EmailSender.sendEmail.callsArgWith(1, "error")
opts =
to: "bob@bob.com"
subject:"hello bob"
@EmailHandler.sendEmail "welcome", opts, (err)=>
err.should.equal "error"
done()
it "should not send an email if lifecycle is not enabled", (done)->
@settings.email.lifecycle = false
@EmailBuilder.buildEmail.returns({type:"lifecycle"})
@EmailHandler.sendEmail "welcome", {}, =>
@EmailSender.sendEmail.called.should.equal false
done()
it "should send an email if lifecycle is not enabled but the type is notification", (done)->
@settings.email.lifecycle = false
@EmailBuilder.buildEmail.returns({type:"notification"})
@EmailSender.sendEmail.callsArgWith(1)
opts =
to: "bob@bob.com"
@EmailHandler.sendEmail "welcome", opts, =>
@EmailSender.sendEmail.called.should.equal true
done()
it "should send lifecycle email if it is enabled", (done)->
@settings.email.lifecycle = true
@EmailBuilder.buildEmail.returns({type:"lifecycle"})
@EmailSender.sendEmail.callsArgWith(1)
opts =
to: "bob@bob.com"
@EmailHandler.sendEmail "welcome", opts, =>
@EmailSender.sendEmail.called.should.equal true
done()
| 97199 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Email/EmailHandler"
expect = require("chai").expect
describe "EmailHandler", ->
beforeEach ->
@settings =
email:{}
@EmailBuilder =
buildEmail:sinon.stub()
@EmailSender =
sendEmail:sinon.stub()
@EmailHandler = SandboxedModule.require modulePath, requires:
"./EmailBuilder":@EmailBuilder
"./EmailSender":@EmailSender
"settings-sharelatex":@settings
"logger-sharelatex": log:->
@html = "<html>hello</html>"
describe "send email", ->
it "should use the correct options", (done)->
@EmailBuilder.buildEmail.returns({html:@html})
@EmailSender.sendEmail.callsArgWith(1)
opts =
to: "<EMAIL>"
@EmailHandler.sendEmail "welcome", opts, =>
args = @EmailSender.sendEmail.args[0][0]
args.html.should.equal @html
done()
it "should return the erroor", (done)->
@EmailBuilder.buildEmail.returns({html:@html})
@EmailSender.sendEmail.callsArgWith(1, "error")
opts =
to: "<EMAIL>"
subject:"hello bob"
@EmailHandler.sendEmail "welcome", opts, (err)=>
err.should.equal "error"
done()
it "should not send an email if lifecycle is not enabled", (done)->
@settings.email.lifecycle = false
@EmailBuilder.buildEmail.returns({type:"lifecycle"})
@EmailHandler.sendEmail "welcome", {}, =>
@EmailSender.sendEmail.called.should.equal false
done()
it "should send an email if lifecycle is not enabled but the type is notification", (done)->
@settings.email.lifecycle = false
@EmailBuilder.buildEmail.returns({type:"notification"})
@EmailSender.sendEmail.callsArgWith(1)
opts =
to: "<EMAIL>"
@EmailHandler.sendEmail "welcome", opts, =>
@EmailSender.sendEmail.called.should.equal true
done()
it "should send lifecycle email if it is enabled", (done)->
@settings.email.lifecycle = true
@EmailBuilder.buildEmail.returns({type:"lifecycle"})
@EmailSender.sendEmail.callsArgWith(1)
opts =
to: "<EMAIL>"
@EmailHandler.sendEmail "welcome", opts, =>
@EmailSender.sendEmail.called.should.equal true
done()
| true | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Email/EmailHandler"
expect = require("chai").expect
describe "EmailHandler", ->
beforeEach ->
@settings =
email:{}
@EmailBuilder =
buildEmail:sinon.stub()
@EmailSender =
sendEmail:sinon.stub()
@EmailHandler = SandboxedModule.require modulePath, requires:
"./EmailBuilder":@EmailBuilder
"./EmailSender":@EmailSender
"settings-sharelatex":@settings
"logger-sharelatex": log:->
@html = "<html>hello</html>"
describe "send email", ->
it "should use the correct options", (done)->
@EmailBuilder.buildEmail.returns({html:@html})
@EmailSender.sendEmail.callsArgWith(1)
opts =
to: "PI:EMAIL:<EMAIL>END_PI"
@EmailHandler.sendEmail "welcome", opts, =>
args = @EmailSender.sendEmail.args[0][0]
args.html.should.equal @html
done()
it "should return the erroor", (done)->
@EmailBuilder.buildEmail.returns({html:@html})
@EmailSender.sendEmail.callsArgWith(1, "error")
opts =
to: "PI:EMAIL:<EMAIL>END_PI"
subject:"hello bob"
@EmailHandler.sendEmail "welcome", opts, (err)=>
err.should.equal "error"
done()
it "should not send an email if lifecycle is not enabled", (done)->
@settings.email.lifecycle = false
@EmailBuilder.buildEmail.returns({type:"lifecycle"})
@EmailHandler.sendEmail "welcome", {}, =>
@EmailSender.sendEmail.called.should.equal false
done()
it "should send an email if lifecycle is not enabled but the type is notification", (done)->
@settings.email.lifecycle = false
@EmailBuilder.buildEmail.returns({type:"notification"})
@EmailSender.sendEmail.callsArgWith(1)
opts =
to: "PI:EMAIL:<EMAIL>END_PI"
@EmailHandler.sendEmail "welcome", opts, =>
@EmailSender.sendEmail.called.should.equal true
done()
it "should send lifecycle email if it is enabled", (done)->
@settings.email.lifecycle = true
@EmailBuilder.buildEmail.returns({type:"lifecycle"})
@EmailSender.sendEmail.callsArgWith(1)
opts =
to: "PI:EMAIL:<EMAIL>END_PI"
@EmailHandler.sendEmail "welcome", opts, =>
@EmailSender.sendEmail.called.should.equal true
done()
|
[
{
"context": "er? and (@fn is 'auth' or key is false)\n user = @user\n else if key isnt false\n if (@params.access_t",
"end": 1057,
"score": 0.9972274303436279,
"start": 1052,
"tag": "USERNAME",
"value": "@user"
},
{
"context": ".trim().toLowerCase()\n from ?= S.auth?.from ... | worker/src/auth.coffee | oaworks/api | 0 |
# curl -X GET "https://api.oa.works/auth" -H "x-id:YOURUSERIDHERE" -H "x-apikey:YOURAPIKEYHERE"
# curl -X GET "https://api.oa.works/auth?apikey=YOURAPIKEYHERE"
# store user record object in kv as users/:UID (value is stringified json object)
# and store a map of API keys as well, auth/apikey/:KEY (value is user ID) (could have more than one, and have ones that give different permissions)
# store a login token at auth/token/:TOKEN (value is email) (autoexpire login tokens at 20mins 1200s)
# and store a resume token at auth/resume/:UID/:RESUMETOKEN (value is a timestamp) (autoexpire resume tokens at about three months 7890000s, but rotate them on non-cookie use)
# and store users to the index as well if available
P.auth = (key) ->
# if params.auth, someone looking up the URL route for this acc. Who would have the right to see that?
if typeof key is 'string' # or key can be false, to pass through to unauthorised / login / request page
return @users._get key
if not key and @user? and (@fn is 'auth' or key is false)
user = @user
else if key isnt false
if (@params.access_token and oauth = await @auth._oauth @params.access_token) or ((@params.token or @params.auth) and email = await @kv 'auth/token/' + (@params.token ? @params.auth), '') # true causes delete after found
if not user = await @users._get(oauth?.email ? email) # get the user record if it already exists
user = await @users._create oauth ? email # create the user record if not existing, as this is the first token login attempt for this email address
if not user and @apikey
if @S.bg is true
user = await @users._get undefined, @apikey
if not user and uid = await @kv 'auth/apikey/' + @apikey
user = await @users._get uid # no user creation if apikey doesn't match here - only create on login token above
if not user and (@params.resume or @cookie) # accept resume on a header too?
if not resume = @params.resume # login by resume token if provided in param or cookie
try
cookie = JSON.parse decodeURIComponent(@cookie).split((S.auth?.cookie?.name ? 'oaworksLogin') + "=")[1].split(';')[0]
resume = cookie.resume
uid = cookie._id
uid ?= @headers['x-id']
if @params.email and not uid
uid = @hashhex @params.email.trim().toLowerCase() # accept resume with email instead of id?
if resume and uid and restok = await @kv 'auth/resume/' + uid + '/' + resume
user = await @users._get uid
user.resume = resume if user?
if typeof user is 'object' and user._id
# if 2fa is enabled, request a second form of ID (see below about implementing 2fa)
# record the user login timestamp, and if login came from a service the user does not yet have a role in, add the service user role
# who can add the service param?
if @params.service and not user.roles?[@params.service]?
user.roles ?= {}
user.roles[@params.service] = 'user'
@users._update user
if not user.resume? and not @apikey
user.resume = @uid()
@kv 'auth/resume/' + user._id + '/' + user.resume, {createdAt: Date.now()}, 7890000 # resume token lasts three months (could make six at 15768000)
if await @auth.role 'root', @user
@log msg: 'root login' #, notify: true
# if this is called with no variables, and no defaults, provide a count of users?
# but then if logged in and on this route, what does it provide? the user account?
if not @format and (@fn is 'auth' or @unauthorised) and @headers['user-agent'] and @headers['user-agent'].toLowerCase().includes('mozilla') and @headers.accept and @headers.accept.includes('/html') and not @headers.accept.includes '/json'
@format = 'html'
if not key and @format is 'html'
ret = '<body>'
ret += '<script type="text/javascript" src="/client/oaworksLogin.min.js?v=' + @S.version + '"></script>\n'
ret += '<h1>' + (if @base then @base.replace('bg.', '(bg) ') else @S.name) + '</h1>'
if not @user?
ret += '<input autofocus id="OALoginEmail" class="OALoginEmail" type="text" name="email" placeholder="email">'
ret += '<input id="OALoginToken" class="OALoginToken" style="display:none;" type="text" name="token" placeholder="token (check your email)">'
ret += '<p class="OALoginWelcome" style="display:none;">Welcome back</p>'
ret += '<p class="OALoginLogout" style="display:none;"><a id="OALoginLogout" href="#">logout</a></p>'
else
ret += '<p>' + user.email + '</p><p><a id="PLogout" href="#">logout</a></p>'
return ret + '</body>'
else
return user
P.auth.token = (email, from, subject, text, html, template, url) ->
email ?= @params.email
if email
email = email.trim().toLowerCase()
from ?= S.auth?.from ? 'login@oa.works'
token = @uid 8
console.log(email, token) if @S.dev and @S.bg is true
url ?= @params.url
if url
url += '#' + token
subject ?= 'Complete your login to ' + (if url.includes('//') then url.split('//')[1] else url).split('/')[0]
else
url = @base + '/' + @route.replace '/token', '/' + token
subject ?= 'Complete your login to ' + (if @base then @base.replace('bg.', '(bg) ') else @S.name)
@kv 'auth/token/' + token, email, 1200 # create a token that expires in 20 minutes
@waitUntil @mail
from: from
to: email
subject: subject
text: text ? 'Your login code is:\r\n\r\n' + token + '\r\n\r\nor use this link:\r\n\r\n' + url + '\r\n\r\nnote: this single-use code is only valid for 20 minutes.'
html: html ? '<html><body><p>Your login code is:</p><p><b>' + token + '</b></p><p>or click on this link</p><p><a href=\"' + url + '\">' + url + '</a></p><p>note: this single-use code is only valid for 10 minutes.</p></body></html>'
#template: template
params: {token: token, url: url}
return email: email
else
return #@uid 8 # is there a case where this would somehow be useful? It's not getting saved anywhere for later confirmation...
# auth/:uid/role/:grl
# check if a user has a role or one of a list of roles
P.auth.role = (grl, user) ->
grl ?= @params.role
user = if typeof user is 'object' then user else if user or @params.auth then await @users._get(user ? @params.auth) else @user
return 'system' if grl is 'system' and @system
return 'root' if user?.email and user.email in (if typeof @S.root is 'string' then [@S.root] else if Array.isArray(@S.root) then @S.root else [])
return grl if grl.startsWith('@') and user?.email? and user.email.endsWith grl # a user can be allowed if the required auth is the @domain.com of their email address
if user?.roles?
for g in (if typeof grl is 'string' then grl.split(',') else if grl then grl else [])
[group, role] = g.replace('/', '.').split '.'
return 'owner' if group is user._id # user is owner on their own group
if role
if role in (user.roles[group] ? [])
return role
else if user.roles[group]?
cascade = ['service', 'owner', 'super', 'admin', 'auth', 'bulk', 'delete', 'remove', 'create', 'insert', 'publish', 'put', 'draft', 'post', 'edit', 'update', 'user', 'get', 'read', 'info', 'public', 'request']
if -1 < ri = cascade.indexOf role
for rl in cascade.splice 0, ri
return rl if rl in user.roles[group]
return false
# /auth/:uid/add/:grl
# add a user to a role, or remove, or deny
# deny meaning automatically not allowed any other role on the group
# whereas otherwise a user (or system on behalf of) should be able to request a role (TODO)
P.auth.add = (grl, user, remove, deny) ->
user = if typeof user is 'object' then user else if user or @params.auth then await @users._get(user ? @params.auth) else @user
if not grl and @user._id isnt user._id
# TODO what about one logged in user acting on the roles route of another? - which groups could a user add another user to?
return false if not await @auth.role 'system'
grl ?= @params.add ? @params.remove ? @params.deny
return false if not grl
[group, role] = grl.replace('/', '.').split '.'
remove ?= (@request.method is 'DELETE' or @params._delete is true) and @fn is 'auth.roles'
if group is 'root' or role is 'root' # root only allowed by config. can't be set via API.
return false
else if deny
user.roles[group] = ['deny'] # no other roles can be kept
@users._update user
else if not role
if user.roles[group]?
if remove?
delete user.roles[group]
@users._update user
else
user.roles[group] = ['user']
@users._update user
else if user.roles?[group] and role in user.roles[group]
if remove?
user.roles[group].splice user.roles[group].indexOf(role), 1
delete user.roles[group] if not user.roles[group].length
@users._update user
else if role isnt 'request' or 'deny' not in (user.roles[group] ? []) # a denied user cannot request
user.roles[group] ?= []
user.roles[group] = user.roles[group].splice(user.roles[group].indexOf('request'), 1) if 'request' in user.roles[group] # when any other role is added, request is removed
user.roles.group.push role
@users._update user
# TODO if role to add is 'request' then notify someone who can authorise - or have a cron job send batch notifications
return user
P.auth.remove = (grl, user) -> return @auth.add grl, user, true # remove and deny would auth on add
P.auth.deny = (grl, user) -> return @auth.add grl, user, undefined, true
P.auth.request = (grl, user) ->
grl ?= @params.request # anyone can request so no auth needed for request
grl = grl.split('/')[0] + '/request'
return @auth.add grl, user
P.auth.logout = (user) -> # how about triggering a logout on a different user account
user ?= @user
if user
await @kv._each 'auth/resume/' + (if typeof user is 'string' then (if user.includes('@') then @hashhex(user.trim().toLowerCase()) else user) else user._id), ''
return true
else
return false
P.auth._oauth = (token, cid) ->
# https://developers.google.com/identity/protocols/OAuth2UserAgent#validatetoken
sets = {}
if token #?= @params.access_token
try
# we did also have facebook oauth in here, still in old code, but decided to drop it unless explicitly required again
validate = await @fetch 'https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=' + token, method: 'POST' # has to be a POST even though it sends nothing
cid ?= @S.svc[@params.service ? 'z']?.google?.oauth?.client?.id ? S.use?.google?.oauth?.client?.id
if cid? and validate.data?.aud is cid
ret = await @fetch 'https://www.googleapis.com/oauth2/v2/userinfo?access_token=' + token
return
email: ret.data.email.toLowerCase()
google: {id: ret.data.id}
name: ret.data.name ? (ret.data.given_name + (if ret.data.family_name then ' ' + ret.data.family_name else ''))
avatar: ret.data.picture
return
# an oauth client-side would require the google oauth client token. It's not a secret, but must be got in advance from google account provider
# ours is '360291218230-r9lteuqaah0veseihnk7nc6obialug84.apps.googleusercontent.com' - but that's no use to anyone else, unless wanting to login with us
# the Oauth URL that would trigger something like this would be like:
# grl = 'https://accounts.google.com/o/oauth2/v2/auth?response_type=token&include_granted_scopes=true'
# grl += '&scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile'
# grl += '&state=' + state + '&redirect_uri=' + P.oauthRedirectUri + '&client_id=' + P.oauthGoogleClientId
# state would be something like Math.random().toString(36).substring(2,8) and would be sent and also kept for checking against the response
# the response from oauth login page would go back to current page and have a # with access_token= and state=
# NOTE as it is after a # these would only be available on a browser, as servers don't get the # part of a URL
# if the states match, send the access_token into the above method and if it validates then we can login the user
P.users = _index: true, _auth: 'system'
P.users._get = (uid, apikey) ->
if apikey
us = await @index 'users', 'apikey:"' + apikey + '"'
if us?.hits?.total is 1
user = us.hits.hits[0]._source
user._id ?= us.hits.hits[0]._id
else if typeof uid is 'string'
uid = uid.replace('users/','') if uid.startsWith 'users/'
uid = @hashhex(uid.trim().toLowerCase()) if uid.includes '@'
if @S.bg isnt true
try user = await @kv 'users/' + uid
if not user?
try user = await @index 'users/' + uid
if user? and @S.bg isnt true # may have found a user from the index who isn't in the local kv yet, so put it in
try await @kv 'users/' + uid, user
try await @kv 'auth/apikey/' + user.apikey, uid
return user
P.users._create = (user) ->
user = {email: user} if typeof user is 'string'
return false if typeof user.email isnt 'string' or not user.email.includes '@'
u =
_id: @hashhex user.email.trim().toLowerCase()
email: user.email
apikey: @uid()
delete user.email
try u.profile = user # could use other input as profile input data? better for services to store this where necessary though
try u.creation = @base + '/' + @route # which domain the user was created from
u.roles = {}
u.createdAt = new Date()
try await @kv 'users/' + u._id, u
try await @kv 'auth/apikey/' + u.apikey, u._id
try @waitUntil @index 'users/' + u._id, u
return u
P.users._update = (uid, user) ->
# TODO how to decide who can update users, remotely or locally, and is it always a total update or could be a partial?
if typeof uid is 'object' and user._id and not user?
user = uid
uid = user._id
if typeof uid is 'string' and typeof user is 'object' and JSON.stringify(user) isnt '{}'
uid = uid.replace('users/','') if uid.startsWith 'users/'
uid = @hashhex(uid.trim().toLowerCase()) if uid.includes '@'
user.updatedAt = new Date()
try await @kv 'users/' + uid, user
try @waitUntil @index 'users/' + uid, user
return true
else
return false
P.users._delete = (uid) ->
if user = (if typeof uid is 'object' then uid else if @user?._id is uid then @user else await @users._get uid)
try await @kv._each 'auth/resume/' + user._id, ''
try await @kv 'auth/apikey/' + user.apikey, ''
try await @kv 'users/' + user._id, ''
try await @index 'users/' + user._id, ''
| 56288 |
# curl -X GET "https://api.oa.works/auth" -H "x-id:YOURUSERIDHERE" -H "x-apikey:YOURAPIKEYHERE"
# curl -X GET "https://api.oa.works/auth?apikey=YOURAPIKEYHERE"
# store user record object in kv as users/:UID (value is stringified json object)
# and store a map of API keys as well, auth/apikey/:KEY (value is user ID) (could have more than one, and have ones that give different permissions)
# store a login token at auth/token/:TOKEN (value is email) (autoexpire login tokens at 20mins 1200s)
# and store a resume token at auth/resume/:UID/:RESUMETOKEN (value is a timestamp) (autoexpire resume tokens at about three months 7890000s, but rotate them on non-cookie use)
# and store users to the index as well if available
P.auth = (key) ->
# if params.auth, someone looking up the URL route for this acc. Who would have the right to see that?
if typeof key is 'string' # or key can be false, to pass through to unauthorised / login / request page
return @users._get key
if not key and @user? and (@fn is 'auth' or key is false)
user = @user
else if key isnt false
if (@params.access_token and oauth = await @auth._oauth @params.access_token) or ((@params.token or @params.auth) and email = await @kv 'auth/token/' + (@params.token ? @params.auth), '') # true causes delete after found
if not user = await @users._get(oauth?.email ? email) # get the user record if it already exists
user = await @users._create oauth ? email # create the user record if not existing, as this is the first token login attempt for this email address
if not user and @apikey
if @S.bg is true
user = await @users._get undefined, @apikey
if not user and uid = await @kv 'auth/apikey/' + @apikey
user = await @users._get uid # no user creation if apikey doesn't match here - only create on login token above
if not user and (@params.resume or @cookie) # accept resume on a header too?
if not resume = @params.resume # login by resume token if provided in param or cookie
try
cookie = JSON.parse decodeURIComponent(@cookie).split((S.auth?.cookie?.name ? 'oaworksLogin') + "=")[1].split(';')[0]
resume = cookie.resume
uid = cookie._id
uid ?= @headers['x-id']
if @params.email and not uid
uid = @hashhex @params.email.trim().toLowerCase() # accept resume with email instead of id?
if resume and uid and restok = await @kv 'auth/resume/' + uid + '/' + resume
user = await @users._get uid
user.resume = resume if user?
if typeof user is 'object' and user._id
# if 2fa is enabled, request a second form of ID (see below about implementing 2fa)
# record the user login timestamp, and if login came from a service the user does not yet have a role in, add the service user role
# who can add the service param?
if @params.service and not user.roles?[@params.service]?
user.roles ?= {}
user.roles[@params.service] = 'user'
@users._update user
if not user.resume? and not @apikey
user.resume = @uid()
@kv 'auth/resume/' + user._id + '/' + user.resume, {createdAt: Date.now()}, 7890000 # resume token lasts three months (could make six at 15768000)
if await @auth.role 'root', @user
@log msg: 'root login' #, notify: true
# if this is called with no variables, and no defaults, provide a count of users?
# but then if logged in and on this route, what does it provide? the user account?
if not @format and (@fn is 'auth' or @unauthorised) and @headers['user-agent'] and @headers['user-agent'].toLowerCase().includes('mozilla') and @headers.accept and @headers.accept.includes('/html') and not @headers.accept.includes '/json'
@format = 'html'
if not key and @format is 'html'
ret = '<body>'
ret += '<script type="text/javascript" src="/client/oaworksLogin.min.js?v=' + @S.version + '"></script>\n'
ret += '<h1>' + (if @base then @base.replace('bg.', '(bg) ') else @S.name) + '</h1>'
if not @user?
ret += '<input autofocus id="OALoginEmail" class="OALoginEmail" type="text" name="email" placeholder="email">'
ret += '<input id="OALoginToken" class="OALoginToken" style="display:none;" type="text" name="token" placeholder="token (check your email)">'
ret += '<p class="OALoginWelcome" style="display:none;">Welcome back</p>'
ret += '<p class="OALoginLogout" style="display:none;"><a id="OALoginLogout" href="#">logout</a></p>'
else
ret += '<p>' + user.email + '</p><p><a id="PLogout" href="#">logout</a></p>'
return ret + '</body>'
else
return user
P.auth.token = (email, from, subject, text, html, template, url) ->
email ?= @params.email
if email
email = email.trim().toLowerCase()
from ?= S.auth?.from ? '<EMAIL>'
token = <PASSWORD> 8
console.log(email, token) if @S.dev and @S.bg is true
url ?= @params.url
if url
url += '#' + token
subject ?= 'Complete your login to ' + (if url.includes('//') then url.split('//')[1] else url).split('/')[0]
else
url = @base + '/' + @route.replace '/token', '/' + token
subject ?= 'Complete your login to ' + (if @base then @base.replace('bg.', '(bg) ') else @S.name)
@kv 'auth/token/' + token, email, 1200 # create a token that expires in 20 minutes
@waitUntil @mail
from: from
to: email
subject: subject
text: text ? 'Your login code is:\r\n\r\n' + token + '\r\n\r\nor use this link:\r\n\r\n' + url + '\r\n\r\nnote: this single-use code is only valid for 20 minutes.'
html: html ? '<html><body><p>Your login code is:</p><p><b>' + token + '</b></p><p>or click on this link</p><p><a href=\"' + url + '\">' + url + '</a></p><p>note: this single-use code is only valid for 10 minutes.</p></body></html>'
#template: template
params: {token: token, url: url}
return email: email
else
return #@uid 8 # is there a case where this would somehow be useful? It's not getting saved anywhere for later confirmation...
# auth/:uid/role/:grl
# check if a user has a role or one of a list of roles
P.auth.role = (grl, user) ->
grl ?= @params.role
user = if typeof user is 'object' then user else if user or @params.auth then await @users._get(user ? @params.auth) else @user
return 'system' if grl is 'system' and @system
return 'root' if user?.email and user.email in (if typeof @S.root is 'string' then [@S.root] else if Array.isArray(@S.root) then @S.root else [])
return grl if grl.startsWith('@') and user?.email? and user.email.endsWith grl # a user can be allowed if the required auth is the @domain.com of their email address
if user?.roles?
for g in (if typeof grl is 'string' then grl.split(',') else if grl then grl else [])
[group, role] = g.replace('/', '.').split '.'
return 'owner' if group is user._id # user is owner on their own group
if role
if role in (user.roles[group] ? [])
return role
else if user.roles[group]?
cascade = ['service', 'owner', 'super', 'admin', 'auth', 'bulk', 'delete', 'remove', 'create', 'insert', 'publish', 'put', 'draft', 'post', 'edit', 'update', 'user', 'get', 'read', 'info', 'public', 'request']
if -1 < ri = cascade.indexOf role
for rl in cascade.splice 0, ri
return rl if rl in user.roles[group]
return false
# /auth/:uid/add/:grl
# add a user to a role, or remove, or deny
# deny meaning automatically not allowed any other role on the group
# whereas otherwise a user (or system on behalf of) should be able to request a role (TODO)
P.auth.add = (grl, user, remove, deny) ->
user = if typeof user is 'object' then user else if user or @params.auth then await @users._get(user ? @params.auth) else @user
if not grl and @user._id isnt user._id
# TODO what about one logged in user acting on the roles route of another? - which groups could a user add another user to?
return false if not await @auth.role 'system'
grl ?= @params.add ? @params.remove ? @params.deny
return false if not grl
[group, role] = grl.replace('/', '.').split '.'
remove ?= (@request.method is 'DELETE' or @params._delete is true) and @fn is 'auth.roles'
if group is 'root' or role is 'root' # root only allowed by config. can't be set via API.
return false
else if deny
user.roles[group] = ['deny'] # no other roles can be kept
@users._update user
else if not role
if user.roles[group]?
if remove?
delete user.roles[group]
@users._update user
else
user.roles[group] = ['user']
@users._update user
else if user.roles?[group] and role in user.roles[group]
if remove?
user.roles[group].splice user.roles[group].indexOf(role), 1
delete user.roles[group] if not user.roles[group].length
@users._update user
else if role isnt 'request' or 'deny' not in (user.roles[group] ? []) # a denied user cannot request
user.roles[group] ?= []
user.roles[group] = user.roles[group].splice(user.roles[group].indexOf('request'), 1) if 'request' in user.roles[group] # when any other role is added, request is removed
user.roles.group.push role
@users._update user
# TODO if role to add is 'request' then notify someone who can authorise - or have a cron job send batch notifications
return user
P.auth.remove = (grl, user) -> return @auth.add grl, user, true # remove and deny would auth on add
P.auth.deny = (grl, user) -> return @auth.add grl, user, undefined, true
P.auth.request = (grl, user) ->
grl ?= @params.request # anyone can request so no auth needed for request
grl = grl.split('/')[0] + '/request'
return @auth.add grl, user
P.auth.logout = (user) -> # how about triggering a logout on a different user account
user ?= @user
if user
await @kv._each 'auth/resume/' + (if typeof user is 'string' then (if user.includes('@') then @hashhex(user.trim().toLowerCase()) else user) else user._id), ''
return true
else
return false
P.auth._oauth = (token, cid) ->
# https://developers.google.com/identity/protocols/OAuth2UserAgent#validatetoken
sets = {}
if token #?= @params.access_token
try
# we did also have facebook oauth in here, still in old code, but decided to drop it unless explicitly required again
validate = await @fetch 'https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=' + token, method: 'POST' # has to be a POST even though it sends nothing
cid ?= @S.svc[@params.service ? 'z']?.google?.oauth?.client?.id ? S.use?.google?.oauth?.client?.id
if cid? and validate.data?.aud is cid
ret = await @fetch 'https://www.googleapis.com/oauth2/v2/userinfo?access_token=' + token
return
email: ret.data.email.toLowerCase()
google: {id: ret.data.id}
name: ret.data.name ? (ret.data.given_name + (if ret.data.family_name then ' ' + ret.data.family_name else ''))
avatar: ret.data.picture
return
# an oauth client-side would require the google oauth client token. It's not a secret, but must be got in advance from google account provider
# ours is '360291218230-r9lteuqaah0veseihnk7nc6obialug84.apps.googleusercontent.com' - but that's no use to anyone else, unless wanting to login with us
# the Oauth URL that would trigger something like this would be like:
# grl = 'https://accounts.google.com/o/oauth2/v2/auth?response_type=token&include_granted_scopes=true'
# grl += '&scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile'
# grl += '&state=' + state + '&redirect_uri=' + P.oauthRedirectUri + '&client_id=' + P.oauthGoogleClientId
# state would be something like Math.random().toString(36).substring(2,8) and would be sent and also kept for checking against the response
# the response from oauth login page would go back to current page and have a # with access_token= and state=
# NOTE as it is after a # these would only be available on a browser, as servers don't get the # part of a URL
# if the states match, send the access_token into the above method and if it validates then we can login the user
P.users = _index: true, _auth: 'system'
P.users._get = (uid, apikey) ->
if apikey
us = await @index 'users', 'apikey:"' + apikey + '"'
if us?.hits?.total is 1
user = us.hits.hits[0]._source
user._id ?= us.hits.hits[0]._id
else if typeof uid is 'string'
uid = uid.replace('users/','') if uid.startsWith 'users/'
uid = @hashhex(uid.trim().toLowerCase()) if uid.includes '@'
if @S.bg isnt true
try user = await @kv 'users/' + uid
if not user?
try user = await @index 'users/' + uid
if user? and @S.bg isnt true # may have found a user from the index who isn't in the local kv yet, so put it in
try await @kv 'users/' + uid, user
try await @kv 'auth/apikey/' + user.apikey, uid
return user
P.users._create = (user) ->
user = {email: user} if typeof user is 'string'
return false if typeof user.email isnt 'string' or not user.email.includes '@'
u =
_id: @hashhex user.email.trim().toLowerCase()
email: user.email
apikey: @uid()
delete user.email
try u.profile = user # could use other input as profile input data? better for services to store this where necessary though
try u.creation = @base + '/' + @route # which domain the user was created from
u.roles = {}
u.createdAt = new Date()
try await @kv 'users/' + u._id, u
try await @kv 'auth/apikey/' + u.apikey, u._id
try @waitUntil @index 'users/' + u._id, u
return u
P.users._update = (uid, user) ->
# TODO how to decide who can update users, remotely or locally, and is it always a total update or could be a partial?
if typeof uid is 'object' and user._id and not user?
user = uid
uid = user._id
if typeof uid is 'string' and typeof user is 'object' and JSON.stringify(user) isnt '{}'
uid = uid.replace('users/','') if uid.startsWith 'users/'
uid = @hashhex(uid.trim().toLowerCase()) if uid.includes '@'
user.updatedAt = new Date()
try await @kv 'users/' + uid, user
try @waitUntil @index 'users/' + uid, user
return true
else
return false
P.users._delete = (uid) ->
if user = (if typeof uid is 'object' then uid else if @user?._id is uid then @user else await @users._get uid)
try await @kv._each 'auth/resume/' + user._id, ''
try await @kv 'auth/apikey/' + user.apikey, ''
try await @kv 'users/' + user._id, ''
try await @index 'users/' + user._id, ''
| true |
# curl -X GET "https://api.oa.works/auth" -H "x-id:YOURUSERIDHERE" -H "x-apikey:YOURAPIKEYHERE"
# curl -X GET "https://api.oa.works/auth?apikey=YOURAPIKEYHERE"
# store user record object in kv as users/:UID (value is stringified json object)
# and store a map of API keys as well, auth/apikey/:KEY (value is user ID) (could have more than one, and have ones that give different permissions)
# store a login token at auth/token/:TOKEN (value is email) (autoexpire login tokens at 20mins 1200s)
# and store a resume token at auth/resume/:UID/:RESUMETOKEN (value is a timestamp) (autoexpire resume tokens at about three months 7890000s, but rotate them on non-cookie use)
# and store users to the index as well if available
P.auth = (key) ->
# if params.auth, someone looking up the URL route for this acc. Who would have the right to see that?
if typeof key is 'string' # or key can be false, to pass through to unauthorised / login / request page
return @users._get key
if not key and @user? and (@fn is 'auth' or key is false)
user = @user
else if key isnt false
if (@params.access_token and oauth = await @auth._oauth @params.access_token) or ((@params.token or @params.auth) and email = await @kv 'auth/token/' + (@params.token ? @params.auth), '') # true causes delete after found
if not user = await @users._get(oauth?.email ? email) # get the user record if it already exists
user = await @users._create oauth ? email # create the user record if not existing, as this is the first token login attempt for this email address
if not user and @apikey
if @S.bg is true
user = await @users._get undefined, @apikey
if not user and uid = await @kv 'auth/apikey/' + @apikey
user = await @users._get uid # no user creation if apikey doesn't match here - only create on login token above
if not user and (@params.resume or @cookie) # accept resume on a header too?
if not resume = @params.resume # login by resume token if provided in param or cookie
try
cookie = JSON.parse decodeURIComponent(@cookie).split((S.auth?.cookie?.name ? 'oaworksLogin') + "=")[1].split(';')[0]
resume = cookie.resume
uid = cookie._id
uid ?= @headers['x-id']
if @params.email and not uid
uid = @hashhex @params.email.trim().toLowerCase() # accept resume with email instead of id?
if resume and uid and restok = await @kv 'auth/resume/' + uid + '/' + resume
user = await @users._get uid
user.resume = resume if user?
if typeof user is 'object' and user._id
# if 2fa is enabled, request a second form of ID (see below about implementing 2fa)
# record the user login timestamp, and if login came from a service the user does not yet have a role in, add the service user role
# who can add the service param?
if @params.service and not user.roles?[@params.service]?
user.roles ?= {}
user.roles[@params.service] = 'user'
@users._update user
if not user.resume? and not @apikey
user.resume = @uid()
@kv 'auth/resume/' + user._id + '/' + user.resume, {createdAt: Date.now()}, 7890000 # resume token lasts three months (could make six at 15768000)
if await @auth.role 'root', @user
@log msg: 'root login' #, notify: true
# if this is called with no variables, and no defaults, provide a count of users?
# but then if logged in and on this route, what does it provide? the user account?
if not @format and (@fn is 'auth' or @unauthorised) and @headers['user-agent'] and @headers['user-agent'].toLowerCase().includes('mozilla') and @headers.accept and @headers.accept.includes('/html') and not @headers.accept.includes '/json'
@format = 'html'
if not key and @format is 'html'
ret = '<body>'
ret += '<script type="text/javascript" src="/client/oaworksLogin.min.js?v=' + @S.version + '"></script>\n'
ret += '<h1>' + (if @base then @base.replace('bg.', '(bg) ') else @S.name) + '</h1>'
if not @user?
ret += '<input autofocus id="OALoginEmail" class="OALoginEmail" type="text" name="email" placeholder="email">'
ret += '<input id="OALoginToken" class="OALoginToken" style="display:none;" type="text" name="token" placeholder="token (check your email)">'
ret += '<p class="OALoginWelcome" style="display:none;">Welcome back</p>'
ret += '<p class="OALoginLogout" style="display:none;"><a id="OALoginLogout" href="#">logout</a></p>'
else
ret += '<p>' + user.email + '</p><p><a id="PLogout" href="#">logout</a></p>'
return ret + '</body>'
else
return user
P.auth.token = (email, from, subject, text, html, template, url) ->
email ?= @params.email
if email
email = email.trim().toLowerCase()
from ?= S.auth?.from ? 'PI:EMAIL:<EMAIL>END_PI'
token = PI:PASSWORD:<PASSWORD>END_PI 8
console.log(email, token) if @S.dev and @S.bg is true
url ?= @params.url
if url
url += '#' + token
subject ?= 'Complete your login to ' + (if url.includes('//') then url.split('//')[1] else url).split('/')[0]
else
url = @base + '/' + @route.replace '/token', '/' + token
subject ?= 'Complete your login to ' + (if @base then @base.replace('bg.', '(bg) ') else @S.name)
@kv 'auth/token/' + token, email, 1200 # create a token that expires in 20 minutes
@waitUntil @mail
from: from
to: email
subject: subject
text: text ? 'Your login code is:\r\n\r\n' + token + '\r\n\r\nor use this link:\r\n\r\n' + url + '\r\n\r\nnote: this single-use code is only valid for 20 minutes.'
html: html ? '<html><body><p>Your login code is:</p><p><b>' + token + '</b></p><p>or click on this link</p><p><a href=\"' + url + '\">' + url + '</a></p><p>note: this single-use code is only valid for 10 minutes.</p></body></html>'
#template: template
params: {token: token, url: url}
return email: email
else
return #@uid 8 # is there a case where this would somehow be useful? It's not getting saved anywhere for later confirmation...
# auth/:uid/role/:grl
# check if a user has a role or one of a list of roles
P.auth.role = (grl, user) ->
grl ?= @params.role
user = if typeof user is 'object' then user else if user or @params.auth then await @users._get(user ? @params.auth) else @user
return 'system' if grl is 'system' and @system
return 'root' if user?.email and user.email in (if typeof @S.root is 'string' then [@S.root] else if Array.isArray(@S.root) then @S.root else [])
return grl if grl.startsWith('@') and user?.email? and user.email.endsWith grl # a user can be allowed if the required auth is the @domain.com of their email address
if user?.roles?
for g in (if typeof grl is 'string' then grl.split(',') else if grl then grl else [])
[group, role] = g.replace('/', '.').split '.'
return 'owner' if group is user._id # user is owner on their own group
if role
if role in (user.roles[group] ? [])
return role
else if user.roles[group]?
cascade = ['service', 'owner', 'super', 'admin', 'auth', 'bulk', 'delete', 'remove', 'create', 'insert', 'publish', 'put', 'draft', 'post', 'edit', 'update', 'user', 'get', 'read', 'info', 'public', 'request']
if -1 < ri = cascade.indexOf role
for rl in cascade.splice 0, ri
return rl if rl in user.roles[group]
return false
# /auth/:uid/add/:grl
# add a user to a role, or remove, or deny
# deny meaning automatically not allowed any other role on the group
# whereas otherwise a user (or system on behalf of) should be able to request a role (TODO)
P.auth.add = (grl, user, remove, deny) ->
user = if typeof user is 'object' then user else if user or @params.auth then await @users._get(user ? @params.auth) else @user
if not grl and @user._id isnt user._id
# TODO what about one logged in user acting on the roles route of another? - which groups could a user add another user to?
return false if not await @auth.role 'system'
grl ?= @params.add ? @params.remove ? @params.deny
return false if not grl
[group, role] = grl.replace('/', '.').split '.'
remove ?= (@request.method is 'DELETE' or @params._delete is true) and @fn is 'auth.roles'
if group is 'root' or role is 'root' # root only allowed by config. can't be set via API.
return false
else if deny
user.roles[group] = ['deny'] # no other roles can be kept
@users._update user
else if not role
if user.roles[group]?
if remove?
delete user.roles[group]
@users._update user
else
user.roles[group] = ['user']
@users._update user
else if user.roles?[group] and role in user.roles[group]
if remove?
user.roles[group].splice user.roles[group].indexOf(role), 1
delete user.roles[group] if not user.roles[group].length
@users._update user
else if role isnt 'request' or 'deny' not in (user.roles[group] ? []) # a denied user cannot request
user.roles[group] ?= []
user.roles[group] = user.roles[group].splice(user.roles[group].indexOf('request'), 1) if 'request' in user.roles[group] # when any other role is added, request is removed
user.roles.group.push role
@users._update user
# TODO if role to add is 'request' then notify someone who can authorise - or have a cron job send batch notifications
return user
P.auth.remove = (grl, user) -> return @auth.add grl, user, true # remove and deny would auth on add
P.auth.deny = (grl, user) -> return @auth.add grl, user, undefined, true
P.auth.request = (grl, user) ->
grl ?= @params.request # anyone can request so no auth needed for request
grl = grl.split('/')[0] + '/request'
return @auth.add grl, user
P.auth.logout = (user) -> # how about triggering a logout on a different user account
user ?= @user
if user
await @kv._each 'auth/resume/' + (if typeof user is 'string' then (if user.includes('@') then @hashhex(user.trim().toLowerCase()) else user) else user._id), ''
return true
else
return false
P.auth._oauth = (token, cid) ->
# https://developers.google.com/identity/protocols/OAuth2UserAgent#validatetoken
sets = {}
if token #?= @params.access_token
try
# we did also have facebook oauth in here, still in old code, but decided to drop it unless explicitly required again
validate = await @fetch 'https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=' + token, method: 'POST' # has to be a POST even though it sends nothing
cid ?= @S.svc[@params.service ? 'z']?.google?.oauth?.client?.id ? S.use?.google?.oauth?.client?.id
if cid? and validate.data?.aud is cid
ret = await @fetch 'https://www.googleapis.com/oauth2/v2/userinfo?access_token=' + token
return
email: ret.data.email.toLowerCase()
google: {id: ret.data.id}
name: ret.data.name ? (ret.data.given_name + (if ret.data.family_name then ' ' + ret.data.family_name else ''))
avatar: ret.data.picture
return
# an oauth client-side would require the google oauth client token. It's not a secret, but must be got in advance from google account provider
# ours is '360291218230-r9lteuqaah0veseihnk7nc6obialug84.apps.googleusercontent.com' - but that's no use to anyone else, unless wanting to login with us
# the Oauth URL that would trigger something like this would be like:
# grl = 'https://accounts.google.com/o/oauth2/v2/auth?response_type=token&include_granted_scopes=true'
# grl += '&scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile'
# grl += '&state=' + state + '&redirect_uri=' + P.oauthRedirectUri + '&client_id=' + P.oauthGoogleClientId
# state would be something like Math.random().toString(36).substring(2,8) and would be sent and also kept for checking against the response
# the response from oauth login page would go back to current page and have a # with access_token= and state=
# NOTE as it is after a # these would only be available on a browser, as servers don't get the # part of a URL
# if the states match, send the access_token into the above method and if it validates then we can login the user
P.users = _index: true, _auth: 'system'
P.users._get = (uid, apikey) ->
if apikey
us = await @index 'users', 'apikey:"' + apikey + '"'
if us?.hits?.total is 1
user = us.hits.hits[0]._source
user._id ?= us.hits.hits[0]._id
else if typeof uid is 'string'
uid = uid.replace('users/','') if uid.startsWith 'users/'
uid = @hashhex(uid.trim().toLowerCase()) if uid.includes '@'
if @S.bg isnt true
try user = await @kv 'users/' + uid
if not user?
try user = await @index 'users/' + uid
if user? and @S.bg isnt true # may have found a user from the index who isn't in the local kv yet, so put it in
try await @kv 'users/' + uid, user
try await @kv 'auth/apikey/' + user.apikey, uid
return user
P.users._create = (user) ->
user = {email: user} if typeof user is 'string'
return false if typeof user.email isnt 'string' or not user.email.includes '@'
u =
_id: @hashhex user.email.trim().toLowerCase()
email: user.email
apikey: @uid()
delete user.email
try u.profile = user # could use other input as profile input data? better for services to store this where necessary though
try u.creation = @base + '/' + @route # which domain the user was created from
u.roles = {}
u.createdAt = new Date()
try await @kv 'users/' + u._id, u
try await @kv 'auth/apikey/' + u.apikey, u._id
try @waitUntil @index 'users/' + u._id, u
return u
P.users._update = (uid, user) ->
# TODO how to decide who can update users, remotely or locally, and is it always a total update or could be a partial?
if typeof uid is 'object' and user._id and not user?
user = uid
uid = user._id
if typeof uid is 'string' and typeof user is 'object' and JSON.stringify(user) isnt '{}'
uid = uid.replace('users/','') if uid.startsWith 'users/'
uid = @hashhex(uid.trim().toLowerCase()) if uid.includes '@'
user.updatedAt = new Date()
try await @kv 'users/' + uid, user
try @waitUntil @index 'users/' + uid, user
return true
else
return false
P.users._delete = (uid) ->
if user = (if typeof uid is 'object' then uid else if @user?._id is uid then @user else await @users._get uid)
try await @kv._each 'auth/resume/' + user._id, ''
try await @kv 'auth/apikey/' + user.apikey, ''
try await @kv 'users/' + user._id, ''
try await @index 'users/' + user._id, ''
|
[
{
"context": "###\n * kopi\n * https://github.com/leny/kopi\n *\n * JS/COFFEE Document - /cli.js - cli ent",
"end": 38,
"score": 0.9995778799057007,
"start": 34,
"tag": "USERNAME",
"value": "leny"
},
{
"context": "ommander setup and runner\n *\n * Copyright (c) 2014 Leny\n * Licensed... | src/kopi.coffee | leny/kopi | 0 | ###
* kopi
* https://github.com/leny/kopi
*
* JS/COFFEE Document - /cli.js - cli entry point, commander setup and runner
*
* Copyright (c) 2014 Leny
* Licensed under the MIT license.
###
"use strict"
pkg = require "../package.json"
fs = require "fs"
cliparoo = require "cliparoo"
chalk = require "chalk"
error = chalk.bold.red
( spinner = require "simple-spinner" )
.change_sequence [
"◓"
"◑"
"◒"
"◐"
]
( program = require "commander" )
.version pkg.version
.usage "[options] <file>"
.description "Command-line tool to copy the content of a file to the clipboard."
.option "-v, --verbose", "show the content of the file in the console"
.parse process.argv
unless sFile = program.args[ 0 ]
console.log error "✘ unknown file '#{ sFile }'."
process.exit 1
spinner.start 50
fs.readFile sFile, { encoding: "utf-8" }, ( oError, sData ) ->
spinner.stop()
if oError
console.log error "✘ #{ oError }."
process.exit 1
console.log sData if program.verbose
cliparoo sData
console.log chalk.green "✔ Content of '#{ sFile }' copied to the clipboard."
process.exit 0
| 209941 | ###
* kopi
* https://github.com/leny/kopi
*
* JS/COFFEE Document - /cli.js - cli entry point, commander setup and runner
*
* Copyright (c) 2014 <NAME>
* Licensed under the MIT license.
###
"use strict"
pkg = require "../package.json"
fs = require "fs"
cliparoo = require "cliparoo"
chalk = require "chalk"
error = chalk.bold.red
( spinner = require "simple-spinner" )
.change_sequence [
"◓"
"◑"
"◒"
"◐"
]
( program = require "commander" )
.version pkg.version
.usage "[options] <file>"
.description "Command-line tool to copy the content of a file to the clipboard."
.option "-v, --verbose", "show the content of the file in the console"
.parse process.argv
unless sFile = program.args[ 0 ]
console.log error "✘ unknown file '#{ sFile }'."
process.exit 1
spinner.start 50
fs.readFile sFile, { encoding: "utf-8" }, ( oError, sData ) ->
spinner.stop()
if oError
console.log error "✘ #{ oError }."
process.exit 1
console.log sData if program.verbose
cliparoo sData
console.log chalk.green "✔ Content of '#{ sFile }' copied to the clipboard."
process.exit 0
| true | ###
* kopi
* https://github.com/leny/kopi
*
* JS/COFFEE Document - /cli.js - cli entry point, commander setup and runner
*
* Copyright (c) 2014 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
"use strict"
pkg = require "../package.json"
fs = require "fs"
cliparoo = require "cliparoo"
chalk = require "chalk"
error = chalk.bold.red
( spinner = require "simple-spinner" )
.change_sequence [
"◓"
"◑"
"◒"
"◐"
]
( program = require "commander" )
.version pkg.version
.usage "[options] <file>"
.description "Command-line tool to copy the content of a file to the clipboard."
.option "-v, --verbose", "show the content of the file in the console"
.parse process.argv
unless sFile = program.args[ 0 ]
console.log error "✘ unknown file '#{ sFile }'."
process.exit 1
spinner.start 50
fs.readFile sFile, { encoding: "utf-8" }, ( oError, sData ) ->
spinner.stop()
if oError
console.log error "✘ #{ oError }."
process.exit 1
console.log sData if program.verbose
cliparoo sData
console.log chalk.green "✔ Content of '#{ sFile }' copied to the clipboard."
process.exit 0
|
[
{
"context": "nents()\n\n\tchangelog: ->\n\t\t@title.html(\"Changelog · Maxmertkit\")\n\t\tBackbone.history.templates = 'changelog'\n\t\tBa",
"end": 3279,
"score": 0.9887621402740479,
"start": 3269,
"tag": "NAME",
"value": "Maxmertkit"
},
{
"context": "og()\n\n\texamplesBlog: ->\n\t\... | docs/coffee/routers/router.coffee | maxmert/maxmertkit | 69 | LayoutIndex = require('../layouts/pages/index').module
LayoutStart = require('../layouts/pages/start').module
LayoutBasic = require('../layouts/pages/basic').module
LayoutWidgets = require('../layouts/pages/widgets').module
LayoutUtilities = require('../layouts/pages/utilities').module
LayoutComponents = require('../layouts/pages/components').module
LayoutChangelog = require('../layouts/pages/changelog').module
LayoutExamples = require('../layouts/pages/examples')
Layout404 = require('../layouts/pages/404').module
mainController =
changeFragment = ( fragment ) ->
if fragment[0] is '!'
fragment.replace /\!\//g, ""
else
fragment
exports.module = Marionette.AppRouter.extend
controller: mainController
title: $('title')
routes:
'': 'index'
'start': 'start'
'basic': 'basic'
'widgets': 'widgets'
'utilities': 'utilities'
'components': 'components'
'changelog': 'changelog'
'examples/blog': 'examplesBlog'
"*error": "error404"
initialize: ->
@bind 'all', @_trackPageview
_trackPageview: ->
url = Backbone.history.getFragment()
if !/^\//.test(url) then url = '/' + url
window._gaq?.push(['_trackPageview', url])
if window['GoogleAnalyticsObject']?
ga('send', 'pageview', url)
route: (route, name, callback) ->
route = "(!/)" + route
route = @_routeToRegExp(route) unless _.isRegExp(route)
if _.isFunction(name)
callback = name
name = ""
callback = this[name] unless callback
router = this
Backbone.history.route route, (fragment) =>
# if fragment[0] is '!' then fragment = fragment.replace /\!\//g, ""
args = router._extractParameters(route, fragment)
$.app.commands.execute 'loader', 'start', Backbone.history.color
setTimeout =>
router.execute callback, args
router.trigger.apply router, ["route:" + name].concat(args)
router.trigger "route", name, args
Backbone.history.trigger "route", router, name, args
$.app.commands.execute 'loader', 'finish'
, 50
return
this
index: ->
@title.html("Maxmertkit")
Backbone.history.templates = 'index'
$.app.main.currentView.content.show new LayoutIndex()
start: ->
@title.html("Start · Maxmertkit")
Backbone.history.color = '#3f3f3f'
Backbone.history.templates = 'start'
$.app.main.currentView.content.show new LayoutStart()
basic: ->
@title.html("Basic · Maxmertkit")
Backbone.history.color = '#b62d93'
Backbone.history.templates = 'basic'
$.app.main.currentView.content.show new LayoutBasic()
# widgets: ->
# Backbone.history.color = '#44a4b6'
# Backbone.history.templates = 'basic'
# $.app.main.currentView.content.show new LayoutBasic()
widgets: ->
@title.html("Widgets · Maxmertkit")
Backbone.history.templates = 'widgets'
Backbone.history.color = '#3087aa'
$.app.main.currentView.content.show new LayoutWidgets()
utilities: ->
@title.html("Utilities · Maxmertkit")
Backbone.history.templates = 'utilities'
Backbone.history.color = '#972822'
$.app.main.currentView.content.show new LayoutUtilities()
components: ->
@title.html("Components · Maxmertkit")
Backbone.history.templates = 'components'
Backbone.history.color = '#25a800'
$.app.main.currentView.content.show new LayoutComponents()
changelog: ->
@title.html("Changelog · Maxmertkit")
Backbone.history.templates = 'changelog'
Backbone.history.color = '#25a800'
$.app.main.currentView.content.show new LayoutChangelog()
examplesBlog: ->
@title.html("Changelog · Maxmertkit")
Backbone.history.templates = null
Backbone.history.color = '#25a800'
$.app.main.currentView.content.show new LayoutExamples.blog()
error404: ->
@title.html("404 · Maxmertkit")
$.app.commands.execute 'menu', 'activate'
$.app.main.currentView.content.close()
$.app.main.currentView.content.show new Layout404()
| 64266 | LayoutIndex = require('../layouts/pages/index').module
LayoutStart = require('../layouts/pages/start').module
LayoutBasic = require('../layouts/pages/basic').module
LayoutWidgets = require('../layouts/pages/widgets').module
LayoutUtilities = require('../layouts/pages/utilities').module
LayoutComponents = require('../layouts/pages/components').module
LayoutChangelog = require('../layouts/pages/changelog').module
LayoutExamples = require('../layouts/pages/examples')
Layout404 = require('../layouts/pages/404').module
mainController =
changeFragment = ( fragment ) ->
if fragment[0] is '!'
fragment.replace /\!\//g, ""
else
fragment
exports.module = Marionette.AppRouter.extend
controller: mainController
title: $('title')
routes:
'': 'index'
'start': 'start'
'basic': 'basic'
'widgets': 'widgets'
'utilities': 'utilities'
'components': 'components'
'changelog': 'changelog'
'examples/blog': 'examplesBlog'
"*error": "error404"
initialize: ->
@bind 'all', @_trackPageview
_trackPageview: ->
url = Backbone.history.getFragment()
if !/^\//.test(url) then url = '/' + url
window._gaq?.push(['_trackPageview', url])
if window['GoogleAnalyticsObject']?
ga('send', 'pageview', url)
route: (route, name, callback) ->
route = "(!/)" + route
route = @_routeToRegExp(route) unless _.isRegExp(route)
if _.isFunction(name)
callback = name
name = ""
callback = this[name] unless callback
router = this
Backbone.history.route route, (fragment) =>
# if fragment[0] is '!' then fragment = fragment.replace /\!\//g, ""
args = router._extractParameters(route, fragment)
$.app.commands.execute 'loader', 'start', Backbone.history.color
setTimeout =>
router.execute callback, args
router.trigger.apply router, ["route:" + name].concat(args)
router.trigger "route", name, args
Backbone.history.trigger "route", router, name, args
$.app.commands.execute 'loader', 'finish'
, 50
return
this
index: ->
@title.html("Maxmertkit")
Backbone.history.templates = 'index'
$.app.main.currentView.content.show new LayoutIndex()
start: ->
@title.html("Start · Maxmertkit")
Backbone.history.color = '#3f3f3f'
Backbone.history.templates = 'start'
$.app.main.currentView.content.show new LayoutStart()
basic: ->
@title.html("Basic · Maxmertkit")
Backbone.history.color = '#b62d93'
Backbone.history.templates = 'basic'
$.app.main.currentView.content.show new LayoutBasic()
# widgets: ->
# Backbone.history.color = '#44a4b6'
# Backbone.history.templates = 'basic'
# $.app.main.currentView.content.show new LayoutBasic()
widgets: ->
@title.html("Widgets · Maxmertkit")
Backbone.history.templates = 'widgets'
Backbone.history.color = '#3087aa'
$.app.main.currentView.content.show new LayoutWidgets()
utilities: ->
@title.html("Utilities · Maxmertkit")
Backbone.history.templates = 'utilities'
Backbone.history.color = '#972822'
$.app.main.currentView.content.show new LayoutUtilities()
components: ->
@title.html("Components · Maxmertkit")
Backbone.history.templates = 'components'
Backbone.history.color = '#25a800'
$.app.main.currentView.content.show new LayoutComponents()
changelog: ->
@title.html("Changelog · <NAME>")
Backbone.history.templates = 'changelog'
Backbone.history.color = '#25a800'
$.app.main.currentView.content.show new LayoutChangelog()
examplesBlog: ->
@title.html("Changelog · <NAME>")
Backbone.history.templates = null
Backbone.history.color = '#25a800'
$.app.main.currentView.content.show new LayoutExamples.blog()
error404: ->
@title.html("404 · <NAME>")
$.app.commands.execute 'menu', 'activate'
$.app.main.currentView.content.close()
$.app.main.currentView.content.show new Layout404()
| true | LayoutIndex = require('../layouts/pages/index').module
LayoutStart = require('../layouts/pages/start').module
LayoutBasic = require('../layouts/pages/basic').module
LayoutWidgets = require('../layouts/pages/widgets').module
LayoutUtilities = require('../layouts/pages/utilities').module
LayoutComponents = require('../layouts/pages/components').module
LayoutChangelog = require('../layouts/pages/changelog').module
LayoutExamples = require('../layouts/pages/examples')
Layout404 = require('../layouts/pages/404').module
mainController =
changeFragment = ( fragment ) ->
if fragment[0] is '!'
fragment.replace /\!\//g, ""
else
fragment
exports.module = Marionette.AppRouter.extend
controller: mainController
title: $('title')
routes:
'': 'index'
'start': 'start'
'basic': 'basic'
'widgets': 'widgets'
'utilities': 'utilities'
'components': 'components'
'changelog': 'changelog'
'examples/blog': 'examplesBlog'
"*error": "error404"
initialize: ->
@bind 'all', @_trackPageview
_trackPageview: ->
url = Backbone.history.getFragment()
if !/^\//.test(url) then url = '/' + url
window._gaq?.push(['_trackPageview', url])
if window['GoogleAnalyticsObject']?
ga('send', 'pageview', url)
route: (route, name, callback) ->
route = "(!/)" + route
route = @_routeToRegExp(route) unless _.isRegExp(route)
if _.isFunction(name)
callback = name
name = ""
callback = this[name] unless callback
router = this
Backbone.history.route route, (fragment) =>
# if fragment[0] is '!' then fragment = fragment.replace /\!\//g, ""
args = router._extractParameters(route, fragment)
$.app.commands.execute 'loader', 'start', Backbone.history.color
setTimeout =>
router.execute callback, args
router.trigger.apply router, ["route:" + name].concat(args)
router.trigger "route", name, args
Backbone.history.trigger "route", router, name, args
$.app.commands.execute 'loader', 'finish'
, 50
return
this
index: ->
@title.html("Maxmertkit")
Backbone.history.templates = 'index'
$.app.main.currentView.content.show new LayoutIndex()
start: ->
@title.html("Start · Maxmertkit")
Backbone.history.color = '#3f3f3f'
Backbone.history.templates = 'start'
$.app.main.currentView.content.show new LayoutStart()
basic: ->
@title.html("Basic · Maxmertkit")
Backbone.history.color = '#b62d93'
Backbone.history.templates = 'basic'
$.app.main.currentView.content.show new LayoutBasic()
# widgets: ->
# Backbone.history.color = '#44a4b6'
# Backbone.history.templates = 'basic'
# $.app.main.currentView.content.show new LayoutBasic()
widgets: ->
@title.html("Widgets · Maxmertkit")
Backbone.history.templates = 'widgets'
Backbone.history.color = '#3087aa'
$.app.main.currentView.content.show new LayoutWidgets()
utilities: ->
@title.html("Utilities · Maxmertkit")
Backbone.history.templates = 'utilities'
Backbone.history.color = '#972822'
$.app.main.currentView.content.show new LayoutUtilities()
components: ->
@title.html("Components · Maxmertkit")
Backbone.history.templates = 'components'
Backbone.history.color = '#25a800'
$.app.main.currentView.content.show new LayoutComponents()
changelog: ->
@title.html("Changelog · PI:NAME:<NAME>END_PI")
Backbone.history.templates = 'changelog'
Backbone.history.color = '#25a800'
$.app.main.currentView.content.show new LayoutChangelog()
examplesBlog: ->
@title.html("Changelog · PI:NAME:<NAME>END_PI")
Backbone.history.templates = null
Backbone.history.color = '#25a800'
$.app.main.currentView.content.show new LayoutExamples.blog()
error404: ->
@title.html("404 · PI:NAME:<NAME>END_PI")
$.app.commands.execute 'menu', 'activate'
$.app.main.currentView.content.close()
$.app.main.currentView.content.show new Layout404()
|
[
{
"context": "gth && chartData\n data = [\n {\n key: i18n.t(\"labels.chart.timers\"),\n values: chartData",
"end": 106,
"score": 0.8513455986976624,
"start": 100,
"tag": "KEY",
"value": "i18n.t"
}
] | app/assets/javascripts/app/chart.coffee | DanielMSchmidt/app | 0 | window.loadChart = ->
if $('#timers-chart').length && chartData
data = [
{
key: i18n.t("labels.chart.timers"),
values: chartData
}
]
nv.addGraph ->
chart = nv.models.multiBarChart()
.margin({top: 20, right: 0, bottom: 40, left: 15})
.noData(i18n.t("labels.chart.no_data"))
.showControls(false)
.stacked(true)
.tooltip (key, x, y, e, graph) ->
return "<h3>#{key}</h3><p>#{decimalToTime(e.value) || "0:00"}h #{i18n.t('labels.chart.on_date')} #{x}</p>"
chart.xAxis
.showMaxMin(false)
.scale(d3.time.scale())
.tickFormat (d) ->
return moment(d).format("D. MMM YY")
chart.yAxis
.tickFormat (d) ->
return d3.format('d')(d || 0)
d3.select('#timers-chart svg')
.datum(chartData)
.transition().duration(500).call(chart)
nv.utils.windowResize(chart.update)
return chart
| 39169 | window.loadChart = ->
if $('#timers-chart').length && chartData
data = [
{
key: <KEY>("labels.chart.timers"),
values: chartData
}
]
nv.addGraph ->
chart = nv.models.multiBarChart()
.margin({top: 20, right: 0, bottom: 40, left: 15})
.noData(i18n.t("labels.chart.no_data"))
.showControls(false)
.stacked(true)
.tooltip (key, x, y, e, graph) ->
return "<h3>#{key}</h3><p>#{decimalToTime(e.value) || "0:00"}h #{i18n.t('labels.chart.on_date')} #{x}</p>"
chart.xAxis
.showMaxMin(false)
.scale(d3.time.scale())
.tickFormat (d) ->
return moment(d).format("D. MMM YY")
chart.yAxis
.tickFormat (d) ->
return d3.format('d')(d || 0)
d3.select('#timers-chart svg')
.datum(chartData)
.transition().duration(500).call(chart)
nv.utils.windowResize(chart.update)
return chart
| true | window.loadChart = ->
if $('#timers-chart').length && chartData
data = [
{
key: PI:KEY:<KEY>END_PI("labels.chart.timers"),
values: chartData
}
]
nv.addGraph ->
chart = nv.models.multiBarChart()
.margin({top: 20, right: 0, bottom: 40, left: 15})
.noData(i18n.t("labels.chart.no_data"))
.showControls(false)
.stacked(true)
.tooltip (key, x, y, e, graph) ->
return "<h3>#{key}</h3><p>#{decimalToTime(e.value) || "0:00"}h #{i18n.t('labels.chart.on_date')} #{x}</p>"
chart.xAxis
.showMaxMin(false)
.scale(d3.time.scale())
.tickFormat (d) ->
return moment(d).format("D. MMM YY")
chart.yAxis
.tickFormat (d) ->
return d3.format('d')(d || 0)
d3.select('#timers-chart svg')
.datum(chartData)
.transition().duration(500).call(chart)
nv.utils.windowResize(chart.update)
return chart
|
[
{
"context": "ter run\": (data) ->\n tableau.password = JSON.stringify\n credentials:\n ",
"end": 3115,
"score": 0.8978278636932373,
"start": 3111,
"tag": "PASSWORD",
"value": "JSON"
},
{
"context": ": data.auth_username\n passwo... | coffee/sap_bo/sap_bo_connector.coffee | enterstudio/tableau-web-table-connector | 59 | $ = require 'jquery'
_ = require 'underscore'
dateFormat = require('dateformat')
helpers = require '../connector_base/tableau_helpers'
wdc_base = require '../connector_base/starschema_wdc_base.coffee'
PROXY_SERVER_CONFIG =
protocol: 'http'
rowConverter = {}
# Transforms type to tableau type
transformType = (type) ->
switch type
when 'STRING' then tableau.dataTypeEnum.string
when 'DOUBLE', 'FLOAT' then tableau.dataTypeEnum.float
when 'INT32', 'INT64', 'UINT32', 'UINT64' then tableau.dataTypeEnum.int
when 'DATE' then tableau.dataTypeEnum.date
when 'DATETIME' then tableau.dataTypeEnum.datetime
else tableau.dataTypeEnum.string
# Attempts to convert a list of fields to a table schema compatible
# with tableau
toTableauSchema = (fields)->
fields.map (field)-> {id: sanitizeId(field.name), dataType: transformType(field.type) }
# Creates a converter from the given schema
makeRowConverter = (schema) ->
converters = {}
Object.keys(schema).map (k)->
converters[schema[k].id] = switch schema[k].dataType
when tableau.dataTypeEnum.datetime then (x) -> convertToDateString(x, "yyyy-mm-dd HH:MM:ss")
when tableau.dataTypeEnum.date then (x) -> convertToDateString(x, "yyyy-mm-dd")
else (x)-> x
(row) ->
Object.keys(row).map (k)->
converters[sanitizeId k](row[k])
# Replaces any non-id characters with an underscore
sanitizeId = (name)->
name.replace(/[^a-zA-Z0-9_]/g, '_')
# Parse date to a given format
convertToDateString = (dateString, format) ->
date = new Date(dateString)
return dateFormat(date, format) if not isNaN(date) and isFinite(date.getTime())
dateString
wdc_base.make_tableau_connector
steps:
start:
template: require './start.jade'
configuration:
template: require './configuration.jade'
run:
template: require './run.jade'
transitions:
"enter start": (data)->
if data.error
$('#error').show().text(data.error)
else
$('#error').hide().text()
"start > configuration": (data) ->
_.extend data, wdc_base.fetch_inputs("#state-start")
"configuration > run": (data) ->
_.extend data, wdc_base.fetch_inputs("#state-configuration")
"enter configuration": (data, from,to, transitionTo) ->
url = "#{PROXY_SERVER_CONFIG.protocol}://#{window.location.host}/sap/tablelist"
$.ajax
url: url
dataType: 'json'
data:
"wsdl": data.wsdl
success: (data, textStatus, request) ->
for table in data
$("<option>").val(table).text(table).appendTo('#tables')
error: (o, statusStr, err) ->
console.log o
console.error err
transitionTo "start", error: "While fetching '#{url}':\n#{o.responseText}\n#{err}"
"enter run": (data) ->
tableau.password = JSON.stringify
credentials:
username: data.auth_username
password: data.auth_password
delete data.auth_username
delete data.auth_password
wdc_base.set_connection_data data
tableau.submit()
columns: (connection_data, schemaCallback) ->
connectionUrl = "#{PROXY_SERVER_CONFIG.protocol}://#{window.location.host}/sap/tabledefinitions"
config = JSON.parse(tableau.password)
config.wsdl = connection_data.wsdl
config.table = connection_data.table
xhr_params =
url: connectionUrl
dataType: 'json'
data: config
success: (data, textStatus, request)->
if data?.length > 0
schema = toTableauSchema(data)
rowConverter = makeRowConverter schema
schemaCallback [
id: sanitizeId(config.table),
columns: schema
]
error: (err) ->
console.error "Error while loading headers from `#{connectionUrl}`:", err
tableau.abortWithError err.responseText
$.ajax xhr_params
rows: (connection_data, table, doneCallback) ->
connectionUrl = window.location.protocol + '//' + window.location.host + '/sap/tablerows'
config = JSON.parse(tableau.password)
config.wsdl = connection_data.wsdl
config.table = connection_data.table
_.extend connection_data, JSON.parse(tableau.password)
xhr_params =
url: connectionUrl
dataType: 'json'
data: config
success: (data, textStatus, request)->
if data.length > 0
table.appendRows(data.map(rowConverter))
doneCallback()
error: (err) ->
console.error "Error while loading rows from `#{connectionUrl}`:", err
tableau.abortWithError err.responseText
$.ajax xhr_params
| 211081 | $ = require 'jquery'
_ = require 'underscore'
dateFormat = require('dateformat')
helpers = require '../connector_base/tableau_helpers'
wdc_base = require '../connector_base/starschema_wdc_base.coffee'
PROXY_SERVER_CONFIG =
protocol: 'http'
rowConverter = {}
# Transforms type to tableau type
transformType = (type) ->
switch type
when 'STRING' then tableau.dataTypeEnum.string
when 'DOUBLE', 'FLOAT' then tableau.dataTypeEnum.float
when 'INT32', 'INT64', 'UINT32', 'UINT64' then tableau.dataTypeEnum.int
when 'DATE' then tableau.dataTypeEnum.date
when 'DATETIME' then tableau.dataTypeEnum.datetime
else tableau.dataTypeEnum.string
# Attempts to convert a list of fields to a table schema compatible
# with tableau
toTableauSchema = (fields)->
fields.map (field)-> {id: sanitizeId(field.name), dataType: transformType(field.type) }
# Creates a converter from the given schema
makeRowConverter = (schema) ->
converters = {}
Object.keys(schema).map (k)->
converters[schema[k].id] = switch schema[k].dataType
when tableau.dataTypeEnum.datetime then (x) -> convertToDateString(x, "yyyy-mm-dd HH:MM:ss")
when tableau.dataTypeEnum.date then (x) -> convertToDateString(x, "yyyy-mm-dd")
else (x)-> x
(row) ->
Object.keys(row).map (k)->
converters[sanitizeId k](row[k])
# Replaces any non-id characters with an underscore
sanitizeId = (name)->
name.replace(/[^a-zA-Z0-9_]/g, '_')
# Parse date to a given format
convertToDateString = (dateString, format) ->
date = new Date(dateString)
return dateFormat(date, format) if not isNaN(date) and isFinite(date.getTime())
dateString
wdc_base.make_tableau_connector
steps:
start:
template: require './start.jade'
configuration:
template: require './configuration.jade'
run:
template: require './run.jade'
transitions:
"enter start": (data)->
if data.error
$('#error').show().text(data.error)
else
$('#error').hide().text()
"start > configuration": (data) ->
_.extend data, wdc_base.fetch_inputs("#state-start")
"configuration > run": (data) ->
_.extend data, wdc_base.fetch_inputs("#state-configuration")
"enter configuration": (data, from,to, transitionTo) ->
url = "#{PROXY_SERVER_CONFIG.protocol}://#{window.location.host}/sap/tablelist"
$.ajax
url: url
dataType: 'json'
data:
"wsdl": data.wsdl
success: (data, textStatus, request) ->
for table in data
$("<option>").val(table).text(table).appendTo('#tables')
error: (o, statusStr, err) ->
console.log o
console.error err
transitionTo "start", error: "While fetching '#{url}':\n#{o.responseText}\n#{err}"
"enter run": (data) ->
tableau.password = <PASSWORD>.stringify
credentials:
username: data.auth_username
password: <PASSWORD>
delete data.auth_username
delete data.auth_password
wdc_base.set_connection_data data
tableau.submit()
columns: (connection_data, schemaCallback) ->
connectionUrl = "#{PROXY_SERVER_CONFIG.protocol}://#{window.location.host}/sap/tabledefinitions"
config = JSON.parse(tableau.password)
config.wsdl = connection_data.wsdl
config.table = connection_data.table
xhr_params =
url: connectionUrl
dataType: 'json'
data: config
success: (data, textStatus, request)->
if data?.length > 0
schema = toTableauSchema(data)
rowConverter = makeRowConverter schema
schemaCallback [
id: sanitizeId(config.table),
columns: schema
]
error: (err) ->
console.error "Error while loading headers from `#{connectionUrl}`:", err
tableau.abortWithError err.responseText
$.ajax xhr_params
rows: (connection_data, table, doneCallback) ->
connectionUrl = window.location.protocol + '//' + window.location.host + '/sap/tablerows'
config = JSON.parse(tableau.password)
config.wsdl = connection_data.wsdl
config.table = connection_data.table
_.extend connection_data, JSON.parse(tableau.password)
xhr_params =
url: connectionUrl
dataType: 'json'
data: config
success: (data, textStatus, request)->
if data.length > 0
table.appendRows(data.map(rowConverter))
doneCallback()
error: (err) ->
console.error "Error while loading rows from `#{connectionUrl}`:", err
tableau.abortWithError err.responseText
$.ajax xhr_params
| true | $ = require 'jquery'
_ = require 'underscore'
dateFormat = require('dateformat')
helpers = require '../connector_base/tableau_helpers'
wdc_base = require '../connector_base/starschema_wdc_base.coffee'
PROXY_SERVER_CONFIG =
protocol: 'http'
rowConverter = {}
# Transforms type to tableau type
transformType = (type) ->
switch type
when 'STRING' then tableau.dataTypeEnum.string
when 'DOUBLE', 'FLOAT' then tableau.dataTypeEnum.float
when 'INT32', 'INT64', 'UINT32', 'UINT64' then tableau.dataTypeEnum.int
when 'DATE' then tableau.dataTypeEnum.date
when 'DATETIME' then tableau.dataTypeEnum.datetime
else tableau.dataTypeEnum.string
# Attempts to convert a list of fields to a table schema compatible
# with tableau
toTableauSchema = (fields)->
fields.map (field)-> {id: sanitizeId(field.name), dataType: transformType(field.type) }
# Creates a converter from the given schema
makeRowConverter = (schema) ->
converters = {}
Object.keys(schema).map (k)->
converters[schema[k].id] = switch schema[k].dataType
when tableau.dataTypeEnum.datetime then (x) -> convertToDateString(x, "yyyy-mm-dd HH:MM:ss")
when tableau.dataTypeEnum.date then (x) -> convertToDateString(x, "yyyy-mm-dd")
else (x)-> x
(row) ->
Object.keys(row).map (k)->
converters[sanitizeId k](row[k])
# Replaces any non-id characters with an underscore
sanitizeId = (name)->
name.replace(/[^a-zA-Z0-9_]/g, '_')
# Parse date to a given format
convertToDateString = (dateString, format) ->
date = new Date(dateString)
return dateFormat(date, format) if not isNaN(date) and isFinite(date.getTime())
dateString
wdc_base.make_tableau_connector
steps:
start:
template: require './start.jade'
configuration:
template: require './configuration.jade'
run:
template: require './run.jade'
transitions:
"enter start": (data)->
if data.error
$('#error').show().text(data.error)
else
$('#error').hide().text()
"start > configuration": (data) ->
_.extend data, wdc_base.fetch_inputs("#state-start")
"configuration > run": (data) ->
_.extend data, wdc_base.fetch_inputs("#state-configuration")
"enter configuration": (data, from,to, transitionTo) ->
url = "#{PROXY_SERVER_CONFIG.protocol}://#{window.location.host}/sap/tablelist"
$.ajax
url: url
dataType: 'json'
data:
"wsdl": data.wsdl
success: (data, textStatus, request) ->
for table in data
$("<option>").val(table).text(table).appendTo('#tables')
error: (o, statusStr, err) ->
console.log o
console.error err
transitionTo "start", error: "While fetching '#{url}':\n#{o.responseText}\n#{err}"
"enter run": (data) ->
tableau.password = PI:PASSWORD:<PASSWORD>END_PI.stringify
credentials:
username: data.auth_username
password: PI:PASSWORD:<PASSWORD>END_PI
delete data.auth_username
delete data.auth_password
wdc_base.set_connection_data data
tableau.submit()
columns: (connection_data, schemaCallback) ->
connectionUrl = "#{PROXY_SERVER_CONFIG.protocol}://#{window.location.host}/sap/tabledefinitions"
config = JSON.parse(tableau.password)
config.wsdl = connection_data.wsdl
config.table = connection_data.table
xhr_params =
url: connectionUrl
dataType: 'json'
data: config
success: (data, textStatus, request)->
if data?.length > 0
schema = toTableauSchema(data)
rowConverter = makeRowConverter schema
schemaCallback [
id: sanitizeId(config.table),
columns: schema
]
error: (err) ->
console.error "Error while loading headers from `#{connectionUrl}`:", err
tableau.abortWithError err.responseText
$.ajax xhr_params
rows: (connection_data, table, doneCallback) ->
connectionUrl = window.location.protocol + '//' + window.location.host + '/sap/tablerows'
config = JSON.parse(tableau.password)
config.wsdl = connection_data.wsdl
config.table = connection_data.table
_.extend connection_data, JSON.parse(tableau.password)
xhr_params =
url: connectionUrl
dataType: 'json'
data: config
success: (data, textStatus, request)->
if data.length > 0
table.appendRows(data.map(rowConverter))
doneCallback()
error: (err) ->
console.error "Error while loading rows from `#{connectionUrl}`:", err
tableau.abortWithError err.responseText
$.ajax xhr_params
|
[
{
"context": ", name: global.DEFAULT_ROOM)\n\n # Test\n context 'alice: nlp', ->\n beforeEach ->\n co =>\n y",
"end": 255,
"score": 0.8905132412910461,
"start": 250,
"tag": "NAME",
"value": "alice"
},
{
"context": "Each ->\n co =>\n yield @room.user.say '... | test/scripts/test_hello_ai.coffee | NandanSharma/AIDetails | 0 | helper = new Helper('../scripts/hello_ai.js')
describe 'scripts/hello_ai.js', ->
beforeEach ->
# creating room with 'httpd: false' will auto tear-down
@room = helper.createRoom(httpd: false, name: global.DEFAULT_ROOM)
# Test
context 'alice: nlp', ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot nlp'
yield delayer()
# response
it 'hubot: `nlp <text>`', ->
@room.messages.should.eql [
['alice', '@hubot nlp']
['hubot', '`nlp <text>`']
]
# Test
context 'alice: nlp find me flights from New York to London at 9pm tomorrow.', ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot nlp find me flights from New York to London at 9pm tomorrow.'
yield delayer()
# response
it 'hubot: <nlp results>', ->
@room.messages.should.have.length 2
| 12876 | helper = new Helper('../scripts/hello_ai.js')
describe 'scripts/hello_ai.js', ->
beforeEach ->
# creating room with 'httpd: false' will auto tear-down
@room = helper.createRoom(httpd: false, name: global.DEFAULT_ROOM)
# Test
context '<NAME>: nlp', ->
beforeEach ->
co =>
yield @room.user.say '<NAME>', '@hubot nlp'
yield delayer()
# response
it 'hubot: `nlp <text>`', ->
@room.messages.should.eql [
['<NAME>', '@hubot nlp']
['hubot', '`nlp <text>`']
]
# Test
context '<NAME>: nlp find me flights from New York to London at 9pm tomorrow.', ->
beforeEach ->
co =>
yield @room.user.say '<NAME>', '@hubot nlp find me flights from New York to London at 9pm tomorrow.'
yield delayer()
# response
it 'hubot: <nlp results>', ->
@room.messages.should.have.length 2
| true | helper = new Helper('../scripts/hello_ai.js')
describe 'scripts/hello_ai.js', ->
beforeEach ->
# creating room with 'httpd: false' will auto tear-down
@room = helper.createRoom(httpd: false, name: global.DEFAULT_ROOM)
# Test
context 'PI:NAME:<NAME>END_PI: nlp', ->
beforeEach ->
co =>
yield @room.user.say 'PI:NAME:<NAME>END_PI', '@hubot nlp'
yield delayer()
# response
it 'hubot: `nlp <text>`', ->
@room.messages.should.eql [
['PI:NAME:<NAME>END_PI', '@hubot nlp']
['hubot', '`nlp <text>`']
]
# Test
context 'PI:NAME:<NAME>END_PI: nlp find me flights from New York to London at 9pm tomorrow.', ->
beforeEach ->
co =>
yield @room.user.say 'PI:NAME:<NAME>END_PI', '@hubot nlp find me flights from New York to London at 9pm tomorrow.'
yield delayer()
# response
it 'hubot: <nlp results>', ->
@room.messages.should.have.length 2
|
[
{
"context": "l)\n#\n# Commands:\n# hubot enhance\n#\n# Author:\n# Evan Coleman (edc1591)\n\nenhanceDelay = 1000\n\ngm = require('gm'",
"end": 222,
"score": 0.9998666644096375,
"start": 210,
"tag": "NAME",
"value": "Evan Coleman"
},
{
"context": ":\n# hubot enhance\n#\n# Author... | src/enhance.coffee | edc1591/hubot-enhance | 1 | # Description:
# Enhance an image
#
# Dependencies:
# gm
# request
#
# Configuration:
# HUBOT_IMGUR_CLIENT_ID (Required)
# HUBOT_SLACK_TOKEN (Optional)
#
# Commands:
# hubot enhance
#
# Author:
# Evan Coleman (edc1591)
enhanceDelay = 1000
gm = require('gm')
request = require('request');
module.exports = (robot) ->
robot.respond /enhance$/i, (msg) ->
fetchLatestImage msg, (url, w, h) ->
if url != null
processImage url, w, h, 50, 50, (url) ->
msg.send url
robot.respond /enhance [0-9][0-9]?[0-9]? [0-9][0-9]?[0-9]?(.*)?/i, (msg) ->
split = msg.match.input.split(" ")
x = split[2]
y = split[3]
if split.length > 4
input = split[4].replace(">", "").replace("<", "")
getDimensions input, (width, height) ->
enhance msg, input, width, height, x, y
else
fetchLatestImage msg, (url, width, height) ->
enhance msg, url, width, height, x, y
getDimensions = (url, cb) ->
gm(request(url), "image.jpg")
.options({imageMagick: true})
.size (err, size) ->
cb size.width, size.height
enhance = (msg, url, w, h, x, y) ->
processImage url, w, h, x, y, (url) ->
msg.send url
setTimeout ( ->
processImage url, w, h, 50, 50, (url) ->
msg.send url
setTimeout ( ->
processImage url, w, h, 50, 50, (url) ->
msg.send url
setTimeout ( ->
processImage url, w, h, 50, 50, (url) ->
msg.send url
), enhanceDelay
), enhanceDelay
), enhanceDelay
fetchLatestImage = (msg, cb) ->
if msg.robot.adapterName == "slack"
request.get "https://slack.com/api/channels.list?token="+process.env.HUBOT_SLACK_TOKEN, (err, resp, body) ->
channelsResp = JSON.parse body
channelId = item.id for item in channelsResp.channels when item.name == msg.message.room
request.get "https://slack.com/api/channels.history?token="+process.env.HUBOT_SLACK_TOKEN+"&channel="+channelId, (err, resp, body) ->
history = JSON.parse body
for item in history.messages
if item.attachments and item.attachments.length > 0 and item.attachments[0].image_url
attachment = item.attachments[0]
cb item.attachments[0].image_url, item.attachments[0].image_width, item.attachments[0].image_height
return
else if item.file and item.file.url
getDimensions item.file.url, (w, h) ->
cb item.file.url, w, h
msg.reply "Couldn't find any images."
else
msg.reply "You must specify an image URL."
cb null, 0, 0
processImage = (url, w, h, x, y, cb) ->
if url != null
console.log "Enhancing " + url
width = w / 2
height = h / 2
console.log "Width: " + width + ", Height: " + height + ", x:" + ((width * (x / 100))) + ", y:" + ((height * (y / 100)))
gm(request(url), "image.jpg")
.options({imageMagick: true})
.crop(width, height, (width * (x / 100)), (height * (y / 100)))
.resize(w, h)
.stream (err, stdout, stderr) ->
buf = new Buffer(0)
stdout.on 'data', (d) ->
buf = Buffer.concat([buf, d])
stdout.on 'end', () ->
options =
url: "https://api.imgur.com/3/image"
formData:
image: buf
headers:
"Authorization": "Client-ID " + process.env.HUBOT_IMGUR_CLIENT_ID
request.post options, (err, httpResponse, body) ->
cb JSON.parse(body).data.link | 68772 | # Description:
# Enhance an image
#
# Dependencies:
# gm
# request
#
# Configuration:
# HUBOT_IMGUR_CLIENT_ID (Required)
# HUBOT_SLACK_TOKEN (Optional)
#
# Commands:
# hubot enhance
#
# Author:
# <NAME> (edc1591)
enhanceDelay = 1000
gm = require('gm')
request = require('request');
module.exports = (robot) ->
robot.respond /enhance$/i, (msg) ->
fetchLatestImage msg, (url, w, h) ->
if url != null
processImage url, w, h, 50, 50, (url) ->
msg.send url
robot.respond /enhance [0-9][0-9]?[0-9]? [0-9][0-9]?[0-9]?(.*)?/i, (msg) ->
split = msg.match.input.split(" ")
x = split[2]
y = split[3]
if split.length > 4
input = split[4].replace(">", "").replace("<", "")
getDimensions input, (width, height) ->
enhance msg, input, width, height, x, y
else
fetchLatestImage msg, (url, width, height) ->
enhance msg, url, width, height, x, y
getDimensions = (url, cb) ->
gm(request(url), "image.jpg")
.options({imageMagick: true})
.size (err, size) ->
cb size.width, size.height
enhance = (msg, url, w, h, x, y) ->
processImage url, w, h, x, y, (url) ->
msg.send url
setTimeout ( ->
processImage url, w, h, 50, 50, (url) ->
msg.send url
setTimeout ( ->
processImage url, w, h, 50, 50, (url) ->
msg.send url
setTimeout ( ->
processImage url, w, h, 50, 50, (url) ->
msg.send url
), enhanceDelay
), enhanceDelay
), enhanceDelay
fetchLatestImage = (msg, cb) ->
if msg.robot.adapterName == "slack"
request.get "https://slack.com/api/channels.list?token="+process.env.HUBOT_SLACK_TOKEN, (err, resp, body) ->
channelsResp = JSON.parse body
channelId = item.id for item in channelsResp.channels when item.name == msg.message.room
request.get "https://slack.com/api/channels.history?token="+process.env.HUBOT_SLACK_TOKEN+"&channel="+channelId, (err, resp, body) ->
history = JSON.parse body
for item in history.messages
if item.attachments and item.attachments.length > 0 and item.attachments[0].image_url
attachment = item.attachments[0]
cb item.attachments[0].image_url, item.attachments[0].image_width, item.attachments[0].image_height
return
else if item.file and item.file.url
getDimensions item.file.url, (w, h) ->
cb item.file.url, w, h
msg.reply "Couldn't find any images."
else
msg.reply "You must specify an image URL."
cb null, 0, 0
processImage = (url, w, h, x, y, cb) ->
if url != null
console.log "Enhancing " + url
width = w / 2
height = h / 2
console.log "Width: " + width + ", Height: " + height + ", x:" + ((width * (x / 100))) + ", y:" + ((height * (y / 100)))
gm(request(url), "image.jpg")
.options({imageMagick: true})
.crop(width, height, (width * (x / 100)), (height * (y / 100)))
.resize(w, h)
.stream (err, stdout, stderr) ->
buf = new Buffer(0)
stdout.on 'data', (d) ->
buf = Buffer.concat([buf, d])
stdout.on 'end', () ->
options =
url: "https://api.imgur.com/3/image"
formData:
image: buf
headers:
"Authorization": "Client-ID " + process.env.HUBOT_IMGUR_CLIENT_ID
request.post options, (err, httpResponse, body) ->
cb JSON.parse(body).data.link | true | # Description:
# Enhance an image
#
# Dependencies:
# gm
# request
#
# Configuration:
# HUBOT_IMGUR_CLIENT_ID (Required)
# HUBOT_SLACK_TOKEN (Optional)
#
# Commands:
# hubot enhance
#
# Author:
# PI:NAME:<NAME>END_PI (edc1591)
enhanceDelay = 1000
gm = require('gm')
request = require('request');
module.exports = (robot) ->
robot.respond /enhance$/i, (msg) ->
fetchLatestImage msg, (url, w, h) ->
if url != null
processImage url, w, h, 50, 50, (url) ->
msg.send url
robot.respond /enhance [0-9][0-9]?[0-9]? [0-9][0-9]?[0-9]?(.*)?/i, (msg) ->
split = msg.match.input.split(" ")
x = split[2]
y = split[3]
if split.length > 4
input = split[4].replace(">", "").replace("<", "")
getDimensions input, (width, height) ->
enhance msg, input, width, height, x, y
else
fetchLatestImage msg, (url, width, height) ->
enhance msg, url, width, height, x, y
getDimensions = (url, cb) ->
gm(request(url), "image.jpg")
.options({imageMagick: true})
.size (err, size) ->
cb size.width, size.height
enhance = (msg, url, w, h, x, y) ->
processImage url, w, h, x, y, (url) ->
msg.send url
setTimeout ( ->
processImage url, w, h, 50, 50, (url) ->
msg.send url
setTimeout ( ->
processImage url, w, h, 50, 50, (url) ->
msg.send url
setTimeout ( ->
processImage url, w, h, 50, 50, (url) ->
msg.send url
), enhanceDelay
), enhanceDelay
), enhanceDelay
fetchLatestImage = (msg, cb) ->
if msg.robot.adapterName == "slack"
request.get "https://slack.com/api/channels.list?token="+process.env.HUBOT_SLACK_TOKEN, (err, resp, body) ->
channelsResp = JSON.parse body
channelId = item.id for item in channelsResp.channels when item.name == msg.message.room
request.get "https://slack.com/api/channels.history?token="+process.env.HUBOT_SLACK_TOKEN+"&channel="+channelId, (err, resp, body) ->
history = JSON.parse body
for item in history.messages
if item.attachments and item.attachments.length > 0 and item.attachments[0].image_url
attachment = item.attachments[0]
cb item.attachments[0].image_url, item.attachments[0].image_width, item.attachments[0].image_height
return
else if item.file and item.file.url
getDimensions item.file.url, (w, h) ->
cb item.file.url, w, h
msg.reply "Couldn't find any images."
else
msg.reply "You must specify an image URL."
cb null, 0, 0
processImage = (url, w, h, x, y, cb) ->
if url != null
console.log "Enhancing " + url
width = w / 2
height = h / 2
console.log "Width: " + width + ", Height: " + height + ", x:" + ((width * (x / 100))) + ", y:" + ((height * (y / 100)))
gm(request(url), "image.jpg")
.options({imageMagick: true})
.crop(width, height, (width * (x / 100)), (height * (y / 100)))
.resize(w, h)
.stream (err, stdout, stderr) ->
buf = new Buffer(0)
stdout.on 'data', (d) ->
buf = Buffer.concat([buf, d])
stdout.on 'end', () ->
options =
url: "https://api.imgur.com/3/image"
formData:
image: buf
headers:
"Authorization": "Client-ID " + process.env.HUBOT_IMGUR_CLIENT_ID
request.post options, (err, httpResponse, body) ->
cb JSON.parse(body).data.link |
[
{
"context": "t(ctx).Line data\n\n# Events\npusher = new Pusher 'c0c48e95487a739c50df'\nchannel = pusher.subscribe 'notif",
"end": 651,
"score": 0.5184395909309387,
"start": 647,
"tag": "PASSWORD",
"value": "0c48"
},
{
"context": ").Line data\n\n# Events\npusher = new Pusher 'c0c48... | resources/assets/coffee/app.coffee | Vugario/Shipping | 1 | Chart.defaults.global.responsive = true;
Chart.defaults.global.showScale = false;
data = {
showScale: false,
labels: ["June 9", "June 10", "June 11", "Yesterday", "Today"],
datasets: [
{
label: "Number of shipments",
fillColor: "rgba(42, 205, 252,0)",
strokeColor: "rgba(42, 205, 252,1)",
pointColor: "rgba(42, 205, 252,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(42, 205, 252,1)",
data: [45, 48, 52, 54, 58]
}
]
};
# Statistics
ctx = $('#chart').get(0).getContext '2d'
chart = new Chart(ctx).Line data
# Events
pusher = new Pusher 'c0c48e95487a739c50df'
channel = pusher.subscribe 'notifications'
channel.bind 'App\\Events\\SampleNotification', (data) ->
console.log data
window.demo.items.pop() | 200959 | Chart.defaults.global.responsive = true;
Chart.defaults.global.showScale = false;
data = {
showScale: false,
labels: ["June 9", "June 10", "June 11", "Yesterday", "Today"],
datasets: [
{
label: "Number of shipments",
fillColor: "rgba(42, 205, 252,0)",
strokeColor: "rgba(42, 205, 252,1)",
pointColor: "rgba(42, 205, 252,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(42, 205, 252,1)",
data: [45, 48, 52, 54, 58]
}
]
};
# Statistics
ctx = $('#chart').get(0).getContext '2d'
chart = new Chart(ctx).Line data
# Events
pusher = new Pusher 'c<PASSWORD>e<PASSWORD>'
channel = pusher.subscribe 'notifications'
channel.bind 'App\\Events\\SampleNotification', (data) ->
console.log data
window.demo.items.pop() | true | Chart.defaults.global.responsive = true;
Chart.defaults.global.showScale = false;
data = {
showScale: false,
labels: ["June 9", "June 10", "June 11", "Yesterday", "Today"],
datasets: [
{
label: "Number of shipments",
fillColor: "rgba(42, 205, 252,0)",
strokeColor: "rgba(42, 205, 252,1)",
pointColor: "rgba(42, 205, 252,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(42, 205, 252,1)",
data: [45, 48, 52, 54, 58]
}
]
};
# Statistics
ctx = $('#chart').get(0).getContext '2d'
chart = new Chart(ctx).Line data
# Events
pusher = new Pusher 'cPI:PASSWORD:<PASSWORD>END_PIePI:PASSWORD:<PASSWORD>END_PI'
channel = pusher.subscribe 'notifications'
channel.bind 'App\\Events\\SampleNotification', (data) ->
console.log data
window.demo.items.pop() |
[
{
"context": "rootB, children, insert, remove, update);\n#\n# @see Zhang, Kaizhong, and Dennis Shasha. \"Simple fast algori",
"end": 1162,
"score": 0.9995278120040894,
"start": 1157,
"tag": "NAME",
"value": "Zhang"
},
{
"context": "children, insert, remove, update);\n#\n# @see Zhang,... | src/ted.coffee | schulzch/ted-js | 22 | {Mapping, zero, trackedMin} = require './util'
#
# Implements a post-order walk of a given tree.
#
postOrderWalk = (root, childrenCb, visitCb) ->
# Create stacks
stack1 = []
stack2 = []
# Push root to stack1
stack1.push [undefined, root]
# Run while stack1 is not empty
while stack1.length > 0
# Pop a node from stack1 and push it to stack2
[index, node] = stack1.pop()
children = childrenCb(node)
firstChild = children?[0] ? null
stack2.push [index, node, firstChild]
# Push its children to stack1
for child, index in children ? []
stack1.push [index, child]
# Visit all elements of stack2
while stack2.length > 0
[index, node, firstChild] = stack2.pop()
visitCb index, node, firstChild
return
#
# Computes the tree edit distance (TED).
#
# @example
# var rootA = {id: 1, children: [{id: 2}, {id: 3}]};
# var rootB = {id: 1, children: [{id: 4}, {id: 3}, {id: 5}]};
# var children = function(node) { return node.children; };
# var insert = remove = function(node) { return 1; };
# var update = function(nodeA, nodeB) { return nodeA.id !== nodeB.id ? 1 : 0; };
# ted(rootA, rootB, children, insert, remove, update);
#
# @see Zhang, Kaizhong, and Dennis Shasha. "Simple fast algorithms for the
# editing distance between trees and related problems." SIAM journal on
# computing 18.6 (1989): 1245-1262.
#
# Could be improved using:
# @see Pawlik, Mateusz, and Nikolaus Augsten. "Tree edit distance: Robust and
# memory-efficient." Information Systems 56 (2016): 157-173.
#
ted = (rootA, rootB, childrenCb, insertCb, removeCb, updateCb) ->
preprocess = (root) ->
t = {
# Nodes in post-order.
nodes: []
# Leftmost leaf descendant (see paper).
llds: []
# Keyroots (see paper).
keyroots: []
}
postOrderWalk root, childrenCb, (index, node, firstChild) ->
# Push nodes in post-order.
nIndex = t.nodes.length
t.nodes.push node
# Exploit post-order walk to fetch left-most leaf.
unless firstChild?
lldIndex = nIndex
else
# XXX: replace O(n) lookup with O(1) lookup using node decorator?
childIndex = t.nodes.indexOf(firstChild)
lldIndex = t.llds[childIndex]
t.llds.push lldIndex
# Exploit property of keyroots.
if index isnt 0
t.keyroots.push nIndex
return
return t
treeDistance = (i, j) ->
aL = tA.llds
bL = tB.llds
aN = tA.nodes
bN = tB.nodes
iOff = aL[i] - 1
jOff = bL[j] - 1
m = i - aL[i] + 2
n = j - bL[j] + 2
# Minimize from upper left to lower right (dynamic programming, see paper).
for a in [1...m] by 1
fdist[a][0] = fdist[a - 1][0] + removeCb(aN[a + iOff])
for b in [1...n] by 1
fdist[0][b] = fdist[0][b - 1] + insertCb(bN[b + jOff])
for a in [1...m] by 1
for b in [1...n] by 1
if aL[i] is aL[a + iOff] and bL[j] is bL[b + jOff]
min = trackedMin(
fdist[a - 1][b] + removeCb(aN[a + iOff]),
fdist[a][b - 1] + insertCb(bN[b + jOff]),
fdist[a - 1][b - 1] + updateCb(aN[a + iOff], bN[b + jOff]))
ttrack[a + iOff][b + jOff] = min.index
tdist[a + iOff][b + jOff] = fdist[a][b] = min.value
else
p = aL[a + iOff] - 1 - iOff
q = bL[b + jOff] - 1 - jOff
fdist[a][b] = Math.min(
fdist[a - 1][b] + removeCb(aN[a + iOff]),
fdist[a][b - 1] + insertCb(bN[b + jOff]),
fdist[p][q] + tdist[a + iOff][b + jOff])
return
tA = preprocess rootA
tB = preprocess rootB
ttrack = zero tA.nodes.length, tB.nodes.length
tdist = zero tA.nodes.length, tB.nodes.length
fdist = zero tA.nodes.length + 1, tB.nodes.length + 1
# Iterate keyroots.
for i in tA.keyroots
for j in tB.keyroots
treeDistance i, j
tdistance = tdist[tA.nodes.length - 1][tB.nodes.length - 1]
return new Mapping tA, tB, tdistance, ttrack, tedBt
#
# Backtracks the tree-to-tree mapping from lower right to upper left.
#
tedBt = (tA, tB, ttrack) ->
mapping = []
i = tA.nodes.length - 1
j = tB.nodes.length - 1
while i >= 0 and j >= 0
switch ttrack[i][j]
when 0
# Remove
mapping.push [tA.nodes[i], null]
--i
when 1
# Insert
mapping.push [null, tB.nodes[j]]
--j
when 2
# Update
mapping.push [tA.nodes[i], tB.nodes[j]]
--i
--j
else
throw new Error "Invalid operation #{ttrack[i][j]} at (#{i}, #{j})"
# Handle epsilon nodes.
if i is -1 and j isnt -1
while j >= 0
mapping.push [null, tB.nodes[j]]
--j
if i isnt -1 and j is -1
while i >= 0
mapping.push [tA.nodes[i], null]
--i
return mapping
module.exports = ted
| 44220 | {Mapping, zero, trackedMin} = require './util'
#
# Implements a post-order walk of a given tree.
#
postOrderWalk = (root, childrenCb, visitCb) ->
# Create stacks
stack1 = []
stack2 = []
# Push root to stack1
stack1.push [undefined, root]
# Run while stack1 is not empty
while stack1.length > 0
# Pop a node from stack1 and push it to stack2
[index, node] = stack1.pop()
children = childrenCb(node)
firstChild = children?[0] ? null
stack2.push [index, node, firstChild]
# Push its children to stack1
for child, index in children ? []
stack1.push [index, child]
# Visit all elements of stack2
while stack2.length > 0
[index, node, firstChild] = stack2.pop()
visitCb index, node, firstChild
return
#
# Computes the tree edit distance (TED).
#
# @example
# var rootA = {id: 1, children: [{id: 2}, {id: 3}]};
# var rootB = {id: 1, children: [{id: 4}, {id: 3}, {id: 5}]};
# var children = function(node) { return node.children; };
# var insert = remove = function(node) { return 1; };
# var update = function(nodeA, nodeB) { return nodeA.id !== nodeB.id ? 1 : 0; };
# ted(rootA, rootB, children, insert, remove, update);
#
# @see <NAME>, <NAME>, and <NAME>. "Simple fast algorithms for the
# editing distance between trees and related problems." SIAM journal on
# computing 18.6 (1989): 1245-1262.
#
# Could be improved using:
# @see <NAME>, <NAME>, and <NAME>. "Tree edit distance: Robust and
# memory-efficient." Information Systems 56 (2016): 157-173.
#
ted = (rootA, rootB, childrenCb, insertCb, removeCb, updateCb) ->
preprocess = (root) ->
t = {
# Nodes in post-order.
nodes: []
# Leftmost leaf descendant (see paper).
llds: []
# Keyroots (see paper).
keyroots: []
}
postOrderWalk root, childrenCb, (index, node, firstChild) ->
# Push nodes in post-order.
nIndex = t.nodes.length
t.nodes.push node
# Exploit post-order walk to fetch left-most leaf.
unless firstChild?
lldIndex = nIndex
else
# XXX: replace O(n) lookup with O(1) lookup using node decorator?
childIndex = t.nodes.indexOf(firstChild)
lldIndex = t.llds[childIndex]
t.llds.push lldIndex
# Exploit property of keyroots.
if index isnt 0
t.keyroots.push nIndex
return
return t
treeDistance = (i, j) ->
aL = tA.llds
bL = tB.llds
aN = tA.nodes
bN = tB.nodes
iOff = aL[i] - 1
jOff = bL[j] - 1
m = i - aL[i] + 2
n = j - bL[j] + 2
# Minimize from upper left to lower right (dynamic programming, see paper).
for a in [1...m] by 1
fdist[a][0] = fdist[a - 1][0] + removeCb(aN[a + iOff])
for b in [1...n] by 1
fdist[0][b] = fdist[0][b - 1] + insertCb(bN[b + jOff])
for a in [1...m] by 1
for b in [1...n] by 1
if aL[i] is aL[a + iOff] and bL[j] is bL[b + jOff]
min = trackedMin(
fdist[a - 1][b] + removeCb(aN[a + iOff]),
fdist[a][b - 1] + insertCb(bN[b + jOff]),
fdist[a - 1][b - 1] + updateCb(aN[a + iOff], bN[b + jOff]))
ttrack[a + iOff][b + jOff] = min.index
tdist[a + iOff][b + jOff] = fdist[a][b] = min.value
else
p = aL[a + iOff] - 1 - iOff
q = bL[b + jOff] - 1 - jOff
fdist[a][b] = Math.min(
fdist[a - 1][b] + removeCb(aN[a + iOff]),
fdist[a][b - 1] + insertCb(bN[b + jOff]),
fdist[p][q] + tdist[a + iOff][b + jOff])
return
tA = preprocess rootA
tB = preprocess rootB
ttrack = zero tA.nodes.length, tB.nodes.length
tdist = zero tA.nodes.length, tB.nodes.length
fdist = zero tA.nodes.length + 1, tB.nodes.length + 1
# Iterate keyroots.
for i in tA.keyroots
for j in tB.keyroots
treeDistance i, j
tdistance = tdist[tA.nodes.length - 1][tB.nodes.length - 1]
return new Mapping tA, tB, tdistance, ttrack, tedBt
#
# Backtracks the tree-to-tree mapping from lower right to upper left.
#
tedBt = (tA, tB, ttrack) ->
mapping = []
i = tA.nodes.length - 1
j = tB.nodes.length - 1
while i >= 0 and j >= 0
switch ttrack[i][j]
when 0
# Remove
mapping.push [tA.nodes[i], null]
--i
when 1
# Insert
mapping.push [null, tB.nodes[j]]
--j
when 2
# Update
mapping.push [tA.nodes[i], tB.nodes[j]]
--i
--j
else
throw new Error "Invalid operation #{ttrack[i][j]} at (#{i}, #{j})"
# Handle epsilon nodes.
if i is -1 and j isnt -1
while j >= 0
mapping.push [null, tB.nodes[j]]
--j
if i isnt -1 and j is -1
while i >= 0
mapping.push [tA.nodes[i], null]
--i
return mapping
module.exports = ted
| true | {Mapping, zero, trackedMin} = require './util'
#
# Implements a post-order walk of a given tree.
#
postOrderWalk = (root, childrenCb, visitCb) ->
# Create stacks
stack1 = []
stack2 = []
# Push root to stack1
stack1.push [undefined, root]
# Run while stack1 is not empty
while stack1.length > 0
# Pop a node from stack1 and push it to stack2
[index, node] = stack1.pop()
children = childrenCb(node)
firstChild = children?[0] ? null
stack2.push [index, node, firstChild]
# Push its children to stack1
for child, index in children ? []
stack1.push [index, child]
# Visit all elements of stack2
while stack2.length > 0
[index, node, firstChild] = stack2.pop()
visitCb index, node, firstChild
return
#
# Computes the tree edit distance (TED).
#
# @example
# var rootA = {id: 1, children: [{id: 2}, {id: 3}]};
# var rootB = {id: 1, children: [{id: 4}, {id: 3}, {id: 5}]};
# var children = function(node) { return node.children; };
# var insert = remove = function(node) { return 1; };
# var update = function(nodeA, nodeB) { return nodeA.id !== nodeB.id ? 1 : 0; };
# ted(rootA, rootB, children, insert, remove, update);
#
# @see PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI. "Simple fast algorithms for the
# editing distance between trees and related problems." SIAM journal on
# computing 18.6 (1989): 1245-1262.
#
# Could be improved using:
# @see PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI. "Tree edit distance: Robust and
# memory-efficient." Information Systems 56 (2016): 157-173.
#
ted = (rootA, rootB, childrenCb, insertCb, removeCb, updateCb) ->
preprocess = (root) ->
t = {
# Nodes in post-order.
nodes: []
# Leftmost leaf descendant (see paper).
llds: []
# Keyroots (see paper).
keyroots: []
}
postOrderWalk root, childrenCb, (index, node, firstChild) ->
# Push nodes in post-order.
nIndex = t.nodes.length
t.nodes.push node
# Exploit post-order walk to fetch left-most leaf.
unless firstChild?
lldIndex = nIndex
else
# XXX: replace O(n) lookup with O(1) lookup using node decorator?
childIndex = t.nodes.indexOf(firstChild)
lldIndex = t.llds[childIndex]
t.llds.push lldIndex
# Exploit property of keyroots.
if index isnt 0
t.keyroots.push nIndex
return
return t
treeDistance = (i, j) ->
aL = tA.llds
bL = tB.llds
aN = tA.nodes
bN = tB.nodes
iOff = aL[i] - 1
jOff = bL[j] - 1
m = i - aL[i] + 2
n = j - bL[j] + 2
# Minimize from upper left to lower right (dynamic programming, see paper).
for a in [1...m] by 1
fdist[a][0] = fdist[a - 1][0] + removeCb(aN[a + iOff])
for b in [1...n] by 1
fdist[0][b] = fdist[0][b - 1] + insertCb(bN[b + jOff])
for a in [1...m] by 1
for b in [1...n] by 1
if aL[i] is aL[a + iOff] and bL[j] is bL[b + jOff]
min = trackedMin(
fdist[a - 1][b] + removeCb(aN[a + iOff]),
fdist[a][b - 1] + insertCb(bN[b + jOff]),
fdist[a - 1][b - 1] + updateCb(aN[a + iOff], bN[b + jOff]))
ttrack[a + iOff][b + jOff] = min.index
tdist[a + iOff][b + jOff] = fdist[a][b] = min.value
else
p = aL[a + iOff] - 1 - iOff
q = bL[b + jOff] - 1 - jOff
fdist[a][b] = Math.min(
fdist[a - 1][b] + removeCb(aN[a + iOff]),
fdist[a][b - 1] + insertCb(bN[b + jOff]),
fdist[p][q] + tdist[a + iOff][b + jOff])
return
tA = preprocess rootA
tB = preprocess rootB
ttrack = zero tA.nodes.length, tB.nodes.length
tdist = zero tA.nodes.length, tB.nodes.length
fdist = zero tA.nodes.length + 1, tB.nodes.length + 1
# Iterate keyroots.
for i in tA.keyroots
for j in tB.keyroots
treeDistance i, j
tdistance = tdist[tA.nodes.length - 1][tB.nodes.length - 1]
return new Mapping tA, tB, tdistance, ttrack, tedBt
#
# Backtracks the tree-to-tree mapping from lower right to upper left.
#
tedBt = (tA, tB, ttrack) ->
mapping = []
i = tA.nodes.length - 1
j = tB.nodes.length - 1
while i >= 0 and j >= 0
switch ttrack[i][j]
when 0
# Remove
mapping.push [tA.nodes[i], null]
--i
when 1
# Insert
mapping.push [null, tB.nodes[j]]
--j
when 2
# Update
mapping.push [tA.nodes[i], tB.nodes[j]]
--i
--j
else
throw new Error "Invalid operation #{ttrack[i][j]} at (#{i}, #{j})"
# Handle epsilon nodes.
if i is -1 and j isnt -1
while j >= 0
mapping.push [null, tB.nodes[j]]
--j
if i isnt -1 and j is -1
while i >= 0
mapping.push [tA.nodes[i], null]
--i
return mapping
module.exports = ted
|
[
{
"context": "Each ->\n co =>\n yield @room.user.say 'alice', '@hubot give me a random number'\n yield ",
"end": 447,
"score": 0.823952853679657,
"start": 442,
"tag": "NAME",
"value": "alice"
},
{
"context": " co =>\n yield @room.user.say 'alice', '@hubot... | test/mock-response_test.coffee | EdtechFoundry/hubot-test-helper | 0 | Helper = require('../src/index')
helper = new Helper('./scripts/mock-response.coffee')
co = require('co')
expect = require('chai').expect
class NewMockResponse extends Helper.Response
random: (items) ->
3
describe 'mock-response', ->
beforeEach ->
@room = helper.createRoom(response: NewMockResponse)
context 'user says "give me a random" number to hubot', ->
beforeEach ->
co =>
yield @room.user.say 'alice', '@hubot give me a random number'
yield @room.user.say 'bob', '@hubot give me a random number'
it 'should reply to user with a random number', ->
expect(@room.messages).to.eql [
['alice', '@hubot give me a random number']
['hubot', '@alice 3']
['bob', '@hubot give me a random number']
['hubot', '@bob 3']
]
| 120612 | Helper = require('../src/index')
helper = new Helper('./scripts/mock-response.coffee')
co = require('co')
expect = require('chai').expect
class NewMockResponse extends Helper.Response
random: (items) ->
3
describe 'mock-response', ->
beforeEach ->
@room = helper.createRoom(response: NewMockResponse)
context 'user says "give me a random" number to hubot', ->
beforeEach ->
co =>
yield @room.user.say '<NAME>', '@hubot give me a random number'
yield @room.user.say '<NAME>', '@hubot give me a random number'
it 'should reply to user with a random number', ->
expect(@room.messages).to.eql [
['alice', '@hubot give me a random number']
['hubot', '@alice 3']
['bob', '@hubot give me a random number']
['hubot', '@bob 3']
]
| true | Helper = require('../src/index')
helper = new Helper('./scripts/mock-response.coffee')
co = require('co')
expect = require('chai').expect
class NewMockResponse extends Helper.Response
random: (items) ->
3
describe 'mock-response', ->
beforeEach ->
@room = helper.createRoom(response: NewMockResponse)
context 'user says "give me a random" number to hubot', ->
beforeEach ->
co =>
yield @room.user.say 'PI:NAME:<NAME>END_PI', '@hubot give me a random number'
yield @room.user.say 'PI:NAME:<NAME>END_PI', '@hubot give me a random number'
it 'should reply to user with a random number', ->
expect(@room.messages).to.eql [
['alice', '@hubot give me a random number']
['hubot', '@alice 3']
['bob', '@hubot give me a random number']
['hubot', '@bob 3']
]
|
[
{
"context": "yData =\n\t\t\t\tuser_id: \t\t\t\t\tuserId\n\t\t\t\tkey_id: \t\t\t\t\tgeneratePushId()\n\t\t\t\tkey_type: \t\t\t\tkeyType\n\t\t\t\ttransaction_type: t",
"end": 8968,
"score": 0.8876200914382935,
"start": 8952,
"tag": "KEY",
"value": "generatePushId()"
},
{
"context": "h... | server/lib/data_access/cosmetic_chests.coffee | willroberts/duelyst | 5 | Promise = require 'bluebird'
util = require 'util'
FirebasePromises = require '../firebase_promises'
DuelystFirebase = require '../duelyst_firebase_module'
GamesModule = require './games'
Logger = require '../../../app/common/logger.coffee'
colors = require 'colors'
moment = require 'moment'
_ = require 'underscore'
SyncModule = require './sync'
Errors = require '../custom_errors'
knex = require("../data_access/knex")
config = require '../../../config/config.js'
generatePushId = require '../../../app/common/generate_push_id'
# redis
{Redis, Jobs, GameManager} = require '../../redis/'
# SDK imports
SDK = require '../../../app/sdk'
UtilsGameSession = require '../../../app/common/utils/utils_game_session.coffee'
InventoryModule = require './inventory.coffee'
class CosmeticChestsModule
@CHEST_GAME_COUNT_WINDOW: 10
@BOSS_CHEST_EXPIRATION_HOURS: 48
@CHEST_EXPIRATION_BUFFER_MINUTES: 15
###*
# Give a user 1 or more cosmetic chests.
# @public
# @param {Promise} trxPromise Transaction promise that resolves if transaction succeeds.
# @param {Transaction} trx KNEX transaction to attach this operation to.
# @param {String} userId User ID to give the chest to.
# @param {String} chestType Type of chest to give the user
# @param {Integer} chestAmount Amount of chests to add to user.
# @param {String} transactionType 'soft','hard'
# @param {String} transactionId the identifier that caused this chest to be added.
# @param {Integer} bossId card id for boss or null
# @param {String} eventId push id for event
# @return {Promise} Promise that will resolve on completion.
###
@giveUserChest: (trxPromise,trx,userId,chestType,bossId,eventId,chestAmount,transactionType,transactionId,systemTime)->
# userId must be defined
unless userId
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid user ID - #{userId}.".red
return Promise.reject(new Error("Can not give chest to user: invalid user ID - #{userId}"))
# chestType must be defined and be a valid type
unless chestType and _.contains(_.values(SDK.CosmeticsChestTypeLookup),chestType)?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid chest type - #{chestType}.".red
return Promise.reject(new Error("Can not give chest to user: invalid chest type - #{chestType}"))
# Boss Id is required for boss chests
if chestType == SDK.CosmeticsChestTypeLookup.Boss and not bossId?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid bossId for boss chest - #{bossId}.".red
return Promise.reject(new Error("Can not give chest to user: invalid bossId for boss chest - #{bossId}"))
# Boss crates require an event id
if chestType == SDK.CosmeticsChestTypeLookup.Boss and not eventId?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid bossId for boss chest - #{bossId}.".red
return Promise.reject(new Error("Can not give chest to user: invalid bossId for boss chest - #{bossId}"))
# Non boss crates should not have a boss id
if chestType != SDK.CosmeticsChestTypeLookup.Boss and bossId?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> bossId should not exist for non boss chest - #{bossId}.".red
return Promise.reject(new Error("Can not give chest to user: bossId should not exist for non boss chest - #{bossId}"))
# chestAmount must be defined and greater than 0
chestAmount = parseInt(chestAmount)
unless chestAmount and chestAmount > 0
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid chest amount - #{chestAmount}.".red
return Promise.reject(new Error("Can not give chest to user: invalid chest amount - #{chestAmount}"))
# Can only give 1 boss crate at a time
if chestType == SDK.CosmeticsChestTypeLookup.Boss and chestAmount != 1
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid boss chest amount - #{chestAmount}.".red
return Promise.reject(new Error("Can not give chest to user: invalid boss chest amount - #{chestAmount}"))
this_obj = {}
NOW_UTC_MOMENT = systemTime || moment.utc()
getMaxChestCountForType = (chestType) ->
if chestType == SDK.CosmeticsChestTypeLookup.Boss
return null
else
return 5
maxChestCount = getMaxChestCountForType(chestType)
expirationMoment = null
if chestType == SDK.CosmeticsChestTypeLookup.Boss
expirationMoment = NOW_UTC_MOMENT.clone()
expirationMoment.add(CosmeticChestsModule.BOSS_CHEST_EXPIRATION_HOURS,"hours")
this_obj.chestDatas = []
return trx("user_cosmetic_chests").where('user_id',userId).andWhere('chest_type',chestType).count('chest_type as count')
.bind this_obj
.then (response)->
chestCount = response[0].count
if (maxChestCount?)
slotsLeft = Math.max(0,maxChestCount-chestCount)
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> User #{userId.blue}".green + " currently has #{slotsLeft} slots left for chests of type #{chestType}."
chestAmount = Math.min(chestAmount,slotsLeft)
Logger.module("CosmeticChestsModule").time "giveUserChest() -> User #{userId.blue}".green + " received #{chestAmount} chests of type #{chestType}.".green
return Promise.map [0...chestAmount], () ->
chestData =
user_id: userId
chest_id: generatePushId()
chest_type: chestType
transaction_type: transactionType
transaction_id: transactionId
boss_id: bossId
boss_event_id: eventId
created_at: NOW_UTC_MOMENT.toDate()
if expirationMoment?
chestData.expires_at = expirationMoment.toDate()
this_obj.chestDatas.push(chestData)
return trx("user_cosmetic_chests").insert(chestData)
.then ()->
Logger.module("CosmeticChestsModule").timeEnd "giveUserChest() -> User #{userId.blue}".green + " received #{chestAmount} chests of type #{chestType}.".green
# Attach to txPromise adding fb writes
trxPromise
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.rootRef = rootRef
allFbPromises = []
for chestData in @.chestDatas
fbChestData = _.extend({},chestData)
fbChestData.created_at = NOW_UTC_MOMENT.valueOf()
if expirationMoment?
fbChestData.expires_at = expirationMoment.valueOf()
allFbPromises.push(FirebasePromises.set(@.rootRef.child('user-inventory').child(userId).child("cosmetic-chests").child(chestData.chest_id),fbChestData))
return Promise.all(allFbPromises)
# Resolve to the chest data being received
return Promise.resolve(@.chestDatas)
@giveUserChestKey: (trxPromise,trx,userId,keyType,keyAmount,transactionType,transactionId,systemTime)->
if keyType == SDK.CosmeticsChestTypeLookup.Boss
keyType = SDK.CosmeticsChestTypeLookup.Rare
@giveUserChest(trxPromise,trx,userId,keyType,null,null,keyAmount,transactionType,transactionId,systemTime)
###*
# Give a user 1 or more cosmetic chest keys.
# @public
# @param {Promise} trxPromise Transaction promise that resolves if transaction succeeds.
# @param {Transaction} trx KNEX transaction to attach this operation to.
# @param {String} userId User ID to give the chest keys to.
# @param {String} keyType Type of chest keys to give the user
# @param {Integer} keyAmount Amount of chest keys to add to user.
# @param {String} transactionType 'soft','hard'
# @param {String} transactionId the identifier that caused this chest to be added.
# @return {Promise} Promise that will resolve on completion.
###
###
@giveUserChestKey: (trxPromise,trx,userId,keyType,keyAmount,transactionType,transactionId,systemTime)->
# userId must be defined
unless userId
Logger.module("CosmeticChestsModule").debug "giveUserChestKey() -> invalid user ID - #{userId}.".red
return Promise.reject(new Error("Can not give chest key to user: invalid user ID - #{userId}"))
# keyType must be defined and be a valid type
unless keyType and _.contains(_.values(SDK.CosmeticsChestTypeLookup),keyType)
Logger.module("CosmeticChestsModule").debug "giveUserChestKey() -> invalid chest key type - #{keyType}.".red
return Promise.reject(new Error("Can not give chest key to user: invalid chest key type - #{keyType}"))
# keyAmount must be defined and greater than 0
keyAmount = parseInt(keyAmount)
unless keyAmount and keyAmount > 0
Logger.module("CosmeticChestsModule").debug "giveUserChestKey() -> invalid chest key amount - #{keyAmount}.".red
return Promise.reject(new Error("Can not give chest key to user: invalid chest key amount - #{keyAmount}"))
NOW_UTC_MOMENT = systemTime || moment.utc()
Logger.module("CosmeticChestsModule").time "giveUserChestKey() -> User #{userId.blue}".green + " received #{keyAmount} chest keys of type #{keyType}.".green
this_obj = {}
this_obj.chestKeyDatas = []
return Promise.map([1..keyAmount], () ->
keyData =
user_id: userId
key_id: generatePushId()
key_type: keyType
transaction_type: transactionType
transaction_id: transactionId
created_at: NOW_UTC_MOMENT.toDate()
this_obj.chestKeyDatas.push(keyData)
return trx("user_cosmetic_chest_keys").insert(keyData)
)
.bind this_obj
.then ()->
Logger.module("CosmeticChestsModule").timeEnd "giveUserChestKey() -> User #{userId.blue}".green + " received #{keyAmount} chest keys of type #{keyType}.".green
# Attach to txPromise adding fb writes
trxPromise
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
allFbPromises = []
for chestKeyData in @.chestKeyDatas
fbChestKeyData = _.extend({},chestKeyData)
fbChestKeyData.created_at = NOW_UTC_MOMENT.valueOf()
allFbPromises.push(FirebasePromises.set(rootRef.child('user-inventory').child(userId).child("cosmetic-chest-keys").child(fbChestKeyData.key_id),fbChestKeyData))
return Promise.all(allFbPromises)
return Promise.resolve(@.chestKeyDatas)
###
###*
# Opens a cosmetic chest for a user given a key and chest id
# Uses an explicit chest and key id to respect that chests and keys are unique items in database (which could be potentially handled by more than type, e.g. Legacy Silver Chest!)
# @public
# @param {String} userId User ID for which to open the chest.
# @param {String} chestId Chest ID to open.
# @param {String} keyId Key ID to open.
# @return {Promise} Promise that will post UNLOCKED BOOSTER PACK DATA on completion.
###
@openChest: (userId, chestId, systemTime) ->
# userId must be defined
unless userId
Logger.module("CosmeticChestsModule").debug "openChest() -> invalid user ID - #{userId}.".red
return Promise.reject(new Error("Can not open chest: invalid user ID - #{userId}"))
# chestId must be defined
unless chestId
Logger.module("CosmeticChestsModule").debug "openChest() -> invalid chest ID - #{chestId}.".red
return Promise.reject(new Error("Can not open chest: invalid chest ID - #{chestId}"))
# keyId must be defined
#unless keyId
# Logger.module("CosmeticChestsModule").debug "openChest() -> invalid key ID - #{keyId}.".red
# return Promise.reject(new Error("Can not open chest: invalid key ID - #{keyId}"))
NOW_UTC_MOMENT = systemTime || moment.utc()
this_obj = {}
Logger.module("CosmeticChestsModule").time "openChest() -> User #{userId.blue}".green + " opened chest ID #{chestId}.".green
txPromise = knex.transaction (tx)->
tx("users").where('id',userId).first("id").forUpdate()
.bind this_obj
.then ()->
return Promise.all([
tx.first().from('user_cosmetic_chests').where('chest_id',chestId).forUpdate(),
tx.select('cosmetic_id').from('user_cosmetic_inventory').where('user_id',userId).forUpdate()
])
.spread (chestRow,userCosmeticRows)->
if not chestRow? or chestRow.user_id != userId
return Promise.reject(new Errors.NotFoundError("The chest ID you provided does not exist or belong to you."))
# Check if chest is expired, if grab instead the chest of that type for the user that expires last
if chestRow.expires_at?
chestExpirationMoment = moment.utc(chestRow.expires_at)
bufferedChestExpirationMoment = chestExpirationMoment.clone().add(CosmeticChestsModule.CHEST_EXPIRATION_BUFFER_MINUTES,"minutes")
if bufferedChestExpirationMoment.isBefore(NOW_UTC_MOMENT)
return Promise.reject(new Errors.InvalidRequestError("The chest id provided has expired."))
@.chestRow = chestRow
#@.keyRow = keyRow
#if not keyRow? or keyRow.user_id != userId
# return Promise.reject(new Errors.NotFoundError("The chest key ID you provided does not exist or belong to you."))
#if keyRow.key_type != chestRow.chest_type
# return Promise.reject(new Errors.ChestAndKeyTypeDoNotMatchError("The chest and key you provided do not match in type."))
# Gather rewards
@.rewardDatas = CosmeticChestsModule._generateChestOpeningRewards(@.chestRow)
@.ownedCosmeticIds = []
if userCosmeticRows?
@.ownedCosmeticIds = _.map(userCosmeticRows,(cosmeticRow) -> return cosmeticRow.cosmetic_id)
@.resValue = []
# Create promises to give rewards
return Promise.each(@.rewardDatas, (rewardData) =>
if rewardData.cosmetic_common?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Common,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.cosmetic_rare?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Rare,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.cosmetic_epic?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Epic,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.cosmetic_legendary?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Legendary,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.spirit_orb?
return InventoryModule.addBoosterPackToUser(txPromise,tx,userId,rewardData.spirit_orb,"cosmetic chest",@.chestRow.chest_id)
.then (spiritOrbRewardedId) =>
@.resValue.push({spirit_orbs:rewardData.spirit_orb})
else if rewardData.prismatic_common?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Common).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.prismatic_rare?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Rare).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.prismatic_epic?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Epic).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.prismatic_legendary?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Legendary).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.chest_key?
return CosmeticChestsModule.giveUserChestKey(txPromise,tx,userId,rewardData.chest_key,1,"cosmetic chest",@.chestRow.chest_id,NOW_UTC_MOMENT)
.then () =>
@.resValue.push({chest_key:rewardData.chest_key})
else if rewardData.gold?
return InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({gold:rewardData.gold})
else if rewardData.spirit?
return InventoryModule.giveUserSpirit(txPromise,tx,userId,rewardData.spirit,"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({spirit:rewardData.spirit})
else if rewardData.common_card?
commonCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Common).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(commonCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.rare_card?
rareCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Rare).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(rareCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.epic_card?
epicCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Epic).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(epicCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.legendary_card?
legendaryCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Legendary).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(legendaryCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.card_ids?
return InventoryModule.giveUserCards(txPromise,tx,userId,rewardData.card_ids,"cosmetic chest",@.chestRow.chest_id)
.then () =>
for card_id in rewardData.card_ids
@.resValue.push({card_id:card_id})
else if rewardData.gauntlet_tickets?
return InventoryModule.addArenaTicketToUser(txPromise,tx,userId,'cosmetic chest',@.chestRow.chest_id)
.then () =>
@.resValue.push({gauntlet_tickets:rewardData.gauntlet_tickets})
else
Logger.module("CosmeticChestsModule").debug "openChest() -> Error opening chest id #{@.chestRow.chest_id}.".red
return Promise.reject(new Error("Error opening chest: Unknown reward type in data - #{JSON.stringify(rewardData)}"))
,{concurrency: 1})
.then () ->
# NOTE: The following is the cosmetic ids generated, some may be dupes and reward spirit instead
@.rewardedCosmeticIds = _.map(_.filter(@.resValue, (rewardData) -> return rewardData.cosmetic_id?), (rewardData) -> return rewardData.cosmetic_id)
@.openedChestRow = _.extend({},@.chestRow)
@.openedChestRow.opened_with_key_id = "-1"
@.openedChestRow.rewarded_cosmetic_ids = @.rewardedCosmeticIds
@.openedChestRow.opened_at = NOW_UTC_MOMENT.toDate()
#@.usedKeyRow = _.extend({},@.keyRow)
#@.usedKeyRow.used_with_chest_id = @.chestRow.chest_id
#@.usedKeyRow.used_at = NOW_UTC_MOMENT.toDate()
# Move key and chest into used tables
return Promise.all([
tx("user_cosmetic_chests").where('chest_id',@.chestRow.chest_id).delete(),
tx("user_cosmetic_chests_opened").insert(@.openedChestRow)
])
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
return txPromise
.bind this_obj
.then () ->
# Attach to txPromise adding fb writes
txPromise
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return Promise.all([
FirebasePromises.remove(rootRef.child('user-inventory').child(userId).child("cosmetic-chests").child(@.chestRow.chest_id))
])
Logger.module("CosmeticChestsModule").timeEnd "openChest() -> User #{userId.blue}".green + " opened chest ID #{chestId}.".green
return Promise.resolve(@.resValue)
###*
# Module method to create reward data for cosmetic chest opens
# - Reference doc: https://docs.google.com/spreadsheets/d/1sf82iRe7_4TV89wTUB9KZKYdm_sqj-SG3TwvCEyKUcs/
# @public
# @param {Object} chestRow - the sql db data for the chest being opened
# @return {[Object]} Returns an array of reward datas each with one of the following formats:
# card_id: {integer} a single card id rewarded (most likely prismatic)
# cosmetic_id: {integer} a single cosmetic id rewarded
# spirit_orb: {integer} (always 1) a single spirit orb
# chest_key: {integer} a CosmeticsChestType
# Potential
###
@_generateChestOpeningRewards: (chestRow)->
chestType = chestRow.chest_type
rewards = []
if chestType == SDK.CosmeticsChestTypeLookup.Common
###
# Drop 1 - prismatic card
drop1Seed = Math.random()
if drop1Seed < 0.75
# Prismatic common
rewards.push({prismatic_common:1})
else if drop1Seed < 0.95
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop1Seed < 0.99
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
###
# Drop 2 - Always a cosmetic common
rewards.push({cosmetic_common:1})
# Drop 3 - Cosmetic
drop3Seed = Math.random()
if drop3Seed < 0.85
# Cosmetic Rare
rewards.push({cosmetic_rare:1})
else if drop3Seed < 0.98
# Cosmetic epic
rewards.push({cosmetic_epic:1})
else
# Cosmetic legendary
rewards.push({cosmetic_legendary:1})
if chestType == SDK.CosmeticsChestTypeLookup.Rare
###
# Drop 1 - Prismatic
drop1Seed = Math.random()
if drop1Seed < 0.85
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop1Seed < 0.95
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
###
# Drop 2 - Always a cosmetic common
rewards.push({cosmetic_common:1})
# Drop 3
drop3Seed = Math.random()
if drop3Seed < 0.60
# Cosmetic common
rewards.push({cosmetic_common:1})
else if drop3Seed < 0.90
# Cosmetic rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic Epic
rewards.push({cosmetic_epic:1})
# Drop 4
drop4Seed = Math.random()
if drop4Seed < 0.85
# Cosmetic rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic epic
rewards.push({cosmetic_epic:1})
# Drop 5
drop5Seed = Math.random()
if drop5Seed < 0.90
# Cosmetic epic
rewards.push({cosmetic_epic:1})
else
# Cosmetic legendary
rewards.push({cosmetic_legendary:1})
if chestType == SDK.CosmeticsChestTypeLookup.Epic
###
# Drop 1 -
drop1Seed = Math.random()
if drop1Seed < 0.85
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop1Seed < 0.95
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
# Drop 2
drop2Seed = Math.random()
if drop2Seed < 0.45
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop2Seed < 0.90
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
###
# Drop 3 - Always a cosmetic common
rewards.push({cosmetic_common:1})
# Drop 4
drop4Seed = Math.random()
if drop4Seed < 0.60
# Cosmetic Common
rewards.push({cosmetic_common:1})
else if drop4Seed < 0.90
# Cosmetic Rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic Rare
rewards.push({cosmetic_epic:1})
# Drop 5
drop5Seed = Math.random()
if drop5Seed < 0.85
# Cosmetic rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic epic
rewards.push({cosmetic_epic:1})
# Drop 6
drop6Seed = Math.random()
if drop6Seed < 0.90
# Cosmetic epic
rewards.push({cosmetic_epic:1})
else
# Cosmetic legendary
rewards.push({cosmetic_legendary:1})
# Drop 7 - guaranteed cosmetic legendary
rewards.push({cosmetic_legendary:1})
if chestType == SDK.CosmeticsChestTypeLookup.Boss
if chestRow.boss_id == "example"
# rewards.push({cosmetic_epic:1})
else
# Default
# 1 common cosmetic, 1 random orb from any set, 100 spirit
rewards.push({cosmetic_common:1})
rewards.push({spirit:100})
possibleOrbs = [SDK.CardSet.Core, SDK.CardSet.Shimzar, SDK.CardSet.FirstWatch, SDK.CardSet.Wartech, SDK.CardSet.CombinedUnlockables, SDK.CardSet.Coreshatter]
rewards.push(spirit_orb:possibleOrbs[Math.floor(Math.random()*possibleOrbs.length)])
return rewards
###*
# Update a user with cosmetic chest rewards by game outcome
# MUST BE CALLED AFTER PROGRESSION IS UPDATED WITH GAME (WILL THROW ERROR IF NOT)
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored (if a user conceded too early for example?)
# @param {Boolean} isDraw Are we updating for a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserChestRewardWithGameOutcome: (userId,isWinner,gameId,gameType,isUnscored,isDraw,systemTime,probabilityOverride) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserChestRewardWithGameOutcome(): invalid user ID - #{userId}"))
# gameId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserChestRewardWithGameOutcome(): invalid game ID - #{gameId}"))
# must be a competitive game
if !SDK.GameType.isCompetitiveGameType(gameType)
return Promise.resolve(false)
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").where("id",userId).first("id").forUpdate())
.bind this_obj
.then ()->
return tx('user_progression').where('user_id',userId).first().forUpdate()
.then (userProgressionRow) ->
@.userProgressionRow = userProgressionRow
if userProgressionRow.last_game_id != gameId
return Promise.reject(new Error("Can not updateUserChestRewardWithGameOutcome(): game ID - #{gameId} does not match user ID's #{userId} last game ID in progression #{userProgressionRow.last_game_id}"))
if isWinner
chestType = CosmeticChestsModule._chestTypeForProgressionData(userProgressionRow, MOMENT_NOW_UTC, probabilityOverride)
if chestType? and (not userProgressionRow.last_crate_awarded_at?)
# For a user's first chest, always give a bronze chest
chestType = SDK.CosmeticsChestTypeLookup.Common
Logger.module("CosmeticChestsModule").debug "updateUserChestRewardWithGameOutcome() -> user #{userId} receiving first chest for game #{gameId}"
if chestType?
Logger.module("CosmeticChestsModule").debug "updateUserChestRewardWithGameOutcome() -> user #{userId} received #{chestType} chest for game #{gameId} with #{userProgressionRow.win_count} wins"
return CosmeticChestsModule.giveUserChest(txPromise,tx,userId,chestType,null,null,1,'win count',gameId,MOMENT_NOW_UTC)
return Promise.resolve([])
.then (awardedChestData)->
@.awardedChestData = awardedChestData
allPromises = []
if @.awardedChestData.length > 0
# reward row
@.rewardData = rewardData = {
id: generatePushId()
user_id: userId
reward_category: "loot crate"
reward_type: @.awardedChestData[0].chest_type
cosmetic_chests: [ @.awardedChestData[0].chest_type ]
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
is_unread: true
}
allPromises.push tx("user_rewards").insert(rewardData)
allPromises.push GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id)
allPromises.push tx("user_progression").where('user_id',userId).update({
last_crate_awarded_at: MOMENT_NOW_UTC.toDate()
last_crate_awarded_win_count: @.userProgressionRow.win_count
last_crate_awarded_game_count: @.userProgressionRow.game_count
})
return Promise.all(allPromises)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("CosmeticChestsModule").error "updateUserChestRewardWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()->
for chestData in @.awardedChestData
# Currently there is only an achievement for first bronze chest so don't bother with others
if chestData.chest_type == SDK.CosmeticsChestTypeLookup.Common and (not @.userProgressionRow.last_crate_awarded_at?)
Jobs.create("update-user-achievements",
name: "Update User Cosmetic Chest Achievements"
title: util.format("User %s :: Update Cosmetic Chest Achievements", userId)
userId: userId
receivedCosmeticChestType: chestData.chest_type
).removeOnComplete(true).ttl(15000).save()
return @.rewardData
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'cosmetic_chests')
return txPromise
###*
# Update a user with cosmetic chest rewards by boss game outcome
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored (if a user conceded too early for example?)
# @param {Boolean} isDraw Are we updating for a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserChestRewardWithBossGameOutcome: (userId,isWinner,gameId,gameType,isUnscored,isDraw,gameSessionData,systemTime,probabilityOverride) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): invalid user ID - #{userId}"))
# gameId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): invalid game ID - #{gameId}"))
# must be a boss battle game
if gameType != SDK.GameType.BossBattle
return Promise.resolve(false)
if !isWinner
return Promise.resolve(false)
# Oppenent general must be part of the boss faction
opponentPlayerId = UtilsGameSession.getOpponentIdToPlayerId(gameSessionData,userId)
opponentPlayerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameSessionData,opponentPlayerId)
bossId = opponentPlayerSetupData?.generalId
sdkBossData = SDK.GameSession.getCardCaches().getCardById(bossId)
if (not bossId?) or (not sdkBossData?) or (sdkBossData.getFactionId() != SDK.Factions.Boss)
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): invalid boss ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").where("id",userId).first("id").forUpdate())
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
bossEventsRef = @.fbRootRef.child("boss-events")
return FirebasePromises.once(bossEventsRef,'value')
.then (bossEventsSnapshot)->
bossEventsData = bossEventsSnapshot.val()
# data will have
# event-id :
# event_id
# boss_id
# event_start
# event_end
# valid_end (event_end + 30 minute buffer)
@.matchingEventData = null
for eventId,eventData of bossEventsData
if eventData.boss_id != bossId
continue
if eventData.event_start > MOMENT_NOW_UTC.valueOf()
continue
if eventData.valid_end < MOMENT_NOW_UTC.valueOf()
continue
# Reaching here means we have a matching event
@.matchingEventData = eventData
@.matchingEventId = eventData.event_id
break
if not @.matchingEventData?
Logger.module("CosmeticChestsModule").debug "updateUserChestRewardWithBossGameOutcome() -> no matching boss event id for user #{userId} in game #{gameId}.".red
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): No matching boss event - #{gameId}"))
.then ()->
return Promise.all([
tx('user_cosmetic_chests').where('user_id',userId).andWhere("boss_id",bossId).andWhere("boss_event_id",@.matchingEventId).first().forUpdate(),
tx('user_cosmetic_chests_opened').where('user_id',userId).andWhere("boss_id",bossId).andWhere("boss_event_id",@.matchingEventId).first().forUpdate()
])
.spread (userChestForBossRow,userOpenedChestForBossRow) ->
if (userChestForBossRow? or userOpenedChestForBossRow?)
# Chest for this boss already earned
return Promise.resolve([])
return CosmeticChestsModule.giveUserChest(txPromise,tx,userId,SDK.CosmeticsChestTypeLookup.Boss,bossId,@.matchingEventData.event_id,1,'boss battle',gameId,MOMENT_NOW_UTC)
.then (awardedChestData)->
@.awardedChestData = awardedChestData
allPromises = []
if @.awardedChestData.length > 0
# reward row
@.rewardData = rewardData = {
id: generatePushId()
user_id: userId
reward_category: "loot crate"
reward_type: @.awardedChestData[0].chest_type
cosmetic_chests: [ @.awardedChestData[0].chest_type ]
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
is_unread: true
}
allPromises.push tx("user_rewards").insert(rewardData)
allPromises.push GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id)
return Promise.all(allPromises)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("CosmeticChestsModule").error "updateUserChestRewardWithBossGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()->
for chestData in @.awardedChestData
# Currently there is only an achievement for first bronze chest so don't bother with others
if chestData.chest_type == SDK.CosmeticsChestTypeLookup.Common and (not @.userProgressionRow.last_crate_awarded_at?)
Jobs.create("update-user-achievements",
name: "Update User Cosmetic Chest Achievements"
title: util.format("User %s :: Update Cosmetic Chest Achievements", userId)
userId: userId
receivedCosmeticChestType: chestData.chest_type
).removeOnComplete(true).ttl(15000).save()
return @.rewardData
.finally ()->
return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'cosmetic_chests')
return txPromise
@_chestProbabilityForProgressionData: (userProgressionAttrs,systemTime)->
lastAwardedAtMoment = moment.utc(userProgressionAttrs.last_crate_awarded_at || 0)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> last awarded moment: ", lastAwardedAtMoment.format())
timeFactor = 1.0
if lastAwardedAtMoment?
now = systemTime || moment.utc()
diff = now.valueOf() - lastAwardedAtMoment.valueOf()
duration = moment.duration(diff)
days = duration.asDays() # this can be partial like 0.3 etc...
timeFactor = Math.pow(4,(days-4)) # or Math.pow(3,(days-3))
timeFactor = Math.min(timeFactor,1.0)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> time factor:#{timeFactor}")
gameDelta = (userProgressionAttrs.game_count || 0) - (userProgressionAttrs.last_crate_awarded_game_count || 0)
gameFactor = Math.min(1.0, gameDelta / CosmeticChestsModule.CHEST_GAME_COUNT_WINDOW)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game delta:#{gameDelta}")
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game factor:#{gameFactor}")
gameDeltaOverage = Math.max(0.0, gameDelta - 2*CosmeticChestsModule.CHEST_GAME_COUNT_WINDOW)
gameExtraFactor = Math.min(1.0, gameDeltaOverage / (3 * CosmeticChestsModule.CHEST_GAME_COUNT_WINDOW))
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game overage:#{gameDeltaOverage}")
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game extra factor:#{(gameExtraFactor)}")
finalProb = Math.min(1.0, (gameFactor * timeFactor))
# # add game extra factor
# finalProb += finalProb * gameExtraFactor * 0.5
# finalProb = Math.min(1.0,finalProb)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> final:#{finalProb}")
return finalProb
@_chestTypeForProgressionData: (userProgressionAttrs,systemTime,probabilityOverride)->
# at least 5 wins needed
if userProgressionAttrs.win_count < 5
Logger.module("CosmeticChestsModule").debug("_chestTypeForProgressionData() -> 5 wins required before any chest")
return null
chestDropRng = probabilityOverride || Math.random()
probabilityWindow = 1.0 - CosmeticChestsModule._chestProbabilityForProgressionData(userProgressionAttrs,systemTime)
Logger.module("CosmeticChestsModule").debug("_chestTypeForProgressionData() -> rng < probability -> #{chestDropRng} < #{probabilityWindow}")
if chestDropRng < probabilityWindow
return null
chestTypeRng = probabilityOverride || Math.random()
if chestTypeRng > 0.95
return SDK.CosmeticsChestTypeLookup.Epic
else if chestTypeRng > 0.85
return SDK.CosmeticsChestTypeLookup.Rare
else if chestTypeRng > 0.00
return SDK.CosmeticsChestTypeLookup.Common
return null
module.exports = CosmeticChestsModule
| 189178 | Promise = require 'bluebird'
util = require 'util'
FirebasePromises = require '../firebase_promises'
DuelystFirebase = require '../duelyst_firebase_module'
GamesModule = require './games'
Logger = require '../../../app/common/logger.coffee'
colors = require 'colors'
moment = require 'moment'
_ = require 'underscore'
SyncModule = require './sync'
Errors = require '../custom_errors'
knex = require("../data_access/knex")
config = require '../../../config/config.js'
generatePushId = require '../../../app/common/generate_push_id'
# redis
{Redis, Jobs, GameManager} = require '../../redis/'
# SDK imports
SDK = require '../../../app/sdk'
UtilsGameSession = require '../../../app/common/utils/utils_game_session.coffee'
InventoryModule = require './inventory.coffee'
class CosmeticChestsModule
@CHEST_GAME_COUNT_WINDOW: 10
@BOSS_CHEST_EXPIRATION_HOURS: 48
@CHEST_EXPIRATION_BUFFER_MINUTES: 15
###*
# Give a user 1 or more cosmetic chests.
# @public
# @param {Promise} trxPromise Transaction promise that resolves if transaction succeeds.
# @param {Transaction} trx KNEX transaction to attach this operation to.
# @param {String} userId User ID to give the chest to.
# @param {String} chestType Type of chest to give the user
# @param {Integer} chestAmount Amount of chests to add to user.
# @param {String} transactionType 'soft','hard'
# @param {String} transactionId the identifier that caused this chest to be added.
# @param {Integer} bossId card id for boss or null
# @param {String} eventId push id for event
# @return {Promise} Promise that will resolve on completion.
###
@giveUserChest: (trxPromise,trx,userId,chestType,bossId,eventId,chestAmount,transactionType,transactionId,systemTime)->
# userId must be defined
unless userId
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid user ID - #{userId}.".red
return Promise.reject(new Error("Can not give chest to user: invalid user ID - #{userId}"))
# chestType must be defined and be a valid type
unless chestType and _.contains(_.values(SDK.CosmeticsChestTypeLookup),chestType)?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid chest type - #{chestType}.".red
return Promise.reject(new Error("Can not give chest to user: invalid chest type - #{chestType}"))
# Boss Id is required for boss chests
if chestType == SDK.CosmeticsChestTypeLookup.Boss and not bossId?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid bossId for boss chest - #{bossId}.".red
return Promise.reject(new Error("Can not give chest to user: invalid bossId for boss chest - #{bossId}"))
# Boss crates require an event id
if chestType == SDK.CosmeticsChestTypeLookup.Boss and not eventId?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid bossId for boss chest - #{bossId}.".red
return Promise.reject(new Error("Can not give chest to user: invalid bossId for boss chest - #{bossId}"))
# Non boss crates should not have a boss id
if chestType != SDK.CosmeticsChestTypeLookup.Boss and bossId?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> bossId should not exist for non boss chest - #{bossId}.".red
return Promise.reject(new Error("Can not give chest to user: bossId should not exist for non boss chest - #{bossId}"))
# chestAmount must be defined and greater than 0
chestAmount = parseInt(chestAmount)
unless chestAmount and chestAmount > 0
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid chest amount - #{chestAmount}.".red
return Promise.reject(new Error("Can not give chest to user: invalid chest amount - #{chestAmount}"))
# Can only give 1 boss crate at a time
if chestType == SDK.CosmeticsChestTypeLookup.Boss and chestAmount != 1
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid boss chest amount - #{chestAmount}.".red
return Promise.reject(new Error("Can not give chest to user: invalid boss chest amount - #{chestAmount}"))
this_obj = {}
NOW_UTC_MOMENT = systemTime || moment.utc()
getMaxChestCountForType = (chestType) ->
if chestType == SDK.CosmeticsChestTypeLookup.Boss
return null
else
return 5
maxChestCount = getMaxChestCountForType(chestType)
expirationMoment = null
if chestType == SDK.CosmeticsChestTypeLookup.Boss
expirationMoment = NOW_UTC_MOMENT.clone()
expirationMoment.add(CosmeticChestsModule.BOSS_CHEST_EXPIRATION_HOURS,"hours")
this_obj.chestDatas = []
return trx("user_cosmetic_chests").where('user_id',userId).andWhere('chest_type',chestType).count('chest_type as count')
.bind this_obj
.then (response)->
chestCount = response[0].count
if (maxChestCount?)
slotsLeft = Math.max(0,maxChestCount-chestCount)
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> User #{userId.blue}".green + " currently has #{slotsLeft} slots left for chests of type #{chestType}."
chestAmount = Math.min(chestAmount,slotsLeft)
Logger.module("CosmeticChestsModule").time "giveUserChest() -> User #{userId.blue}".green + " received #{chestAmount} chests of type #{chestType}.".green
return Promise.map [0...chestAmount], () ->
chestData =
user_id: userId
chest_id: generatePushId()
chest_type: chestType
transaction_type: transactionType
transaction_id: transactionId
boss_id: bossId
boss_event_id: eventId
created_at: NOW_UTC_MOMENT.toDate()
if expirationMoment?
chestData.expires_at = expirationMoment.toDate()
this_obj.chestDatas.push(chestData)
return trx("user_cosmetic_chests").insert(chestData)
.then ()->
Logger.module("CosmeticChestsModule").timeEnd "giveUserChest() -> User #{userId.blue}".green + " received #{chestAmount} chests of type #{chestType}.".green
# Attach to txPromise adding fb writes
trxPromise
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.rootRef = rootRef
allFbPromises = []
for chestData in @.chestDatas
fbChestData = _.extend({},chestData)
fbChestData.created_at = NOW_UTC_MOMENT.valueOf()
if expirationMoment?
fbChestData.expires_at = expirationMoment.valueOf()
allFbPromises.push(FirebasePromises.set(@.rootRef.child('user-inventory').child(userId).child("cosmetic-chests").child(chestData.chest_id),fbChestData))
return Promise.all(allFbPromises)
# Resolve to the chest data being received
return Promise.resolve(@.chestDatas)
@giveUserChestKey: (trxPromise,trx,userId,keyType,keyAmount,transactionType,transactionId,systemTime)->
if keyType == SDK.CosmeticsChestTypeLookup.Boss
keyType = SDK.CosmeticsChestTypeLookup.Rare
@giveUserChest(trxPromise,trx,userId,keyType,null,null,keyAmount,transactionType,transactionId,systemTime)
###*
# Give a user 1 or more cosmetic chest keys.
# @public
# @param {Promise} trxPromise Transaction promise that resolves if transaction succeeds.
# @param {Transaction} trx KNEX transaction to attach this operation to.
# @param {String} userId User ID to give the chest keys to.
# @param {String} keyType Type of chest keys to give the user
# @param {Integer} keyAmount Amount of chest keys to add to user.
# @param {String} transactionType 'soft','hard'
# @param {String} transactionId the identifier that caused this chest to be added.
# @return {Promise} Promise that will resolve on completion.
###
###
@giveUserChestKey: (trxPromise,trx,userId,keyType,keyAmount,transactionType,transactionId,systemTime)->
# userId must be defined
unless userId
Logger.module("CosmeticChestsModule").debug "giveUserChestKey() -> invalid user ID - #{userId}.".red
return Promise.reject(new Error("Can not give chest key to user: invalid user ID - #{userId}"))
# keyType must be defined and be a valid type
unless keyType and _.contains(_.values(SDK.CosmeticsChestTypeLookup),keyType)
Logger.module("CosmeticChestsModule").debug "giveUserChestKey() -> invalid chest key type - #{keyType}.".red
return Promise.reject(new Error("Can not give chest key to user: invalid chest key type - #{keyType}"))
# keyAmount must be defined and greater than 0
keyAmount = parseInt(keyAmount)
unless keyAmount and keyAmount > 0
Logger.module("CosmeticChestsModule").debug "giveUserChestKey() -> invalid chest key amount - #{keyAmount}.".red
return Promise.reject(new Error("Can not give chest key to user: invalid chest key amount - #{keyAmount}"))
NOW_UTC_MOMENT = systemTime || moment.utc()
Logger.module("CosmeticChestsModule").time "giveUserChestKey() -> User #{userId.blue}".green + " received #{keyAmount} chest keys of type #{keyType}.".green
this_obj = {}
this_obj.chestKeyDatas = []
return Promise.map([1..keyAmount], () ->
keyData =
user_id: userId
key_id: <KEY>
key_type: keyType
transaction_type: transactionType
transaction_id: transactionId
created_at: NOW_UTC_MOMENT.toDate()
this_obj.chestKeyDatas.push(keyData)
return trx("user_cosmetic_chest_keys").insert(keyData)
)
.bind this_obj
.then ()->
Logger.module("CosmeticChestsModule").timeEnd "giveUserChestKey() -> User #{userId.blue}".green + " received #{keyAmount} chest keys of type #{keyType}.".green
# Attach to txPromise adding fb writes
trxPromise
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
allFbPromises = []
for chestKeyData in @.chestKeyDatas
fbChestKeyData = _.extend({},chestKeyData)
fbChestKeyData.created_at = NOW_UTC_MOMENT.valueOf()
allFbPromises.push(FirebasePromises.set(rootRef.child('user-inventory').child(userId).child("cosmetic-chest-keys").child(fbChestKeyData.key_id),fbChestKeyData))
return Promise.all(allFbPromises)
return Promise.resolve(@.chestKeyDatas)
###
###*
# Opens a cosmetic chest for a user given a key and chest id
# Uses an explicit chest and key id to respect that chests and keys are unique items in database (which could be potentially handled by more than type, e.g. Legacy Silver Chest!)
# @public
# @param {String} userId User ID for which to open the chest.
# @param {String} chestId Chest ID to open.
# @param {String} keyId Key ID to open.
# @return {Promise} Promise that will post UNLOCKED BOOSTER PACK DATA on completion.
###
@openChest: (userId, chestId, systemTime) ->
# userId must be defined
unless userId
Logger.module("CosmeticChestsModule").debug "openChest() -> invalid user ID - #{userId}.".red
return Promise.reject(new Error("Can not open chest: invalid user ID - #{userId}"))
# chestId must be defined
unless chestId
Logger.module("CosmeticChestsModule").debug "openChest() -> invalid chest ID - #{chestId}.".red
return Promise.reject(new Error("Can not open chest: invalid chest ID - #{chestId}"))
# keyId must be defined
#unless keyId
# Logger.module("CosmeticChestsModule").debug "openChest() -> invalid key ID - #{keyId}.".red
# return Promise.reject(new Error("Can not open chest: invalid key ID - #{keyId}"))
NOW_UTC_MOMENT = systemTime || moment.utc()
this_obj = {}
Logger.module("CosmeticChestsModule").time "openChest() -> User #{userId.blue}".green + " opened chest ID #{chestId}.".green
txPromise = knex.transaction (tx)->
tx("users").where('id',userId).first("id").forUpdate()
.bind this_obj
.then ()->
return Promise.all([
tx.first().from('user_cosmetic_chests').where('chest_id',chestId).forUpdate(),
tx.select('cosmetic_id').from('user_cosmetic_inventory').where('user_id',userId).forUpdate()
])
.spread (chestRow,userCosmeticRows)->
if not chestRow? or chestRow.user_id != userId
return Promise.reject(new Errors.NotFoundError("The chest ID you provided does not exist or belong to you."))
# Check if chest is expired, if grab instead the chest of that type for the user that expires last
if chestRow.expires_at?
chestExpirationMoment = moment.utc(chestRow.expires_at)
bufferedChestExpirationMoment = chestExpirationMoment.clone().add(CosmeticChestsModule.CHEST_EXPIRATION_BUFFER_MINUTES,"minutes")
if bufferedChestExpirationMoment.isBefore(NOW_UTC_MOMENT)
return Promise.reject(new Errors.InvalidRequestError("The chest id provided has expired."))
@.chestRow = chestRow
#@.keyRow = keyRow
#if not keyRow? or keyRow.user_id != userId
# return Promise.reject(new Errors.NotFoundError("The chest key ID you provided does not exist or belong to you."))
#if keyRow.key_type != chestRow.chest_type
# return Promise.reject(new Errors.ChestAndKeyTypeDoNotMatchError("The chest and key you provided do not match in type."))
# Gather rewards
@.rewardDatas = CosmeticChestsModule._generateChestOpeningRewards(@.chestRow)
@.ownedCosmeticIds = []
if userCosmeticRows?
@.ownedCosmeticIds = _.map(userCosmeticRows,(cosmeticRow) -> return cosmeticRow.cosmetic_id)
@.resValue = []
# Create promises to give rewards
return Promise.each(@.rewardDatas, (rewardData) =>
if rewardData.cosmetic_common?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Common,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.cosmetic_rare?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Rare,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.cosmetic_epic?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Epic,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.cosmetic_legendary?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Legendary,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.spirit_orb?
return InventoryModule.addBoosterPackToUser(txPromise,tx,userId,rewardData.spirit_orb,"cosmetic chest",@.chestRow.chest_id)
.then (spiritOrbRewardedId) =>
@.resValue.push({spirit_orbs:rewardData.spirit_orb})
else if rewardData.prismatic_common?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Common).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.prismatic_rare?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Rare).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.prismatic_epic?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Epic).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.prismatic_legendary?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Legendary).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.chest_key?
return CosmeticChestsModule.giveUserChestKey(txPromise,tx,userId,rewardData.chest_key,1,"cosmetic chest",@.chestRow.chest_id,NOW_UTC_MOMENT)
.then () =>
@.resValue.push({chest_key:rewardData.chest_key})
else if rewardData.gold?
return InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({gold:rewardData.gold})
else if rewardData.spirit?
return InventoryModule.giveUserSpirit(txPromise,tx,userId,rewardData.spirit,"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({spirit:rewardData.spirit})
else if rewardData.common_card?
commonCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Common).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(commonCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.rare_card?
rareCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Rare).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(rareCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.epic_card?
epicCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Epic).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(epicCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.legendary_card?
legendaryCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Legendary).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(legendaryCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.card_ids?
return InventoryModule.giveUserCards(txPromise,tx,userId,rewardData.card_ids,"cosmetic chest",@.chestRow.chest_id)
.then () =>
for card_id in rewardData.card_ids
@.resValue.push({card_id:card_id})
else if rewardData.gauntlet_tickets?
return InventoryModule.addArenaTicketToUser(txPromise,tx,userId,'cosmetic chest',@.chestRow.chest_id)
.then () =>
@.resValue.push({gauntlet_tickets:rewardData.gauntlet_tickets})
else
Logger.module("CosmeticChestsModule").debug "openChest() -> Error opening chest id #{@.chestRow.chest_id}.".red
return Promise.reject(new Error("Error opening chest: Unknown reward type in data - #{JSON.stringify(rewardData)}"))
,{concurrency: 1})
.then () ->
# NOTE: The following is the cosmetic ids generated, some may be dupes and reward spirit instead
@.rewardedCosmeticIds = _.map(_.filter(@.resValue, (rewardData) -> return rewardData.cosmetic_id?), (rewardData) -> return rewardData.cosmetic_id)
@.openedChestRow = _.extend({},@.chestRow)
@.openedChestRow.opened_with_key_id = <KEY>"
@.openedChestRow.rewarded_cosmetic_ids = @.rewardedCosmeticIds
@.openedChestRow.opened_at = NOW_UTC_MOMENT.toDate()
#@.usedKeyRow = _.extend({},@.keyRow)
#@.usedKeyRow.used_with_chest_id = @.chestRow.chest_id
#@.usedKeyRow.used_at = NOW_UTC_MOMENT.toDate()
# Move key and chest into used tables
return Promise.all([
tx("user_cosmetic_chests").where('chest_id',@.chestRow.chest_id).delete(),
tx("user_cosmetic_chests_opened").insert(@.openedChestRow)
])
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
return txPromise
.bind this_obj
.then () ->
# Attach to txPromise adding fb writes
txPromise
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return Promise.all([
FirebasePromises.remove(rootRef.child('user-inventory').child(userId).child("cosmetic-chests").child(@.chestRow.chest_id))
])
Logger.module("CosmeticChestsModule").timeEnd "openChest() -> User #{userId.blue}".green + " opened chest ID #{chestId}.".green
return Promise.resolve(@.resValue)
###*
# Module method to create reward data for cosmetic chest opens
# - Reference doc: https://docs.google.com/spreadsheets/d/1sf82iRe7_4TV89wTUB9KZKYdm_sqj-SG3TwvCEyKUcs/
# @public
# @param {Object} chestRow - the sql db data for the chest being opened
# @return {[Object]} Returns an array of reward datas each with one of the following formats:
# card_id: {integer} a single card id rewarded (most likely prismatic)
# cosmetic_id: {integer} a single cosmetic id rewarded
# spirit_orb: {integer} (always 1) a single spirit orb
# chest_key: {integer} a CosmeticsChestType
# Potential
###
@_generateChestOpeningRewards: (chestRow)->
chestType = chestRow.chest_type
rewards = []
if chestType == SDK.CosmeticsChestTypeLookup.Common
###
# Drop 1 - prismatic card
drop1Seed = Math.random()
if drop1Seed < 0.75
# Prismatic common
rewards.push({prismatic_common:1})
else if drop1Seed < 0.95
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop1Seed < 0.99
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
###
# Drop 2 - Always a cosmetic common
rewards.push({cosmetic_common:1})
# Drop 3 - Cosmetic
drop3Seed = Math.random()
if drop3Seed < 0.85
# Cosmetic Rare
rewards.push({cosmetic_rare:1})
else if drop3Seed < 0.98
# Cosmetic epic
rewards.push({cosmetic_epic:1})
else
# Cosmetic legendary
rewards.push({cosmetic_legendary:1})
if chestType == SDK.CosmeticsChestTypeLookup.Rare
###
# Drop 1 - Prismatic
drop1Seed = Math.random()
if drop1Seed < 0.85
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop1Seed < 0.95
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
###
# Drop 2 - Always a cosmetic common
rewards.push({cosmetic_common:1})
# Drop 3
drop3Seed = Math.random()
if drop3Seed < 0.60
# Cosmetic common
rewards.push({cosmetic_common:1})
else if drop3Seed < 0.90
# Cosmetic rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic Epic
rewards.push({cosmetic_epic:1})
# Drop 4
drop4Seed = Math.random()
if drop4Seed < 0.85
# Cosmetic rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic epic
rewards.push({cosmetic_epic:1})
# Drop 5
drop5Seed = Math.random()
if drop5Seed < 0.90
# Cosmetic epic
rewards.push({cosmetic_epic:1})
else
# Cosmetic legendary
rewards.push({cosmetic_legendary:1})
if chestType == SDK.CosmeticsChestTypeLookup.Epic
###
# Drop 1 -
drop1Seed = Math.random()
if drop1Seed < 0.85
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop1Seed < 0.95
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
# Drop 2
drop2Seed = Math.random()
if drop2Seed < 0.45
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop2Seed < 0.90
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
###
# Drop 3 - Always a cosmetic common
rewards.push({cosmetic_common:1})
# Drop 4
drop4Seed = Math.random()
if drop4Seed < 0.60
# Cosmetic Common
rewards.push({cosmetic_common:1})
else if drop4Seed < 0.90
# Cosmetic Rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic Rare
rewards.push({cosmetic_epic:1})
# Drop 5
drop5Seed = Math.random()
if drop5Seed < 0.85
# Cosmetic rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic epic
rewards.push({cosmetic_epic:1})
# Drop 6
drop6Seed = Math.random()
if drop6Seed < 0.90
# Cosmetic epic
rewards.push({cosmetic_epic:1})
else
# Cosmetic legendary
rewards.push({cosmetic_legendary:1})
# Drop 7 - guaranteed cosmetic legendary
rewards.push({cosmetic_legendary:1})
if chestType == SDK.CosmeticsChestTypeLookup.Boss
if chestRow.boss_id == "example"
# rewards.push({cosmetic_epic:1})
else
# Default
# 1 common cosmetic, 1 random orb from any set, 100 spirit
rewards.push({cosmetic_common:1})
rewards.push({spirit:100})
possibleOrbs = [SDK.CardSet.Core, SDK.CardSet.Shimzar, SDK.CardSet.FirstWatch, SDK.CardSet.Wartech, SDK.CardSet.CombinedUnlockables, SDK.CardSet.Coreshatter]
rewards.push(spirit_orb:possibleOrbs[Math.floor(Math.random()*possibleOrbs.length)])
return rewards
###*
# Update a user with cosmetic chest rewards by game outcome
# MUST BE CALLED AFTER PROGRESSION IS UPDATED WITH GAME (WILL THROW ERROR IF NOT)
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored (if a user conceded too early for example?)
# @param {Boolean} isDraw Are we updating for a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserChestRewardWithGameOutcome: (userId,isWinner,gameId,gameType,isUnscored,isDraw,systemTime,probabilityOverride) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserChestRewardWithGameOutcome(): invalid user ID - #{userId}"))
# gameId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserChestRewardWithGameOutcome(): invalid game ID - #{gameId}"))
# must be a competitive game
if !SDK.GameType.isCompetitiveGameType(gameType)
return Promise.resolve(false)
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").where("id",userId).first("id").forUpdate())
.bind this_obj
.then ()->
return tx('user_progression').where('user_id',userId).first().forUpdate()
.then (userProgressionRow) ->
@.userProgressionRow = userProgressionRow
if userProgressionRow.last_game_id != gameId
return Promise.reject(new Error("Can not updateUserChestRewardWithGameOutcome(): game ID - #{gameId} does not match user ID's #{userId} last game ID in progression #{userProgressionRow.last_game_id}"))
if isWinner
chestType = CosmeticChestsModule._chestTypeForProgressionData(userProgressionRow, MOMENT_NOW_UTC, probabilityOverride)
if chestType? and (not userProgressionRow.last_crate_awarded_at?)
# For a user's first chest, always give a bronze chest
chestType = SDK.CosmeticsChestTypeLookup.Common
Logger.module("CosmeticChestsModule").debug "updateUserChestRewardWithGameOutcome() -> user #{userId} receiving first chest for game #{gameId}"
if chestType?
Logger.module("CosmeticChestsModule").debug "updateUserChestRewardWithGameOutcome() -> user #{userId} received #{chestType} chest for game #{gameId} with #{userProgressionRow.win_count} wins"
return CosmeticChestsModule.giveUserChest(txPromise,tx,userId,chestType,null,null,1,'win count',gameId,MOMENT_NOW_UTC)
return Promise.resolve([])
.then (awardedChestData)->
@.awardedChestData = awardedChestData
allPromises = []
if @.awardedChestData.length > 0
# reward row
@.rewardData = rewardData = {
id: generatePushId()
user_id: userId
reward_category: "loot crate"
reward_type: @.awardedChestData[0].chest_type
cosmetic_chests: [ @.awardedChestData[0].chest_type ]
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
is_unread: true
}
allPromises.push tx("user_rewards").insert(rewardData)
allPromises.push GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id)
allPromises.push tx("user_progression").where('user_id',userId).update({
last_crate_awarded_at: MOMENT_NOW_UTC.toDate()
last_crate_awarded_win_count: @.userProgressionRow.win_count
last_crate_awarded_game_count: @.userProgressionRow.game_count
})
return Promise.all(allPromises)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("CosmeticChestsModule").error "updateUserChestRewardWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()->
for chestData in @.awardedChestData
# Currently there is only an achievement for first bronze chest so don't bother with others
if chestData.chest_type == SDK.CosmeticsChestTypeLookup.Common and (not @.userProgressionRow.last_crate_awarded_at?)
Jobs.create("update-user-achievements",
name: "Update User Cosmetic Chest Achievements"
title: util.format("User %s :: Update Cosmetic Chest Achievements", userId)
userId: userId
receivedCosmeticChestType: chestData.chest_type
).removeOnComplete(true).ttl(15000).save()
return @.rewardData
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'cosmetic_chests')
return txPromise
###*
# Update a user with cosmetic chest rewards by boss game outcome
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored (if a user conceded too early for example?)
# @param {Boolean} isDraw Are we updating for a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserChestRewardWithBossGameOutcome: (userId,isWinner,gameId,gameType,isUnscored,isDraw,gameSessionData,systemTime,probabilityOverride) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): invalid user ID - #{userId}"))
# gameId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): invalid game ID - #{gameId}"))
# must be a boss battle game
if gameType != SDK.GameType.BossBattle
return Promise.resolve(false)
if !isWinner
return Promise.resolve(false)
# Oppenent general must be part of the boss faction
opponentPlayerId = UtilsGameSession.getOpponentIdToPlayerId(gameSessionData,userId)
opponentPlayerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameSessionData,opponentPlayerId)
bossId = opponentPlayerSetupData?.generalId
sdkBossData = SDK.GameSession.getCardCaches().getCardById(bossId)
if (not bossId?) or (not sdkBossData?) or (sdkBossData.getFactionId() != SDK.Factions.Boss)
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): invalid boss ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").where("id",userId).first("id").forUpdate())
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
bossEventsRef = @.fbRootRef.child("boss-events")
return FirebasePromises.once(bossEventsRef,'value')
.then (bossEventsSnapshot)->
bossEventsData = bossEventsSnapshot.val()
# data will have
# event-id :
# event_id
# boss_id
# event_start
# event_end
# valid_end (event_end + 30 minute buffer)
@.matchingEventData = null
for eventId,eventData of bossEventsData
if eventData.boss_id != bossId
continue
if eventData.event_start > MOMENT_NOW_UTC.valueOf()
continue
if eventData.valid_end < MOMENT_NOW_UTC.valueOf()
continue
# Reaching here means we have a matching event
@.matchingEventData = eventData
@.matchingEventId = eventData.event_id
break
if not @.matchingEventData?
Logger.module("CosmeticChestsModule").debug "updateUserChestRewardWithBossGameOutcome() -> no matching boss event id for user #{userId} in game #{gameId}.".red
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): No matching boss event - #{gameId}"))
.then ()->
return Promise.all([
tx('user_cosmetic_chests').where('user_id',userId).andWhere("boss_id",bossId).andWhere("boss_event_id",@.matchingEventId).first().forUpdate(),
tx('user_cosmetic_chests_opened').where('user_id',userId).andWhere("boss_id",bossId).andWhere("boss_event_id",@.matchingEventId).first().forUpdate()
])
.spread (userChestForBossRow,userOpenedChestForBossRow) ->
if (userChestForBossRow? or userOpenedChestForBossRow?)
# Chest for this boss already earned
return Promise.resolve([])
return CosmeticChestsModule.giveUserChest(txPromise,tx,userId,SDK.CosmeticsChestTypeLookup.Boss,bossId,@.matchingEventData.event_id,1,'boss battle',gameId,MOMENT_NOW_UTC)
.then (awardedChestData)->
@.awardedChestData = awardedChestData
allPromises = []
if @.awardedChestData.length > 0
# reward row
@.rewardData = rewardData = {
id: generatePushId()
user_id: userId
reward_category: "loot crate"
reward_type: @.awardedChestData[0].chest_type
cosmetic_chests: [ @.awardedChestData[0].chest_type ]
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
is_unread: true
}
allPromises.push tx("user_rewards").insert(rewardData)
allPromises.push GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id)
return Promise.all(allPromises)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("CosmeticChestsModule").error "updateUserChestRewardWithBossGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()->
for chestData in @.awardedChestData
# Currently there is only an achievement for first bronze chest so don't bother with others
if chestData.chest_type == SDK.CosmeticsChestTypeLookup.Common and (not @.userProgressionRow.last_crate_awarded_at?)
Jobs.create("update-user-achievements",
name: "Update User Cosmetic Chest Achievements"
title: util.format("User %s :: Update Cosmetic Chest Achievements", userId)
userId: userId
receivedCosmeticChestType: chestData.chest_type
).removeOnComplete(true).ttl(15000).save()
return @.rewardData
.finally ()->
return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'cosmetic_chests')
return txPromise
@_chestProbabilityForProgressionData: (userProgressionAttrs,systemTime)->
lastAwardedAtMoment = moment.utc(userProgressionAttrs.last_crate_awarded_at || 0)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> last awarded moment: ", lastAwardedAtMoment.format())
timeFactor = 1.0
if lastAwardedAtMoment?
now = systemTime || moment.utc()
diff = now.valueOf() - lastAwardedAtMoment.valueOf()
duration = moment.duration(diff)
days = duration.asDays() # this can be partial like 0.3 etc...
timeFactor = Math.pow(4,(days-4)) # or Math.pow(3,(days-3))
timeFactor = Math.min(timeFactor,1.0)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> time factor:#{timeFactor}")
gameDelta = (userProgressionAttrs.game_count || 0) - (userProgressionAttrs.last_crate_awarded_game_count || 0)
gameFactor = Math.min(1.0, gameDelta / CosmeticChestsModule.CHEST_GAME_COUNT_WINDOW)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game delta:#{gameDelta}")
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game factor:#{gameFactor}")
gameDeltaOverage = Math.max(0.0, gameDelta - 2*CosmeticChestsModule.CHEST_GAME_COUNT_WINDOW)
gameExtraFactor = Math.min(1.0, gameDeltaOverage / (3 * CosmeticChestsModule.CHEST_GAME_COUNT_WINDOW))
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game overage:#{gameDeltaOverage}")
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game extra factor:#{(gameExtraFactor)}")
finalProb = Math.min(1.0, (gameFactor * timeFactor))
# # add game extra factor
# finalProb += finalProb * gameExtraFactor * 0.5
# finalProb = Math.min(1.0,finalProb)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> final:#{finalProb}")
return finalProb
@_chestTypeForProgressionData: (userProgressionAttrs,systemTime,probabilityOverride)->
# at least 5 wins needed
if userProgressionAttrs.win_count < 5
Logger.module("CosmeticChestsModule").debug("_chestTypeForProgressionData() -> 5 wins required before any chest")
return null
chestDropRng = probabilityOverride || Math.random()
probabilityWindow = 1.0 - CosmeticChestsModule._chestProbabilityForProgressionData(userProgressionAttrs,systemTime)
Logger.module("CosmeticChestsModule").debug("_chestTypeForProgressionData() -> rng < probability -> #{chestDropRng} < #{probabilityWindow}")
if chestDropRng < probabilityWindow
return null
chestTypeRng = probabilityOverride || Math.random()
if chestTypeRng > 0.95
return SDK.CosmeticsChestTypeLookup.Epic
else if chestTypeRng > 0.85
return SDK.CosmeticsChestTypeLookup.Rare
else if chestTypeRng > 0.00
return SDK.CosmeticsChestTypeLookup.Common
return null
module.exports = CosmeticChestsModule
| true | Promise = require 'bluebird'
util = require 'util'
FirebasePromises = require '../firebase_promises'
DuelystFirebase = require '../duelyst_firebase_module'
GamesModule = require './games'
Logger = require '../../../app/common/logger.coffee'
colors = require 'colors'
moment = require 'moment'
_ = require 'underscore'
SyncModule = require './sync'
Errors = require '../custom_errors'
knex = require("../data_access/knex")
config = require '../../../config/config.js'
generatePushId = require '../../../app/common/generate_push_id'
# redis
{Redis, Jobs, GameManager} = require '../../redis/'
# SDK imports
SDK = require '../../../app/sdk'
UtilsGameSession = require '../../../app/common/utils/utils_game_session.coffee'
InventoryModule = require './inventory.coffee'
class CosmeticChestsModule
@CHEST_GAME_COUNT_WINDOW: 10
@BOSS_CHEST_EXPIRATION_HOURS: 48
@CHEST_EXPIRATION_BUFFER_MINUTES: 15
###*
# Give a user 1 or more cosmetic chests.
# @public
# @param {Promise} trxPromise Transaction promise that resolves if transaction succeeds.
# @param {Transaction} trx KNEX transaction to attach this operation to.
# @param {String} userId User ID to give the chest to.
# @param {String} chestType Type of chest to give the user
# @param {Integer} chestAmount Amount of chests to add to user.
# @param {String} transactionType 'soft','hard'
# @param {String} transactionId the identifier that caused this chest to be added.
# @param {Integer} bossId card id for boss or null
# @param {String} eventId push id for event
# @return {Promise} Promise that will resolve on completion.
###
@giveUserChest: (trxPromise,trx,userId,chestType,bossId,eventId,chestAmount,transactionType,transactionId,systemTime)->
# userId must be defined
unless userId
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid user ID - #{userId}.".red
return Promise.reject(new Error("Can not give chest to user: invalid user ID - #{userId}"))
# chestType must be defined and be a valid type
unless chestType and _.contains(_.values(SDK.CosmeticsChestTypeLookup),chestType)?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid chest type - #{chestType}.".red
return Promise.reject(new Error("Can not give chest to user: invalid chest type - #{chestType}"))
# Boss Id is required for boss chests
if chestType == SDK.CosmeticsChestTypeLookup.Boss and not bossId?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid bossId for boss chest - #{bossId}.".red
return Promise.reject(new Error("Can not give chest to user: invalid bossId for boss chest - #{bossId}"))
# Boss crates require an event id
if chestType == SDK.CosmeticsChestTypeLookup.Boss and not eventId?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid bossId for boss chest - #{bossId}.".red
return Promise.reject(new Error("Can not give chest to user: invalid bossId for boss chest - #{bossId}"))
# Non boss crates should not have a boss id
if chestType != SDK.CosmeticsChestTypeLookup.Boss and bossId?
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> bossId should not exist for non boss chest - #{bossId}.".red
return Promise.reject(new Error("Can not give chest to user: bossId should not exist for non boss chest - #{bossId}"))
# chestAmount must be defined and greater than 0
chestAmount = parseInt(chestAmount)
unless chestAmount and chestAmount > 0
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid chest amount - #{chestAmount}.".red
return Promise.reject(new Error("Can not give chest to user: invalid chest amount - #{chestAmount}"))
# Can only give 1 boss crate at a time
if chestType == SDK.CosmeticsChestTypeLookup.Boss and chestAmount != 1
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> invalid boss chest amount - #{chestAmount}.".red
return Promise.reject(new Error("Can not give chest to user: invalid boss chest amount - #{chestAmount}"))
this_obj = {}
NOW_UTC_MOMENT = systemTime || moment.utc()
getMaxChestCountForType = (chestType) ->
if chestType == SDK.CosmeticsChestTypeLookup.Boss
return null
else
return 5
maxChestCount = getMaxChestCountForType(chestType)
expirationMoment = null
if chestType == SDK.CosmeticsChestTypeLookup.Boss
expirationMoment = NOW_UTC_MOMENT.clone()
expirationMoment.add(CosmeticChestsModule.BOSS_CHEST_EXPIRATION_HOURS,"hours")
this_obj.chestDatas = []
return trx("user_cosmetic_chests").where('user_id',userId).andWhere('chest_type',chestType).count('chest_type as count')
.bind this_obj
.then (response)->
chestCount = response[0].count
if (maxChestCount?)
slotsLeft = Math.max(0,maxChestCount-chestCount)
Logger.module("CosmeticChestsModule").debug "giveUserChest() -> User #{userId.blue}".green + " currently has #{slotsLeft} slots left for chests of type #{chestType}."
chestAmount = Math.min(chestAmount,slotsLeft)
Logger.module("CosmeticChestsModule").time "giveUserChest() -> User #{userId.blue}".green + " received #{chestAmount} chests of type #{chestType}.".green
return Promise.map [0...chestAmount], () ->
chestData =
user_id: userId
chest_id: generatePushId()
chest_type: chestType
transaction_type: transactionType
transaction_id: transactionId
boss_id: bossId
boss_event_id: eventId
created_at: NOW_UTC_MOMENT.toDate()
if expirationMoment?
chestData.expires_at = expirationMoment.toDate()
this_obj.chestDatas.push(chestData)
return trx("user_cosmetic_chests").insert(chestData)
.then ()->
Logger.module("CosmeticChestsModule").timeEnd "giveUserChest() -> User #{userId.blue}".green + " received #{chestAmount} chests of type #{chestType}.".green
# Attach to txPromise adding fb writes
trxPromise
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.rootRef = rootRef
allFbPromises = []
for chestData in @.chestDatas
fbChestData = _.extend({},chestData)
fbChestData.created_at = NOW_UTC_MOMENT.valueOf()
if expirationMoment?
fbChestData.expires_at = expirationMoment.valueOf()
allFbPromises.push(FirebasePromises.set(@.rootRef.child('user-inventory').child(userId).child("cosmetic-chests").child(chestData.chest_id),fbChestData))
return Promise.all(allFbPromises)
# Resolve to the chest data being received
return Promise.resolve(@.chestDatas)
@giveUserChestKey: (trxPromise,trx,userId,keyType,keyAmount,transactionType,transactionId,systemTime)->
if keyType == SDK.CosmeticsChestTypeLookup.Boss
keyType = SDK.CosmeticsChestTypeLookup.Rare
@giveUserChest(trxPromise,trx,userId,keyType,null,null,keyAmount,transactionType,transactionId,systemTime)
###*
# Give a user 1 or more cosmetic chest keys.
# @public
# @param {Promise} trxPromise Transaction promise that resolves if transaction succeeds.
# @param {Transaction} trx KNEX transaction to attach this operation to.
# @param {String} userId User ID to give the chest keys to.
# @param {String} keyType Type of chest keys to give the user
# @param {Integer} keyAmount Amount of chest keys to add to user.
# @param {String} transactionType 'soft','hard'
# @param {String} transactionId the identifier that caused this chest to be added.
# @return {Promise} Promise that will resolve on completion.
###
###
@giveUserChestKey: (trxPromise,trx,userId,keyType,keyAmount,transactionType,transactionId,systemTime)->
# userId must be defined
unless userId
Logger.module("CosmeticChestsModule").debug "giveUserChestKey() -> invalid user ID - #{userId}.".red
return Promise.reject(new Error("Can not give chest key to user: invalid user ID - #{userId}"))
# keyType must be defined and be a valid type
unless keyType and _.contains(_.values(SDK.CosmeticsChestTypeLookup),keyType)
Logger.module("CosmeticChestsModule").debug "giveUserChestKey() -> invalid chest key type - #{keyType}.".red
return Promise.reject(new Error("Can not give chest key to user: invalid chest key type - #{keyType}"))
# keyAmount must be defined and greater than 0
keyAmount = parseInt(keyAmount)
unless keyAmount and keyAmount > 0
Logger.module("CosmeticChestsModule").debug "giveUserChestKey() -> invalid chest key amount - #{keyAmount}.".red
return Promise.reject(new Error("Can not give chest key to user: invalid chest key amount - #{keyAmount}"))
NOW_UTC_MOMENT = systemTime || moment.utc()
Logger.module("CosmeticChestsModule").time "giveUserChestKey() -> User #{userId.blue}".green + " received #{keyAmount} chest keys of type #{keyType}.".green
this_obj = {}
this_obj.chestKeyDatas = []
return Promise.map([1..keyAmount], () ->
keyData =
user_id: userId
key_id: PI:KEY:<KEY>END_PI
key_type: keyType
transaction_type: transactionType
transaction_id: transactionId
created_at: NOW_UTC_MOMENT.toDate()
this_obj.chestKeyDatas.push(keyData)
return trx("user_cosmetic_chest_keys").insert(keyData)
)
.bind this_obj
.then ()->
Logger.module("CosmeticChestsModule").timeEnd "giveUserChestKey() -> User #{userId.blue}".green + " received #{keyAmount} chest keys of type #{keyType}.".green
# Attach to txPromise adding fb writes
trxPromise
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
allFbPromises = []
for chestKeyData in @.chestKeyDatas
fbChestKeyData = _.extend({},chestKeyData)
fbChestKeyData.created_at = NOW_UTC_MOMENT.valueOf()
allFbPromises.push(FirebasePromises.set(rootRef.child('user-inventory').child(userId).child("cosmetic-chest-keys").child(fbChestKeyData.key_id),fbChestKeyData))
return Promise.all(allFbPromises)
return Promise.resolve(@.chestKeyDatas)
###
###*
# Opens a cosmetic chest for a user given a key and chest id
# Uses an explicit chest and key id to respect that chests and keys are unique items in database (which could be potentially handled by more than type, e.g. Legacy Silver Chest!)
# @public
# @param {String} userId User ID for which to open the chest.
# @param {String} chestId Chest ID to open.
# @param {String} keyId Key ID to open.
# @return {Promise} Promise that will post UNLOCKED BOOSTER PACK DATA on completion.
###
@openChest: (userId, chestId, systemTime) ->
# userId must be defined
unless userId
Logger.module("CosmeticChestsModule").debug "openChest() -> invalid user ID - #{userId}.".red
return Promise.reject(new Error("Can not open chest: invalid user ID - #{userId}"))
# chestId must be defined
unless chestId
Logger.module("CosmeticChestsModule").debug "openChest() -> invalid chest ID - #{chestId}.".red
return Promise.reject(new Error("Can not open chest: invalid chest ID - #{chestId}"))
# keyId must be defined
#unless keyId
# Logger.module("CosmeticChestsModule").debug "openChest() -> invalid key ID - #{keyId}.".red
# return Promise.reject(new Error("Can not open chest: invalid key ID - #{keyId}"))
NOW_UTC_MOMENT = systemTime || moment.utc()
this_obj = {}
Logger.module("CosmeticChestsModule").time "openChest() -> User #{userId.blue}".green + " opened chest ID #{chestId}.".green
txPromise = knex.transaction (tx)->
tx("users").where('id',userId).first("id").forUpdate()
.bind this_obj
.then ()->
return Promise.all([
tx.first().from('user_cosmetic_chests').where('chest_id',chestId).forUpdate(),
tx.select('cosmetic_id').from('user_cosmetic_inventory').where('user_id',userId).forUpdate()
])
.spread (chestRow,userCosmeticRows)->
if not chestRow? or chestRow.user_id != userId
return Promise.reject(new Errors.NotFoundError("The chest ID you provided does not exist or belong to you."))
# Check if chest is expired, if grab instead the chest of that type for the user that expires last
if chestRow.expires_at?
chestExpirationMoment = moment.utc(chestRow.expires_at)
bufferedChestExpirationMoment = chestExpirationMoment.clone().add(CosmeticChestsModule.CHEST_EXPIRATION_BUFFER_MINUTES,"minutes")
if bufferedChestExpirationMoment.isBefore(NOW_UTC_MOMENT)
return Promise.reject(new Errors.InvalidRequestError("The chest id provided has expired."))
@.chestRow = chestRow
#@.keyRow = keyRow
#if not keyRow? or keyRow.user_id != userId
# return Promise.reject(new Errors.NotFoundError("The chest key ID you provided does not exist or belong to you."))
#if keyRow.key_type != chestRow.chest_type
# return Promise.reject(new Errors.ChestAndKeyTypeDoNotMatchError("The chest and key you provided do not match in type."))
# Gather rewards
@.rewardDatas = CosmeticChestsModule._generateChestOpeningRewards(@.chestRow)
@.ownedCosmeticIds = []
if userCosmeticRows?
@.ownedCosmeticIds = _.map(userCosmeticRows,(cosmeticRow) -> return cosmeticRow.cosmetic_id)
@.resValue = []
# Create promises to give rewards
return Promise.each(@.rewardDatas, (rewardData) =>
if rewardData.cosmetic_common?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Common,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.cosmetic_rare?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Rare,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.cosmetic_epic?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Epic,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.cosmetic_legendary?
return InventoryModule.giveUserNewPurchasableCosmetic(txPromise,tx,userId,"cosmetic chest",@.chestRow.chest_id,SDK.Rarity.Legendary,null,@.ownedCosmeticIds,NOW_UTC_MOMENT)
.then (cosmeticReward) =>
if cosmeticReward? and cosmeticReward.cosmetic_id?
@.ownedCosmeticIds.push(cosmeticReward.cosmetic_id)
@.resValue.push(cosmeticReward)
else if rewardData.spirit_orb?
return InventoryModule.addBoosterPackToUser(txPromise,tx,userId,rewardData.spirit_orb,"cosmetic chest",@.chestRow.chest_id)
.then (spiritOrbRewardedId) =>
@.resValue.push({spirit_orbs:rewardData.spirit_orb})
else if rewardData.prismatic_common?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Common).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.prismatic_rare?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Rare).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.prismatic_epic?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Epic).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.prismatic_legendary?
prismaticCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Legendary).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(true).getCardIds()
rewardedCardId = _.sample(prismaticCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.chest_key?
return CosmeticChestsModule.giveUserChestKey(txPromise,tx,userId,rewardData.chest_key,1,"cosmetic chest",@.chestRow.chest_id,NOW_UTC_MOMENT)
.then () =>
@.resValue.push({chest_key:rewardData.chest_key})
else if rewardData.gold?
return InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({gold:rewardData.gold})
else if rewardData.spirit?
return InventoryModule.giveUserSpirit(txPromise,tx,userId,rewardData.spirit,"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({spirit:rewardData.spirit})
else if rewardData.common_card?
commonCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Common).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(commonCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.rare_card?
rareCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Rare).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(rareCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.epic_card?
epicCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Epic).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(epicCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.legendary_card?
legendaryCardIds = SDK.GameSession.getCardCaches().getRarity(SDK.Rarity.Legendary).getIsUnlockable(false).getIsCollectible(true).getIsPrismatic(false).getCardIds()
rewardedCardId = _.sample(legendaryCardIds)
return InventoryModule.giveUserCards(txPromise,tx,userId,[rewardedCardId],"cosmetic chest",@.chestRow.chest_id)
.then () =>
@.resValue.push({card_id:rewardedCardId})
else if rewardData.card_ids?
return InventoryModule.giveUserCards(txPromise,tx,userId,rewardData.card_ids,"cosmetic chest",@.chestRow.chest_id)
.then () =>
for card_id in rewardData.card_ids
@.resValue.push({card_id:card_id})
else if rewardData.gauntlet_tickets?
return InventoryModule.addArenaTicketToUser(txPromise,tx,userId,'cosmetic chest',@.chestRow.chest_id)
.then () =>
@.resValue.push({gauntlet_tickets:rewardData.gauntlet_tickets})
else
Logger.module("CosmeticChestsModule").debug "openChest() -> Error opening chest id #{@.chestRow.chest_id}.".red
return Promise.reject(new Error("Error opening chest: Unknown reward type in data - #{JSON.stringify(rewardData)}"))
,{concurrency: 1})
.then () ->
# NOTE: The following is the cosmetic ids generated, some may be dupes and reward spirit instead
@.rewardedCosmeticIds = _.map(_.filter(@.resValue, (rewardData) -> return rewardData.cosmetic_id?), (rewardData) -> return rewardData.cosmetic_id)
@.openedChestRow = _.extend({},@.chestRow)
@.openedChestRow.opened_with_key_id = PI:KEY:<KEY>END_PI"
@.openedChestRow.rewarded_cosmetic_ids = @.rewardedCosmeticIds
@.openedChestRow.opened_at = NOW_UTC_MOMENT.toDate()
#@.usedKeyRow = _.extend({},@.keyRow)
#@.usedKeyRow.used_with_chest_id = @.chestRow.chest_id
#@.usedKeyRow.used_at = NOW_UTC_MOMENT.toDate()
# Move key and chest into used tables
return Promise.all([
tx("user_cosmetic_chests").where('chest_id',@.chestRow.chest_id).delete(),
tx("user_cosmetic_chests_opened").insert(@.openedChestRow)
])
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
return txPromise
.bind this_obj
.then () ->
# Attach to txPromise adding fb writes
txPromise
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return Promise.all([
FirebasePromises.remove(rootRef.child('user-inventory').child(userId).child("cosmetic-chests").child(@.chestRow.chest_id))
])
Logger.module("CosmeticChestsModule").timeEnd "openChest() -> User #{userId.blue}".green + " opened chest ID #{chestId}.".green
return Promise.resolve(@.resValue)
###*
# Module method to create reward data for cosmetic chest opens
# - Reference doc: https://docs.google.com/spreadsheets/d/1sf82iRe7_4TV89wTUB9KZKYdm_sqj-SG3TwvCEyKUcs/
# @public
# @param {Object} chestRow - the sql db data for the chest being opened
# @return {[Object]} Returns an array of reward datas each with one of the following formats:
# card_id: {integer} a single card id rewarded (most likely prismatic)
# cosmetic_id: {integer} a single cosmetic id rewarded
# spirit_orb: {integer} (always 1) a single spirit orb
# chest_key: {integer} a CosmeticsChestType
# Potential
###
@_generateChestOpeningRewards: (chestRow)->
chestType = chestRow.chest_type
rewards = []
if chestType == SDK.CosmeticsChestTypeLookup.Common
###
# Drop 1 - prismatic card
drop1Seed = Math.random()
if drop1Seed < 0.75
# Prismatic common
rewards.push({prismatic_common:1})
else if drop1Seed < 0.95
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop1Seed < 0.99
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
###
# Drop 2 - Always a cosmetic common
rewards.push({cosmetic_common:1})
# Drop 3 - Cosmetic
drop3Seed = Math.random()
if drop3Seed < 0.85
# Cosmetic Rare
rewards.push({cosmetic_rare:1})
else if drop3Seed < 0.98
# Cosmetic epic
rewards.push({cosmetic_epic:1})
else
# Cosmetic legendary
rewards.push({cosmetic_legendary:1})
if chestType == SDK.CosmeticsChestTypeLookup.Rare
###
# Drop 1 - Prismatic
drop1Seed = Math.random()
if drop1Seed < 0.85
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop1Seed < 0.95
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
###
# Drop 2 - Always a cosmetic common
rewards.push({cosmetic_common:1})
# Drop 3
drop3Seed = Math.random()
if drop3Seed < 0.60
# Cosmetic common
rewards.push({cosmetic_common:1})
else if drop3Seed < 0.90
# Cosmetic rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic Epic
rewards.push({cosmetic_epic:1})
# Drop 4
drop4Seed = Math.random()
if drop4Seed < 0.85
# Cosmetic rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic epic
rewards.push({cosmetic_epic:1})
# Drop 5
drop5Seed = Math.random()
if drop5Seed < 0.90
# Cosmetic epic
rewards.push({cosmetic_epic:1})
else
# Cosmetic legendary
rewards.push({cosmetic_legendary:1})
if chestType == SDK.CosmeticsChestTypeLookup.Epic
###
# Drop 1 -
drop1Seed = Math.random()
if drop1Seed < 0.85
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop1Seed < 0.95
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
# Drop 2
drop2Seed = Math.random()
if drop2Seed < 0.45
# Prismatic rare
rewards.push({prismatic_rare:1})
else if drop2Seed < 0.90
# Prismatic epic
rewards.push({prismatic_epic:1})
else
# Prismatic legendary
rewards.push({prismatic_legendary:1})
###
# Drop 3 - Always a cosmetic common
rewards.push({cosmetic_common:1})
# Drop 4
drop4Seed = Math.random()
if drop4Seed < 0.60
# Cosmetic Common
rewards.push({cosmetic_common:1})
else if drop4Seed < 0.90
# Cosmetic Rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic Rare
rewards.push({cosmetic_epic:1})
# Drop 5
drop5Seed = Math.random()
if drop5Seed < 0.85
# Cosmetic rare
rewards.push({cosmetic_rare:1})
else
# Cosmetic epic
rewards.push({cosmetic_epic:1})
# Drop 6
drop6Seed = Math.random()
if drop6Seed < 0.90
# Cosmetic epic
rewards.push({cosmetic_epic:1})
else
# Cosmetic legendary
rewards.push({cosmetic_legendary:1})
# Drop 7 - guaranteed cosmetic legendary
rewards.push({cosmetic_legendary:1})
if chestType == SDK.CosmeticsChestTypeLookup.Boss
if chestRow.boss_id == "example"
# rewards.push({cosmetic_epic:1})
else
# Default
# 1 common cosmetic, 1 random orb from any set, 100 spirit
rewards.push({cosmetic_common:1})
rewards.push({spirit:100})
possibleOrbs = [SDK.CardSet.Core, SDK.CardSet.Shimzar, SDK.CardSet.FirstWatch, SDK.CardSet.Wartech, SDK.CardSet.CombinedUnlockables, SDK.CardSet.Coreshatter]
rewards.push(spirit_orb:possibleOrbs[Math.floor(Math.random()*possibleOrbs.length)])
return rewards
###*
# Update a user with cosmetic chest rewards by game outcome
# MUST BE CALLED AFTER PROGRESSION IS UPDATED WITH GAME (WILL THROW ERROR IF NOT)
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored (if a user conceded too early for example?)
# @param {Boolean} isDraw Are we updating for a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserChestRewardWithGameOutcome: (userId,isWinner,gameId,gameType,isUnscored,isDraw,systemTime,probabilityOverride) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserChestRewardWithGameOutcome(): invalid user ID - #{userId}"))
# gameId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserChestRewardWithGameOutcome(): invalid game ID - #{gameId}"))
# must be a competitive game
if !SDK.GameType.isCompetitiveGameType(gameType)
return Promise.resolve(false)
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").where("id",userId).first("id").forUpdate())
.bind this_obj
.then ()->
return tx('user_progression').where('user_id',userId).first().forUpdate()
.then (userProgressionRow) ->
@.userProgressionRow = userProgressionRow
if userProgressionRow.last_game_id != gameId
return Promise.reject(new Error("Can not updateUserChestRewardWithGameOutcome(): game ID - #{gameId} does not match user ID's #{userId} last game ID in progression #{userProgressionRow.last_game_id}"))
if isWinner
chestType = CosmeticChestsModule._chestTypeForProgressionData(userProgressionRow, MOMENT_NOW_UTC, probabilityOverride)
if chestType? and (not userProgressionRow.last_crate_awarded_at?)
# For a user's first chest, always give a bronze chest
chestType = SDK.CosmeticsChestTypeLookup.Common
Logger.module("CosmeticChestsModule").debug "updateUserChestRewardWithGameOutcome() -> user #{userId} receiving first chest for game #{gameId}"
if chestType?
Logger.module("CosmeticChestsModule").debug "updateUserChestRewardWithGameOutcome() -> user #{userId} received #{chestType} chest for game #{gameId} with #{userProgressionRow.win_count} wins"
return CosmeticChestsModule.giveUserChest(txPromise,tx,userId,chestType,null,null,1,'win count',gameId,MOMENT_NOW_UTC)
return Promise.resolve([])
.then (awardedChestData)->
@.awardedChestData = awardedChestData
allPromises = []
if @.awardedChestData.length > 0
# reward row
@.rewardData = rewardData = {
id: generatePushId()
user_id: userId
reward_category: "loot crate"
reward_type: @.awardedChestData[0].chest_type
cosmetic_chests: [ @.awardedChestData[0].chest_type ]
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
is_unread: true
}
allPromises.push tx("user_rewards").insert(rewardData)
allPromises.push GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id)
allPromises.push tx("user_progression").where('user_id',userId).update({
last_crate_awarded_at: MOMENT_NOW_UTC.toDate()
last_crate_awarded_win_count: @.userProgressionRow.win_count
last_crate_awarded_game_count: @.userProgressionRow.game_count
})
return Promise.all(allPromises)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("CosmeticChestsModule").error "updateUserChestRewardWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()->
for chestData in @.awardedChestData
# Currently there is only an achievement for first bronze chest so don't bother with others
if chestData.chest_type == SDK.CosmeticsChestTypeLookup.Common and (not @.userProgressionRow.last_crate_awarded_at?)
Jobs.create("update-user-achievements",
name: "Update User Cosmetic Chest Achievements"
title: util.format("User %s :: Update Cosmetic Chest Achievements", userId)
userId: userId
receivedCosmeticChestType: chestData.chest_type
).removeOnComplete(true).ttl(15000).save()
return @.rewardData
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'cosmetic_chests')
return txPromise
###*
# Update a user with cosmetic chest rewards by boss game outcome
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored (if a user conceded too early for example?)
# @param {Boolean} isDraw Are we updating for a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserChestRewardWithBossGameOutcome: (userId,isWinner,gameId,gameType,isUnscored,isDraw,gameSessionData,systemTime,probabilityOverride) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): invalid user ID - #{userId}"))
# gameId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): invalid game ID - #{gameId}"))
# must be a boss battle game
if gameType != SDK.GameType.BossBattle
return Promise.resolve(false)
if !isWinner
return Promise.resolve(false)
# Oppenent general must be part of the boss faction
opponentPlayerId = UtilsGameSession.getOpponentIdToPlayerId(gameSessionData,userId)
opponentPlayerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameSessionData,opponentPlayerId)
bossId = opponentPlayerSetupData?.generalId
sdkBossData = SDK.GameSession.getCardCaches().getCardById(bossId)
if (not bossId?) or (not sdkBossData?) or (sdkBossData.getFactionId() != SDK.Factions.Boss)
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): invalid boss ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").where("id",userId).first("id").forUpdate())
.bind this_obj
.then () ->
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
bossEventsRef = @.fbRootRef.child("boss-events")
return FirebasePromises.once(bossEventsRef,'value')
.then (bossEventsSnapshot)->
bossEventsData = bossEventsSnapshot.val()
# data will have
# event-id :
# event_id
# boss_id
# event_start
# event_end
# valid_end (event_end + 30 minute buffer)
@.matchingEventData = null
for eventId,eventData of bossEventsData
if eventData.boss_id != bossId
continue
if eventData.event_start > MOMENT_NOW_UTC.valueOf()
continue
if eventData.valid_end < MOMENT_NOW_UTC.valueOf()
continue
# Reaching here means we have a matching event
@.matchingEventData = eventData
@.matchingEventId = eventData.event_id
break
if not @.matchingEventData?
Logger.module("CosmeticChestsModule").debug "updateUserChestRewardWithBossGameOutcome() -> no matching boss event id for user #{userId} in game #{gameId}.".red
return Promise.reject(new Error("Can not updateUserChestRewardWithBossGameOutcome(): No matching boss event - #{gameId}"))
.then ()->
return Promise.all([
tx('user_cosmetic_chests').where('user_id',userId).andWhere("boss_id",bossId).andWhere("boss_event_id",@.matchingEventId).first().forUpdate(),
tx('user_cosmetic_chests_opened').where('user_id',userId).andWhere("boss_id",bossId).andWhere("boss_event_id",@.matchingEventId).first().forUpdate()
])
.spread (userChestForBossRow,userOpenedChestForBossRow) ->
if (userChestForBossRow? or userOpenedChestForBossRow?)
# Chest for this boss already earned
return Promise.resolve([])
return CosmeticChestsModule.giveUserChest(txPromise,tx,userId,SDK.CosmeticsChestTypeLookup.Boss,bossId,@.matchingEventData.event_id,1,'boss battle',gameId,MOMENT_NOW_UTC)
.then (awardedChestData)->
@.awardedChestData = awardedChestData
allPromises = []
if @.awardedChestData.length > 0
# reward row
@.rewardData = rewardData = {
id: generatePushId()
user_id: userId
reward_category: "loot crate"
reward_type: @.awardedChestData[0].chest_type
cosmetic_chests: [ @.awardedChestData[0].chest_type ]
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
is_unread: true
}
allPromises.push tx("user_rewards").insert(rewardData)
allPromises.push GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id)
return Promise.all(allPromises)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("CosmeticChestsModule").error "updateUserChestRewardWithBossGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()->
for chestData in @.awardedChestData
# Currently there is only an achievement for first bronze chest so don't bother with others
if chestData.chest_type == SDK.CosmeticsChestTypeLookup.Common and (not @.userProgressionRow.last_crate_awarded_at?)
Jobs.create("update-user-achievements",
name: "Update User Cosmetic Chest Achievements"
title: util.format("User %s :: Update Cosmetic Chest Achievements", userId)
userId: userId
receivedCosmeticChestType: chestData.chest_type
).removeOnComplete(true).ttl(15000).save()
return @.rewardData
.finally ()->
return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'cosmetic_chests')
return txPromise
@_chestProbabilityForProgressionData: (userProgressionAttrs,systemTime)->
lastAwardedAtMoment = moment.utc(userProgressionAttrs.last_crate_awarded_at || 0)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> last awarded moment: ", lastAwardedAtMoment.format())
timeFactor = 1.0
if lastAwardedAtMoment?
now = systemTime || moment.utc()
diff = now.valueOf() - lastAwardedAtMoment.valueOf()
duration = moment.duration(diff)
days = duration.asDays() # this can be partial like 0.3 etc...
timeFactor = Math.pow(4,(days-4)) # or Math.pow(3,(days-3))
timeFactor = Math.min(timeFactor,1.0)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> time factor:#{timeFactor}")
gameDelta = (userProgressionAttrs.game_count || 0) - (userProgressionAttrs.last_crate_awarded_game_count || 0)
gameFactor = Math.min(1.0, gameDelta / CosmeticChestsModule.CHEST_GAME_COUNT_WINDOW)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game delta:#{gameDelta}")
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game factor:#{gameFactor}")
gameDeltaOverage = Math.max(0.0, gameDelta - 2*CosmeticChestsModule.CHEST_GAME_COUNT_WINDOW)
gameExtraFactor = Math.min(1.0, gameDeltaOverage / (3 * CosmeticChestsModule.CHEST_GAME_COUNT_WINDOW))
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game overage:#{gameDeltaOverage}")
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> game extra factor:#{(gameExtraFactor)}")
finalProb = Math.min(1.0, (gameFactor * timeFactor))
# # add game extra factor
# finalProb += finalProb * gameExtraFactor * 0.5
# finalProb = Math.min(1.0,finalProb)
Logger.module("CosmeticChestsModule").debug("_chestProbabilityForProgressionData() -> final:#{finalProb}")
return finalProb
@_chestTypeForProgressionData: (userProgressionAttrs,systemTime,probabilityOverride)->
# at least 5 wins needed
if userProgressionAttrs.win_count < 5
Logger.module("CosmeticChestsModule").debug("_chestTypeForProgressionData() -> 5 wins required before any chest")
return null
chestDropRng = probabilityOverride || Math.random()
probabilityWindow = 1.0 - CosmeticChestsModule._chestProbabilityForProgressionData(userProgressionAttrs,systemTime)
Logger.module("CosmeticChestsModule").debug("_chestTypeForProgressionData() -> rng < probability -> #{chestDropRng} < #{probabilityWindow}")
if chestDropRng < probabilityWindow
return null
chestTypeRng = probabilityOverride || Math.random()
if chestTypeRng > 0.95
return SDK.CosmeticsChestTypeLookup.Epic
else if chestTypeRng > 0.85
return SDK.CosmeticsChestTypeLookup.Rare
else if chestTypeRng > 0.00
return SDK.CosmeticsChestTypeLookup.Common
return null
module.exports = CosmeticChestsModule
|
[
{
"context": "0]\n author = ef.createAuthor(paper, first_name: \"Bob\", last_name: \"Dole\")\n payload = ef.createPayload",
"end": 265,
"score": 0.9998660087585449,
"start": 262,
"tag": "NAME",
"value": "Bob"
},
{
"context": "reateAuthor(paper, first_name: \"Bob\", last_name: \"Dol... | test/javascripts/integration/financial_disclosure_test.js.coffee | johan--/tahi | 1 | module 'Integration: Financial Disclosure', ->
teardown: -> ETahi.reset()
test "Viewing the card", ->
ef = ETahi.Factory
records = ETahi.Setups.paperWithTask ('FinancialDisclosureTask')
paper = records[0]
author = ef.createAuthor(paper, first_name: "Bob", last_name: "Dole")
payload = ef.createPayload('paper')
payload.addRecords(records)
payload.addRecords([author])
server.respondWith 'GET', "/papers/1", [
200, {"Content-Type": "application/json"}, JSON.stringify payload.toJSON()
]
mirrorCreateResponse = (key, newId) ->
(xhr) ->
createdItem = JSON.parse(xhr.requestBody)
createdItem[key].id = newId
response = JSON.stringify createdItem
xhr.respond(201,{"Content-Type": "application/json"}, response)
server.respondWith 'POST', "/funders", mirrorCreateResponse('funder', 1)
visit '/papers/1/tasks/1'
click "input#received-funding-yes"
click ".chosen-author input"
click "li.active-result:contains('Bob Dole')"
andThen ->
ok _.findWhere(server.requests, {method: "POST", url: "/funders"}), "It posts to the server"
ok find("button:contains('Add Another Funder')").length, "User can add another funder"
ok find("a.remove-funder-link").length, "User can add remove the funder"
test "Removing an existing funder when there's only 1", ->
ef = ETahi.Factory
records = ETahi.Setups.paperWithTask ('FinancialDisclosureTask')
paper = records[0]
task = records[1]
author = ef.createAuthor(paper)
funder = ef.createRecord('Funder', author_ids: [author.id], task_id: task.id, id: 1)
task.funder_ids = [1]
payload = ef.createPayload('paper')
payload.addRecords(records.concat([author, funder]))
server.respondWith 'GET', "/papers/1", [
200, {"Content-Type": "application/json"}, JSON.stringify payload.toJSON()
]
server.respondWith 'DELETE', "/funders/1", [
204, {"Content-Type": "application/html"}, ""
]
visit '/papers/1/tasks/1'
click "a.remove-funder-link"
andThen ->
ok _.findWhere(server.requests, {method: "DELETE", url: "/funders/1"}), "It posts to the server to delete the funder"
ok find('input#received-funding-no:checked').length, "Received funding is set to 'no'"
| 101618 | module 'Integration: Financial Disclosure', ->
teardown: -> ETahi.reset()
test "Viewing the card", ->
ef = ETahi.Factory
records = ETahi.Setups.paperWithTask ('FinancialDisclosureTask')
paper = records[0]
author = ef.createAuthor(paper, first_name: "<NAME>", last_name: "<NAME>")
payload = ef.createPayload('paper')
payload.addRecords(records)
payload.addRecords([author])
server.respondWith 'GET', "/papers/1", [
200, {"Content-Type": "application/json"}, JSON.stringify payload.toJSON()
]
mirrorCreateResponse = (key, newId) ->
(xhr) ->
createdItem = JSON.parse(xhr.requestBody)
createdItem[key].id = newId
response = JSON.stringify createdItem
xhr.respond(201,{"Content-Type": "application/json"}, response)
server.respondWith 'POST', "/funders", mirrorCreateResponse('funder', 1)
visit '/papers/1/tasks/1'
click "input#received-funding-yes"
click ".chosen-author input"
click "li.active-result:contains('<NAME>')"
andThen ->
ok _.findWhere(server.requests, {method: "POST", url: "/funders"}), "It posts to the server"
ok find("button:contains('Add Another Funder')").length, "User can add another funder"
ok find("a.remove-funder-link").length, "User can add remove the funder"
test "Removing an existing funder when there's only 1", ->
ef = ETahi.Factory
records = ETahi.Setups.paperWithTask ('FinancialDisclosureTask')
paper = records[0]
task = records[1]
author = ef.createAuthor(paper)
funder = ef.createRecord('Funder', author_ids: [author.id], task_id: task.id, id: 1)
task.funder_ids = [1]
payload = ef.createPayload('paper')
payload.addRecords(records.concat([author, funder]))
server.respondWith 'GET', "/papers/1", [
200, {"Content-Type": "application/json"}, JSON.stringify payload.toJSON()
]
server.respondWith 'DELETE', "/funders/1", [
204, {"Content-Type": "application/html"}, ""
]
visit '/papers/1/tasks/1'
click "a.remove-funder-link"
andThen ->
ok _.findWhere(server.requests, {method: "DELETE", url: "/funders/1"}), "It posts to the server to delete the funder"
ok find('input#received-funding-no:checked').length, "Received funding is set to 'no'"
| true | module 'Integration: Financial Disclosure', ->
teardown: -> ETahi.reset()
test "Viewing the card", ->
ef = ETahi.Factory
records = ETahi.Setups.paperWithTask ('FinancialDisclosureTask')
paper = records[0]
author = ef.createAuthor(paper, first_name: "PI:NAME:<NAME>END_PI", last_name: "PI:NAME:<NAME>END_PI")
payload = ef.createPayload('paper')
payload.addRecords(records)
payload.addRecords([author])
server.respondWith 'GET', "/papers/1", [
200, {"Content-Type": "application/json"}, JSON.stringify payload.toJSON()
]
mirrorCreateResponse = (key, newId) ->
(xhr) ->
createdItem = JSON.parse(xhr.requestBody)
createdItem[key].id = newId
response = JSON.stringify createdItem
xhr.respond(201,{"Content-Type": "application/json"}, response)
server.respondWith 'POST', "/funders", mirrorCreateResponse('funder', 1)
visit '/papers/1/tasks/1'
click "input#received-funding-yes"
click ".chosen-author input"
click "li.active-result:contains('PI:NAME:<NAME>END_PI')"
andThen ->
ok _.findWhere(server.requests, {method: "POST", url: "/funders"}), "It posts to the server"
ok find("button:contains('Add Another Funder')").length, "User can add another funder"
ok find("a.remove-funder-link").length, "User can add remove the funder"
test "Removing an existing funder when there's only 1", ->
ef = ETahi.Factory
records = ETahi.Setups.paperWithTask ('FinancialDisclosureTask')
paper = records[0]
task = records[1]
author = ef.createAuthor(paper)
funder = ef.createRecord('Funder', author_ids: [author.id], task_id: task.id, id: 1)
task.funder_ids = [1]
payload = ef.createPayload('paper')
payload.addRecords(records.concat([author, funder]))
server.respondWith 'GET', "/papers/1", [
200, {"Content-Type": "application/json"}, JSON.stringify payload.toJSON()
]
server.respondWith 'DELETE', "/funders/1", [
204, {"Content-Type": "application/html"}, ""
]
visit '/papers/1/tasks/1'
click "a.remove-funder-link"
andThen ->
ok _.findWhere(server.requests, {method: "DELETE", url: "/funders/1"}), "It posts to the server to delete the funder"
ok find('input#received-funding-no:checked').length, "Received funding is set to 'no'"
|
[
{
"context": "###*\n * Tenbucks admin script\n *\n * @author Web In Color <contact@prestashop.com>\n * @copyright 2012-2015",
"end": 60,
"score": 0.6257595419883728,
"start": 48,
"tag": "NAME",
"value": "Web In Color"
},
{
"context": "ucks admin script\n *\n * @author Web In... | views/coffee/back.coffee | Web-In-Color/tenbucks_prestashop | 0 | ###*
* Tenbucks admin script
*
* @author Web In Color <contact@prestashop.com>
* @copyright 2012-2015 Web In Color
* @license http://www.apache.org/licenses/ Apache License
* International Registered Trademark & Property of Web In Color
###
$(document).ready ->
$('#deactivate_help').click (e) ->
e.preventDefault()
$panel = $(@).parents('.panel')
url = "#{document.location.href}&ajax=1&action=hide_help"
$.getJSON url, (data) ->
$panel.slideUp()
| 95470 | ###*
* Tenbucks admin script
*
* @author <NAME> <<EMAIL>>
* @copyright 2012-2015 Web In Color
* @license http://www.apache.org/licenses/ Apache License
* International Registered Trademark & Property of Web In Color
###
$(document).ready ->
$('#deactivate_help').click (e) ->
e.preventDefault()
$panel = $(@).parents('.panel')
url = "#{document.location.href}&ajax=1&action=hide_help"
$.getJSON url, (data) ->
$panel.slideUp()
| true | ###*
* Tenbucks admin script
*
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
* @copyright 2012-2015 Web In Color
* @license http://www.apache.org/licenses/ Apache License
* International Registered Trademark & Property of Web In Color
###
$(document).ready ->
$('#deactivate_help').click (e) ->
e.preventDefault()
$panel = $(@).parents('.panel')
url = "#{document.location.href}&ajax=1&action=hide_help"
$.getJSON url, (data) ->
$panel.slideUp()
|
[
{
"context": " 'alias' => 'my-name',\n 'name' => 'My Name'\n );\n $projectPages = sql::insert('",
"end": 562,
"score": 0.9925601482391357,
"start": 555,
"tag": "NAME",
"value": "My Name"
}
] | snippets/codelab-sql.cson | g3ck/atom-g3ck-snippets | 1 | '.source.php':
'Codelab - SQL string':
'prefix': 'sqlStr'
'body': """
sql::str(${1:$string})
"""
'Codelab - SQL Get':
'prefix': 'sqlGet'
'body': """
$param = array(
'table' => '${1}',
'columns' => sql::columns('${1}'),
'where' => 'id = ${2})',
'limit' => 1
);
$projectPages = sql::get($param);
"""
'Codelab - SQL Insert':
'prefix': 'sqlInsert'
'body': """
$param = array(
'alias' => 'my-name',
'name' => 'My Name'
);
$projectPages = sql::insert('', $param);
"""
'Codelab - SQL Update':
'prefix': 'sqlUpdate'
'body': """
$update = array(
'active' => 1,
);
sql::update('users', 'LOWER(email) = LOWER("' . sql::str($_POST['email']) . '")', $update);
"""
| 93269 | '.source.php':
'Codelab - SQL string':
'prefix': 'sqlStr'
'body': """
sql::str(${1:$string})
"""
'Codelab - SQL Get':
'prefix': 'sqlGet'
'body': """
$param = array(
'table' => '${1}',
'columns' => sql::columns('${1}'),
'where' => 'id = ${2})',
'limit' => 1
);
$projectPages = sql::get($param);
"""
'Codelab - SQL Insert':
'prefix': 'sqlInsert'
'body': """
$param = array(
'alias' => 'my-name',
'name' => '<NAME>'
);
$projectPages = sql::insert('', $param);
"""
'Codelab - SQL Update':
'prefix': 'sqlUpdate'
'body': """
$update = array(
'active' => 1,
);
sql::update('users', 'LOWER(email) = LOWER("' . sql::str($_POST['email']) . '")', $update);
"""
| true | '.source.php':
'Codelab - SQL string':
'prefix': 'sqlStr'
'body': """
sql::str(${1:$string})
"""
'Codelab - SQL Get':
'prefix': 'sqlGet'
'body': """
$param = array(
'table' => '${1}',
'columns' => sql::columns('${1}'),
'where' => 'id = ${2})',
'limit' => 1
);
$projectPages = sql::get($param);
"""
'Codelab - SQL Insert':
'prefix': 'sqlInsert'
'body': """
$param = array(
'alias' => 'my-name',
'name' => 'PI:NAME:<NAME>END_PI'
);
$projectPages = sql::insert('', $param);
"""
'Codelab - SQL Update':
'prefix': 'sqlUpdate'
'body': """
$update = array(
'active' => 1,
);
sql::update('users', 'LOWER(email) = LOWER("' . sql::str($_POST['email']) . '")', $update);
"""
|
[
{
"context": "###\n@fileoverview\n\nCreated by Davide on 2/1/18.\n###\n\nrequire 'coffeescript/register'\nf",
"end": 36,
"score": 0.9997860789299011,
"start": 30,
"tag": "NAME",
"value": "Davide"
}
] | js/atom-macros/test/files.spec.coffee | pokemoncentral/wiki-util | 1 | ###
@fileoverview
Created by Davide on 2/1/18.
###
require 'coffeescript/register'
fs = require 'fs'
util = require 'util'
should = require 'chai'
.should()
runMacros = require '../lib/run-macro'
stat = util.promisify fs.stat
readFile = util.promisify fs.readFile
describe 'run-macros', () ->
before () ->
@fileName = "#{ __dirname }/lua/test.lua"
@modTime = () ->
(await stat @fileName).mtimeMs
@readFile = () ->
await readFile @fileName, 'utf-8'
it 'should modify the file in place', () ->
oldModTime = await @modTime()
await runMacros.macrosOnFile @fileName, 'toModule'
newModTime = await @modTime()
oldModTime.should.be.below newModTime
it 'should modify the file accordingly to the macro', () ->
macroName = 'toLua'
oldFileContents = await @readFile()
result = runMacros.applyMacro oldFileContents, macroName
await runMacros.macrosOnFile @fileName, macroName
newFileContents = await @readFile()
newFileContents.should.equal result
| 162549 | ###
@fileoverview
Created by <NAME> on 2/1/18.
###
require 'coffeescript/register'
fs = require 'fs'
util = require 'util'
should = require 'chai'
.should()
runMacros = require '../lib/run-macro'
stat = util.promisify fs.stat
readFile = util.promisify fs.readFile
describe 'run-macros', () ->
before () ->
@fileName = "#{ __dirname }/lua/test.lua"
@modTime = () ->
(await stat @fileName).mtimeMs
@readFile = () ->
await readFile @fileName, 'utf-8'
it 'should modify the file in place', () ->
oldModTime = await @modTime()
await runMacros.macrosOnFile @fileName, 'toModule'
newModTime = await @modTime()
oldModTime.should.be.below newModTime
it 'should modify the file accordingly to the macro', () ->
macroName = 'toLua'
oldFileContents = await @readFile()
result = runMacros.applyMacro oldFileContents, macroName
await runMacros.macrosOnFile @fileName, macroName
newFileContents = await @readFile()
newFileContents.should.equal result
| true | ###
@fileoverview
Created by PI:NAME:<NAME>END_PI on 2/1/18.
###
require 'coffeescript/register'
fs = require 'fs'
util = require 'util'
should = require 'chai'
.should()
runMacros = require '../lib/run-macro'
stat = util.promisify fs.stat
readFile = util.promisify fs.readFile
describe 'run-macros', () ->
before () ->
@fileName = "#{ __dirname }/lua/test.lua"
@modTime = () ->
(await stat @fileName).mtimeMs
@readFile = () ->
await readFile @fileName, 'utf-8'
it 'should modify the file in place', () ->
oldModTime = await @modTime()
await runMacros.macrosOnFile @fileName, 'toModule'
newModTime = await @modTime()
oldModTime.should.be.below newModTime
it 'should modify the file accordingly to the macro', () ->
macroName = 'toLua'
oldFileContents = await @readFile()
result = runMacros.applyMacro oldFileContents, macroName
await runMacros.macrosOnFile @fileName, macroName
newFileContents = await @readFile()
newFileContents.should.equal result
|
[
{
"context": "# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplan",
"end": 18,
"score": 0.9998881220817566,
"start": 10,
"tag": "NAME",
"value": "Tim Knip"
},
{
"context": "orplanner.com/ / tim at floorplanner.com\n# @author aladjev.andrew@gmail.com\n\n#= require new... | source/javascripts/new_src/loaders/collada/animation.coffee | andrew-aladev/three.js | 0 | # @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
# @author aladjev.andrew@gmail.com
#= require new_src/loaders/collada/source
#= require new_src/loaders/collada/sampler
class Animation
constructor: (loader) ->
@id = ""
@name = ""
@source = {}
@sampler = []
@channel = []
@loader = loader
parse: (element) ->
@id = element.getAttribute "id"
@name = element.getAttribute "name"
@source = {}
length = element.childNodes.length
for i in [0...length]
child = element.childNodes[i]
unless child.nodeType is 1
continue
switch child.nodeName
when "animation"
anim = new Animation().parse child
for src of anim.source
@source[src] = anim.source[src]
anim_length = anim.channel.length
for j in [0...anim_length]
@channel.push anim.channel[j]
@sampler.push anim.sampler[j]
when "source"
src = new THREE.Collada.Source(@loader).parse child
@source[src.id] = src
when "sampler"
@sampler.push new THREE.Collada.Sampler(this).parse child
when "channel"
@channel.push new THREE.Collada.Channel(this).parse child
this
namespace "THREE.Collada", (exports) ->
exports.Animation = Animation | 156029 | # @author <NAME> / http://www.floorplanner.com/ / tim at floorplanner.com
# @author <EMAIL>
#= require new_src/loaders/collada/source
#= require new_src/loaders/collada/sampler
class Animation
constructor: (loader) ->
@id = ""
@name = ""
@source = {}
@sampler = []
@channel = []
@loader = loader
parse: (element) ->
@id = element.getAttribute "id"
@name = element.getAttribute "name"
@source = {}
length = element.childNodes.length
for i in [0...length]
child = element.childNodes[i]
unless child.nodeType is 1
continue
switch child.nodeName
when "animation"
anim = new Animation().parse child
for src of anim.source
@source[src] = anim.source[src]
anim_length = anim.channel.length
for j in [0...anim_length]
@channel.push anim.channel[j]
@sampler.push anim.sampler[j]
when "source"
src = new THREE.Collada.Source(@loader).parse child
@source[src.id] = src
when "sampler"
@sampler.push new THREE.Collada.Sampler(this).parse child
when "channel"
@channel.push new THREE.Collada.Channel(this).parse child
this
namespace "THREE.Collada", (exports) ->
exports.Animation = Animation | true | # @author PI:NAME:<NAME>END_PI / http://www.floorplanner.com/ / tim at floorplanner.com
# @author PI:EMAIL:<EMAIL>END_PI
#= require new_src/loaders/collada/source
#= require new_src/loaders/collada/sampler
class Animation
constructor: (loader) ->
@id = ""
@name = ""
@source = {}
@sampler = []
@channel = []
@loader = loader
parse: (element) ->
@id = element.getAttribute "id"
@name = element.getAttribute "name"
@source = {}
length = element.childNodes.length
for i in [0...length]
child = element.childNodes[i]
unless child.nodeType is 1
continue
switch child.nodeName
when "animation"
anim = new Animation().parse child
for src of anim.source
@source[src] = anim.source[src]
anim_length = anim.channel.length
for j in [0...anim_length]
@channel.push anim.channel[j]
@sampler.push anim.sampler[j]
when "source"
src = new THREE.Collada.Source(@loader).parse child
@source[src.id] = src
when "sampler"
@sampler.push new THREE.Collada.Sampler(this).parse child
when "channel"
@channel.push new THREE.Collada.Channel(this).parse child
this
namespace "THREE.Collada", (exports) ->
exports.Animation = Animation |
[
{
"context": "angular: [\n { key: \"autoLaunchSkype\" }\n { key: \"desiredState.meeting.url\" }\n { k",
"end": 33,
"score": 0.6374709010124207,
"start": 21,
"tag": "KEY",
"value": "autoLaunchSk"
}
] | configs/default/form.coffee | octoblu/meshblu-connector-skype | 0 | angular: [
{ key: "autoLaunchSkype" }
{ key: "desiredState.meeting.url" }
{ key: "desiredState.videoEnabled" }
{ key: "desiredState.audioEnabled" }
]
| 68186 | angular: [
{ key: "<KEY>ype" }
{ key: "desiredState.meeting.url" }
{ key: "desiredState.videoEnabled" }
{ key: "desiredState.audioEnabled" }
]
| true | angular: [
{ key: "PI:KEY:<KEY>END_PIype" }
{ key: "desiredState.meeting.url" }
{ key: "desiredState.videoEnabled" }
{ key: "desiredState.audioEnabled" }
]
|
[
{
"context": "ret: 'secret'\n scope: 'email'\n username: username\n password: password\n\n req =\n method:",
"end": 481,
"score": 0.9975075721740723,
"start": 473,
"tag": "USERNAME",
"value": "username"
},
{
"context": ": 'email'\n username: username\n ... | src/app/components/services/api.service.coffee | yoophi/gulp-angular-coffee | 0 | class ApiService extends BaseService
@inject '$http', '$httpParamSerializer', '$interval', '$log', '$q',
'API_ENDPOINT', 'authService', 'localStorageService',
initialize: ->
login: (username, password) ->
@$log.debug 'ApiService.login:'
@$log.debug username, password
LOGIN_URL = @API_ENDPOINT + '/oauth/token'
params =
grant_type: 'password'
client_id: 'angular'
client_secret: 'secret'
scope: 'email'
username: username
password: password
req =
method: 'POST'
url: LOGIN_URL
headers:
'Content-Type': 'application/x-www-form-urlencoded'
data: @$httpParamSerializer(params)
ignoreAuthModule: true
@$http(req).success (response) =>
q = @$q.defer()
if response.access_token?
configUpdater = (config) =>
config.params = config.params or {}
config.params.access_token = response.access_token
config
@localStorageService.set 'accessToken', response.access_token
@localStorageService.set 'refreshToken', response.refresh_token
@authService.loginConfirmed null, configUpdater
q.resolve true
else
q.reject 'login failed'
.error (data, status) =>
@$q.reject data
logout: ->
@$log.debug 'logout:'
for s in ['accessToken', 'refreshToken', 'refreshed']
@localStorageService.remove s
getEndpoint: ->
@API_ENDPOINT
getUserProfile: () ->
@$log.debug 'getUserProfile'
@$http.get "#{@API_ENDPOINT}/users/self"
.error (data, status) =>
@$log.debug 'error', data, status
getAccessToken: ->
@localStorageService.get 'accessToken'
isLoggedIn: () ->
!! @getAccessToken()
angular.module 'hashtagramSandbox'
.service 'ApiService', ApiService
| 15030 | class ApiService extends BaseService
@inject '$http', '$httpParamSerializer', '$interval', '$log', '$q',
'API_ENDPOINT', 'authService', 'localStorageService',
initialize: ->
login: (username, password) ->
@$log.debug 'ApiService.login:'
@$log.debug username, password
LOGIN_URL = @API_ENDPOINT + '/oauth/token'
params =
grant_type: 'password'
client_id: 'angular'
client_secret: 'secret'
scope: 'email'
username: username
password: <PASSWORD>
req =
method: 'POST'
url: LOGIN_URL
headers:
'Content-Type': 'application/x-www-form-urlencoded'
data: @$httpParamSerializer(params)
ignoreAuthModule: true
@$http(req).success (response) =>
q = @$q.defer()
if response.access_token?
configUpdater = (config) =>
config.params = config.params or {}
config.params.access_token = response.access_token
config
@localStorageService.set 'accessToken', response.access_token
@localStorageService.set 'refreshToken', response.refresh_token
@authService.loginConfirmed null, configUpdater
q.resolve true
else
q.reject 'login failed'
.error (data, status) =>
@$q.reject data
logout: ->
@$log.debug 'logout:'
for s in ['accessToken', 'refreshToken', 'refreshed']
@localStorageService.remove s
getEndpoint: ->
@API_ENDPOINT
getUserProfile: () ->
@$log.debug 'getUserProfile'
@$http.get "#{@API_ENDPOINT}/users/self"
.error (data, status) =>
@$log.debug 'error', data, status
getAccessToken: ->
@localStorageService.get 'accessToken'
isLoggedIn: () ->
!! @getAccessToken()
angular.module 'hashtagramSandbox'
.service 'ApiService', ApiService
| true | class ApiService extends BaseService
@inject '$http', '$httpParamSerializer', '$interval', '$log', '$q',
'API_ENDPOINT', 'authService', 'localStorageService',
initialize: ->
login: (username, password) ->
@$log.debug 'ApiService.login:'
@$log.debug username, password
LOGIN_URL = @API_ENDPOINT + '/oauth/token'
params =
grant_type: 'password'
client_id: 'angular'
client_secret: 'secret'
scope: 'email'
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
req =
method: 'POST'
url: LOGIN_URL
headers:
'Content-Type': 'application/x-www-form-urlencoded'
data: @$httpParamSerializer(params)
ignoreAuthModule: true
@$http(req).success (response) =>
q = @$q.defer()
if response.access_token?
configUpdater = (config) =>
config.params = config.params or {}
config.params.access_token = response.access_token
config
@localStorageService.set 'accessToken', response.access_token
@localStorageService.set 'refreshToken', response.refresh_token
@authService.loginConfirmed null, configUpdater
q.resolve true
else
q.reject 'login failed'
.error (data, status) =>
@$q.reject data
logout: ->
@$log.debug 'logout:'
for s in ['accessToken', 'refreshToken', 'refreshed']
@localStorageService.remove s
getEndpoint: ->
@API_ENDPOINT
getUserProfile: () ->
@$log.debug 'getUserProfile'
@$http.get "#{@API_ENDPOINT}/users/self"
.error (data, status) =>
@$log.debug 'error', data, status
getAccessToken: ->
@localStorageService.get 'accessToken'
isLoggedIn: () ->
!! @getAccessToken()
angular.module 'hashtagramSandbox'
.service 'ApiService', ApiService
|
[
{
"context": "gin and (@_login = opt.login)\n opt.password and (@_password = opt.password)\n opt.host and (@_host ",
"end": 679,
"score": 0.730953574180603,
"start": 676,
"tag": "PASSWORD",
"value": "(@_"
},
{
"context": "in = opt.login)\n opt.password and (@_password = opt.... | src/AmqpDsl.coffee | FGRibreau/node-amqp-dsl | 2 | # Amqp-DSL - Fluent interface for node-amqp
async = require 'async'
IndexedList = require './IndexedList'
AmqpQueue = require './AmqpQueue'
AmqpExchange = require './AmqpExchange'
module.exports = class AmqpDsl
LISTENNERS =['error','close','ready']
## Public API
#### require('amqp-dsl').login
# * `login( options = {} )`
#
AmqpDsl.login = (opt = {}) ->
new AmqpDsl(opt)
constructor:(opt = {}) ->
# Defaults
@_login = ''
@_password = ''
@_host = ''
@_port = 5672
@_vhost = '/'
@_conn = null
@_callback = ->
# Constructor arguments
opt.login and (@_login = opt.login)
opt.password and (@_password = opt.password)
opt.host and (@_host = opt.host)
opt.port and (@_port = opt.port)
opt.vhost and (@_vhost = opt.vhost)
opt.login and (@_login = opt.login)
# Events
@_events = {}
# Exchanges
@_exchanges = new IndexedList()
# Queues
@_queues = new IndexedList()
#### .on
# * `on( event, listener )`
on:( event, listener ) ->
if !~LISTENNERS.indexOf(event)
throw new Error("Event '#{event}' is invalid")
@_events[event] = [] if(!@_events[event])
@_events[event].push(listener)
this
#### .exchange
# * `.exchange( name, options )`
# * `.exchange( name, callback(exchange) )`
# * `.exchange( name, options, callback(exchange) )`
exchange:( name, options, openCallback ) ->
@_exchanges.set(name, new AmqpExchange(name, options, openCallback))
this
#### .queue
# * `.queue( name, options )`
# * `.queue( name, callback(queue) )`
# * `.queue( name, options, callback(queue) )`
queue:( name, options, openCallback ) ->
@_queues.set(name, new AmqpQueue(name, options, openCallback))
this
#### .queue(...).subscribe
# * `.subscribe( callback(message, header, deliveryInfo) )`
# * `.subscribe( options, callback(message, header, deliveryInfo) )`
subscribe:( options, messageListener ) ->
queue = @_queues.last()
throw new Error("At least one queue must be declared") if !queue
queue.subscribe(options, messageListener)
this
#### .queue(...).bind
# * `.bind( name, routingKey )`
bind:( name, routingKey ) ->
queue = @_queues.last()
throw new Error("At least one queue must be declared") if !queue
queue.bind(name, routingKey)
this
#### .connect
# * `.connect( amqp, callback(err, amqp) )`
# * `.connect( callback(err, amqp) )`
#
# `amqp` parameter is an hashtable which contain
#
# queues:
# sampleQueue:[Amqp::Queue]
#
# exchanges:
# sampleExchange:[Amqp::Exchange]
#
# connection: [Amqp::Connection]
#
connect:(amqp, @_callback)->
if amqp is undefined
@_callback = ->
amqp = require 'amqp'
if typeof amqp is "function"
@_callback = amqp
amqp = require 'amqp'
@_connect(amqp)
null
## Private API
# Create the connection to amqp and bind events
_connect:(amqp) ->
# Create connection
@conn = amqp.createConnection({
host: @_host,
port: @_port,
login: @_login,
password: @_password,
vhost: @_vhost
})
# When the connection will be ready, connect the exchanges
@on 'ready', () => @_connectExchanges(@_connectQueues.bind(this))
# Set event listeners
@conn.on(event, @_getListenerFor(event)) for event of @_events
# Return a listener fonction for the event `event`.
_getListenerFor: (event) ->
if @_events[event].length == 1
return @_events[event][0]
else
return (args...) =>
listener.apply(null, args) for listener in @_events[event]
true
# Connect to exchanges
_connectExchanges:(next) ->
async.forEach @_exchanges.list(), @_connectExchange.bind(@), (err) =>
if err
throw new Error("Couldn't connect to the exchanges: #{err.message}")
return
next()
# Exchange connection iterator
_connectExchange:(exchange, callback) ->
@conn.exchange exchange.name, exchange.options, (exchangeRef) ->
exchange.ref = exchangeRef
exchange.openCallback(exchangeRef)
callback(null, true)
# Connect to queues
_connectQueues:() ->
async.forEach @_queues.list(), @_connectQueue.bind(@), (err) =>
if err
throw new Error("Couldn't connect to the queues: #{err.message}")
return
@_done()
# Queue connection iterator
_connectQueue:(queue, callback) ->
@conn.queue queue.name, queue.options, (queueRef) ->
queue.ref = queueRef
queue.openCallback(queueRef)
queue.bindTo.forEach((bind) ->
[exchange, routingKey] = bind
queueRef.bind exchange, routingKey
)
queue.listenTo.forEach((listen) ->
[option, listener] = listen
queueRef.subscribe option, listener
)
callback(null, true)
# When everything's connected, trigger the final callback
_done:() ->
msg =
queues : {}
exchanges : {}
connection : @conn
for k,v of @_queues.index()
msg.queues[k] = v.ref
for k,v of @_exchanges.index()
msg.exchanges[k] = v.ref
@_callback(null, msg)
| 185313 | # Amqp-DSL - Fluent interface for node-amqp
async = require 'async'
IndexedList = require './IndexedList'
AmqpQueue = require './AmqpQueue'
AmqpExchange = require './AmqpExchange'
module.exports = class AmqpDsl
LISTENNERS =['error','close','ready']
## Public API
#### require('amqp-dsl').login
# * `login( options = {} )`
#
AmqpDsl.login = (opt = {}) ->
new AmqpDsl(opt)
constructor:(opt = {}) ->
# Defaults
@_login = ''
@_password = ''
@_host = ''
@_port = 5672
@_vhost = '/'
@_conn = null
@_callback = ->
# Constructor arguments
opt.login and (@_login = opt.login)
opt.password and <PASSWORD>password = <PASSWORD>)
opt.host and (@_host = opt.host)
opt.port and (@_port = opt.port)
opt.vhost and (@_vhost = opt.vhost)
opt.login and (@_login = opt.login)
# Events
@_events = {}
# Exchanges
@_exchanges = new IndexedList()
# Queues
@_queues = new IndexedList()
#### .on
# * `on( event, listener )`
on:( event, listener ) ->
if !~LISTENNERS.indexOf(event)
throw new Error("Event '#{event}' is invalid")
@_events[event] = [] if(!@_events[event])
@_events[event].push(listener)
this
#### .exchange
# * `.exchange( name, options )`
# * `.exchange( name, callback(exchange) )`
# * `.exchange( name, options, callback(exchange) )`
exchange:( name, options, openCallback ) ->
@_exchanges.set(name, new AmqpExchange(name, options, openCallback))
this
#### .queue
# * `.queue( name, options )`
# * `.queue( name, callback(queue) )`
# * `.queue( name, options, callback(queue) )`
queue:( name, options, openCallback ) ->
@_queues.set(name, new AmqpQueue(name, options, openCallback))
this
#### .queue(...).subscribe
# * `.subscribe( callback(message, header, deliveryInfo) )`
# * `.subscribe( options, callback(message, header, deliveryInfo) )`
subscribe:( options, messageListener ) ->
queue = @_queues.last()
throw new Error("At least one queue must be declared") if !queue
queue.subscribe(options, messageListener)
this
#### .queue(...).bind
# * `.bind( name, routingKey )`
bind:( name, routingKey ) ->
queue = @_queues.last()
throw new Error("At least one queue must be declared") if !queue
queue.bind(name, routingKey)
this
#### .connect
# * `.connect( amqp, callback(err, amqp) )`
# * `.connect( callback(err, amqp) )`
#
# `amqp` parameter is an hashtable which contain
#
# queues:
# sampleQueue:[Amqp::Queue]
#
# exchanges:
# sampleExchange:[Amqp::Exchange]
#
# connection: [Amqp::Connection]
#
connect:(amqp, @_callback)->
if amqp is undefined
@_callback = ->
amqp = require 'amqp'
if typeof amqp is "function"
@_callback = amqp
amqp = require 'amqp'
@_connect(amqp)
null
## Private API
# Create the connection to amqp and bind events
_connect:(amqp) ->
# Create connection
@conn = amqp.createConnection({
host: @_host,
port: @_port,
login: @_login,
password: <PASSWORD>,
vhost: @_vhost
})
# When the connection will be ready, connect the exchanges
@on 'ready', () => @_connectExchanges(@_connectQueues.bind(this))
# Set event listeners
@conn.on(event, @_getListenerFor(event)) for event of @_events
# Return a listener fonction for the event `event`.
_getListenerFor: (event) ->
if @_events[event].length == 1
return @_events[event][0]
else
return (args...) =>
listener.apply(null, args) for listener in @_events[event]
true
# Connect to exchanges
_connectExchanges:(next) ->
async.forEach @_exchanges.list(), @_connectExchange.bind(@), (err) =>
if err
throw new Error("Couldn't connect to the exchanges: #{err.message}")
return
next()
# Exchange connection iterator
_connectExchange:(exchange, callback) ->
@conn.exchange exchange.name, exchange.options, (exchangeRef) ->
exchange.ref = exchangeRef
exchange.openCallback(exchangeRef)
callback(null, true)
# Connect to queues
_connectQueues:() ->
async.forEach @_queues.list(), @_connectQueue.bind(@), (err) =>
if err
throw new Error("Couldn't connect to the queues: #{err.message}")
return
@_done()
# Queue connection iterator
_connectQueue:(queue, callback) ->
@conn.queue queue.name, queue.options, (queueRef) ->
queue.ref = queueRef
queue.openCallback(queueRef)
queue.bindTo.forEach((bind) ->
[exchange, routingKey] = bind
queueRef.bind exchange, routingKey
)
queue.listenTo.forEach((listen) ->
[option, listener] = listen
queueRef.subscribe option, listener
)
callback(null, true)
# When everything's connected, trigger the final callback
_done:() ->
msg =
queues : {}
exchanges : {}
connection : @conn
for k,v of @_queues.index()
msg.queues[k] = v.ref
for k,v of @_exchanges.index()
msg.exchanges[k] = v.ref
@_callback(null, msg)
| true | # Amqp-DSL - Fluent interface for node-amqp
async = require 'async'
IndexedList = require './IndexedList'
AmqpQueue = require './AmqpQueue'
AmqpExchange = require './AmqpExchange'
module.exports = class AmqpDsl
LISTENNERS =['error','close','ready']
## Public API
#### require('amqp-dsl').login
# * `login( options = {} )`
#
AmqpDsl.login = (opt = {}) ->
new AmqpDsl(opt)
constructor:(opt = {}) ->
# Defaults
@_login = ''
@_password = ''
@_host = ''
@_port = 5672
@_vhost = '/'
@_conn = null
@_callback = ->
# Constructor arguments
opt.login and (@_login = opt.login)
opt.password and PI:PASSWORD:<PASSWORD>END_PIpassword = PI:PASSWORD:<PASSWORD>END_PI)
opt.host and (@_host = opt.host)
opt.port and (@_port = opt.port)
opt.vhost and (@_vhost = opt.vhost)
opt.login and (@_login = opt.login)
# Events
@_events = {}
# Exchanges
@_exchanges = new IndexedList()
# Queues
@_queues = new IndexedList()
#### .on
# * `on( event, listener )`
on:( event, listener ) ->
if !~LISTENNERS.indexOf(event)
throw new Error("Event '#{event}' is invalid")
@_events[event] = [] if(!@_events[event])
@_events[event].push(listener)
this
#### .exchange
# * `.exchange( name, options )`
# * `.exchange( name, callback(exchange) )`
# * `.exchange( name, options, callback(exchange) )`
exchange:( name, options, openCallback ) ->
@_exchanges.set(name, new AmqpExchange(name, options, openCallback))
this
#### .queue
# * `.queue( name, options )`
# * `.queue( name, callback(queue) )`
# * `.queue( name, options, callback(queue) )`
queue:( name, options, openCallback ) ->
@_queues.set(name, new AmqpQueue(name, options, openCallback))
this
#### .queue(...).subscribe
# * `.subscribe( callback(message, header, deliveryInfo) )`
# * `.subscribe( options, callback(message, header, deliveryInfo) )`
subscribe:( options, messageListener ) ->
queue = @_queues.last()
throw new Error("At least one queue must be declared") if !queue
queue.subscribe(options, messageListener)
this
#### .queue(...).bind
# * `.bind( name, routingKey )`
bind:( name, routingKey ) ->
queue = @_queues.last()
throw new Error("At least one queue must be declared") if !queue
queue.bind(name, routingKey)
this
#### .connect
# * `.connect( amqp, callback(err, amqp) )`
# * `.connect( callback(err, amqp) )`
#
# `amqp` parameter is an hashtable which contain
#
# queues:
# sampleQueue:[Amqp::Queue]
#
# exchanges:
# sampleExchange:[Amqp::Exchange]
#
# connection: [Amqp::Connection]
#
connect:(amqp, @_callback)->
if amqp is undefined
@_callback = ->
amqp = require 'amqp'
if typeof amqp is "function"
@_callback = amqp
amqp = require 'amqp'
@_connect(amqp)
null
## Private API
# Create the connection to amqp and bind events
_connect:(amqp) ->
# Create connection
@conn = amqp.createConnection({
host: @_host,
port: @_port,
login: @_login,
password: PI:PASSWORD:<PASSWORD>END_PI,
vhost: @_vhost
})
# When the connection will be ready, connect the exchanges
@on 'ready', () => @_connectExchanges(@_connectQueues.bind(this))
# Set event listeners
@conn.on(event, @_getListenerFor(event)) for event of @_events
# Return a listener fonction for the event `event`.
_getListenerFor: (event) ->
if @_events[event].length == 1
return @_events[event][0]
else
return (args...) =>
listener.apply(null, args) for listener in @_events[event]
true
# Connect to exchanges
_connectExchanges:(next) ->
async.forEach @_exchanges.list(), @_connectExchange.bind(@), (err) =>
if err
throw new Error("Couldn't connect to the exchanges: #{err.message}")
return
next()
# Exchange connection iterator
_connectExchange:(exchange, callback) ->
@conn.exchange exchange.name, exchange.options, (exchangeRef) ->
exchange.ref = exchangeRef
exchange.openCallback(exchangeRef)
callback(null, true)
# Connect to queues
_connectQueues:() ->
async.forEach @_queues.list(), @_connectQueue.bind(@), (err) =>
if err
throw new Error("Couldn't connect to the queues: #{err.message}")
return
@_done()
# Queue connection iterator
_connectQueue:(queue, callback) ->
@conn.queue queue.name, queue.options, (queueRef) ->
queue.ref = queueRef
queue.openCallback(queueRef)
queue.bindTo.forEach((bind) ->
[exchange, routingKey] = bind
queueRef.bind exchange, routingKey
)
queue.listenTo.forEach((listen) ->
[option, listener] = listen
queueRef.subscribe option, listener
)
callback(null, true)
# When everything's connected, trigger the final callback
_done:() ->
msg =
queues : {}
exchanges : {}
connection : @conn
for k,v of @_queues.index()
msg.queues[k] = v.ref
for k,v of @_exchanges.index()
msg.exchanges[k] = v.ref
@_callback(null, msg)
|
[
{
"context": " in a nice environment\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nexports.init = (args) ->\n fs = require('",
"end": 190,
"score": 0.9998936653137207,
"start": 173,
"tag": "NAME",
"value": "Nikolay Nemshilov"
},
{
"context": " server.listen(port)\n\n p... | cli/commands/server.coffee | lovely-io/lovely.io-stl | 2 | #
# The package local server. It builds a user's
# package on fly alowing to effectively split it
# apart and work with it in a nice environment
#
# Copyright (C) 2011-2012 Nikolay Nemshilov
#
exports.init = (args) ->
fs = require('fs')
source = require('../source')
pack = require('../package')
express = require('express')
lovelyrc = require('../lovelyrc')
server = express(express.bodyParser())
port = args[0] || lovelyrc.port || 3000
base = lovelyrc.base + "/packages"
minify = false
#
# serving the modules
# NOTE: if the module name is the same as the current package name
# then the module will be dynamically compiled out of the source
#
server.all '/:module.js', (req, res) ->
module = req.params.module
host = "http://#{req.host}:#{port}"
if module == pack.name || module == 'main'
src = if minify then source.minify() else source.compile()
size = Math.round(src.length/102.4)/10
console.log(" Compiling: ".cyan+ "/#{module}.js (#{size}Kb #{if minify then 'minified' else 'source'})".grey)
else if fs.existsSync("#{process.cwd()}/#{module}.js")
src = fs.readFileSync("#{process.cwd()}/#{module}.js")
console.log(" Sending: "+ "/#{module}.js (text/javascript)".grey)
else
if match = module.match(/^(.+?)\-(\d+\.\d+\.\d+.*?)$/)
module = match[1]
version = match[2]
else
version = 'active'
src = "/#{module}/#{version}/build.js"
console.log(" Serving: ".magenta + "/#{module}.js -> ~/.lovely/packages#{src}".grey)
src = fs.readFileSync("#{base}/#{src}").toString()
# adding the local domain-name/port to the CSS sources
for match in (src.match(/url\(('|")[^'"]+?\/images\/[^'"]+?\1\)/g) || [])
src = src.replace(match, match.replace(/^url\(('|")/, "url($1#{host}"))
res.charset = 'utf-8'
res.header('Cache-Control', 'no-cache')
res.header('Content-Type', 'text/javascript')
res.send src
# just a dummy favicon response
server.get '/favicon.ico', (req, res) ->
res.send ''
# listening all the static content in the user project
server.all /^\/(.*?)$/, (req, res) ->
minify = req.query.minify is 'true'
shared = "#{lovelyrc.base}/server"
file_in = (directory)->
for ext in ['', '.html', 'index.html', '/index.html']
relname = "#{req.params[0]}#{ext}"
fullname = "#{directory}/#{relname}"
if fs.existsSync(fullname) and !fs.statSync(fullname).isDirectory()
return relname
return false
content_type = (name)->
extension = (name || '').split('.')
switch extension[extension.length - 1]
when 'css' then return 'text/css'
when 'sass' then return 'text/css'
when 'scss' then return 'text/css'
when 'styl' then return 'text/css'
when 'js' then return 'text/javascript'
when 'coffee' then return 'text/javascript'
when 'ico' then return 'image/icon'
when 'png' then return 'image/png'
when 'jpg' then return 'image/jpg'
when 'gif' then return 'image/gif'
when 'swf' then return 'application/x-shockwave-flash'
when 'eot' then return "application/vnd.ms-fontobject"
when 'ttf' then return "application/x-font-ttf"
when 'woff' then return "application/x-font-woff"
when 'json' then return "application/json"
else return 'text/html'
if req.method is 'POST'
console.log("\n POST: ", JSON.stringify(req.body).grey)
if filename = file_in(process.cwd())
console.log("") if filename.substr(filename.length-4) is 'html'
console.log(" Sending: "+ "/#{filename} (#{content_type(filename)})".grey)
filepath = "#{process.cwd()}/#{filename}"
else if filename = file_in("#{lovelyrc.base}/packages")
console.log(" Sending: "+ "/#{filename} -> ~/.lovely/packages/#{filename}".grey)
filepath = "#{lovelyrc.base}/packages/#{filename}"
else if filename = file_in(shared)
console.log("") if filename.substr(filename.length-4) is 'html'
console.log(" Sending: "+ "/#{filename} -> ~/.lovely/server/#{filename}".grey)
filepath = "#{shared}/#{filename}"
else
console.log("\n Sending: "+ "404 Error".red + " /#{req.params[0]} is not found".grey)
filepath = "#{shared}/404.html"
content = fs.readFileSync(filepath)
if /\.coffee$/.test(filename)
content = source.assemble(content.toString(), 'coffee')
if /\.sass$/.test(filename)
content = source.style(content.toString(), 'sass')
if /\.styl$/.test(filename)
content = source.style(content.toString(), 'styl')
if /\.scss$/.test(filename)
content = source.style(content.toString(), 'scss')
res.charset = 'utf-8'
res.header('Content-Type', content_type(filename))
res.send content
server.listen(port)
print "Listening: http://127.0.0.1:#{port}\n"+
"Press Ctrl+C to hung up".grey
exports.help = (args) ->
"""
Runs a development server in a LovelyIO module project
Usage:
lovely server [port]
""" | 190794 | #
# The package local server. It builds a user's
# package on fly alowing to effectively split it
# apart and work with it in a nice environment
#
# Copyright (C) 2011-2012 <NAME>
#
exports.init = (args) ->
fs = require('fs')
source = require('../source')
pack = require('../package')
express = require('express')
lovelyrc = require('../lovelyrc')
server = express(express.bodyParser())
port = args[0] || lovelyrc.port || 3000
base = lovelyrc.base + "/packages"
minify = false
#
# serving the modules
# NOTE: if the module name is the same as the current package name
# then the module will be dynamically compiled out of the source
#
server.all '/:module.js', (req, res) ->
module = req.params.module
host = "http://#{req.host}:#{port}"
if module == pack.name || module == 'main'
src = if minify then source.minify() else source.compile()
size = Math.round(src.length/102.4)/10
console.log(" Compiling: ".cyan+ "/#{module}.js (#{size}Kb #{if minify then 'minified' else 'source'})".grey)
else if fs.existsSync("#{process.cwd()}/#{module}.js")
src = fs.readFileSync("#{process.cwd()}/#{module}.js")
console.log(" Sending: "+ "/#{module}.js (text/javascript)".grey)
else
if match = module.match(/^(.+?)\-(\d+\.\d+\.\d+.*?)$/)
module = match[1]
version = match[2]
else
version = 'active'
src = "/#{module}/#{version}/build.js"
console.log(" Serving: ".magenta + "/#{module}.js -> ~/.lovely/packages#{src}".grey)
src = fs.readFileSync("#{base}/#{src}").toString()
# adding the local domain-name/port to the CSS sources
for match in (src.match(/url\(('|")[^'"]+?\/images\/[^'"]+?\1\)/g) || [])
src = src.replace(match, match.replace(/^url\(('|")/, "url($1#{host}"))
res.charset = 'utf-8'
res.header('Cache-Control', 'no-cache')
res.header('Content-Type', 'text/javascript')
res.send src
# just a dummy favicon response
server.get '/favicon.ico', (req, res) ->
res.send ''
# listening all the static content in the user project
server.all /^\/(.*?)$/, (req, res) ->
minify = req.query.minify is 'true'
shared = "#{lovelyrc.base}/server"
file_in = (directory)->
for ext in ['', '.html', 'index.html', '/index.html']
relname = "#{req.params[0]}#{ext}"
fullname = "#{directory}/#{relname}"
if fs.existsSync(fullname) and !fs.statSync(fullname).isDirectory()
return relname
return false
content_type = (name)->
extension = (name || '').split('.')
switch extension[extension.length - 1]
when 'css' then return 'text/css'
when 'sass' then return 'text/css'
when 'scss' then return 'text/css'
when 'styl' then return 'text/css'
when 'js' then return 'text/javascript'
when 'coffee' then return 'text/javascript'
when 'ico' then return 'image/icon'
when 'png' then return 'image/png'
when 'jpg' then return 'image/jpg'
when 'gif' then return 'image/gif'
when 'swf' then return 'application/x-shockwave-flash'
when 'eot' then return "application/vnd.ms-fontobject"
when 'ttf' then return "application/x-font-ttf"
when 'woff' then return "application/x-font-woff"
when 'json' then return "application/json"
else return 'text/html'
if req.method is 'POST'
console.log("\n POST: ", JSON.stringify(req.body).grey)
if filename = file_in(process.cwd())
console.log("") if filename.substr(filename.length-4) is 'html'
console.log(" Sending: "+ "/#{filename} (#{content_type(filename)})".grey)
filepath = "#{process.cwd()}/#{filename}"
else if filename = file_in("#{lovelyrc.base}/packages")
console.log(" Sending: "+ "/#{filename} -> ~/.lovely/packages/#{filename}".grey)
filepath = "#{lovelyrc.base}/packages/#{filename}"
else if filename = file_in(shared)
console.log("") if filename.substr(filename.length-4) is 'html'
console.log(" Sending: "+ "/#{filename} -> ~/.lovely/server/#{filename}".grey)
filepath = "#{shared}/#{filename}"
else
console.log("\n Sending: "+ "404 Error".red + " /#{req.params[0]} is not found".grey)
filepath = "#{shared}/404.html"
content = fs.readFileSync(filepath)
if /\.coffee$/.test(filename)
content = source.assemble(content.toString(), 'coffee')
if /\.sass$/.test(filename)
content = source.style(content.toString(), 'sass')
if /\.styl$/.test(filename)
content = source.style(content.toString(), 'styl')
if /\.scss$/.test(filename)
content = source.style(content.toString(), 'scss')
res.charset = 'utf-8'
res.header('Content-Type', content_type(filename))
res.send content
server.listen(port)
print "Listening: http://127.0.0.1:#{port}\n"+
"Press Ctrl+C to hung up".grey
exports.help = (args) ->
"""
Runs a development server in a LovelyIO module project
Usage:
lovely server [port]
""" | true | #
# The package local server. It builds a user's
# package on fly alowing to effectively split it
# apart and work with it in a nice environment
#
# Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI
#
exports.init = (args) ->
fs = require('fs')
source = require('../source')
pack = require('../package')
express = require('express')
lovelyrc = require('../lovelyrc')
server = express(express.bodyParser())
port = args[0] || lovelyrc.port || 3000
base = lovelyrc.base + "/packages"
minify = false
#
# serving the modules
# NOTE: if the module name is the same as the current package name
# then the module will be dynamically compiled out of the source
#
server.all '/:module.js', (req, res) ->
module = req.params.module
host = "http://#{req.host}:#{port}"
if module == pack.name || module == 'main'
src = if minify then source.minify() else source.compile()
size = Math.round(src.length/102.4)/10
console.log(" Compiling: ".cyan+ "/#{module}.js (#{size}Kb #{if minify then 'minified' else 'source'})".grey)
else if fs.existsSync("#{process.cwd()}/#{module}.js")
src = fs.readFileSync("#{process.cwd()}/#{module}.js")
console.log(" Sending: "+ "/#{module}.js (text/javascript)".grey)
else
if match = module.match(/^(.+?)\-(\d+\.\d+\.\d+.*?)$/)
module = match[1]
version = match[2]
else
version = 'active'
src = "/#{module}/#{version}/build.js"
console.log(" Serving: ".magenta + "/#{module}.js -> ~/.lovely/packages#{src}".grey)
src = fs.readFileSync("#{base}/#{src}").toString()
# adding the local domain-name/port to the CSS sources
for match in (src.match(/url\(('|")[^'"]+?\/images\/[^'"]+?\1\)/g) || [])
src = src.replace(match, match.replace(/^url\(('|")/, "url($1#{host}"))
res.charset = 'utf-8'
res.header('Cache-Control', 'no-cache')
res.header('Content-Type', 'text/javascript')
res.send src
# just a dummy favicon response
server.get '/favicon.ico', (req, res) ->
res.send ''
# listening all the static content in the user project
server.all /^\/(.*?)$/, (req, res) ->
minify = req.query.minify is 'true'
shared = "#{lovelyrc.base}/server"
file_in = (directory)->
for ext in ['', '.html', 'index.html', '/index.html']
relname = "#{req.params[0]}#{ext}"
fullname = "#{directory}/#{relname}"
if fs.existsSync(fullname) and !fs.statSync(fullname).isDirectory()
return relname
return false
content_type = (name)->
extension = (name || '').split('.')
switch extension[extension.length - 1]
when 'css' then return 'text/css'
when 'sass' then return 'text/css'
when 'scss' then return 'text/css'
when 'styl' then return 'text/css'
when 'js' then return 'text/javascript'
when 'coffee' then return 'text/javascript'
when 'ico' then return 'image/icon'
when 'png' then return 'image/png'
when 'jpg' then return 'image/jpg'
when 'gif' then return 'image/gif'
when 'swf' then return 'application/x-shockwave-flash'
when 'eot' then return "application/vnd.ms-fontobject"
when 'ttf' then return "application/x-font-ttf"
when 'woff' then return "application/x-font-woff"
when 'json' then return "application/json"
else return 'text/html'
if req.method is 'POST'
console.log("\n POST: ", JSON.stringify(req.body).grey)
if filename = file_in(process.cwd())
console.log("") if filename.substr(filename.length-4) is 'html'
console.log(" Sending: "+ "/#{filename} (#{content_type(filename)})".grey)
filepath = "#{process.cwd()}/#{filename}"
else if filename = file_in("#{lovelyrc.base}/packages")
console.log(" Sending: "+ "/#{filename} -> ~/.lovely/packages/#{filename}".grey)
filepath = "#{lovelyrc.base}/packages/#{filename}"
else if filename = file_in(shared)
console.log("") if filename.substr(filename.length-4) is 'html'
console.log(" Sending: "+ "/#{filename} -> ~/.lovely/server/#{filename}".grey)
filepath = "#{shared}/#{filename}"
else
console.log("\n Sending: "+ "404 Error".red + " /#{req.params[0]} is not found".grey)
filepath = "#{shared}/404.html"
content = fs.readFileSync(filepath)
if /\.coffee$/.test(filename)
content = source.assemble(content.toString(), 'coffee')
if /\.sass$/.test(filename)
content = source.style(content.toString(), 'sass')
if /\.styl$/.test(filename)
content = source.style(content.toString(), 'styl')
if /\.scss$/.test(filename)
content = source.style(content.toString(), 'scss')
res.charset = 'utf-8'
res.header('Content-Type', content_type(filename))
res.send content
server.listen(port)
print "Listening: http://127.0.0.1:#{port}\n"+
"Press Ctrl+C to hung up".grey
exports.help = (args) ->
"""
Runs a development server in a LovelyIO module project
Usage:
lovely server [port]
""" |
[
{
"context": " place_mock(x, y, info)\n chunk_key = \"#{Math.floor(x/20)}x#{Math.floor(y/20)}\"\n item = {\n id: Utils.uuid()\n ",
"end": 2427,
"score": 0.9992887377738953,
"start": 2386,
"tag": "KEY",
"value": "\"#{Math.floor(x/20)}x#{Math.floor(y/20)}\""
... | src/setup/mock-building-factory.coffee | starpeace-project/starpeace-server-galaxy-nodejs | 0 |
import Logger from '~/plugins/starpeace-client/logger.coffee'
import Utils from '~/plugins/starpeace-client/utils/utils.coffee'
import RoadManager from '~/plugins/starpeace-client/manager/road-manager.coffee'
MOCK_DATA = {}
MOCK_TYCOONS = ['tycoon-id-1', 'tycoon-id-2', 'tycoon-id-3', 'tycoon-id-4', 'tycoon-id-5']
TYCOON_ID_CORP_ID_COMPANY_IDS = {
'tycoon-id-1': {
corporation_id: 'corp-id-1'
'DIS': 'company-id-1'
'MAGNA': 'company-id-2'
'MKO': 'company-id-3'
'MOAB': 'company-id-4'
'PGI': 'company-id-5'
},
'tycoon-id-2': {
corporation_id: 'corp-id-4'
'DIS': 'company-id-6'
'MAGNA': 'company-id-7'
'MKO': 'company-id-8'
'MOAB': 'company-id-9'
'PGI': 'company-id-10'
},
'tycoon-id-3': {
corporation_id: 'corp-id-5'
'DIS': 'company-id-11'
'MAGNA': 'company-id-12'
'MKO': 'company-id-13'
'MOAB': 'company-id-14'
'PGI': 'company-id-15'
},
'tycoon-id-4': {
corporation_id: 'corp-id-6'
'DIS': 'company-id-16'
'MAGNA': 'company-id-17'
'MKO': 'company-id-18'
'MOAB': 'company-id-19'
'PGI': 'company-id-20'
},
'tycoon-id-5': {
corporation_id: 'corp-id-7'
'DIS': 'company-id-21'
'MAGNA': 'company-id-22'
'MKO': 'company-id-23'
'MOAB': 'company-id-24'
'PGI': 'company-id-25'
}
}
export default class MockBuildingFactory
constructor: (@translation_manager, @client_state) ->
setup_mocks: () ->
mock_map_buildings = []
can_place = (xt, yt, info) =>
for j in [0...info.h]
for i in [0...info.w]
index = 1000 * (yt - j) + (xt - i)
return false if mock_map_buildings[index]? || RoadManager.DUMMY_ROAD_DATA[index] || @client_state.planet.game_map?.ground_map?.is_coast_at(xt - i, yt - j) || @client_state.planet.game_map?.ground_map?.is_water_at(xt - i, yt - j) && @client_state.planet.game_map?.ground_map?.is_coast_around(xt - i, yt - j)
true
place_mock = (xt, yt, info) ->
for j in [0...info.h]
for i in [0...info.w]
mock_map_buildings[1000 * (yt - j) + (xt - i)] = info
buildings_for_company = {}
x = 195
y = 90
for key,info of @client_state.core.building_library.all_metadata()
found_position = false
until found_position
if can_place(x, y, info)
found_position = true
place_mock(x, y, info)
chunk_key = "#{Math.floor(x/20)}x#{Math.floor(y/20)}"
item = {
id: Utils.uuid()
tycoon_id: MOCK_TYCOONS[Math.floor(Math.random() * MOCK_TYCOONS.length)]
name: "#{@translation_manager.text(info.name_key)} 1"
key: key
x: x
y: y
}
item.corporation_id = TYCOON_ID_CORP_ID_COMPANY_IDS[item.tycoon_id].corporation_id
item.company_id = TYCOON_ID_CORP_ID_COMPANY_IDS[item.tycoon_id][info.seal_ids[Math.floor(Math.random() * info.seal_ids.length)]]
MOCK_DATA[chunk_key] ||= []
MOCK_DATA[chunk_key].push item
if item.tycoon_id == 'tycoon-id-1'
buildings_for_company[item.company_id] ||= []
buildings_for_company[item.company_id].push item
x += info.w
else
x += 1
if x > 235
x = 195
y += 1
# return if ~key.indexOf('tennis')
| 25090 |
import Logger from '~/plugins/starpeace-client/logger.coffee'
import Utils from '~/plugins/starpeace-client/utils/utils.coffee'
import RoadManager from '~/plugins/starpeace-client/manager/road-manager.coffee'
MOCK_DATA = {}
MOCK_TYCOONS = ['tycoon-id-1', 'tycoon-id-2', 'tycoon-id-3', 'tycoon-id-4', 'tycoon-id-5']
TYCOON_ID_CORP_ID_COMPANY_IDS = {
'tycoon-id-1': {
corporation_id: 'corp-id-1'
'DIS': 'company-id-1'
'MAGNA': 'company-id-2'
'MKO': 'company-id-3'
'MOAB': 'company-id-4'
'PGI': 'company-id-5'
},
'tycoon-id-2': {
corporation_id: 'corp-id-4'
'DIS': 'company-id-6'
'MAGNA': 'company-id-7'
'MKO': 'company-id-8'
'MOAB': 'company-id-9'
'PGI': 'company-id-10'
},
'tycoon-id-3': {
corporation_id: 'corp-id-5'
'DIS': 'company-id-11'
'MAGNA': 'company-id-12'
'MKO': 'company-id-13'
'MOAB': 'company-id-14'
'PGI': 'company-id-15'
},
'tycoon-id-4': {
corporation_id: 'corp-id-6'
'DIS': 'company-id-16'
'MAGNA': 'company-id-17'
'MKO': 'company-id-18'
'MOAB': 'company-id-19'
'PGI': 'company-id-20'
},
'tycoon-id-5': {
corporation_id: 'corp-id-7'
'DIS': 'company-id-21'
'MAGNA': 'company-id-22'
'MKO': 'company-id-23'
'MOAB': 'company-id-24'
'PGI': 'company-id-25'
}
}
export default class MockBuildingFactory
constructor: (@translation_manager, @client_state) ->
setup_mocks: () ->
mock_map_buildings = []
can_place = (xt, yt, info) =>
for j in [0...info.h]
for i in [0...info.w]
index = 1000 * (yt - j) + (xt - i)
return false if mock_map_buildings[index]? || RoadManager.DUMMY_ROAD_DATA[index] || @client_state.planet.game_map?.ground_map?.is_coast_at(xt - i, yt - j) || @client_state.planet.game_map?.ground_map?.is_water_at(xt - i, yt - j) && @client_state.planet.game_map?.ground_map?.is_coast_around(xt - i, yt - j)
true
place_mock = (xt, yt, info) ->
for j in [0...info.h]
for i in [0...info.w]
mock_map_buildings[1000 * (yt - j) + (xt - i)] = info
buildings_for_company = {}
x = 195
y = 90
for key,info of @client_state.core.building_library.all_metadata()
found_position = false
until found_position
if can_place(x, y, info)
found_position = true
place_mock(x, y, info)
chunk_key = <KEY>
item = {
id: Utils.uuid()
tycoon_id: MOCK_TYCOONS[Math.floor(Math.random() * MOCK_TYCOONS.length)]
name: "#{@translation_manager.text(info.name_key)} <KEY>"
key: key
x: x
y: y
}
item.corporation_id = TYCOON_ID_CORP_ID_COMPANY_IDS[item.tycoon_id].corporation_id
item.company_id = TYCOON_ID_CORP_ID_COMPANY_IDS[item.tycoon_id][info.seal_ids[Math.floor(Math.random() * info.seal_ids.length)]]
MOCK_DATA[chunk_key] ||= []
MOCK_DATA[chunk_key].push item
if item.tycoon_id == 'tycoon-id-1'
buildings_for_company[item.company_id] ||= []
buildings_for_company[item.company_id].push item
x += info.w
else
x += 1
if x > 235
x = 195
y += 1
# return if ~key.indexOf('tennis')
| true |
import Logger from '~/plugins/starpeace-client/logger.coffee'
import Utils from '~/plugins/starpeace-client/utils/utils.coffee'
import RoadManager from '~/plugins/starpeace-client/manager/road-manager.coffee'
MOCK_DATA = {}
MOCK_TYCOONS = ['tycoon-id-1', 'tycoon-id-2', 'tycoon-id-3', 'tycoon-id-4', 'tycoon-id-5']
TYCOON_ID_CORP_ID_COMPANY_IDS = {
'tycoon-id-1': {
corporation_id: 'corp-id-1'
'DIS': 'company-id-1'
'MAGNA': 'company-id-2'
'MKO': 'company-id-3'
'MOAB': 'company-id-4'
'PGI': 'company-id-5'
},
'tycoon-id-2': {
corporation_id: 'corp-id-4'
'DIS': 'company-id-6'
'MAGNA': 'company-id-7'
'MKO': 'company-id-8'
'MOAB': 'company-id-9'
'PGI': 'company-id-10'
},
'tycoon-id-3': {
corporation_id: 'corp-id-5'
'DIS': 'company-id-11'
'MAGNA': 'company-id-12'
'MKO': 'company-id-13'
'MOAB': 'company-id-14'
'PGI': 'company-id-15'
},
'tycoon-id-4': {
corporation_id: 'corp-id-6'
'DIS': 'company-id-16'
'MAGNA': 'company-id-17'
'MKO': 'company-id-18'
'MOAB': 'company-id-19'
'PGI': 'company-id-20'
},
'tycoon-id-5': {
corporation_id: 'corp-id-7'
'DIS': 'company-id-21'
'MAGNA': 'company-id-22'
'MKO': 'company-id-23'
'MOAB': 'company-id-24'
'PGI': 'company-id-25'
}
}
export default class MockBuildingFactory
constructor: (@translation_manager, @client_state) ->
setup_mocks: () ->
mock_map_buildings = []
can_place = (xt, yt, info) =>
for j in [0...info.h]
for i in [0...info.w]
index = 1000 * (yt - j) + (xt - i)
return false if mock_map_buildings[index]? || RoadManager.DUMMY_ROAD_DATA[index] || @client_state.planet.game_map?.ground_map?.is_coast_at(xt - i, yt - j) || @client_state.planet.game_map?.ground_map?.is_water_at(xt - i, yt - j) && @client_state.planet.game_map?.ground_map?.is_coast_around(xt - i, yt - j)
true
place_mock = (xt, yt, info) ->
for j in [0...info.h]
for i in [0...info.w]
mock_map_buildings[1000 * (yt - j) + (xt - i)] = info
buildings_for_company = {}
x = 195
y = 90
for key,info of @client_state.core.building_library.all_metadata()
found_position = false
until found_position
if can_place(x, y, info)
found_position = true
place_mock(x, y, info)
chunk_key = PI:KEY:<KEY>END_PI
item = {
id: Utils.uuid()
tycoon_id: MOCK_TYCOONS[Math.floor(Math.random() * MOCK_TYCOONS.length)]
name: "#{@translation_manager.text(info.name_key)} PI:KEY:<KEY>END_PI"
key: key
x: x
y: y
}
item.corporation_id = TYCOON_ID_CORP_ID_COMPANY_IDS[item.tycoon_id].corporation_id
item.company_id = TYCOON_ID_CORP_ID_COMPANY_IDS[item.tycoon_id][info.seal_ids[Math.floor(Math.random() * info.seal_ids.length)]]
MOCK_DATA[chunk_key] ||= []
MOCK_DATA[chunk_key].push item
if item.tycoon_id == 'tycoon-id-1'
buildings_for_company[item.company_id] ||= []
buildings_for_company[item.company_id].push item
x += info.w
else
x += 1
if x > 235
x = 195
y += 1
# return if ~key.indexOf('tennis')
|
[
{
"context": "chine Based on Functional Programming Concepts* by Yasushi KIYOKI, Kazuhiko KATO\nand Takashi MASUDA, University of ",
"end": 542,
"score": 0.9997735023498535,
"start": 528,
"tag": "NAME",
"value": "Yasushi KIYOKI"
},
{
"context": "unctional Programming Concepts* by Yas... | dev/in-memory-sql/src/demo-frp.coffee | loveencounterflow/hengist | 0 |
###
**Note** 'FRP' here is 'Functional *Relational* Programming' whereas it's most often used for 'Functional
*Reactive* Programming' these days, so maybe better call it **FunRelPro** or something like that.
> In FRP all *essential state* takes the form of relations, and the *essential logic* is expressed using
> relational algebra extended with (pure) user defined functions.—
> https://softwareengineering.stackexchange.com/a/170566/281585
[*A Relational Database Machine Based on Functional Programming Concepts* by Yasushi KIYOKI, Kazuhiko KATO
and Takashi MASUDA, University of Tsukuba, ca.
1985—1995](https://thelackthereof.org/docs/library/cs/database/KIYOKI,%20Yasushi%20et%20al:%20A%20Relational%20Database%20Machine%20Based%20on%20Functional%20Programming%20Concepts.pdf)
###
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'FRP'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
echo = CND.echo.bind CND
#...........................................................................................................
PATH = require 'path'
FS = require 'fs'
RBW = require '../../../apps/rustybuzz-wasm/demo-nodejs-using-wasm'
ICQL = require '../../../apps/icql'
connector = require 'better-sqlite3'
icql_path = PATH.resolve PATH.join __dirname, '../demo-frp.icql'
db_path = ':memory:'
#-----------------------------------------------------------------------------------------------------------
@new_db = ( cfg ) ->
db = ICQL.bind { connector, db_path, icql_path, }
# db.pragma 'cache_size = 32000'
# db.pragma 'synchronous = OFF' # makes file-based DBs much faster
return db
#-----------------------------------------------------------------------------------------------------------
@create_tables = ( cfg ) ->
cfg.db.create_table_text()
#-----------------------------------------------------------------------------------------------------------
@insert_text = ( cfg ) ->
linenr = 0
for line in cfg.text.split /\n/
linenr++
cfg.db.insert_line { linenr, line, }
return linenr
#-----------------------------------------------------------------------------------------------------------
@demo_frp = ( cfg ) ->
cfg ?= {}
cfg.db = @new_db cfg
@create_tables cfg
@insert_text cfg
debug '^3334^', d for d from cfg.db.sqlite_index_infos()
#.........................................................................................................
for row from cfg.db.get_all_texts()
info row
cfg.db.$.close()
return null
#-----------------------------------------------------------------------------------------------------------
@bettersqlite3_memory = ( cfg ) => @_bettersqlite3 cfg, ':memory:'
@bettersqlite3_backup = ( cfg ) => @_bettersqlite3 cfg, ':memory:', true
@bettersqlite3_file = ( cfg ) => @_bettersqlite3 cfg, '/tmp/hengist-in-memory-sql.benchmarks.db'
############################################################################################################
if require.main is module then do =>
cfg =
db_path: ':memory:'
text: """Knuth–Liang hyphenation operates at the level of individual words, but there can be
ambiguity as to what constitutes a word. All hyphenation dictionaries handle the expected set of
word-forming graphemes"""
await @demo_frp cfg
| 11773 |
###
**Note** 'FRP' here is 'Functional *Relational* Programming' whereas it's most often used for 'Functional
*Reactive* Programming' these days, so maybe better call it **FunRelPro** or something like that.
> In FRP all *essential state* takes the form of relations, and the *essential logic* is expressed using
> relational algebra extended with (pure) user defined functions.—
> https://softwareengineering.stackexchange.com/a/170566/281585
[*A Relational Database Machine Based on Functional Programming Concepts* by <NAME>, <NAME>
and <NAME>, University of Tsukuba, ca.
1985—1995](https://thelackthereof.org/docs/library/cs/database/KIYOKI,%20Yasushi%20et%20al:%20A%20Relational%20Database%20Machine%20Based%20on%20Functional%20Programming%20Concepts.pdf)
###
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'FRP'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
echo = CND.echo.bind CND
#...........................................................................................................
PATH = require 'path'
FS = require 'fs'
RBW = require '../../../apps/rustybuzz-wasm/demo-nodejs-using-wasm'
ICQL = require '../../../apps/icql'
connector = require 'better-sqlite3'
icql_path = PATH.resolve PATH.join __dirname, '../demo-frp.icql'
db_path = ':memory:'
#-----------------------------------------------------------------------------------------------------------
@new_db = ( cfg ) ->
db = ICQL.bind { connector, db_path, icql_path, }
# db.pragma 'cache_size = 32000'
# db.pragma 'synchronous = OFF' # makes file-based DBs much faster
return db
#-----------------------------------------------------------------------------------------------------------
@create_tables = ( cfg ) ->
cfg.db.create_table_text()
#-----------------------------------------------------------------------------------------------------------
@insert_text = ( cfg ) ->
linenr = 0
for line in cfg.text.split /\n/
linenr++
cfg.db.insert_line { linenr, line, }
return linenr
#-----------------------------------------------------------------------------------------------------------
@demo_frp = ( cfg ) ->
cfg ?= {}
cfg.db = @new_db cfg
@create_tables cfg
@insert_text cfg
debug '^3334^', d for d from cfg.db.sqlite_index_infos()
#.........................................................................................................
for row from cfg.db.get_all_texts()
info row
cfg.db.$.close()
return null
#-----------------------------------------------------------------------------------------------------------
@bettersqlite3_memory = ( cfg ) => @_bettersqlite3 cfg, ':memory:'
@bettersqlite3_backup = ( cfg ) => @_bettersqlite3 cfg, ':memory:', true
@bettersqlite3_file = ( cfg ) => @_bettersqlite3 cfg, '/tmp/hengist-in-memory-sql.benchmarks.db'
############################################################################################################
if require.main is module then do =>
cfg =
db_path: ':memory:'
text: """Knuth–Liang hyphenation operates at the level of individual words, but there can be
ambiguity as to what constitutes a word. All hyphenation dictionaries handle the expected set of
word-forming graphemes"""
await @demo_frp cfg
| true |
###
**Note** 'FRP' here is 'Functional *Relational* Programming' whereas it's most often used for 'Functional
*Reactive* Programming' these days, so maybe better call it **FunRelPro** or something like that.
> In FRP all *essential state* takes the form of relations, and the *essential logic* is expressed using
> relational algebra extended with (pure) user defined functions.—
> https://softwareengineering.stackexchange.com/a/170566/281585
[*A Relational Database Machine Based on Functional Programming Concepts* by PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
and PI:NAME:<NAME>END_PI, University of Tsukuba, ca.
1985—1995](https://thelackthereof.org/docs/library/cs/database/KIYOKI,%20Yasushi%20et%20al:%20A%20Relational%20Database%20Machine%20Based%20on%20Functional%20Programming%20Concepts.pdf)
###
'use strict'
############################################################################################################
CND = require 'cnd'
rpr = CND.rpr
badge = 'FRP'
log = CND.get_logger 'plain', badge
info = CND.get_logger 'info', badge
whisper = CND.get_logger 'whisper', badge
alert = CND.get_logger 'alert', badge
debug = CND.get_logger 'debug', badge
warn = CND.get_logger 'warn', badge
help = CND.get_logger 'help', badge
urge = CND.get_logger 'urge', badge
echo = CND.echo.bind CND
#...........................................................................................................
PATH = require 'path'
FS = require 'fs'
RBW = require '../../../apps/rustybuzz-wasm/demo-nodejs-using-wasm'
ICQL = require '../../../apps/icql'
connector = require 'better-sqlite3'
icql_path = PATH.resolve PATH.join __dirname, '../demo-frp.icql'
db_path = ':memory:'
#-----------------------------------------------------------------------------------------------------------
@new_db = ( cfg ) ->
db = ICQL.bind { connector, db_path, icql_path, }
# db.pragma 'cache_size = 32000'
# db.pragma 'synchronous = OFF' # makes file-based DBs much faster
return db
#-----------------------------------------------------------------------------------------------------------
@create_tables = ( cfg ) ->
cfg.db.create_table_text()
#-----------------------------------------------------------------------------------------------------------
@insert_text = ( cfg ) ->
linenr = 0
for line in cfg.text.split /\n/
linenr++
cfg.db.insert_line { linenr, line, }
return linenr
#-----------------------------------------------------------------------------------------------------------
@demo_frp = ( cfg ) ->
cfg ?= {}
cfg.db = @new_db cfg
@create_tables cfg
@insert_text cfg
debug '^3334^', d for d from cfg.db.sqlite_index_infos()
#.........................................................................................................
for row from cfg.db.get_all_texts()
info row
cfg.db.$.close()
return null
#-----------------------------------------------------------------------------------------------------------
@bettersqlite3_memory = ( cfg ) => @_bettersqlite3 cfg, ':memory:'
@bettersqlite3_backup = ( cfg ) => @_bettersqlite3 cfg, ':memory:', true
@bettersqlite3_file = ( cfg ) => @_bettersqlite3 cfg, '/tmp/hengist-in-memory-sql.benchmarks.db'
############################################################################################################
if require.main is module then do =>
cfg =
db_path: ':memory:'
text: """Knuth–Liang hyphenation operates at the level of individual words, but there can be
ambiguity as to what constitutes a word. All hyphenation dictionaries handle the expected set of
word-forming graphemes"""
await @demo_frp cfg
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.