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": "plit(' ')[1]\n\n form.set\n 'fullname': 'John Doe'\n\n expect(form.get 'margin').to.equal 2325 -",
"end": 1774,
"score": 0.9996998310089111,
"start": 1766,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " expect(form.get 'name.firstName').to.eq... | test/form._.spec.coffee | nrako/formal | 2 | ### global describe, it, beforeEach ###
chai = require 'chai'
expect = chai.expect
Form = require '../lib/form'
FieldTypes = Form.FieldTypes
Field = require '../lib/field/field'
describe 'Form', ->
describe 'form constructor and field path and definition', ->
it 'supports dot notation for path accessors', ->
form = new Form
nested:
property: String
deep:
property: Date
'nested.string.property': String
expect(form.path 'nested.property').to.be.an.instanceof FieldTypes.String
expect(form.path 'nested.deep.property').to.be.an.instanceof FieldTypes.Date
expect(form.path 'nested.string.property').to.be.an.instanceof FieldTypes.String
expect(form.path 'nested.inexistant').to.be.undefined
it 'supports add and field methods', ->
form = new Form
test: String
form.field
test2: String
form.add
test3: Date
expect(form.path 'test').to.be.an.instanceof FieldTypes.String
expect(form.path 'test2').to.be.an.instanceof FieldTypes.String
expect(form.path 'test3').to.be.an.instanceof FieldTypes.Date
fn = ->
form.field
type: 'unknown'
expect(fn).to.throw(Error);
it 'supports virtuals!', ->
form = new Form
price: Number
cost: Number
name:
firstName: String
familyName:
type: String
uppercase: true
form.set
price: 2325
cost: 2100
form.virtual('margin').get ->
this.price - this.cost
form.virtual('fullname').set (val) ->
this.name =
firstName: val.split(' ')[0]
familyName: val.split(' ')[1]
form.set
'fullname': 'John Doe'
expect(form.get 'margin').to.equal 2325 - 2100
expect(form.get 'name.firstName').to.equal 'John'
expect(form.get 'name.familyName').to.equal 'Doe'
describe 'fieldtypes and casting', ->
it 'supports different fieldtypes with casting', ->
form = new Form
string: String
date: Date
number: Number
bool: Boolean
obj =
string: 'string'
date: new Date
number: 234
bool: true
unknown:
sub: 'not set'
form.set obj
expect(form.get 'string').to.equal obj.string
expect(form.get 'date').to.equal obj.date
expect(form.get 'number').to.equal obj.number
expect(form.get 'bool').to.equal obj.bool
expect(form.get 'unknown.sub').to.be.undefined
fn = ->
form.field
err:
type: null
expect(fn).to.throw TypeError
it 'supports String', ->
form = new Form
1: String
2: String
3: String
4: String
5: String
6:
type: String
default: 'string default'
7: String
form.set
1: 'value'
2: 444
3: true
4: ['val',3]
5: null
expect(form.get '1').to.equal 'value'
expect(form.get '2').to.equal '444'
expect(form.get '3').to.equal 'true'
expect(form.get '4').to.equal 'val,3'
expect(form.get '5').to.be.null
expect(form.get '6').to.equal form.path('6').default()
form.set '1', null
expect(form.get '1').to.be.null
it 'supports Number', ->
form = new Form
1: Number
2: Number
3: Number
4: Number
5: Number
class Test
constructor: () ->
toString: () ->
return '1'
form.set
1: 1
2: 2.2
3: '-3'
4: []
5: new Test
expect(form.get '1').to.equal 1
expect(form.get '2').to.equal 2.2
expect(form.get '3').to.equal -3
it 'supports Date', ->
form = new Form
1: Date
2: Date
3: Date
now = new Date
form.set
1: now
2: now.getTime()
3: now.toString()
expect(form.get '1').to.equal now
# TODO make it works
#expect(form.get '2'.toString()).to.deep.equal now.toString()
#expect(form.get '3').to.equal now
form.set
1: 'not a date'
#expect(fn).to.throw require '../lib/errors/cast'
it 'supports Boolean', ->
form = new Form
1: Boolean
2: Boolean
3: Boolean
4: Boolean
5: Boolean
6: Boolean
7: Boolean
8: Boolean
form.set
1: true
2: 'false'
3: 1
4: 'adsf'
5: null
6: undefined
7: 0
8: '0'
expect(form.get '1').to.equal true
expect(form.get '2').to.equal false
expect(form.get '3').to.equal true
expect(form.get '4').to.equal true
expect(form.get '5').to.equal null
expect(form.get '6').to.be.null
expect(form.get '7').to.equal false
expect(form.get '8').to.equal false
describe 'options', ->
it 'supports options through constructor and form.option method', ->
form = new Form
test: String
,
autoTrim: true
expect(form.option 'autoTrim').to.be.true
form.option 'autoTrim', false
expect(form.option 'autoTrim').to.be.false
nbErrorsOpt = Object.keys(form.options.errors).length
form.option 'errors',
customType: 'Custom error msg added'
expect(Object.keys(form.options.errors).length).to.equal ++nbErrorsOpt
it 'supports option.autoTrim', ->
form = new Form
test:String
,
autoTrim: true
form.set
test: ' test '
expect(form.get 'test').to.equal 'test'
it 'supports option.autoLocals', (done) ->
form = new Form
test: String
,
autoLocals: false
request =
body:
test: 'no locals'
response =
locals: {}
cb = ->
expect(response.locals.form).to.be.undefined
done()
form.middleware() request, response, cb
it 'supports option.body', (done) ->
form = new Form
test: String
test2: String
test3: String
,
dataSources: ['query', 'params']
request =
body:
test: 'body'
query:
test2: 'query'
params:
test3: 'params'
response =
locals: {}
cb = ->
expect(request.form.get 'test').to.be.null
expect(request.form.get 'test2').to.equal 'query'
expect(request.form.get 'test3').to.equal 'params'
done()
form.middleware() request, response, cb
describe 'setters and getters', ->
it 'supports mongoose-like setters for string', ->
form = new Form
lower:
type: String
lowercase: true
upper:
type: String,
uppercase: true
trim: true
form.set
lower: 'UPPERcase'
upper: ' lowerCASE '
expect(form.get 'lower').to.equal 'uppercase'
expect(form.get 'upper').to.equal 'LOWERCASE'
it 'supports all kind of setters', ->
form = new Form
set:
type: Number
set: (val) ->
return val * -1
form.set
set: 23
expect(form.get 'set').to.equal -23
fn = ->
form.path('set').set
set: null
expect(fn).to.throw TypeError
it 'supports all kind of getters', ->
form = new Form
get:
type: String
get: (val) ->
return val.toUpperCase()
obj =
get: 'ToUpperCase'
form.set obj
expect(form.getValue 'get').to.be.equal obj.get
expect(form.get 'get').to.be.equal obj.get.toUpperCase()
fn = ->
form.path('get').get
get: null
expect(fn).to.throw TypeError
it 'supports form.getData', ->
form = new Form
a:
type: String
get: (val) ->
return this.get('b.c') + ' ' + val
b:
c:
type: Number
get: (val) ->
return val / 100
form.set
a: 'CHF'
b:
c: 99995
expect(form.getData()).to.deep.equal
a: '999.95 CHF'
b:
c: 999.95
it 'can have a 100% coverage', ->
form = new Form
a: String
b: Date
form.path('a').cast null
form.path('b').cast null
fn = ->
o = ->
o.toString = undefined
form.path('a').cast o
expect(fn).to.throw TypeError
| 23252 | ### global describe, it, beforeEach ###
chai = require 'chai'
expect = chai.expect
Form = require '../lib/form'
FieldTypes = Form.FieldTypes
Field = require '../lib/field/field'
describe 'Form', ->
describe 'form constructor and field path and definition', ->
it 'supports dot notation for path accessors', ->
form = new Form
nested:
property: String
deep:
property: Date
'nested.string.property': String
expect(form.path 'nested.property').to.be.an.instanceof FieldTypes.String
expect(form.path 'nested.deep.property').to.be.an.instanceof FieldTypes.Date
expect(form.path 'nested.string.property').to.be.an.instanceof FieldTypes.String
expect(form.path 'nested.inexistant').to.be.undefined
it 'supports add and field methods', ->
form = new Form
test: String
form.field
test2: String
form.add
test3: Date
expect(form.path 'test').to.be.an.instanceof FieldTypes.String
expect(form.path 'test2').to.be.an.instanceof FieldTypes.String
expect(form.path 'test3').to.be.an.instanceof FieldTypes.Date
fn = ->
form.field
type: 'unknown'
expect(fn).to.throw(Error);
it 'supports virtuals!', ->
form = new Form
price: Number
cost: Number
name:
firstName: String
familyName:
type: String
uppercase: true
form.set
price: 2325
cost: 2100
form.virtual('margin').get ->
this.price - this.cost
form.virtual('fullname').set (val) ->
this.name =
firstName: val.split(' ')[0]
familyName: val.split(' ')[1]
form.set
'fullname': '<NAME>'
expect(form.get 'margin').to.equal 2325 - 2100
expect(form.get 'name.firstName').to.equal '<NAME>'
expect(form.get 'name.familyName').to.equal '<NAME>e'
describe 'fieldtypes and casting', ->
it 'supports different fieldtypes with casting', ->
form = new Form
string: String
date: Date
number: Number
bool: Boolean
obj =
string: 'string'
date: new Date
number: 234
bool: true
unknown:
sub: 'not set'
form.set obj
expect(form.get 'string').to.equal obj.string
expect(form.get 'date').to.equal obj.date
expect(form.get 'number').to.equal obj.number
expect(form.get 'bool').to.equal obj.bool
expect(form.get 'unknown.sub').to.be.undefined
fn = ->
form.field
err:
type: null
expect(fn).to.throw TypeError
it 'supports String', ->
form = new Form
1: String
2: String
3: String
4: String
5: String
6:
type: String
default: 'string default'
7: String
form.set
1: 'value'
2: 444
3: true
4: ['val',3]
5: null
expect(form.get '1').to.equal 'value'
expect(form.get '2').to.equal '444'
expect(form.get '3').to.equal 'true'
expect(form.get '4').to.equal 'val,3'
expect(form.get '5').to.be.null
expect(form.get '6').to.equal form.path('6').default()
form.set '1', null
expect(form.get '1').to.be.null
it 'supports Number', ->
form = new Form
1: Number
2: Number
3: Number
4: Number
5: Number
class Test
constructor: () ->
toString: () ->
return '1'
form.set
1: 1
2: 2.2
3: '-3'
4: []
5: new Test
expect(form.get '1').to.equal 1
expect(form.get '2').to.equal 2.2
expect(form.get '3').to.equal -3
it 'supports Date', ->
form = new Form
1: Date
2: Date
3: Date
now = new Date
form.set
1: now
2: now.getTime()
3: now.toString()
expect(form.get '1').to.equal now
# TODO make it works
#expect(form.get '2'.toString()).to.deep.equal now.toString()
#expect(form.get '3').to.equal now
form.set
1: 'not a date'
#expect(fn).to.throw require '../lib/errors/cast'
it 'supports Boolean', ->
form = new Form
1: Boolean
2: Boolean
3: Boolean
4: Boolean
5: Boolean
6: Boolean
7: Boolean
8: Boolean
form.set
1: true
2: 'false'
3: 1
4: 'adsf'
5: null
6: undefined
7: 0
8: '0'
expect(form.get '1').to.equal true
expect(form.get '2').to.equal false
expect(form.get '3').to.equal true
expect(form.get '4').to.equal true
expect(form.get '5').to.equal null
expect(form.get '6').to.be.null
expect(form.get '7').to.equal false
expect(form.get '8').to.equal false
describe 'options', ->
it 'supports options through constructor and form.option method', ->
form = new Form
test: String
,
autoTrim: true
expect(form.option 'autoTrim').to.be.true
form.option 'autoTrim', false
expect(form.option 'autoTrim').to.be.false
nbErrorsOpt = Object.keys(form.options.errors).length
form.option 'errors',
customType: 'Custom error msg added'
expect(Object.keys(form.options.errors).length).to.equal ++nbErrorsOpt
it 'supports option.autoTrim', ->
form = new Form
test:String
,
autoTrim: true
form.set
test: ' test '
expect(form.get 'test').to.equal 'test'
it 'supports option.autoLocals', (done) ->
form = new Form
test: String
,
autoLocals: false
request =
body:
test: 'no locals'
response =
locals: {}
cb = ->
expect(response.locals.form).to.be.undefined
done()
form.middleware() request, response, cb
it 'supports option.body', (done) ->
form = new Form
test: String
test2: String
test3: String
,
dataSources: ['query', 'params']
request =
body:
test: 'body'
query:
test2: 'query'
params:
test3: 'params'
response =
locals: {}
cb = ->
expect(request.form.get 'test').to.be.null
expect(request.form.get 'test2').to.equal 'query'
expect(request.form.get 'test3').to.equal 'params'
done()
form.middleware() request, response, cb
describe 'setters and getters', ->
it 'supports mongoose-like setters for string', ->
form = new Form
lower:
type: String
lowercase: true
upper:
type: String,
uppercase: true
trim: true
form.set
lower: 'UPPERcase'
upper: ' lowerCASE '
expect(form.get 'lower').to.equal 'uppercase'
expect(form.get 'upper').to.equal 'LOWERCASE'
it 'supports all kind of setters', ->
form = new Form
set:
type: Number
set: (val) ->
return val * -1
form.set
set: 23
expect(form.get 'set').to.equal -23
fn = ->
form.path('set').set
set: null
expect(fn).to.throw TypeError
it 'supports all kind of getters', ->
form = new Form
get:
type: String
get: (val) ->
return val.toUpperCase()
obj =
get: 'ToUpperCase'
form.set obj
expect(form.getValue 'get').to.be.equal obj.get
expect(form.get 'get').to.be.equal obj.get.toUpperCase()
fn = ->
form.path('get').get
get: null
expect(fn).to.throw TypeError
it 'supports form.getData', ->
form = new Form
a:
type: String
get: (val) ->
return this.get('b.c') + ' ' + val
b:
c:
type: Number
get: (val) ->
return val / 100
form.set
a: 'CHF'
b:
c: 99995
expect(form.getData()).to.deep.equal
a: '999.95 CHF'
b:
c: 999.95
it 'can have a 100% coverage', ->
form = new Form
a: String
b: Date
form.path('a').cast null
form.path('b').cast null
fn = ->
o = ->
o.toString = undefined
form.path('a').cast o
expect(fn).to.throw TypeError
| true | ### global describe, it, beforeEach ###
chai = require 'chai'
expect = chai.expect
Form = require '../lib/form'
FieldTypes = Form.FieldTypes
Field = require '../lib/field/field'
describe 'Form', ->
describe 'form constructor and field path and definition', ->
it 'supports dot notation for path accessors', ->
form = new Form
nested:
property: String
deep:
property: Date
'nested.string.property': String
expect(form.path 'nested.property').to.be.an.instanceof FieldTypes.String
expect(form.path 'nested.deep.property').to.be.an.instanceof FieldTypes.Date
expect(form.path 'nested.string.property').to.be.an.instanceof FieldTypes.String
expect(form.path 'nested.inexistant').to.be.undefined
it 'supports add and field methods', ->
form = new Form
test: String
form.field
test2: String
form.add
test3: Date
expect(form.path 'test').to.be.an.instanceof FieldTypes.String
expect(form.path 'test2').to.be.an.instanceof FieldTypes.String
expect(form.path 'test3').to.be.an.instanceof FieldTypes.Date
fn = ->
form.field
type: 'unknown'
expect(fn).to.throw(Error);
it 'supports virtuals!', ->
form = new Form
price: Number
cost: Number
name:
firstName: String
familyName:
type: String
uppercase: true
form.set
price: 2325
cost: 2100
form.virtual('margin').get ->
this.price - this.cost
form.virtual('fullname').set (val) ->
this.name =
firstName: val.split(' ')[0]
familyName: val.split(' ')[1]
form.set
'fullname': 'PI:NAME:<NAME>END_PI'
expect(form.get 'margin').to.equal 2325 - 2100
expect(form.get 'name.firstName').to.equal 'PI:NAME:<NAME>END_PI'
expect(form.get 'name.familyName').to.equal 'PI:NAME:<NAME>END_PIe'
describe 'fieldtypes and casting', ->
it 'supports different fieldtypes with casting', ->
form = new Form
string: String
date: Date
number: Number
bool: Boolean
obj =
string: 'string'
date: new Date
number: 234
bool: true
unknown:
sub: 'not set'
form.set obj
expect(form.get 'string').to.equal obj.string
expect(form.get 'date').to.equal obj.date
expect(form.get 'number').to.equal obj.number
expect(form.get 'bool').to.equal obj.bool
expect(form.get 'unknown.sub').to.be.undefined
fn = ->
form.field
err:
type: null
expect(fn).to.throw TypeError
it 'supports String', ->
form = new Form
1: String
2: String
3: String
4: String
5: String
6:
type: String
default: 'string default'
7: String
form.set
1: 'value'
2: 444
3: true
4: ['val',3]
5: null
expect(form.get '1').to.equal 'value'
expect(form.get '2').to.equal '444'
expect(form.get '3').to.equal 'true'
expect(form.get '4').to.equal 'val,3'
expect(form.get '5').to.be.null
expect(form.get '6').to.equal form.path('6').default()
form.set '1', null
expect(form.get '1').to.be.null
it 'supports Number', ->
form = new Form
1: Number
2: Number
3: Number
4: Number
5: Number
class Test
constructor: () ->
toString: () ->
return '1'
form.set
1: 1
2: 2.2
3: '-3'
4: []
5: new Test
expect(form.get '1').to.equal 1
expect(form.get '2').to.equal 2.2
expect(form.get '3').to.equal -3
it 'supports Date', ->
form = new Form
1: Date
2: Date
3: Date
now = new Date
form.set
1: now
2: now.getTime()
3: now.toString()
expect(form.get '1').to.equal now
# TODO make it works
#expect(form.get '2'.toString()).to.deep.equal now.toString()
#expect(form.get '3').to.equal now
form.set
1: 'not a date'
#expect(fn).to.throw require '../lib/errors/cast'
it 'supports Boolean', ->
form = new Form
1: Boolean
2: Boolean
3: Boolean
4: Boolean
5: Boolean
6: Boolean
7: Boolean
8: Boolean
form.set
1: true
2: 'false'
3: 1
4: 'adsf'
5: null
6: undefined
7: 0
8: '0'
expect(form.get '1').to.equal true
expect(form.get '2').to.equal false
expect(form.get '3').to.equal true
expect(form.get '4').to.equal true
expect(form.get '5').to.equal null
expect(form.get '6').to.be.null
expect(form.get '7').to.equal false
expect(form.get '8').to.equal false
describe 'options', ->
it 'supports options through constructor and form.option method', ->
form = new Form
test: String
,
autoTrim: true
expect(form.option 'autoTrim').to.be.true
form.option 'autoTrim', false
expect(form.option 'autoTrim').to.be.false
nbErrorsOpt = Object.keys(form.options.errors).length
form.option 'errors',
customType: 'Custom error msg added'
expect(Object.keys(form.options.errors).length).to.equal ++nbErrorsOpt
it 'supports option.autoTrim', ->
form = new Form
test:String
,
autoTrim: true
form.set
test: ' test '
expect(form.get 'test').to.equal 'test'
it 'supports option.autoLocals', (done) ->
form = new Form
test: String
,
autoLocals: false
request =
body:
test: 'no locals'
response =
locals: {}
cb = ->
expect(response.locals.form).to.be.undefined
done()
form.middleware() request, response, cb
it 'supports option.body', (done) ->
form = new Form
test: String
test2: String
test3: String
,
dataSources: ['query', 'params']
request =
body:
test: 'body'
query:
test2: 'query'
params:
test3: 'params'
response =
locals: {}
cb = ->
expect(request.form.get 'test').to.be.null
expect(request.form.get 'test2').to.equal 'query'
expect(request.form.get 'test3').to.equal 'params'
done()
form.middleware() request, response, cb
describe 'setters and getters', ->
it 'supports mongoose-like setters for string', ->
form = new Form
lower:
type: String
lowercase: true
upper:
type: String,
uppercase: true
trim: true
form.set
lower: 'UPPERcase'
upper: ' lowerCASE '
expect(form.get 'lower').to.equal 'uppercase'
expect(form.get 'upper').to.equal 'LOWERCASE'
it 'supports all kind of setters', ->
form = new Form
set:
type: Number
set: (val) ->
return val * -1
form.set
set: 23
expect(form.get 'set').to.equal -23
fn = ->
form.path('set').set
set: null
expect(fn).to.throw TypeError
it 'supports all kind of getters', ->
form = new Form
get:
type: String
get: (val) ->
return val.toUpperCase()
obj =
get: 'ToUpperCase'
form.set obj
expect(form.getValue 'get').to.be.equal obj.get
expect(form.get 'get').to.be.equal obj.get.toUpperCase()
fn = ->
form.path('get').get
get: null
expect(fn).to.throw TypeError
it 'supports form.getData', ->
form = new Form
a:
type: String
get: (val) ->
return this.get('b.c') + ' ' + val
b:
c:
type: Number
get: (val) ->
return val / 100
form.set
a: 'CHF'
b:
c: 99995
expect(form.getData()).to.deep.equal
a: '999.95 CHF'
b:
c: 999.95
it 'can have a 100% coverage', ->
form = new Form
a: String
b: Date
form.path('a').cast null
form.path('b').cast null
fn = ->
o = ->
o.toString = undefined
form.path('a').cast o
expect(fn).to.throw TypeError
|
[
{
"context": "\n e.g. curl -D /tmp/h.txt -H \"x-forwarded-user: user\" -H \"x-forwarded-email: user@abc.com\" http://node",
"end": 127,
"score": 0.9970291256904602,
"start": 123,
"tag": "USERNAME",
"value": "user"
},
{
"context": "-H \"x-forwarded-user: user\" -H \"x-forwarded-ema... | config/routes.coffee | twhtanghk/restfile | 0 | module.exports =
routes:
###
get details of current login user
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" http://node-1337.service.consul:1337/user/me
###
'GET /user/:id':
controller: 'UserController'
action: 'findOne'
###
get list of registered users
###
'GET /user':
controller: 'UserController'
action: 'find'
###
create file with filename, createdBy (derived by current login user)
and file content in multipart form
e.g. curl -D /tmp/h.txt -X POST -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" -H "Content-Type: multipart/form-data" -F "filename=/usr/src/app/package.json" -F "file=@/usr/src/app/package.json" http://node-1337.service.consul:1337/file
###
'POST /file':
controller: 'FileController'
action: 'create'
###
get file content of the specified "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" 'http://node-1337.service.consul:1337/file?filename=/usr/src/app/package.json&version=-2'
###
'GET /file/:id?':
controller: 'FileController'
action: 'content'
sort:
uploadDate: 'desc'
###
get property of all versions of the specified "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" http://node-1337.service.consul:1337/file/version?filename=/usr/src/app/package.json
###
'GET /file/version':
controller: 'FileController'
action: 'version'
sort:
uploadDate: 'desc'
###
get property of the specified version (default -1) of the
specified "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" 'http://node-1337.service.consul:1337/file/property?filename=/usr/src/app/package.json&version=-2'
###
'GET /file/property':
controller: 'FileController'
action: 'findOne'
sort:
uploadDate: 'desc'
###
update file content with filename, createdBy (derived by current login user)
defined in multipart form
e.g. curl -D /tmp/h.txt -X PUT -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" -H "Content-Type: multipart/form-data" -F "filename=/usr/src/app/package.json" -F "file=@/usr/src/app/package.json" http://node-1337.service.consul:1337/file
###
'PUT /file':
controller: 'FileController'
action: 'update'
###
rm file with filename, createdBy (derived by current login user)
or only the specified versions
e.g.
curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" 'http://node-1337.service.consul:1337/file?filename=/usr/src/app/package.json'
curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" -H "Content-Type: application/json" -d '{"version": [-2, -4]}' 'http://node-1337.service.consul:1337/file/:id'
###
'DELETE /file/:id':
controller: 'FileController'
action: 'destroy'
###
add file permission
e.g.
curl -D /tmp/h.txt -X POST -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" -d '{"user": ".*", "file": "/usr/src/app/package.json", mode: 7}' 'http://node-1337.service.consul:1337/permission?filename=/usr/src/app/package.json'
###
'POST /permission':
controller: 'PermissionController'
action: 'create'
###
delete file permission
e.g.
curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" 'http://node-1337.service.consul:1337/permission/:id'
###
'DELETE /permissioin/:id':
controller: 'PermissionController'
action: 'destroy'
###
create dir for "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" -H "Content-Type: application/json" -d '{"filename": "/usr/src/New Folder"}' http://node-1337.service.consul:1337/dir
###
'POST /dir':
controller: 'DirController'
action: 'create'
###
get dir details for "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" -H "Content-Type: application/json" -d '{"filename": "/usr/src/New Folder"}' http://node-1337.service.consul:1337/dir/:id
###
'GET /dir/:id?':
controller: 'DirController'
action: 'findOne'
###
put dir details for "filename" parameter
e.g. curl -D /tmp/h.txt -X PUT -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" -H "Content-Type: application/json" -d '{"filename": "Folder"}' http://node-1337.service.consul:1337/dir/:id
###
'PUT /dir/:id':
controller: 'FileController'
action: 'update'
###
delete dir for "filename" parameter
e.g. curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: user@abc.com" -H "Content-Type: application/json" -d '{"filename": "/usr/src/New Folder"}' http://node-1337.service.consul:1337/dir
###
'DELETE /dir/:id':
controller: 'DirController'
action: 'destroy'
| 148130 | module.exports =
routes:
###
get details of current login user
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" http://node-1337.service.consul:1337/user/me
###
'GET /user/:id':
controller: 'UserController'
action: 'findOne'
###
get list of registered users
###
'GET /user':
controller: 'UserController'
action: 'find'
###
create file with filename, createdBy (derived by current login user)
and file content in multipart form
e.g. curl -D /tmp/h.txt -X POST -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" -H "Content-Type: multipart/form-data" -F "filename=/usr/src/app/package.json" -F "file=@/usr/src/app/package.json" http://node-1337.service.consul:1337/file
###
'POST /file':
controller: 'FileController'
action: 'create'
###
get file content of the specified "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" 'http://node-1337.service.consul:1337/file?filename=/usr/src/app/package.json&version=-2'
###
'GET /file/:id?':
controller: 'FileController'
action: 'content'
sort:
uploadDate: 'desc'
###
get property of all versions of the specified "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" http://node-1337.service.consul:1337/file/version?filename=/usr/src/app/package.json
###
'GET /file/version':
controller: 'FileController'
action: 'version'
sort:
uploadDate: 'desc'
###
get property of the specified version (default -1) of the
specified "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" 'http://node-1337.service.consul:1337/file/property?filename=/usr/src/app/package.json&version=-2'
###
'GET /file/property':
controller: 'FileController'
action: 'findOne'
sort:
uploadDate: 'desc'
###
update file content with filename, createdBy (derived by current login user)
defined in multipart form
e.g. curl -D /tmp/h.txt -X PUT -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" -H "Content-Type: multipart/form-data" -F "filename=/usr/src/app/package.json" -F "file=@/usr/src/app/package.json" http://node-1337.service.consul:1337/file
###
'PUT /file':
controller: 'FileController'
action: 'update'
###
rm file with filename, createdBy (derived by current login user)
or only the specified versions
e.g.
curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" 'http://node-1337.service.consul:1337/file?filename=/usr/src/app/package.json'
curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" -H "Content-Type: application/json" -d '{"version": [-2, -4]}' 'http://node-1337.service.consul:1337/file/:id'
###
'DELETE /file/:id':
controller: 'FileController'
action: 'destroy'
###
add file permission
e.g.
curl -D /tmp/h.txt -X POST -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" -d '{"user": ".*", "file": "/usr/src/app/package.json", mode: 7}' 'http://node-1337.service.consul:1337/permission?filename=/usr/src/app/package.json'
###
'POST /permission':
controller: 'PermissionController'
action: 'create'
###
delete file permission
e.g.
curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" 'http://node-1337.service.consul:1337/permission/:id'
###
'DELETE /permissioin/:id':
controller: 'PermissionController'
action: 'destroy'
###
create dir for "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" -H "Content-Type: application/json" -d '{"filename": "/usr/src/New Folder"}' http://node-1337.service.consul:1337/dir
###
'POST /dir':
controller: 'DirController'
action: 'create'
###
get dir details for "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" -H "Content-Type: application/json" -d '{"filename": "/usr/src/New Folder"}' http://node-1337.service.consul:1337/dir/:id
###
'GET /dir/:id?':
controller: 'DirController'
action: 'findOne'
###
put dir details for "filename" parameter
e.g. curl -D /tmp/h.txt -X PUT -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" -H "Content-Type: application/json" -d '{"filename": "Folder"}' http://node-1337.service.consul:1337/dir/:id
###
'PUT /dir/:id':
controller: 'FileController'
action: 'update'
###
delete dir for "filename" parameter
e.g. curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: <EMAIL>" -H "Content-Type: application/json" -d '{"filename": "/usr/src/New Folder"}' http://node-1337.service.consul:1337/dir
###
'DELETE /dir/:id':
controller: 'DirController'
action: 'destroy'
| true | module.exports =
routes:
###
get details of current login user
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" http://node-1337.service.consul:1337/user/me
###
'GET /user/:id':
controller: 'UserController'
action: 'findOne'
###
get list of registered users
###
'GET /user':
controller: 'UserController'
action: 'find'
###
create file with filename, createdBy (derived by current login user)
and file content in multipart form
e.g. curl -D /tmp/h.txt -X POST -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" -H "Content-Type: multipart/form-data" -F "filename=/usr/src/app/package.json" -F "file=@/usr/src/app/package.json" http://node-1337.service.consul:1337/file
###
'POST /file':
controller: 'FileController'
action: 'create'
###
get file content of the specified "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" 'http://node-1337.service.consul:1337/file?filename=/usr/src/app/package.json&version=-2'
###
'GET /file/:id?':
controller: 'FileController'
action: 'content'
sort:
uploadDate: 'desc'
###
get property of all versions of the specified "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" http://node-1337.service.consul:1337/file/version?filename=/usr/src/app/package.json
###
'GET /file/version':
controller: 'FileController'
action: 'version'
sort:
uploadDate: 'desc'
###
get property of the specified version (default -1) of the
specified "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" 'http://node-1337.service.consul:1337/file/property?filename=/usr/src/app/package.json&version=-2'
###
'GET /file/property':
controller: 'FileController'
action: 'findOne'
sort:
uploadDate: 'desc'
###
update file content with filename, createdBy (derived by current login user)
defined in multipart form
e.g. curl -D /tmp/h.txt -X PUT -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" -H "Content-Type: multipart/form-data" -F "filename=/usr/src/app/package.json" -F "file=@/usr/src/app/package.json" http://node-1337.service.consul:1337/file
###
'PUT /file':
controller: 'FileController'
action: 'update'
###
rm file with filename, createdBy (derived by current login user)
or only the specified versions
e.g.
curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" 'http://node-1337.service.consul:1337/file?filename=/usr/src/app/package.json'
curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" -H "Content-Type: application/json" -d '{"version": [-2, -4]}' 'http://node-1337.service.consul:1337/file/:id'
###
'DELETE /file/:id':
controller: 'FileController'
action: 'destroy'
###
add file permission
e.g.
curl -D /tmp/h.txt -X POST -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" -d '{"user": ".*", "file": "/usr/src/app/package.json", mode: 7}' 'http://node-1337.service.consul:1337/permission?filename=/usr/src/app/package.json'
###
'POST /permission':
controller: 'PermissionController'
action: 'create'
###
delete file permission
e.g.
curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" 'http://node-1337.service.consul:1337/permission/:id'
###
'DELETE /permissioin/:id':
controller: 'PermissionController'
action: 'destroy'
###
create dir for "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" -H "Content-Type: application/json" -d '{"filename": "/usr/src/New Folder"}' http://node-1337.service.consul:1337/dir
###
'POST /dir':
controller: 'DirController'
action: 'create'
###
get dir details for "filename" parameter
e.g. curl -D /tmp/h.txt -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" -H "Content-Type: application/json" -d '{"filename": "/usr/src/New Folder"}' http://node-1337.service.consul:1337/dir/:id
###
'GET /dir/:id?':
controller: 'DirController'
action: 'findOne'
###
put dir details for "filename" parameter
e.g. curl -D /tmp/h.txt -X PUT -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" -H "Content-Type: application/json" -d '{"filename": "Folder"}' http://node-1337.service.consul:1337/dir/:id
###
'PUT /dir/:id':
controller: 'FileController'
action: 'update'
###
delete dir for "filename" parameter
e.g. curl -D /tmp/h.txt -X DELETE -H "x-forwarded-user: user" -H "x-forwarded-email: PI:EMAIL:<EMAIL>END_PI" -H "Content-Type: application/json" -d '{"filename": "/usr/src/New Folder"}' http://node-1337.service.consul:1337/dir
###
'DELETE /dir/:id':
controller: 'DirController'
action: 'destroy'
|
[
{
"context": ", ->\n user = new User\n id: 1\n name: \"Someone\" \n \n # The model store shouldn't know about",
"end": 472,
"score": 0.9989557266235352,
"start": 465,
"tag": "NAME",
"value": "Someone"
},
{
"context": ", ->\n user = new User\n id: 1\n n... | test/spec_coffee/model_save_spec.coffee | kirkbowers/mvcoffee | 0 | MVCoffee = require("../lib/mvcoffee")
theUser = class User extends MVCoffee.Model
theUser.hasMany "activity"
theUser.validates "name", test: "presence"
theActivity = class Activity extends MVCoffee.Model
theActivity.belongsTo "user"
describe "using the model save method", ->
beforeEach ->
store = new MVCoffee.ModelStore
user: User
activity: Activity
it "should save a valid model", ->
user = new User
id: 1
name: "Someone"
# The model store shouldn't know about this unsaved model yet
expect(User.all().length).toEqual(0)
result = user.save()
expect(result).toBeTruthy()
expect(result).toEqual(user)
users = User.all()
expect(users.length).toEqual(1)
expect(users[0].name).toEqual("Someone")
it "should not save an invalid model", ->
user = new User
id: 1
result = user.save()
expect(result).toBeFalsy()
users = User.all()
expect(users.length).toEqual(0)
it "should always store an invalid model anyway", ->
user = new User
id: 1
result = user.store()
expect(result).toEqual(user)
users = User.all()
expect(users.length).toEqual(1)
expect(users[0].id).toEqual(1)
it "should save a valid model and find an association", ->
user = new User
id: 1
name: "Someone"
activity = new Activity
id: 1
user_id: 1
name: "Do something"
user.save()
activity.save()
user = User.find(1)
expect(user.name).toEqual("Someone")
expect(user.activities().length).toEqual(1)
expect(user.activities()[0].name).toEqual("Do something")
activity = Activity.find(1)
expect(activity.name).toEqual("Do something")
expect(activity.user().name).toEqual("Someone")
| 166922 | MVCoffee = require("../lib/mvcoffee")
theUser = class User extends MVCoffee.Model
theUser.hasMany "activity"
theUser.validates "name", test: "presence"
theActivity = class Activity extends MVCoffee.Model
theActivity.belongsTo "user"
describe "using the model save method", ->
beforeEach ->
store = new MVCoffee.ModelStore
user: User
activity: Activity
it "should save a valid model", ->
user = new User
id: 1
name: "<NAME>"
# The model store shouldn't know about this unsaved model yet
expect(User.all().length).toEqual(0)
result = user.save()
expect(result).toBeTruthy()
expect(result).toEqual(user)
users = User.all()
expect(users.length).toEqual(1)
expect(users[0].name).toEqual("Someone")
it "should not save an invalid model", ->
user = new User
id: 1
result = user.save()
expect(result).toBeFalsy()
users = User.all()
expect(users.length).toEqual(0)
it "should always store an invalid model anyway", ->
user = new User
id: 1
result = user.store()
expect(result).toEqual(user)
users = User.all()
expect(users.length).toEqual(1)
expect(users[0].id).toEqual(1)
it "should save a valid model and find an association", ->
user = new User
id: 1
name: "<NAME>"
activity = new Activity
id: 1
user_id: 1
name: "Do something"
user.save()
activity.save()
user = User.find(1)
expect(user.name).toEqual("<NAME>")
expect(user.activities().length).toEqual(1)
expect(user.activities()[0].name).toEqual("Do something")
activity = Activity.find(1)
expect(activity.name).toEqual("Do something")
expect(activity.user().name).toEqual("<NAME>")
| true | MVCoffee = require("../lib/mvcoffee")
theUser = class User extends MVCoffee.Model
theUser.hasMany "activity"
theUser.validates "name", test: "presence"
theActivity = class Activity extends MVCoffee.Model
theActivity.belongsTo "user"
describe "using the model save method", ->
beforeEach ->
store = new MVCoffee.ModelStore
user: User
activity: Activity
it "should save a valid model", ->
user = new User
id: 1
name: "PI:NAME:<NAME>END_PI"
# The model store shouldn't know about this unsaved model yet
expect(User.all().length).toEqual(0)
result = user.save()
expect(result).toBeTruthy()
expect(result).toEqual(user)
users = User.all()
expect(users.length).toEqual(1)
expect(users[0].name).toEqual("Someone")
it "should not save an invalid model", ->
user = new User
id: 1
result = user.save()
expect(result).toBeFalsy()
users = User.all()
expect(users.length).toEqual(0)
it "should always store an invalid model anyway", ->
user = new User
id: 1
result = user.store()
expect(result).toEqual(user)
users = User.all()
expect(users.length).toEqual(1)
expect(users[0].id).toEqual(1)
it "should save a valid model and find an association", ->
user = new User
id: 1
name: "PI:NAME:<NAME>END_PI"
activity = new Activity
id: 1
user_id: 1
name: "Do something"
user.save()
activity.save()
user = User.find(1)
expect(user.name).toEqual("PI:NAME:<NAME>END_PI")
expect(user.activities().length).toEqual(1)
expect(user.activities()[0].name).toEqual("Do something")
activity = Activity.find(1)
expect(activity.name).toEqual("Do something")
expect(activity.user().name).toEqual("PI:NAME:<NAME>END_PI")
|
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998427033424377,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai... | library/membrane/duplex.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
assert = require "assert"
colors = require "colors"
nconf = require "nconf"
https = require "https"
http = require "http"
weak = require "weak"
util = require "util"
plumbs = require "../nucleus/plumbs"
extendz = require "../nucleus/extends"
compose = require "../nucleus/compose"
{format} = require "util"
{STATUS_CODES} = require "http"
{EventEmitter2} = require "eventemitter2"
{urlOfMaster} = require "../nucleus/toolkit"
{remote, external} = require "./remote"
{Barebones} = require "./skeleton"
{Preflight} = require "./preflight"
# This abstract base class can be used as either a direct parent or
# a compound to the `Screenplay` abstract service. It provides the
# unique ability of half duplex communications between the external
# code that is executed on the call site via `Screenplay` facility
# and an instance of the service that resides on the server site.
# The component itself is built heavily on top of a code emission
# and delivery platform, as implemented by `Screenplay` service.
module.exports.DuplexCore = class DuplexCore extends Preflight
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# A usable hook that gets asynchronously invoked once the user
# is leaving the application page, and the `unload` is emitted.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
leaving: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a new
# channel (socket) gets connected and acknowledged by a server.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
connected: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a socket
# gets disconnected after it has passes through the connection.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
disengage: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a new
# socket connection is going to be setup during the handshake.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
handshaken: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a new
# channel (socket) gets past authorization phase and is rated
# to be good to go through the screening process. This is good
# place to implementation various schemes for authorization. If
# you wish to decline, just don't call `next` and close socket.
screening: (context, socket, binder, next) -> next()
# A usable hook that gets asynchronously invoked once a sentence
# comes through an opened channel. This happens every time when
# a client tries to invoke a server site provider method. This
# is a good place to validate if an invocation is legitimate or
# not. If you do not invoke `next` then the call won't happen!
sentence: (socket, name, provider, args, next) -> next()
# An internal method that is wired into the Socket.IO context to
# take care of the very first socket authorization. This happens
# during the handshake phase. This method checks that handshake
# contains correct session requsities and restores the session!
# The session can normally be used as you would use req session.
authorization: (context) => (socket, accept) ->
assert message = "Authorizing %s at %s"
assert _.isObject handshake = socket.request
assert _.isFunction session = @kernel.session
assert _.isFunction cookies = @kernel.cookieParser
assert idc = try @constructor.identify().underline
assert handshake.originalUrl = handshake.url or "/"
assert _.isString id = try socket.id.toString().bold
assert Response = class RDummy extends EventEmitter2
Response::setHeader = (name, value) -> undefined
Response::end = (data, encoding) -> undefined
cookies handshake, response = new Response, =>
session handshake, response, (parameter) =>
logger.debug message.yellow, id, idc
session = handshake.session or null
ns = new Error "no session detected"
return accept ns, no unless session
handshaken = @downstream handshaken: ->
return accept undefined, true
return handshaken context, socket
# An internal, static method that is used to obtain gurading
# domains for each of the declared server site providers. Please
# refer to the Node.js documentation for more information on
# the domains and error handling itself. This method is generally
# used only once per the domain declaration. See `provider`.
@guarded: (method, socket, explain) ->
killOnError = "duplex:disconnectOnError"
assert _.isFunction o = -> _.head arguments
assert _.isFunction i = -> _.head arguments
assert guarded = require("domain").create()
assert identify = try @identify().underline
comparing = (value, opts) -> value is method
where = => _.findKey this.prototype, comparing
_.extend guarded, body: method, socket: socket
location = "Got interrupted around %s#%s".red
m = "Exception within the duplex core:\r\n%s"
m = "#{explain}:\r\n%s" if _.isString explain
fx = (blob) => blob.call this; return guarded
fx -> guarded.on "error", (error, optional) ->
format = try where().toString().underline
logger.error location, identify, format
do -> logger.error m.red, error.stack
str = error.toString() # got no message
packed = stack: error.stack.toString()
packed.message = error.message or str
try socket.emit "exception", packed
return unless nconf.get killOnError
try socket.disconnect?() catch err
# A utility method to mark the certain function as the provider.
# The method returns the original function back so it can be used
# as the normal function, nothing disrupts that. When function is
# marked as a provider, it will be exposed via Socket.IO channel
# that this compound sets up: a half duplex web sockets channel.
@provider: (parameters, method) ->
supplied = _.isPlainObject parameters
malformed = "got an invalid provider"
assert bound = this.covering.bind this
method = _.find arguments, _.isFunction
assert identify = @identify().underline
assert _.isFunction(method), malformed
applicator = try _.partial bound, method
message = "Add new provider at %s service"
parameters = undefined unless supplied
logger.silly message.yellow, identify
method.provider = parameters or {}
method.isolation = -> return this
method.providing = applicator
method.origin = this; method
# This is a modification of the `provider` method that slightly
# changes the scoping/bind for the provider body implementation.
# Upon the provider invocation, this variation creates a shadow
# object derives from the services, therefore isolating calling
# scope to this object that has all the socket and session set.
@isolated: (parameters, method) ->
assert _.isObject constructor = this or 0
assert m = @provider.apply this, arguments
isolation = (fn) -> m.isolation = fn; return m
assert surrogate = "uis_%s_" # prefix template
return isolation (socket, binder, session) ->
return pci if _.isObject pci = socket.shadow
assert identify = try @constructor.identify()
assert prefix = _.sprintf surrogate, identify
assert this isnt constructor, "scoping error"
assert _.isObject shadow = Object.create this
assert isolating = "Isolated provider call in %s"
logger.debug isolating.yellow, sid = socket.id.bold
_.extend shadow, __uis: uis = _.uniqueId(prefix)
_.extend shadow, __isolated: yes, __origin: this
_.extend shadow, session: session, binder: binder
_.extend shadow, socket: weak(socket) or socket
_.extend shadow, request: try socket.handshake
logger.debug "Set PCI %s of %s", uis.bold, sid
assert shadow.socket; socket.shadow = shadow
# An important method that pertains to the details of internal
# duplex implementation. This method is used to produce a wrapper
# around the provider invocation procedure. This wrapping is of
# protective nature. It also exposes some goodies for the provider.
# Such as Socket.IO handle, session if available and the context.
@covering: (method, socket, context, binder) ->
assert _.isFunction o = -> try _.head arguments
assert _.isFunction i = -> try _.head arguments
assert _.isFunction(method), "missing an method"
socket.on "disconnect", -> try guarded.dispose()
session = try socket.request.session unless session
socket.disconnect "no session found" unless session
e = "Exception happend when executing server provider"
assert _.isObject guarded = @guarded method, socket, e
assert _.isFunction g = guarded.run.bind guarded
s = (f) => session.save -> f.apply this, arguments
assert binder; return (parameters..., callback) ->
pci = method.isolation.call @, socket, binder, session
respond = (a...) => s => g => callback.apply pci, o(a)
execute = (a...) => s => g => method.apply pci, i(a)
assert respond.session = socket.session = session
assert respond.binder = socket.binder = binder
assert respond.socket = socket.socket = socket
return execute parameters..., respond, session
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an synchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
encrypted = request.connection.encrypted
pure = /[a-zA-Z0-9\/-_]+/.test @location()
assert pure, "location is not pure enough"
proto = request.headers["x-forwarded-proto"]
enc = encrypted or proto is "https" and yes
context.scripts.push "/socket.io/socket.io.js"
context.duplex = urlOfMaster enc, @location()
context.nsp = symbol unless context.nsp or 0
identify = @constructor.identify().underline
message = "Injecting Socket.IO into %s context"
logger.debug message.yellow, identify or null
assert _.isArray context.providers ?= Array()
_.forIn this, (value, name, service) =>
providing = value?.providing or null
return unless _.isFunction providing
context.providers.push name
return next undefined
# An internal provider that gets automatically invoked once client
# establishes the protected Socket.IO transport back to the service
# instance at the server site. This implementation uses a composite
# `downstream` mechanism to invoke the `connected` method at every
# peers of the inheritance hierarchy. Refer to the method for info.
trampoline: @isolated (context, callback) ->
isocket = "Executed %s socket trampoline"
message = "Inbound duplex connection at %s"
request = "Acknowledged socket from %s request"
assert try @socket.socket is callback.socket
assert discon = "Disengaging %s of %s".yellow
assert sleave = "Socket %s leaving %s".yellow
assert identify = try @constructor.identify()
assert identity = try callback.socket.id.bold
logger.debug message.magenta, identify.underline
logger.debug request.grey, context.url.underline
logger.debug isocket.green, identity.toString()
fn = (event, msg, method) => @socket.on event, =>
logger.debug msg, identity, identify.underline
assert prepared = {}; prepared[method] = ->
assert streaming = try @downstream prepared
return streaming context, callback.socket
fn "disconnect", discon.toString(), "disengage"
fn "unload", (try sleave.toString()), "leaving"
connected = @downstream connected: callback
connected context, callback.socket; this
# This is an external method that will be automatically executed
# on the client site by the duplex implementation. It sets up a
# client end of the Socket.IO channel and creates wrapper around
# all the providers residing in the current service implementation.
# Refer to other `DuplexCore` methods for understanding what goes on.
bootloader: @autocall z: +101, ->
options = new Object reconnect: yes, url: @duplex
_.extend options, reconnectionDelay: 3000 # millis
_.extend options, "max reconnection attempts": 99999
_.extend options, transports: ["websocket"] # no XHR
try @socket = io.connect @duplex, options catch error
message = "blew up Socket.IO: #{error.message}"
error.message = message.toString(); throw error
@emit "socketing", this.socket, this.duplex, options
failed = "failed to establish the Socket.IO connection"
assert this.socket.emit, failed; this.socketFeedback()
$(window).unload => @emit "unload"; @socket.emit "unload"
@socket.on "orphan", -> @io.disconnect(); @io.connect()
osc = (listener) => this.socket.on "connect", listener
osc => @socket.emit "screening", _.pick(@, @snapshot), =>
this.bootloading = yes # mark the bootloading process
assert @consumeProviders; @consumeProviders @socket
assert o = "Successfully bootloaded at %s".green
@once "booted", -> @broadcast "attached", this
@trampoline _.pick(@, @snapshot), (params) =>
logger.info o, @location.underline.green
assert @booted = yes; @initialized = yes
delete this.bootloading # kinda finished
return this.emit "booted", this.socket
# An externally exposed method that is a part of the bootloader
# implementation. It sets up the communication feedback mechanism
# of a Socket.IO handle. Basically installs a bunch of handlers
# that intercept specific events and log the output to a console.
# Can be overriden to provide more meaningful feedback handlers.
socketFeedback: external ->
assert ulocation = @location.green.underline
r = "an error raised during socket connection: %s"
p = "an exception happend at the server provider: %s"
connected = c = "Established connection at %s".green
disconnect = "lost socket connection at #{@location}"
@on "disconnect", -> @booted = false # connection lost
@seemsBroke = -> @outOfOrder() and not @bootloading
@outOfOrder = -> return @initialized and not @booted
@setInOrder = -> return try @initialized and @booted
breaker = try this.STOP_ROOT_PROPAGATION or undefined
r = (e, s) => this.emit(e, s...); @broadcast(e, s...)
forward = (evt) => @socket.on evt, => r evt, arguments
forward "disconnect" # lost socket connection to server
forward "connect" # a successfull connection happended
forward "exception" # server side indicates exception
@socket.on "exception", (e) -> logger.error p, e.message
@socket.on "error", (e) -> logger.error r, e.message
@socket.on "disconnect", -> logger.error disconnect
@socket.on "connect", -> logger.info c, ulocation
# An external routine that will be invoked once a both way duplex
# channel is established at the client site. This will normally
# unroll and set up all the providers that were deployed by the
# server site in the transferred context. Refer to the server
# method called `publishProviders` for more information on it.
consumeProviders: external (socket) ->
assert _.isFunction o = -> try _.head arguments
assert _.isFunction i = -> try _.head arguments
assert srv = try this.service.toString() or null
noConnection = "service #{srv} has lost connection"
for provider in @providers then do (provider) =>
message = "Provider %s at %s using nsp=%s"
assert _.isString uloc = @location.underline
assert _.isString unsp = @nsp.toString().bold
logger.info message, provider.bold, uloc, unsp
this.emit "install-provider", provider, socket
this[provider] = (parameters..., callback) ->
assert not this.seemsBroke(), noConnection
callback = (->) unless _.isFunction callback
noCallback = "#{callback} is not a callback"
assert _.isFunction(callback), noCallback
assert mangled = "#{@location}/#{provider}"
mangled += "/#{nsp}" if _.isString nsp = @nsp
deliver = => callback.apply this, i(arguments)
socket.emit mangled, o(parameters)..., deliver
# After a both ways duplex channel has been established between
# the client site and the server side, this method will be invoked
# in order to attach all of the providers founds in this service
# to the opened channel. Refer to the `register` implementation
# for more information on when, where and how this is happening.
publishProviders: (context, binder, socket, next) ->
assert ms = "Provide %s to %s in %s".magenta
assert id = @constructor.identify().underline
exec = (arbitrary) -> return next undefined
exec _.forIn this, (value, name, service) =>
internal = "the #{value} is not function"
providing = value?.providing or undefined
return unless _.isFunction providing or 0
assert _.isFunction(value or 0), internal
bound = providing socket, context, binder
assert mangled = "#{@location()}/#{name}"
mangled += "/#{nsp}" if nsp = binder.nsp
assert _.isString si = try socket.id.bold
assert _.isString pn = name.toString().bold
logger.debug ms.magenta, pn, si.bold, id
socket.on mangled, (args..., callback) =>
sentence = @downstream sentence: =>
bound.call this, args..., callback
sentence socket, name, value, args
# A hook that will be called prior to unregistering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
unregister: (kernel, router, next) ->
pure = /[a-zA-Z0-9\/-_]+/.test @location()
resolve = (handler) => try handler.of @location()
assert pure, "service location is not pure enough"
assert sserver = kernel.serverSocket, "no HTTP socket"
assert ssecure = kernel.secureSocket, "no HTTPS socket"
assert f = "Disconnecting %s socket handle".toString()
l = (socket) -> try logger.warn f.blue, socket.id.bold
p = (c) -> l(c); c.emit "shutdown"; try c.disconnect()
assert contexts = _.map [sserver, ssecure], resolve
_.each contexts, (context, vector, addition) =>
try context.removeAllListeners "connection"
intern = "missing a client listing registry"
assert _.isObject(context.connected), intern
assert clients = _.values context.connected
assert clients = _.filter clients, "connected"
assert clients = _.unique clients # go once
do -> p client for client, index in clients
return next undefined
# A hook that will be called prior to registering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
register: (kernel, router, next) ->
pure = /[a-zA-Z0-9\/-_]+/.test @location()
resolve = (handler) => try handler.of @location()
assert pure, "service location is not pure enough"
assert sserver = kernel.serverSocket, "no HTTP socket"
assert ssecure = kernel.secureSocket, "no HTTPS socket"
assert contexts = _.map [sserver, ssecure], resolve
assert makeScreener = (context) => (socket) =>
owners = socket.owned ?= new Array()
owners.push this unless this in owners
socket.on "screening", (binder, ack) =>
screening = @downstream screening: =>
bonding = [context, binder, socket, ack]
@publishProviders.apply this, bonding
screening context, socket, binder
_.each contexts, (context, position, vector) =>
assert screener = makeScreener context
assert applied = @authorization context
context.use applied.bind this # middleware
return context.on "connection", screener
return next undefined
| 10057 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
assert = require "assert"
colors = require "colors"
nconf = require "nconf"
https = require "https"
http = require "http"
weak = require "weak"
util = require "util"
plumbs = require "../nucleus/plumbs"
extendz = require "../nucleus/extends"
compose = require "../nucleus/compose"
{format} = require "util"
{STATUS_CODES} = require "http"
{EventEmitter2} = require "eventemitter2"
{urlOfMaster} = require "../nucleus/toolkit"
{remote, external} = require "./remote"
{Barebones} = require "./skeleton"
{Preflight} = require "./preflight"
# This abstract base class can be used as either a direct parent or
# a compound to the `Screenplay` abstract service. It provides the
# unique ability of half duplex communications between the external
# code that is executed on the call site via `Screenplay` facility
# and an instance of the service that resides on the server site.
# The component itself is built heavily on top of a code emission
# and delivery platform, as implemented by `Screenplay` service.
module.exports.DuplexCore = class DuplexCore extends Preflight
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# A usable hook that gets asynchronously invoked once the user
# is leaving the application page, and the `unload` is emitted.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
leaving: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a new
# channel (socket) gets connected and acknowledged by a server.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
connected: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a socket
# gets disconnected after it has passes through the connection.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
disengage: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a new
# socket connection is going to be setup during the handshake.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
handshaken: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a new
# channel (socket) gets past authorization phase and is rated
# to be good to go through the screening process. This is good
# place to implementation various schemes for authorization. If
# you wish to decline, just don't call `next` and close socket.
screening: (context, socket, binder, next) -> next()
# A usable hook that gets asynchronously invoked once a sentence
# comes through an opened channel. This happens every time when
# a client tries to invoke a server site provider method. This
# is a good place to validate if an invocation is legitimate or
# not. If you do not invoke `next` then the call won't happen!
sentence: (socket, name, provider, args, next) -> next()
# An internal method that is wired into the Socket.IO context to
# take care of the very first socket authorization. This happens
# during the handshake phase. This method checks that handshake
# contains correct session requsities and restores the session!
# The session can normally be used as you would use req session.
authorization: (context) => (socket, accept) ->
assert message = "Authorizing %s at %s"
assert _.isObject handshake = socket.request
assert _.isFunction session = @kernel.session
assert _.isFunction cookies = @kernel.cookieParser
assert idc = try @constructor.identify().underline
assert handshake.originalUrl = handshake.url or "/"
assert _.isString id = try socket.id.toString().bold
assert Response = class RDummy extends EventEmitter2
Response::setHeader = (name, value) -> undefined
Response::end = (data, encoding) -> undefined
cookies handshake, response = new Response, =>
session handshake, response, (parameter) =>
logger.debug message.yellow, id, idc
session = handshake.session or null
ns = new Error "no session detected"
return accept ns, no unless session
handshaken = @downstream handshaken: ->
return accept undefined, true
return handshaken context, socket
# An internal, static method that is used to obtain gurading
# domains for each of the declared server site providers. Please
# refer to the Node.js documentation for more information on
# the domains and error handling itself. This method is generally
# used only once per the domain declaration. See `provider`.
@guarded: (method, socket, explain) ->
killOnError = "duplex:disconnectOnError"
assert _.isFunction o = -> _.head arguments
assert _.isFunction i = -> _.head arguments
assert guarded = require("domain").create()
assert identify = try @identify().underline
comparing = (value, opts) -> value is method
where = => _.findKey this.prototype, comparing
_.extend guarded, body: method, socket: socket
location = "Got interrupted around %s#%s".red
m = "Exception within the duplex core:\r\n%s"
m = "#{explain}:\r\n%s" if _.isString explain
fx = (blob) => blob.call this; return guarded
fx -> guarded.on "error", (error, optional) ->
format = try where().toString().underline
logger.error location, identify, format
do -> logger.error m.red, error.stack
str = error.toString() # got no message
packed = stack: error.stack.toString()
packed.message = error.message or str
try socket.emit "exception", packed
return unless nconf.get killOnError
try socket.disconnect?() catch err
# A utility method to mark the certain function as the provider.
# The method returns the original function back so it can be used
# as the normal function, nothing disrupts that. When function is
# marked as a provider, it will be exposed via Socket.IO channel
# that this compound sets up: a half duplex web sockets channel.
@provider: (parameters, method) ->
supplied = _.isPlainObject parameters
malformed = "got an invalid provider"
assert bound = this.covering.bind this
method = _.find arguments, _.isFunction
assert identify = @identify().underline
assert _.isFunction(method), malformed
applicator = try _.partial bound, method
message = "Add new provider at %s service"
parameters = undefined unless supplied
logger.silly message.yellow, identify
method.provider = parameters or {}
method.isolation = -> return this
method.providing = applicator
method.origin = this; method
# This is a modification of the `provider` method that slightly
# changes the scoping/bind for the provider body implementation.
# Upon the provider invocation, this variation creates a shadow
# object derives from the services, therefore isolating calling
# scope to this object that has all the socket and session set.
@isolated: (parameters, method) ->
assert _.isObject constructor = this or 0
assert m = @provider.apply this, arguments
isolation = (fn) -> m.isolation = fn; return m
assert surrogate = "uis_%s_" # prefix template
return isolation (socket, binder, session) ->
return pci if _.isObject pci = socket.shadow
assert identify = try @constructor.identify()
assert prefix = _.sprintf surrogate, identify
assert this isnt constructor, "scoping error"
assert _.isObject shadow = Object.create this
assert isolating = "Isolated provider call in %s"
logger.debug isolating.yellow, sid = socket.id.bold
_.extend shadow, __uis: uis = _.uniqueId(prefix)
_.extend shadow, __isolated: yes, __origin: this
_.extend shadow, session: session, binder: binder
_.extend shadow, socket: weak(socket) or socket
_.extend shadow, request: try socket.handshake
logger.debug "Set PCI %s of %s", uis.bold, sid
assert shadow.socket; socket.shadow = shadow
# An important method that pertains to the details of internal
# duplex implementation. This method is used to produce a wrapper
# around the provider invocation procedure. This wrapping is of
# protective nature. It also exposes some goodies for the provider.
# Such as Socket.IO handle, session if available and the context.
@covering: (method, socket, context, binder) ->
assert _.isFunction o = -> try _.head arguments
assert _.isFunction i = -> try _.head arguments
assert _.isFunction(method), "missing an method"
socket.on "disconnect", -> try guarded.dispose()
session = try socket.request.session unless session
socket.disconnect "no session found" unless session
e = "Exception happend when executing server provider"
assert _.isObject guarded = @guarded method, socket, e
assert _.isFunction g = guarded.run.bind guarded
s = (f) => session.save -> f.apply this, arguments
assert binder; return (parameters..., callback) ->
pci = method.isolation.call @, socket, binder, session
respond = (a...) => s => g => callback.apply pci, o(a)
execute = (a...) => s => g => method.apply pci, i(a)
assert respond.session = socket.session = session
assert respond.binder = socket.binder = binder
assert respond.socket = socket.socket = socket
return execute parameters..., respond, session
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an synchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
encrypted = request.connection.encrypted
pure = /[a-zA-Z0-9\/-_]+/.test @location()
assert pure, "location is not pure enough"
proto = request.headers["x-forwarded-proto"]
enc = encrypted or proto is "https" and yes
context.scripts.push "/socket.io/socket.io.js"
context.duplex = urlOfMaster enc, @location()
context.nsp = symbol unless context.nsp or 0
identify = @constructor.identify().underline
message = "Injecting Socket.IO into %s context"
logger.debug message.yellow, identify or null
assert _.isArray context.providers ?= Array()
_.forIn this, (value, name, service) =>
providing = value?.providing or null
return unless _.isFunction providing
context.providers.push name
return next undefined
# An internal provider that gets automatically invoked once client
# establishes the protected Socket.IO transport back to the service
# instance at the server site. This implementation uses a composite
# `downstream` mechanism to invoke the `connected` method at every
# peers of the inheritance hierarchy. Refer to the method for info.
trampoline: @isolated (context, callback) ->
isocket = "Executed %s socket trampoline"
message = "Inbound duplex connection at %s"
request = "Acknowledged socket from %s request"
assert try @socket.socket is callback.socket
assert discon = "Disengaging %s of %s".yellow
assert sleave = "Socket %s leaving %s".yellow
assert identify = try @constructor.identify()
assert identity = try callback.socket.id.bold
logger.debug message.magenta, identify.underline
logger.debug request.grey, context.url.underline
logger.debug isocket.green, identity.toString()
fn = (event, msg, method) => @socket.on event, =>
logger.debug msg, identity, identify.underline
assert prepared = {}; prepared[method] = ->
assert streaming = try @downstream prepared
return streaming context, callback.socket
fn "disconnect", discon.toString(), "disengage"
fn "unload", (try sleave.toString()), "leaving"
connected = @downstream connected: callback
connected context, callback.socket; this
# This is an external method that will be automatically executed
# on the client site by the duplex implementation. It sets up a
# client end of the Socket.IO channel and creates wrapper around
# all the providers residing in the current service implementation.
# Refer to other `DuplexCore` methods for understanding what goes on.
bootloader: @autocall z: +101, ->
options = new Object reconnect: yes, url: @duplex
_.extend options, reconnectionDelay: 3000 # millis
_.extend options, "max reconnection attempts": 99999
_.extend options, transports: ["websocket"] # no XHR
try @socket = io.connect @duplex, options catch error
message = "blew up Socket.IO: #{error.message}"
error.message = message.toString(); throw error
@emit "socketing", this.socket, this.duplex, options
failed = "failed to establish the Socket.IO connection"
assert this.socket.emit, failed; this.socketFeedback()
$(window).unload => @emit "unload"; @socket.emit "unload"
@socket.on "orphan", -> @io.disconnect(); @io.connect()
osc = (listener) => this.socket.on "connect", listener
osc => @socket.emit "screening", _.pick(@, @snapshot), =>
this.bootloading = yes # mark the bootloading process
assert @consumeProviders; @consumeProviders @socket
assert o = "Successfully bootloaded at %s".green
@once "booted", -> @broadcast "attached", this
@trampoline _.pick(@, @snapshot), (params) =>
logger.info o, @location.underline.green
assert @booted = yes; @initialized = yes
delete this.bootloading # kinda finished
return this.emit "booted", this.socket
# An externally exposed method that is a part of the bootloader
# implementation. It sets up the communication feedback mechanism
# of a Socket.IO handle. Basically installs a bunch of handlers
# that intercept specific events and log the output to a console.
# Can be overriden to provide more meaningful feedback handlers.
socketFeedback: external ->
assert ulocation = @location.green.underline
r = "an error raised during socket connection: %s"
p = "an exception happend at the server provider: %s"
connected = c = "Established connection at %s".green
disconnect = "lost socket connection at #{@location}"
@on "disconnect", -> @booted = false # connection lost
@seemsBroke = -> @outOfOrder() and not @bootloading
@outOfOrder = -> return @initialized and not @booted
@setInOrder = -> return try @initialized and @booted
breaker = try this.STOP_ROOT_PROPAGATION or undefined
r = (e, s) => this.emit(e, s...); @broadcast(e, s...)
forward = (evt) => @socket.on evt, => r evt, arguments
forward "disconnect" # lost socket connection to server
forward "connect" # a successfull connection happended
forward "exception" # server side indicates exception
@socket.on "exception", (e) -> logger.error p, e.message
@socket.on "error", (e) -> logger.error r, e.message
@socket.on "disconnect", -> logger.error disconnect
@socket.on "connect", -> logger.info c, ulocation
# An external routine that will be invoked once a both way duplex
# channel is established at the client site. This will normally
# unroll and set up all the providers that were deployed by the
# server site in the transferred context. Refer to the server
# method called `publishProviders` for more information on it.
consumeProviders: external (socket) ->
assert _.isFunction o = -> try _.head arguments
assert _.isFunction i = -> try _.head arguments
assert srv = try this.service.toString() or null
noConnection = "service #{srv} has lost connection"
for provider in @providers then do (provider) =>
message = "Provider %s at %s using nsp=%s"
assert _.isString uloc = @location.underline
assert _.isString unsp = @nsp.toString().bold
logger.info message, provider.bold, uloc, unsp
this.emit "install-provider", provider, socket
this[provider] = (parameters..., callback) ->
assert not this.seemsBroke(), noConnection
callback = (->) unless _.isFunction callback
noCallback = "#{callback} is not a callback"
assert _.isFunction(callback), noCallback
assert mangled = "#{@location}/#{provider}"
mangled += "/#{nsp}" if _.isString nsp = @nsp
deliver = => callback.apply this, i(arguments)
socket.emit mangled, o(parameters)..., deliver
# After a both ways duplex channel has been established between
# the client site and the server side, this method will be invoked
# in order to attach all of the providers founds in this service
# to the opened channel. Refer to the `register` implementation
# for more information on when, where and how this is happening.
publishProviders: (context, binder, socket, next) ->
assert ms = "Provide %s to %s in %s".magenta
assert id = @constructor.identify().underline
exec = (arbitrary) -> return next undefined
exec _.forIn this, (value, name, service) =>
internal = "the #{value} is not function"
providing = value?.providing or undefined
return unless _.isFunction providing or 0
assert _.isFunction(value or 0), internal
bound = providing socket, context, binder
assert mangled = "#{@location()}/#{name}"
mangled += "/#{nsp}" if nsp = binder.nsp
assert _.isString si = try socket.id.bold
assert _.isString pn = name.toString().bold
logger.debug ms.magenta, pn, si.bold, id
socket.on mangled, (args..., callback) =>
sentence = @downstream sentence: =>
bound.call this, args..., callback
sentence socket, name, value, args
# A hook that will be called prior to unregistering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
unregister: (kernel, router, next) ->
pure = /[a-zA-Z0-9\/-_]+/.test @location()
resolve = (handler) => try handler.of @location()
assert pure, "service location is not pure enough"
assert sserver = kernel.serverSocket, "no HTTP socket"
assert ssecure = kernel.secureSocket, "no HTTPS socket"
assert f = "Disconnecting %s socket handle".toString()
l = (socket) -> try logger.warn f.blue, socket.id.bold
p = (c) -> l(c); c.emit "shutdown"; try c.disconnect()
assert contexts = _.map [sserver, ssecure], resolve
_.each contexts, (context, vector, addition) =>
try context.removeAllListeners "connection"
intern = "missing a client listing registry"
assert _.isObject(context.connected), intern
assert clients = _.values context.connected
assert clients = _.filter clients, "connected"
assert clients = _.unique clients # go once
do -> p client for client, index in clients
return next undefined
# A hook that will be called prior to registering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
register: (kernel, router, next) ->
pure = /[a-zA-Z0-9\/-_]+/.test @location()
resolve = (handler) => try handler.of @location()
assert pure, "service location is not pure enough"
assert sserver = kernel.serverSocket, "no HTTP socket"
assert ssecure = kernel.secureSocket, "no HTTPS socket"
assert contexts = _.map [sserver, ssecure], resolve
assert makeScreener = (context) => (socket) =>
owners = socket.owned ?= new Array()
owners.push this unless this in owners
socket.on "screening", (binder, ack) =>
screening = @downstream screening: =>
bonding = [context, binder, socket, ack]
@publishProviders.apply this, bonding
screening context, socket, binder
_.each contexts, (context, position, vector) =>
assert screener = makeScreener context
assert applied = @authorization context
context.use applied.bind this # middleware
return context.on "connection", screener
return next undefined
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
assert = require "assert"
colors = require "colors"
nconf = require "nconf"
https = require "https"
http = require "http"
weak = require "weak"
util = require "util"
plumbs = require "../nucleus/plumbs"
extendz = require "../nucleus/extends"
compose = require "../nucleus/compose"
{format} = require "util"
{STATUS_CODES} = require "http"
{EventEmitter2} = require "eventemitter2"
{urlOfMaster} = require "../nucleus/toolkit"
{remote, external} = require "./remote"
{Barebones} = require "./skeleton"
{Preflight} = require "./preflight"
# This abstract base class can be used as either a direct parent or
# a compound to the `Screenplay` abstract service. It provides the
# unique ability of half duplex communications between the external
# code that is executed on the call site via `Screenplay` facility
# and an instance of the service that resides on the server site.
# The component itself is built heavily on top of a code emission
# and delivery platform, as implemented by `Screenplay` service.
module.exports.DuplexCore = class DuplexCore extends Preflight
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# A usable hook that gets asynchronously invoked once the user
# is leaving the application page, and the `unload` is emitted.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
leaving: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a new
# channel (socket) gets connected and acknowledged by a server.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
connected: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a socket
# gets disconnected after it has passes through the connection.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
disengage: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a new
# socket connection is going to be setup during the handshake.
# The method gets a set of parameters that maybe be useful to
# have by the actual implementation. Please remember thet the
# method is asynchronously wired, so be sure to call `next`.
handshaken: (context, socket, next) -> next()
# A usable hook that gets asynchronously invoked once a new
# channel (socket) gets past authorization phase and is rated
# to be good to go through the screening process. This is good
# place to implementation various schemes for authorization. If
# you wish to decline, just don't call `next` and close socket.
screening: (context, socket, binder, next) -> next()
# A usable hook that gets asynchronously invoked once a sentence
# comes through an opened channel. This happens every time when
# a client tries to invoke a server site provider method. This
# is a good place to validate if an invocation is legitimate or
# not. If you do not invoke `next` then the call won't happen!
sentence: (socket, name, provider, args, next) -> next()
# An internal method that is wired into the Socket.IO context to
# take care of the very first socket authorization. This happens
# during the handshake phase. This method checks that handshake
# contains correct session requsities and restores the session!
# The session can normally be used as you would use req session.
authorization: (context) => (socket, accept) ->
assert message = "Authorizing %s at %s"
assert _.isObject handshake = socket.request
assert _.isFunction session = @kernel.session
assert _.isFunction cookies = @kernel.cookieParser
assert idc = try @constructor.identify().underline
assert handshake.originalUrl = handshake.url or "/"
assert _.isString id = try socket.id.toString().bold
assert Response = class RDummy extends EventEmitter2
Response::setHeader = (name, value) -> undefined
Response::end = (data, encoding) -> undefined
cookies handshake, response = new Response, =>
session handshake, response, (parameter) =>
logger.debug message.yellow, id, idc
session = handshake.session or null
ns = new Error "no session detected"
return accept ns, no unless session
handshaken = @downstream handshaken: ->
return accept undefined, true
return handshaken context, socket
# An internal, static method that is used to obtain gurading
# domains for each of the declared server site providers. Please
# refer to the Node.js documentation for more information on
# the domains and error handling itself. This method is generally
# used only once per the domain declaration. See `provider`.
@guarded: (method, socket, explain) ->
killOnError = "duplex:disconnectOnError"
assert _.isFunction o = -> _.head arguments
assert _.isFunction i = -> _.head arguments
assert guarded = require("domain").create()
assert identify = try @identify().underline
comparing = (value, opts) -> value is method
where = => _.findKey this.prototype, comparing
_.extend guarded, body: method, socket: socket
location = "Got interrupted around %s#%s".red
m = "Exception within the duplex core:\r\n%s"
m = "#{explain}:\r\n%s" if _.isString explain
fx = (blob) => blob.call this; return guarded
fx -> guarded.on "error", (error, optional) ->
format = try where().toString().underline
logger.error location, identify, format
do -> logger.error m.red, error.stack
str = error.toString() # got no message
packed = stack: error.stack.toString()
packed.message = error.message or str
try socket.emit "exception", packed
return unless nconf.get killOnError
try socket.disconnect?() catch err
# A utility method to mark the certain function as the provider.
# The method returns the original function back so it can be used
# as the normal function, nothing disrupts that. When function is
# marked as a provider, it will be exposed via Socket.IO channel
# that this compound sets up: a half duplex web sockets channel.
@provider: (parameters, method) ->
supplied = _.isPlainObject parameters
malformed = "got an invalid provider"
assert bound = this.covering.bind this
method = _.find arguments, _.isFunction
assert identify = @identify().underline
assert _.isFunction(method), malformed
applicator = try _.partial bound, method
message = "Add new provider at %s service"
parameters = undefined unless supplied
logger.silly message.yellow, identify
method.provider = parameters or {}
method.isolation = -> return this
method.providing = applicator
method.origin = this; method
# This is a modification of the `provider` method that slightly
# changes the scoping/bind for the provider body implementation.
# Upon the provider invocation, this variation creates a shadow
# object derives from the services, therefore isolating calling
# scope to this object that has all the socket and session set.
@isolated: (parameters, method) ->
assert _.isObject constructor = this or 0
assert m = @provider.apply this, arguments
isolation = (fn) -> m.isolation = fn; return m
assert surrogate = "uis_%s_" # prefix template
return isolation (socket, binder, session) ->
return pci if _.isObject pci = socket.shadow
assert identify = try @constructor.identify()
assert prefix = _.sprintf surrogate, identify
assert this isnt constructor, "scoping error"
assert _.isObject shadow = Object.create this
assert isolating = "Isolated provider call in %s"
logger.debug isolating.yellow, sid = socket.id.bold
_.extend shadow, __uis: uis = _.uniqueId(prefix)
_.extend shadow, __isolated: yes, __origin: this
_.extend shadow, session: session, binder: binder
_.extend shadow, socket: weak(socket) or socket
_.extend shadow, request: try socket.handshake
logger.debug "Set PCI %s of %s", uis.bold, sid
assert shadow.socket; socket.shadow = shadow
# An important method that pertains to the details of internal
# duplex implementation. This method is used to produce a wrapper
# around the provider invocation procedure. This wrapping is of
# protective nature. It also exposes some goodies for the provider.
# Such as Socket.IO handle, session if available and the context.
@covering: (method, socket, context, binder) ->
assert _.isFunction o = -> try _.head arguments
assert _.isFunction i = -> try _.head arguments
assert _.isFunction(method), "missing an method"
socket.on "disconnect", -> try guarded.dispose()
session = try socket.request.session unless session
socket.disconnect "no session found" unless session
e = "Exception happend when executing server provider"
assert _.isObject guarded = @guarded method, socket, e
assert _.isFunction g = guarded.run.bind guarded
s = (f) => session.save -> f.apply this, arguments
assert binder; return (parameters..., callback) ->
pci = method.isolation.call @, socket, binder, session
respond = (a...) => s => g => callback.apply pci, o(a)
execute = (a...) => s => g => method.apply pci, i(a)
assert respond.session = socket.session = session
assert respond.binder = socket.binder = binder
assert respond.socket = socket.socket = socket
return execute parameters..., respond, session
# This server side method is called on the context prior to the
# context being compiled and flushed down to the client site. The
# method is wired in an synchronous way for greater functionality.
# This is the place where you would be importing the dependencies.
# Pay attention that most implementations side effect the context.
prelude: (symbol, context, request, next) ->
encrypted = request.connection.encrypted
pure = /[a-zA-Z0-9\/-_]+/.test @location()
assert pure, "location is not pure enough"
proto = request.headers["x-forwarded-proto"]
enc = encrypted or proto is "https" and yes
context.scripts.push "/socket.io/socket.io.js"
context.duplex = urlOfMaster enc, @location()
context.nsp = symbol unless context.nsp or 0
identify = @constructor.identify().underline
message = "Injecting Socket.IO into %s context"
logger.debug message.yellow, identify or null
assert _.isArray context.providers ?= Array()
_.forIn this, (value, name, service) =>
providing = value?.providing or null
return unless _.isFunction providing
context.providers.push name
return next undefined
# An internal provider that gets automatically invoked once client
# establishes the protected Socket.IO transport back to the service
# instance at the server site. This implementation uses a composite
# `downstream` mechanism to invoke the `connected` method at every
# peers of the inheritance hierarchy. Refer to the method for info.
trampoline: @isolated (context, callback) ->
isocket = "Executed %s socket trampoline"
message = "Inbound duplex connection at %s"
request = "Acknowledged socket from %s request"
assert try @socket.socket is callback.socket
assert discon = "Disengaging %s of %s".yellow
assert sleave = "Socket %s leaving %s".yellow
assert identify = try @constructor.identify()
assert identity = try callback.socket.id.bold
logger.debug message.magenta, identify.underline
logger.debug request.grey, context.url.underline
logger.debug isocket.green, identity.toString()
fn = (event, msg, method) => @socket.on event, =>
logger.debug msg, identity, identify.underline
assert prepared = {}; prepared[method] = ->
assert streaming = try @downstream prepared
return streaming context, callback.socket
fn "disconnect", discon.toString(), "disengage"
fn "unload", (try sleave.toString()), "leaving"
connected = @downstream connected: callback
connected context, callback.socket; this
# This is an external method that will be automatically executed
# on the client site by the duplex implementation. It sets up a
# client end of the Socket.IO channel and creates wrapper around
# all the providers residing in the current service implementation.
# Refer to other `DuplexCore` methods for understanding what goes on.
bootloader: @autocall z: +101, ->
options = new Object reconnect: yes, url: @duplex
_.extend options, reconnectionDelay: 3000 # millis
_.extend options, "max reconnection attempts": 99999
_.extend options, transports: ["websocket"] # no XHR
try @socket = io.connect @duplex, options catch error
message = "blew up Socket.IO: #{error.message}"
error.message = message.toString(); throw error
@emit "socketing", this.socket, this.duplex, options
failed = "failed to establish the Socket.IO connection"
assert this.socket.emit, failed; this.socketFeedback()
$(window).unload => @emit "unload"; @socket.emit "unload"
@socket.on "orphan", -> @io.disconnect(); @io.connect()
osc = (listener) => this.socket.on "connect", listener
osc => @socket.emit "screening", _.pick(@, @snapshot), =>
this.bootloading = yes # mark the bootloading process
assert @consumeProviders; @consumeProviders @socket
assert o = "Successfully bootloaded at %s".green
@once "booted", -> @broadcast "attached", this
@trampoline _.pick(@, @snapshot), (params) =>
logger.info o, @location.underline.green
assert @booted = yes; @initialized = yes
delete this.bootloading # kinda finished
return this.emit "booted", this.socket
# An externally exposed method that is a part of the bootloader
# implementation. It sets up the communication feedback mechanism
# of a Socket.IO handle. Basically installs a bunch of handlers
# that intercept specific events and log the output to a console.
# Can be overriden to provide more meaningful feedback handlers.
socketFeedback: external ->
assert ulocation = @location.green.underline
r = "an error raised during socket connection: %s"
p = "an exception happend at the server provider: %s"
connected = c = "Established connection at %s".green
disconnect = "lost socket connection at #{@location}"
@on "disconnect", -> @booted = false # connection lost
@seemsBroke = -> @outOfOrder() and not @bootloading
@outOfOrder = -> return @initialized and not @booted
@setInOrder = -> return try @initialized and @booted
breaker = try this.STOP_ROOT_PROPAGATION or undefined
r = (e, s) => this.emit(e, s...); @broadcast(e, s...)
forward = (evt) => @socket.on evt, => r evt, arguments
forward "disconnect" # lost socket connection to server
forward "connect" # a successfull connection happended
forward "exception" # server side indicates exception
@socket.on "exception", (e) -> logger.error p, e.message
@socket.on "error", (e) -> logger.error r, e.message
@socket.on "disconnect", -> logger.error disconnect
@socket.on "connect", -> logger.info c, ulocation
# An external routine that will be invoked once a both way duplex
# channel is established at the client site. This will normally
# unroll and set up all the providers that were deployed by the
# server site in the transferred context. Refer to the server
# method called `publishProviders` for more information on it.
consumeProviders: external (socket) ->
assert _.isFunction o = -> try _.head arguments
assert _.isFunction i = -> try _.head arguments
assert srv = try this.service.toString() or null
noConnection = "service #{srv} has lost connection"
for provider in @providers then do (provider) =>
message = "Provider %s at %s using nsp=%s"
assert _.isString uloc = @location.underline
assert _.isString unsp = @nsp.toString().bold
logger.info message, provider.bold, uloc, unsp
this.emit "install-provider", provider, socket
this[provider] = (parameters..., callback) ->
assert not this.seemsBroke(), noConnection
callback = (->) unless _.isFunction callback
noCallback = "#{callback} is not a callback"
assert _.isFunction(callback), noCallback
assert mangled = "#{@location}/#{provider}"
mangled += "/#{nsp}" if _.isString nsp = @nsp
deliver = => callback.apply this, i(arguments)
socket.emit mangled, o(parameters)..., deliver
# After a both ways duplex channel has been established between
# the client site and the server side, this method will be invoked
# in order to attach all of the providers founds in this service
# to the opened channel. Refer to the `register` implementation
# for more information on when, where and how this is happening.
publishProviders: (context, binder, socket, next) ->
assert ms = "Provide %s to %s in %s".magenta
assert id = @constructor.identify().underline
exec = (arbitrary) -> return next undefined
exec _.forIn this, (value, name, service) =>
internal = "the #{value} is not function"
providing = value?.providing or undefined
return unless _.isFunction providing or 0
assert _.isFunction(value or 0), internal
bound = providing socket, context, binder
assert mangled = "#{@location()}/#{name}"
mangled += "/#{nsp}" if nsp = binder.nsp
assert _.isString si = try socket.id.bold
assert _.isString pn = name.toString().bold
logger.debug ms.magenta, pn, si.bold, id
socket.on mangled, (args..., callback) =>
sentence = @downstream sentence: =>
bound.call this, args..., callback
sentence socket, name, value, args
# A hook that will be called prior to unregistering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
unregister: (kernel, router, next) ->
pure = /[a-zA-Z0-9\/-_]+/.test @location()
resolve = (handler) => try handler.of @location()
assert pure, "service location is not pure enough"
assert sserver = kernel.serverSocket, "no HTTP socket"
assert ssecure = kernel.secureSocket, "no HTTPS socket"
assert f = "Disconnecting %s socket handle".toString()
l = (socket) -> try logger.warn f.blue, socket.id.bold
p = (c) -> l(c); c.emit "shutdown"; try c.disconnect()
assert contexts = _.map [sserver, ssecure], resolve
_.each contexts, (context, vector, addition) =>
try context.removeAllListeners "connection"
intern = "missing a client listing registry"
assert _.isObject(context.connected), intern
assert clients = _.values context.connected
assert clients = _.filter clients, "connected"
assert clients = _.unique clients # go once
do -> p client for client, index in clients
return next undefined
# A hook that will be called prior to registering the service
# implementation. Please refer to this prototype signature for
# information on the parameters it accepts. Beware, this hook
# is asynchronously wired in, so consult with `async` package.
# Please be sure invoke the `next` arg to proceed, if relevant.
register: (kernel, router, next) ->
pure = /[a-zA-Z0-9\/-_]+/.test @location()
resolve = (handler) => try handler.of @location()
assert pure, "service location is not pure enough"
assert sserver = kernel.serverSocket, "no HTTP socket"
assert ssecure = kernel.secureSocket, "no HTTPS socket"
assert contexts = _.map [sserver, ssecure], resolve
assert makeScreener = (context) => (socket) =>
owners = socket.owned ?= new Array()
owners.push this unless this in owners
socket.on "screening", (binder, ack) =>
screening = @downstream screening: =>
bonding = [context, binder, socket, ack]
@publishProviders.apply this, bonding
screening context, socket, binder
_.each contexts, (context, position, vector) =>
assert screener = makeScreener context
assert applied = @authorization context
context.use applied.bind this # middleware
return context.on "connection", screener
return next undefined
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9993636012077332,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-child-process-spawnsync.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
spawnSync = require("child_process").spawnSync
TIMER = 100
SLEEP = 1000
timeout = 0
setTimeout (->
timeout = process.hrtime(start)
assert.ok stop, "timer should not fire before process exits"
assert.strictEqual timeout[0], 1, "timer should take as long as sleep"
return
), TIMER
console.log "sleep started"
start = process.hrtime()
ret = spawnSync("sleep", ["1"])
stop = process.hrtime(start)
assert.strictEqual ret.status, 0, "exit status should be zero"
console.log "sleep exited", stop
assert.strictEqual stop[0], 1, "sleep should not take longer or less than 1 second"
# Error test when command does not exist
ret_err = spawnSync("command_does_not_exist")
assert.strictEqual ret_err.error.code, "ENOENT"
# Verify that the cwd option works - GH #7824
(->
response = undefined
cwd = undefined
if process.platform is "win32"
cwd = "c:\\"
response = spawnSync("cmd.exe", [
"/c"
"cd"
],
cwd: cwd
)
else
cwd = "/"
response = spawnSync("pwd", [],
cwd: cwd
)
assert.strictEqual response.stdout.toString().trim(), cwd
return
)()
| 136444 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
spawnSync = require("child_process").spawnSync
TIMER = 100
SLEEP = 1000
timeout = 0
setTimeout (->
timeout = process.hrtime(start)
assert.ok stop, "timer should not fire before process exits"
assert.strictEqual timeout[0], 1, "timer should take as long as sleep"
return
), TIMER
console.log "sleep started"
start = process.hrtime()
ret = spawnSync("sleep", ["1"])
stop = process.hrtime(start)
assert.strictEqual ret.status, 0, "exit status should be zero"
console.log "sleep exited", stop
assert.strictEqual stop[0], 1, "sleep should not take longer or less than 1 second"
# Error test when command does not exist
ret_err = spawnSync("command_does_not_exist")
assert.strictEqual ret_err.error.code, "ENOENT"
# Verify that the cwd option works - GH #7824
(->
response = undefined
cwd = undefined
if process.platform is "win32"
cwd = "c:\\"
response = spawnSync("cmd.exe", [
"/c"
"cd"
],
cwd: cwd
)
else
cwd = "/"
response = spawnSync("pwd", [],
cwd: cwd
)
assert.strictEqual response.stdout.toString().trim(), cwd
return
)()
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
spawnSync = require("child_process").spawnSync
TIMER = 100
SLEEP = 1000
timeout = 0
setTimeout (->
timeout = process.hrtime(start)
assert.ok stop, "timer should not fire before process exits"
assert.strictEqual timeout[0], 1, "timer should take as long as sleep"
return
), TIMER
console.log "sleep started"
start = process.hrtime()
ret = spawnSync("sleep", ["1"])
stop = process.hrtime(start)
assert.strictEqual ret.status, 0, "exit status should be zero"
console.log "sleep exited", stop
assert.strictEqual stop[0], 1, "sleep should not take longer or less than 1 second"
# Error test when command does not exist
ret_err = spawnSync("command_does_not_exist")
assert.strictEqual ret_err.error.code, "ENOENT"
# Verify that the cwd option works - GH #7824
(->
response = undefined
cwd = undefined
if process.platform is "win32"
cwd = "c:\\"
response = spawnSync("cmd.exe", [
"/c"
"cd"
],
cwd: cwd
)
else
cwd = "/"
response = spawnSync("pwd", [],
cwd: cwd
)
assert.strictEqual response.stdout.toString().trim(), cwd
return
)()
|
[
{
"context": "title: \"Welcome to <%= name %>\"\npermalink: \"/\"\n",
"end": 27,
"score": 0.8306341171264648,
"start": 23,
"tag": "NAME",
"value": "name"
}
] | app/templates/data/pages/start.cson | killercup/generator-silicon-zucchini | 0 | title: "Welcome to <%= name %>"
permalink: "/"
| 148820 | title: "Welcome to <%= <NAME> %>"
permalink: "/"
| true | title: "Welcome to <%= PI:NAME:<NAME>END_PI %>"
permalink: "/"
|
[
{
"context": "hr.setRequestHeader('Authorization', ('Token ' + 'fccb3a073f9e7e53e01838d4693d1302e5857cf3'))\n\n Backbone.sync.call(this, method, collec",
"end": 565,
"score": 0.9525273442268372,
"start": 525,
"tag": "PASSWORD",
"value": "fccb3a073f9e7e53e01838d4693d1302e5857cf3"
}
] | coffee/models/base/model.coffee | zedam/backbone_chaplin_api | 0 | define [
'chaplin'
], (Chaplin) ->
class Model extends Chaplin.Model
# Mixin a synchronization state machine.
# _.extend @prototype, Chaplin.SyncMachine
# initialize: ->
# super
# @on 'request', @beginSync
# @on 'sync', @finishSync
# @on 'error', @unsync
# Place your application-specific model features here.
sync: (method, collection, options) ->
options = options || {}
options.beforeSend = (xhr) ->
xhr.setRequestHeader('Authorization', ('Token ' + 'fccb3a073f9e7e53e01838d4693d1302e5857cf3'))
Backbone.sync.call(this, method, collection, options)
| 17623 | define [
'chaplin'
], (Chaplin) ->
class Model extends Chaplin.Model
# Mixin a synchronization state machine.
# _.extend @prototype, Chaplin.SyncMachine
# initialize: ->
# super
# @on 'request', @beginSync
# @on 'sync', @finishSync
# @on 'error', @unsync
# Place your application-specific model features here.
sync: (method, collection, options) ->
options = options || {}
options.beforeSend = (xhr) ->
xhr.setRequestHeader('Authorization', ('Token ' + '<PASSWORD>'))
Backbone.sync.call(this, method, collection, options)
| true | define [
'chaplin'
], (Chaplin) ->
class Model extends Chaplin.Model
# Mixin a synchronization state machine.
# _.extend @prototype, Chaplin.SyncMachine
# initialize: ->
# super
# @on 'request', @beginSync
# @on 'sync', @finishSync
# @on 'error', @unsync
# Place your application-specific model features here.
sync: (method, collection, options) ->
options = options || {}
options.beforeSend = (xhr) ->
xhr.setRequestHeader('Authorization', ('Token ' + 'PI:PASSWORD:<PASSWORD>END_PI'))
Backbone.sync.call(this, method, collection, options)
|
[
{
"context": " false\n __request_forgery_protection_token: 'form_token'\n __form_authenticity_token: 'secret'\n\n __",
"end": 5774,
"score": 0.43778908252716064,
"start": 5774,
"tag": "PASSWORD",
"value": ""
}
] | app/assets/javascripts/ultimate/helpers/url.js.coffee | evrone/ultimate-helpers | 2 | #= require ./base
#= require ./tag
#= require ./javascript
__char_encode = (char) -> "%#{char.charCodeAt(0).toString(16)}"
__escape_path = (str) -> str.replace(/[^*\-.0-9A-Z_a-z]/g, __char_encode).replace(/\+/g, '%20')
__string_encode = (str) -> _.map(str, (char) -> "&##{char.charCodeAt(0)};" ).join('')
@Ultimate.Helpers.Url =
url_for: (options = null) ->
if _.isString(options)
if options is 'back'
'javascript:history.back();'
else
options
else unless _.isEmpty(options)
url = _.result(options, 'url') ? ''
if $.isPlainObject(options)
options = _.clone(options)
delete options['url']
anchor = _.outcasts.delete(options, 'anchor')
url += "?#{_.map(options, (value, key) -> "#{key}=#{value}").sort().join('&')}" unless _.isEmpty(options)
url += "##{anchor}" if anchor
url
else
'javascript:;'
link_to: (name = null, options = null, html_options = null, block = null) ->
[html_options, options] = [options, name] if block = _.outcasts.blockGiven(arguments)
options ||= {}
url = @url_for(options)
html_options = @_convert_options_to_data_attributes(options, html_options)
html_options['href'] ||= url
if block
Ultimate.Helpers.Tag.content_tag('a', html_options, null, false, block)
else
Ultimate.Helpers.Tag.content_tag('a', name ? url, html_options, false)
link_to_js: (name = null, html_options = null, block = null) ->
[options, name] = [name, null] if block = _.outcasts.blockGiven(arguments)
@link_to [name, options, html_options, block]...
# TODO tests
link_to_unless_current_span: (name, options = null, html_options = null, block = null) ->
[html_options, options] = [options, name] if block = _.outcasts.blockGiven(arguments)
url = @url_for(options)
if @current_page_(url)
if block
Ultimate.Helpers.Tag.content_tag('span', html_options, null, false, block)
else
Ultimate.Helpers.Tag.content_tag('span', name ? url, html_options, false)
else
if block
@link_to options, html_options, block
else
@link_to name, options, html_options
# TODO tests
link_to_unless_current: (name, options = {}, html_options = {}, block = null) ->
@link_to_unless @current_page_(options), name, options, html_options, block
# TODO tests
link_to_unless: (condition, name, options = {}, html_options = {}, block = null) ->
if condition
if block = _.outcasts.blockGiven(arguments)
block(name, options, html_options)
else
name
else
@link_to name, options, html_options, block
# TODO tests
link_to_if: (condition, name, options = {}, html_options = {}, block = null) ->
@link_to_unless not condition, name, options, html_options, block
mail_to: (email_address, name = null, html_options = {}) ->
email_address = _.string.escapeHTML(email_address)
encode = _.outcasts.delete(html_options, 'encode')
extras = _.compact _.map _.string.words('cc bcc body subject'), (item) ->
option = _.outcasts.delete(html_options, item)
if option?
"#{item}=#{__escape_path(option)}"
extras = if _.isEmpty(extras) then '' else '?' + _.string.escapeHTML(extras.join('&'))
email_address_obfuscated = email_address
email_address_obfuscated = email_address_obfuscated.replace('@', _.outcasts.delete(html_options, 'replace_at')) if 'replace_at' of html_options
email_address_obfuscated = email_address_obfuscated.replace('.', _.outcasts.delete(html_options, 'replace_dot')) if 'replace_dot' of html_options
switch encode
when 'javascript'
html = @link_to(name or email_address_obfuscated, "mailto:#{email_address}#{extras}", html_options)
html = Ultimate.Helpers.Javascript.escape_javascript(html)
string = _.map("document.write('#{html}');", __char_encode).join('')
"<script>eval(decodeURIComponent('#{string}'))</script>"
when 'hex'
email_address_encoded = __string_encode(email_address_obfuscated)
string = __string_encode('mailto:') + _.map(email_address, (char) -> if /\w/.test(char) then __char_encode(char) else char).join('')
@link_to name or email_address_encoded, "#{string}#{extras}", html_options
else
@link_to name or email_address_obfuscated, "mailto:#{email_address}#{extras}", html_options
# TODO tests
current_page_: (options) ->
url_string = @url_for(options)
request_uri = location.pathname
if /^\w+:\/\//.test(url_string)
url_string == "#{location.protocol}#{location.host}#{request_uri}"
else
url_string == request_uri
_convert_options_to_data_attributes: (options, html_options) ->
if html_options
html_options['data-remote'] = 'true' if @_link_to_remote_options(options) or @_link_to_remote_options(html_options)
method = _.outcasts.delete(html_options, 'method')
@_add_method_to_attributes(html_options, method) if method
html_options
else
if @_link_to_remote_options(options) then {'data-remote': 'true'} else {}
_link_to_remote_options: (options) ->
_.isObject(options) and _.outcasts.delete(options, 'remote')
_add_method_to_attributes: (html_options, method) ->
if _.isString(method) and method.toLowerCase() isnt 'get' and not /nofollow/.test(html_options['rel'])
html_options['rel'] = Ultimate.Helpers.Tag.concat_class(html_options['rel'], 'nofollow')
html_options['data-method'] = method
_convert_boolean_attributes: (html_options, bool_attrs) ->
html_options[x] = x for x in bool_attrs when _.outcasts.delete(html_options, x)
html_options
__protect_against_forgery: false
__request_forgery_protection_token: 'form_token'
__form_authenticity_token: 'secret'
__init_request_forgery_protection: ->
param = $('head meta[name="csrf-param"]').attr('content')
token = $('head meta[name="csrf-token"]').attr('content')
if param and token
@__protect_against_forgery = true
@__request_forgery_protection_token = param
@__form_authenticity_token = token
_token_tag: (token = @__form_authenticity_token) ->
if token isnt false and @__protect_against_forgery
Ultimate.Helpers.Tag.tag 'input', type: 'hidden', name: @__request_forgery_protection_token, value: token
else
''
_method_tag: (method) ->
Ultimate.Helpers.Tag.tag 'input', type: 'hidden', name: '_method', value: method
| 57119 | #= require ./base
#= require ./tag
#= require ./javascript
__char_encode = (char) -> "%#{char.charCodeAt(0).toString(16)}"
__escape_path = (str) -> str.replace(/[^*\-.0-9A-Z_a-z]/g, __char_encode).replace(/\+/g, '%20')
__string_encode = (str) -> _.map(str, (char) -> "&##{char.charCodeAt(0)};" ).join('')
@Ultimate.Helpers.Url =
url_for: (options = null) ->
if _.isString(options)
if options is 'back'
'javascript:history.back();'
else
options
else unless _.isEmpty(options)
url = _.result(options, 'url') ? ''
if $.isPlainObject(options)
options = _.clone(options)
delete options['url']
anchor = _.outcasts.delete(options, 'anchor')
url += "?#{_.map(options, (value, key) -> "#{key}=#{value}").sort().join('&')}" unless _.isEmpty(options)
url += "##{anchor}" if anchor
url
else
'javascript:;'
link_to: (name = null, options = null, html_options = null, block = null) ->
[html_options, options] = [options, name] if block = _.outcasts.blockGiven(arguments)
options ||= {}
url = @url_for(options)
html_options = @_convert_options_to_data_attributes(options, html_options)
html_options['href'] ||= url
if block
Ultimate.Helpers.Tag.content_tag('a', html_options, null, false, block)
else
Ultimate.Helpers.Tag.content_tag('a', name ? url, html_options, false)
link_to_js: (name = null, html_options = null, block = null) ->
[options, name] = [name, null] if block = _.outcasts.blockGiven(arguments)
@link_to [name, options, html_options, block]...
# TODO tests
link_to_unless_current_span: (name, options = null, html_options = null, block = null) ->
[html_options, options] = [options, name] if block = _.outcasts.blockGiven(arguments)
url = @url_for(options)
if @current_page_(url)
if block
Ultimate.Helpers.Tag.content_tag('span', html_options, null, false, block)
else
Ultimate.Helpers.Tag.content_tag('span', name ? url, html_options, false)
else
if block
@link_to options, html_options, block
else
@link_to name, options, html_options
# TODO tests
link_to_unless_current: (name, options = {}, html_options = {}, block = null) ->
@link_to_unless @current_page_(options), name, options, html_options, block
# TODO tests
link_to_unless: (condition, name, options = {}, html_options = {}, block = null) ->
if condition
if block = _.outcasts.blockGiven(arguments)
block(name, options, html_options)
else
name
else
@link_to name, options, html_options, block
# TODO tests
link_to_if: (condition, name, options = {}, html_options = {}, block = null) ->
@link_to_unless not condition, name, options, html_options, block
mail_to: (email_address, name = null, html_options = {}) ->
email_address = _.string.escapeHTML(email_address)
encode = _.outcasts.delete(html_options, 'encode')
extras = _.compact _.map _.string.words('cc bcc body subject'), (item) ->
option = _.outcasts.delete(html_options, item)
if option?
"#{item}=#{__escape_path(option)}"
extras = if _.isEmpty(extras) then '' else '?' + _.string.escapeHTML(extras.join('&'))
email_address_obfuscated = email_address
email_address_obfuscated = email_address_obfuscated.replace('@', _.outcasts.delete(html_options, 'replace_at')) if 'replace_at' of html_options
email_address_obfuscated = email_address_obfuscated.replace('.', _.outcasts.delete(html_options, 'replace_dot')) if 'replace_dot' of html_options
switch encode
when 'javascript'
html = @link_to(name or email_address_obfuscated, "mailto:#{email_address}#{extras}", html_options)
html = Ultimate.Helpers.Javascript.escape_javascript(html)
string = _.map("document.write('#{html}');", __char_encode).join('')
"<script>eval(decodeURIComponent('#{string}'))</script>"
when 'hex'
email_address_encoded = __string_encode(email_address_obfuscated)
string = __string_encode('mailto:') + _.map(email_address, (char) -> if /\w/.test(char) then __char_encode(char) else char).join('')
@link_to name or email_address_encoded, "#{string}#{extras}", html_options
else
@link_to name or email_address_obfuscated, "mailto:#{email_address}#{extras}", html_options
# TODO tests
current_page_: (options) ->
url_string = @url_for(options)
request_uri = location.pathname
if /^\w+:\/\//.test(url_string)
url_string == "#{location.protocol}#{location.host}#{request_uri}"
else
url_string == request_uri
_convert_options_to_data_attributes: (options, html_options) ->
if html_options
html_options['data-remote'] = 'true' if @_link_to_remote_options(options) or @_link_to_remote_options(html_options)
method = _.outcasts.delete(html_options, 'method')
@_add_method_to_attributes(html_options, method) if method
html_options
else
if @_link_to_remote_options(options) then {'data-remote': 'true'} else {}
_link_to_remote_options: (options) ->
_.isObject(options) and _.outcasts.delete(options, 'remote')
_add_method_to_attributes: (html_options, method) ->
if _.isString(method) and method.toLowerCase() isnt 'get' and not /nofollow/.test(html_options['rel'])
html_options['rel'] = Ultimate.Helpers.Tag.concat_class(html_options['rel'], 'nofollow')
html_options['data-method'] = method
_convert_boolean_attributes: (html_options, bool_attrs) ->
html_options[x] = x for x in bool_attrs when _.outcasts.delete(html_options, x)
html_options
__protect_against_forgery: false
__request_forgery_protection_token: 'form<PASSWORD>_token'
__form_authenticity_token: 'secret'
__init_request_forgery_protection: ->
param = $('head meta[name="csrf-param"]').attr('content')
token = $('head meta[name="csrf-token"]').attr('content')
if param and token
@__protect_against_forgery = true
@__request_forgery_protection_token = param
@__form_authenticity_token = token
_token_tag: (token = @__form_authenticity_token) ->
if token isnt false and @__protect_against_forgery
Ultimate.Helpers.Tag.tag 'input', type: 'hidden', name: @__request_forgery_protection_token, value: token
else
''
_method_tag: (method) ->
Ultimate.Helpers.Tag.tag 'input', type: 'hidden', name: '_method', value: method
| true | #= require ./base
#= require ./tag
#= require ./javascript
__char_encode = (char) -> "%#{char.charCodeAt(0).toString(16)}"
__escape_path = (str) -> str.replace(/[^*\-.0-9A-Z_a-z]/g, __char_encode).replace(/\+/g, '%20')
__string_encode = (str) -> _.map(str, (char) -> "&##{char.charCodeAt(0)};" ).join('')
@Ultimate.Helpers.Url =
url_for: (options = null) ->
if _.isString(options)
if options is 'back'
'javascript:history.back();'
else
options
else unless _.isEmpty(options)
url = _.result(options, 'url') ? ''
if $.isPlainObject(options)
options = _.clone(options)
delete options['url']
anchor = _.outcasts.delete(options, 'anchor')
url += "?#{_.map(options, (value, key) -> "#{key}=#{value}").sort().join('&')}" unless _.isEmpty(options)
url += "##{anchor}" if anchor
url
else
'javascript:;'
link_to: (name = null, options = null, html_options = null, block = null) ->
[html_options, options] = [options, name] if block = _.outcasts.blockGiven(arguments)
options ||= {}
url = @url_for(options)
html_options = @_convert_options_to_data_attributes(options, html_options)
html_options['href'] ||= url
if block
Ultimate.Helpers.Tag.content_tag('a', html_options, null, false, block)
else
Ultimate.Helpers.Tag.content_tag('a', name ? url, html_options, false)
link_to_js: (name = null, html_options = null, block = null) ->
[options, name] = [name, null] if block = _.outcasts.blockGiven(arguments)
@link_to [name, options, html_options, block]...
# TODO tests
link_to_unless_current_span: (name, options = null, html_options = null, block = null) ->
[html_options, options] = [options, name] if block = _.outcasts.blockGiven(arguments)
url = @url_for(options)
if @current_page_(url)
if block
Ultimate.Helpers.Tag.content_tag('span', html_options, null, false, block)
else
Ultimate.Helpers.Tag.content_tag('span', name ? url, html_options, false)
else
if block
@link_to options, html_options, block
else
@link_to name, options, html_options
# TODO tests
link_to_unless_current: (name, options = {}, html_options = {}, block = null) ->
@link_to_unless @current_page_(options), name, options, html_options, block
# TODO tests
link_to_unless: (condition, name, options = {}, html_options = {}, block = null) ->
if condition
if block = _.outcasts.blockGiven(arguments)
block(name, options, html_options)
else
name
else
@link_to name, options, html_options, block
# TODO tests
link_to_if: (condition, name, options = {}, html_options = {}, block = null) ->
@link_to_unless not condition, name, options, html_options, block
mail_to: (email_address, name = null, html_options = {}) ->
email_address = _.string.escapeHTML(email_address)
encode = _.outcasts.delete(html_options, 'encode')
extras = _.compact _.map _.string.words('cc bcc body subject'), (item) ->
option = _.outcasts.delete(html_options, item)
if option?
"#{item}=#{__escape_path(option)}"
extras = if _.isEmpty(extras) then '' else '?' + _.string.escapeHTML(extras.join('&'))
email_address_obfuscated = email_address
email_address_obfuscated = email_address_obfuscated.replace('@', _.outcasts.delete(html_options, 'replace_at')) if 'replace_at' of html_options
email_address_obfuscated = email_address_obfuscated.replace('.', _.outcasts.delete(html_options, 'replace_dot')) if 'replace_dot' of html_options
switch encode
when 'javascript'
html = @link_to(name or email_address_obfuscated, "mailto:#{email_address}#{extras}", html_options)
html = Ultimate.Helpers.Javascript.escape_javascript(html)
string = _.map("document.write('#{html}');", __char_encode).join('')
"<script>eval(decodeURIComponent('#{string}'))</script>"
when 'hex'
email_address_encoded = __string_encode(email_address_obfuscated)
string = __string_encode('mailto:') + _.map(email_address, (char) -> if /\w/.test(char) then __char_encode(char) else char).join('')
@link_to name or email_address_encoded, "#{string}#{extras}", html_options
else
@link_to name or email_address_obfuscated, "mailto:#{email_address}#{extras}", html_options
# TODO tests
current_page_: (options) ->
url_string = @url_for(options)
request_uri = location.pathname
if /^\w+:\/\//.test(url_string)
url_string == "#{location.protocol}#{location.host}#{request_uri}"
else
url_string == request_uri
_convert_options_to_data_attributes: (options, html_options) ->
if html_options
html_options['data-remote'] = 'true' if @_link_to_remote_options(options) or @_link_to_remote_options(html_options)
method = _.outcasts.delete(html_options, 'method')
@_add_method_to_attributes(html_options, method) if method
html_options
else
if @_link_to_remote_options(options) then {'data-remote': 'true'} else {}
_link_to_remote_options: (options) ->
_.isObject(options) and _.outcasts.delete(options, 'remote')
_add_method_to_attributes: (html_options, method) ->
if _.isString(method) and method.toLowerCase() isnt 'get' and not /nofollow/.test(html_options['rel'])
html_options['rel'] = Ultimate.Helpers.Tag.concat_class(html_options['rel'], 'nofollow')
html_options['data-method'] = method
_convert_boolean_attributes: (html_options, bool_attrs) ->
html_options[x] = x for x in bool_attrs when _.outcasts.delete(html_options, x)
html_options
__protect_against_forgery: false
__request_forgery_protection_token: 'formPI:PASSWORD:<PASSWORD>END_PI_token'
__form_authenticity_token: 'secret'
__init_request_forgery_protection: ->
param = $('head meta[name="csrf-param"]').attr('content')
token = $('head meta[name="csrf-token"]').attr('content')
if param and token
@__protect_against_forgery = true
@__request_forgery_protection_token = param
@__form_authenticity_token = token
_token_tag: (token = @__form_authenticity_token) ->
if token isnt false and @__protect_against_forgery
Ultimate.Helpers.Tag.tag 'input', type: 'hidden', name: @__request_forgery_protection_token, value: token
else
''
_method_tag: (method) ->
Ultimate.Helpers.Tag.tag 'input', type: 'hidden', name: '_method', value: method
|
[
{
"context": "acket: ->\n loginData =\n userName: @config.userName\n password: @config.password\n database: ",
"end": 12163,
"score": 0.8488771915435791,
"start": 12155,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "=\n userName: @config.userName\n ... | node_modules/tedious/src-coffee/connection.coffee | srolfe/timetrackr | 2 | require('./buffertools')
Debug = require('./debug')
EventEmitter = require('events').EventEmitter
instanceLookup = require('./instance-lookup').instanceLookup
TYPE = require('./packet').TYPE
PreloginPayload = require('./prelogin-payload')
Login7Payload = require('./login7-payload')
Request = require('./request')
RpcRequestPayload = require('./rpcrequest-payload')
SqlBatchPayload = require('./sqlbatch-payload')
MessageIO = require('./message-io')
Socket = require('net').Socket
TokenStreamParser = require('./token/token-stream-parser').Parser
Transaction = require('./transaction').Transaction
ISOLATION_LEVEL = require('./transaction').ISOLATION_LEVEL
crypto = require('crypto')
tls = require('tls')
# A rather basic state machine for managing a connection.
# Implements something approximating s3.2.1.
KEEP_ALIVE_INITIAL_DELAY = 30 * 1000
DEFAULT_CONNECT_TIMEOUT = 15 * 1000
DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000
DEFAULT_CANCEL_TIMEOUT = 5 * 1000
DEFAULT_PACKET_SIZE = 4 * 1024
DEFAULT_TEXTSIZE = '2147483647'
DEFAULT_PORT = 1433
DEFAULT_TDS_VERSION = '7_2'
class Connection extends EventEmitter
STATE:
CONNECTING:
name: 'Connecting'
enter: ->
@initialiseConnection()
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
socketConnect: ->
@sendPreLogin()
@transitionTo(@STATE.SENT_PRELOGIN)
SENT_PRELOGIN:
name: 'SentPrelogin'
enter: ->
@emptyMessageBuffer()
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@addToMessageBuffer(data)
message: ->
@processPreLoginResponse()
noTls: ->
@sendLogin7Packet()
@transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN)
tls: ->
@initiateTlsSslHandshake()
@sendLogin7Packet()
@transitionTo(@STATE.SENT_TLSSSLNEGOTIATION)
SENT_TLSSSLNEGOTIATION:
name: 'SentTLSSSLNegotiation'
enter: ->
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@securePair.encrypted.write(data)
tlsNegotiated: ->
@tlsNegotiationComplete = true
message: ->
if @tlsNegotiationComplete
@transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN)
else
SENT_LOGIN7_WITH_STANDARD_LOGIN:
name: 'SentLogin7WithStandardLogin'
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@sendDataToTokenStreamParser(data)
loggedIn: ->
@transitionTo(@STATE.LOGGED_IN_SENDING_INITIAL_SQL)
loginFailed: ->
@transitionTo(@STATE.FINAL)
message: ->
@processLogin7Response()
LOGGED_IN_SENDING_INITIAL_SQL:
name: 'LoggedInSendingInitialSql'
enter: ->
@sendInitialSql()
events:
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@sendDataToTokenStreamParser(data)
message: (error) ->
@transitionTo(@STATE.LOGGED_IN)
@processedInitialSql()
LOGGED_IN:
name: 'LoggedIn'
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
SENT_CLIENT_REQUEST:
name: 'SentClientRequest'
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@sendDataToTokenStreamParser(data)
message: ->
@transitionTo(@STATE.LOGGED_IN)
sqlRequest = @request
@request = undefined
sqlRequest.callback(sqlRequest.error, sqlRequest.rowCount, sqlRequest.rows)
FINAL:
name: 'Final'
enter: ->
@cleanupConnection()
events:
loginFailed: ->
# Do nothing. The connection was probably closed by the client code.
connectTimeout: ->
# Do nothing, as the timer should be cleaned up.
message: ->
# Do nothing
socketError: ->
# Do nothing
constructor: (@config) ->
@defaultConfig()
@createDebug()
@createTokenStreamParser()
@transactions = []
@transactionDescriptors = [new Buffer([0, 0, 0, 0, 0, 0, 0, 0])]
@transitionTo(@STATE.CONNECTING)
close: ->
@transitionTo(@STATE.FINAL)
initialiseConnection: ->
@connect()
@createConnectTimer()
cleanupConnection: ->
if !@closed
@clearConnectTimer()
@closeConnection()
@emit('end')
@closed = true
defaultConfig: ->
@config.options ||= {}
@config.options.textsize ||= DEFAULT_TEXTSIZE
@config.options.connectTimeout ||= DEFAULT_CONNECT_TIMEOUT
@config.options.requestTimeout ||= DEFAULT_CLIENT_REQUEST_TIMEOUT
@config.options.cancelTimeout ||= DEFAULT_CANCEL_TIMEOUT
@config.options.packetSize ||= DEFAULT_PACKET_SIZE
@config.options.tdsVersion ||= DEFAULT_TDS_VERSION
@config.options.isolationLevel ||= ISOLATION_LEVEL.READ_UNCOMMITTED
@config.options.encrypt ||= false
@config.options.cryptoCredentialsDetails ||= {}
if !@config.options.port && !@config.options.instanceName
@config.options.port = DEFAULT_PORT
else if @config.options.port && @config.options.instanceName
throw new Error("Port and instanceName are mutually exclusive, but #{config.options.port} and #{config.options.instanceName} provided")
createDebug: ->
@debug = new Debug(@config.options.debug)
@debug.on('debug', (message) =>
@emit('debug', message)
)
createTokenStreamParser: ->
@tokenStreamParser = new TokenStreamParser(@debug, undefined, @config.options.tdsVersion)
@tokenStreamParser.on('infoMessage', (token) =>
@emit('infoMessage', token)
)
@tokenStreamParser.on('errorMessage', (token) =>
@emit('errorMessage', token)
if @request
@request.error = token.message
)
@tokenStreamParser.on('databaseChange', (token) =>
@emit('databaseChange', token.newValue)
)
@tokenStreamParser.on('languageChange', (token) =>
@emit('languageChange', token.newValue)
)
@tokenStreamParser.on('charsetChange', (token) =>
@emit('charsetChange', token.newValue)
)
@tokenStreamParser.on('loginack', (token) =>
@loggedIn = true
)
@tokenStreamParser.on('packetSizeChange', (token) =>
@messageIo.packetSize(token.newValue)
)
@tokenStreamParser.on('beginTransaction', (token) =>
@transactionDescriptors.push(token.newValue)
)
@tokenStreamParser.on('commitTransaction', (token) =>
@transactionDescriptors.pop()
)
@tokenStreamParser.on('rollbackTransaction', (token) =>
@transactionDescriptors.pop()
)
@tokenStreamParser.on('columnMetadata', (token) =>
if @request
@request.emit('columnMetadata', token.columns)
else
throw new Error("Received 'columnMetadata' when no sqlRequest is in progress")
)
@tokenStreamParser.on('order', (token) =>
if @request
@request.emit('order', token.orderColumns)
else
throw new Error("Received 'order' when no sqlRequest is in progress")
)
@tokenStreamParser.on('row', (token) =>
if @request
if @config.options.rowCollectionOnRequestCompletion || @config.options.rowCollectionOnDone
@request.rows.push token.columns
@request.emit('row', token.columns)
else
throw new Error("Received 'row' when no sqlRequest is in progress")
)
@tokenStreamParser.on('returnStatus', (token) =>
if @request
# Keep value for passing in 'doneProc' event.
@procReturnStatusValue = token.value
)
@tokenStreamParser.on('returnValue', (token) =>
if @request
@request.emit('returnValue', token.paramName, token.value, token.metadata)
)
@tokenStreamParser.on('doneProc', (token) =>
if @request
@request.emit('doneProc', token.rowCount, token.more, @procReturnStatusValue, @request.rows)
@procReturnStatusValue = undefined
if token.rowCount != undefined
@request.rowCount += token.rowCount
if @config.options.rowCollectionOnDone
@request.rows = []
)
@tokenStreamParser.on('doneInProc', (token) =>
if @request
@request.emit('doneInProc', token.rowCount, token.more, @request.rows)
if token.rowCount != undefined
@request.rowCount += token.rowCount
if @config.options.rowCollectionOnDone
@request.rows = []
)
@tokenStreamParser.on('done', (token) =>
if @request
@request.emit('done', token.rowCount, token.more, @request.rows)
if token.rowCount != undefined
@request.rowCount += token.rowCount
if @config.options.rowCollectionOnDone
@request.rows = []
)
@tokenStreamParser.on('resetConnection', (token) =>
@emit('resetConnection')
)
connect: ->
if (@config.options.port)
@connectOnPort(@config.options.port)
else
instanceLookup(@config.server, @config.options.instanceName, (err, port) =>
if err
throw new Error(err)
else
@connectOnPort(port)
)
connectOnPort: (port) ->
@socket = new Socket({})
@socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY)
@socket.connect(port, @config.server)
@socket.on('error', @socketError)
@socket.on('connect', @socketConnect)
@socket.on('close', @socketClose)
@socket.on('end', @socketClose)
@messageIo = new MessageIO(@socket, @config.options.packetSize, @debug)
@messageIo.on('data', (data) =>
@dispatchEvent('data', data)
)
@messageIo.on('message', =>
@dispatchEvent('message')
)
closeConnection: ->
@socket.destroy()
createConnectTimer: ->
@connectTimer = setTimeout(@connectTimeout, @config.options.connectTimeout)
connectTimeout: =>
message = "timeout : failed to connect to #{@config.server}:#{@config.options.port} in #{@config.options.connectTimeout}ms"
@debug.log(message)
@emit('connect', message)
@connectTimer = undefined
@dispatchEvent('connectTimeout')
clearConnectTimer: ->
if @connectTimer
clearTimeout(@connectTimer)
transitionTo: (newState) ->
if @state?.exit
@state.exit.apply(@)
@debug.log("State change: #{@state?.name} -> #{newState.name}")
@state = newState
if @state.enter
@state.enter.apply(@)
dispatchEvent: (eventName, args...) ->
if @state?.events[eventName]
eventFunction = @state.events[eventName].apply(@, args)
else
throw new Error("No event '#{eventName}' in state '#{@state.name}'")
socketError: (error) =>
message = "connection to #{@config.server}:#{@config.options.port} - failed #{error}"
@debug.log(message)
@dispatchEvent('socketError', error)
socketConnect: =>
@debug.log("connected to #{@config.server}:#{@config.options.port}")
@dispatchEvent('socketConnect')
socketClose: =>
@debug.log("connection to #{@config.server}:#{@config.options.port} closed")
@transitionTo(@STATE.FINAL)
sendPreLogin: ->
payload = new PreloginPayload({encrypt: @config.options.encrypt})
@messageIo.sendMessage(TYPE.PRELOGIN, payload.data)
@debug.payload(->
payload.toString(' ')
)
emptyMessageBuffer: ->
@messageBuffer = new Buffer(0)
addToMessageBuffer: (data) ->
@messageBuffer = Buffer.concat([@messageBuffer, data])
processPreLoginResponse: ->
preloginPayload = new PreloginPayload(@messageBuffer)
@debug.payload(->
preloginPayload.toString(' ')
)
if preloginPayload.encryptionString == 'ON'
@dispatchEvent('tls')
else
@dispatchEvent('noTls')
sendLogin7Packet: ->
loginData =
userName: @config.userName
password: @config.password
database: @config.options.database
appName: @config.options.appName
packetSize: @config.options.packetSize
tdsVersion: @config.options.tdsVersion
payload = new Login7Payload(loginData)
@messageIo.sendMessage(TYPE.LOGIN7, payload.data)
@debug.payload(->
payload.toString(' ')
)
initiateTlsSslHandshake: ->
@config.options.cryptoCredentialsDetails.ciphers ||= 'RC4-MD5'
credentials = crypto.createCredentials(@config.options.cryptoCredentialsDetails)
@securePair = tls.createSecurePair(credentials)
@securePair.on('secure', =>
cipher = @securePair.cleartext.getCipher()
@debug.log("TLS negotiated (#{cipher.name}, #{cipher.version})")
# console.log cipher
# console.log @securePair.cleartext.getPeerCertificate()
@emit('secure', @securePair.cleartext)
@messageIo.encryptAllFutureTraffic()
@dispatchEvent('tlsNegotiated')
)
@securePair.encrypted.on('data', (data) =>
@messageIo.sendMessage(TYPE.PRELOGIN, data)
)
@messageIo.tlsNegotiationStarting(@securePair)
sendDataToTokenStreamParser: (data) ->
@tokenStreamParser.addBuffer(data)
sendInitialSql: ->
payload = new SqlBatchPayload(@getInitialSql(), @currentTransactionDescriptor())
@messageIo.sendMessage(TYPE.SQL_BATCH, payload.data)
getInitialSql: ->
'set textsize ' + @config.options.textsize + '''
set quoted_identifier on
set arithabort off
set numeric_roundabort off
set ansi_warnings on
set ansi_padding on
set ansi_nulls on
set concat_null_yields_null on
set cursor_close_on_commit off
set implicit_transactions off
set language us_english
set dateformat mdy
set datefirst 7
set transaction isolation level read committed'''
processedInitialSql: ->
@clearConnectTimer()
@emit('connect')
processLogin7Response: ->
if @loggedIn
@dispatchEvent('loggedIn')
else
@emit('connect', 'Login failed; one or more errorMessage events should have been emitted')
@dispatchEvent('loginFailed')
execSqlBatch: (request) ->
@makeRequest(request, TYPE.SQL_BATCH, new SqlBatchPayload(request.sqlTextOrProcedure, @currentTransactionDescriptor()))
execSql: (request) ->
request.transformIntoExecuteSqlRpc()
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
prepare: (request) ->
request.transformIntoPrepareRpc()
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
unprepare: (request) ->
request.transformIntoUnprepareRpc()
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
execute: (request, parameters) ->
request.transformIntoExecuteRpc(parameters)
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
callProcedure: (request) ->
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
beginTransaction: (callback, name, isolationLevel) ->
name ||= ''
isolationLevel ||= @config.options.isolationLevel
transaction = new Transaction(name, isolationLevel)
@transactions.push(transaction)
request = new Request(undefined, (err) =>
callback(err, @currentTransactionDescriptor())
)
@makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.beginPayload(@currentTransactionDescriptor()))
commitTransaction: (callback) ->
if @transactions.length == 0
throw new Error('No transaction in progress')
transaction = @transactions.pop()
request = new Request(undefined, callback)
@makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.commitPayload(@currentTransactionDescriptor()))
rollbackTransaction: (callback) ->
if @transactions.length == 0
throw new Error('No transaction in progress')
transaction = @transactions.pop()
request = new Request(undefined, callback)
@makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.rollbackPayload(@currentTransactionDescriptor()))
makeRequest: (request, packetType, payload) ->
if @state != @STATE.LOGGED_IN
message = "Invalid state; requests can only be made in the #{@STATE.LOGGED_IN.name} state, not the #{@state.name} state"
@debug.log(message)
request.callback(message)
else
@request = request
@request.rowCount = 0
@request.rows = []
@messageIo.sendMessage(packetType, payload.data, @resetConnectionOnNextRequest)
@resetConnectionOnNextRequest = false
@debug.payload(->
payload.toString(' ')
)
@transitionTo(@STATE.SENT_CLIENT_REQUEST)
reset: (callback) =>
request = new Request(@getInitialSql(), (err, rowCount, rows) ->
callback(err)
)
@resetConnectionOnNextRequest = true
@execSqlBatch(request)
currentTransactionDescriptor: ->
@transactionDescriptors[@transactionDescriptors.length - 1]
module.exports = Connection
| 204738 | require('./buffertools')
Debug = require('./debug')
EventEmitter = require('events').EventEmitter
instanceLookup = require('./instance-lookup').instanceLookup
TYPE = require('./packet').TYPE
PreloginPayload = require('./prelogin-payload')
Login7Payload = require('./login7-payload')
Request = require('./request')
RpcRequestPayload = require('./rpcrequest-payload')
SqlBatchPayload = require('./sqlbatch-payload')
MessageIO = require('./message-io')
Socket = require('net').Socket
TokenStreamParser = require('./token/token-stream-parser').Parser
Transaction = require('./transaction').Transaction
ISOLATION_LEVEL = require('./transaction').ISOLATION_LEVEL
crypto = require('crypto')
tls = require('tls')
# A rather basic state machine for managing a connection.
# Implements something approximating s3.2.1.
KEEP_ALIVE_INITIAL_DELAY = 30 * 1000
DEFAULT_CONNECT_TIMEOUT = 15 * 1000
DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000
DEFAULT_CANCEL_TIMEOUT = 5 * 1000
DEFAULT_PACKET_SIZE = 4 * 1024
DEFAULT_TEXTSIZE = '2147483647'
DEFAULT_PORT = 1433
DEFAULT_TDS_VERSION = '7_2'
class Connection extends EventEmitter
STATE:
CONNECTING:
name: 'Connecting'
enter: ->
@initialiseConnection()
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
socketConnect: ->
@sendPreLogin()
@transitionTo(@STATE.SENT_PRELOGIN)
SENT_PRELOGIN:
name: 'SentPrelogin'
enter: ->
@emptyMessageBuffer()
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@addToMessageBuffer(data)
message: ->
@processPreLoginResponse()
noTls: ->
@sendLogin7Packet()
@transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN)
tls: ->
@initiateTlsSslHandshake()
@sendLogin7Packet()
@transitionTo(@STATE.SENT_TLSSSLNEGOTIATION)
SENT_TLSSSLNEGOTIATION:
name: 'SentTLSSSLNegotiation'
enter: ->
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@securePair.encrypted.write(data)
tlsNegotiated: ->
@tlsNegotiationComplete = true
message: ->
if @tlsNegotiationComplete
@transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN)
else
SENT_LOGIN7_WITH_STANDARD_LOGIN:
name: 'SentLogin7WithStandardLogin'
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@sendDataToTokenStreamParser(data)
loggedIn: ->
@transitionTo(@STATE.LOGGED_IN_SENDING_INITIAL_SQL)
loginFailed: ->
@transitionTo(@STATE.FINAL)
message: ->
@processLogin7Response()
LOGGED_IN_SENDING_INITIAL_SQL:
name: 'LoggedInSendingInitialSql'
enter: ->
@sendInitialSql()
events:
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@sendDataToTokenStreamParser(data)
message: (error) ->
@transitionTo(@STATE.LOGGED_IN)
@processedInitialSql()
LOGGED_IN:
name: 'LoggedIn'
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
SENT_CLIENT_REQUEST:
name: 'SentClientRequest'
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@sendDataToTokenStreamParser(data)
message: ->
@transitionTo(@STATE.LOGGED_IN)
sqlRequest = @request
@request = undefined
sqlRequest.callback(sqlRequest.error, sqlRequest.rowCount, sqlRequest.rows)
FINAL:
name: 'Final'
enter: ->
@cleanupConnection()
events:
loginFailed: ->
# Do nothing. The connection was probably closed by the client code.
connectTimeout: ->
# Do nothing, as the timer should be cleaned up.
message: ->
# Do nothing
socketError: ->
# Do nothing
constructor: (@config) ->
@defaultConfig()
@createDebug()
@createTokenStreamParser()
@transactions = []
@transactionDescriptors = [new Buffer([0, 0, 0, 0, 0, 0, 0, 0])]
@transitionTo(@STATE.CONNECTING)
close: ->
@transitionTo(@STATE.FINAL)
initialiseConnection: ->
@connect()
@createConnectTimer()
cleanupConnection: ->
if !@closed
@clearConnectTimer()
@closeConnection()
@emit('end')
@closed = true
defaultConfig: ->
@config.options ||= {}
@config.options.textsize ||= DEFAULT_TEXTSIZE
@config.options.connectTimeout ||= DEFAULT_CONNECT_TIMEOUT
@config.options.requestTimeout ||= DEFAULT_CLIENT_REQUEST_TIMEOUT
@config.options.cancelTimeout ||= DEFAULT_CANCEL_TIMEOUT
@config.options.packetSize ||= DEFAULT_PACKET_SIZE
@config.options.tdsVersion ||= DEFAULT_TDS_VERSION
@config.options.isolationLevel ||= ISOLATION_LEVEL.READ_UNCOMMITTED
@config.options.encrypt ||= false
@config.options.cryptoCredentialsDetails ||= {}
if !@config.options.port && !@config.options.instanceName
@config.options.port = DEFAULT_PORT
else if @config.options.port && @config.options.instanceName
throw new Error("Port and instanceName are mutually exclusive, but #{config.options.port} and #{config.options.instanceName} provided")
createDebug: ->
@debug = new Debug(@config.options.debug)
@debug.on('debug', (message) =>
@emit('debug', message)
)
createTokenStreamParser: ->
@tokenStreamParser = new TokenStreamParser(@debug, undefined, @config.options.tdsVersion)
@tokenStreamParser.on('infoMessage', (token) =>
@emit('infoMessage', token)
)
@tokenStreamParser.on('errorMessage', (token) =>
@emit('errorMessage', token)
if @request
@request.error = token.message
)
@tokenStreamParser.on('databaseChange', (token) =>
@emit('databaseChange', token.newValue)
)
@tokenStreamParser.on('languageChange', (token) =>
@emit('languageChange', token.newValue)
)
@tokenStreamParser.on('charsetChange', (token) =>
@emit('charsetChange', token.newValue)
)
@tokenStreamParser.on('loginack', (token) =>
@loggedIn = true
)
@tokenStreamParser.on('packetSizeChange', (token) =>
@messageIo.packetSize(token.newValue)
)
@tokenStreamParser.on('beginTransaction', (token) =>
@transactionDescriptors.push(token.newValue)
)
@tokenStreamParser.on('commitTransaction', (token) =>
@transactionDescriptors.pop()
)
@tokenStreamParser.on('rollbackTransaction', (token) =>
@transactionDescriptors.pop()
)
@tokenStreamParser.on('columnMetadata', (token) =>
if @request
@request.emit('columnMetadata', token.columns)
else
throw new Error("Received 'columnMetadata' when no sqlRequest is in progress")
)
@tokenStreamParser.on('order', (token) =>
if @request
@request.emit('order', token.orderColumns)
else
throw new Error("Received 'order' when no sqlRequest is in progress")
)
@tokenStreamParser.on('row', (token) =>
if @request
if @config.options.rowCollectionOnRequestCompletion || @config.options.rowCollectionOnDone
@request.rows.push token.columns
@request.emit('row', token.columns)
else
throw new Error("Received 'row' when no sqlRequest is in progress")
)
@tokenStreamParser.on('returnStatus', (token) =>
if @request
# Keep value for passing in 'doneProc' event.
@procReturnStatusValue = token.value
)
@tokenStreamParser.on('returnValue', (token) =>
if @request
@request.emit('returnValue', token.paramName, token.value, token.metadata)
)
@tokenStreamParser.on('doneProc', (token) =>
if @request
@request.emit('doneProc', token.rowCount, token.more, @procReturnStatusValue, @request.rows)
@procReturnStatusValue = undefined
if token.rowCount != undefined
@request.rowCount += token.rowCount
if @config.options.rowCollectionOnDone
@request.rows = []
)
@tokenStreamParser.on('doneInProc', (token) =>
if @request
@request.emit('doneInProc', token.rowCount, token.more, @request.rows)
if token.rowCount != undefined
@request.rowCount += token.rowCount
if @config.options.rowCollectionOnDone
@request.rows = []
)
@tokenStreamParser.on('done', (token) =>
if @request
@request.emit('done', token.rowCount, token.more, @request.rows)
if token.rowCount != undefined
@request.rowCount += token.rowCount
if @config.options.rowCollectionOnDone
@request.rows = []
)
@tokenStreamParser.on('resetConnection', (token) =>
@emit('resetConnection')
)
connect: ->
if (@config.options.port)
@connectOnPort(@config.options.port)
else
instanceLookup(@config.server, @config.options.instanceName, (err, port) =>
if err
throw new Error(err)
else
@connectOnPort(port)
)
connectOnPort: (port) ->
@socket = new Socket({})
@socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY)
@socket.connect(port, @config.server)
@socket.on('error', @socketError)
@socket.on('connect', @socketConnect)
@socket.on('close', @socketClose)
@socket.on('end', @socketClose)
@messageIo = new MessageIO(@socket, @config.options.packetSize, @debug)
@messageIo.on('data', (data) =>
@dispatchEvent('data', data)
)
@messageIo.on('message', =>
@dispatchEvent('message')
)
closeConnection: ->
@socket.destroy()
createConnectTimer: ->
@connectTimer = setTimeout(@connectTimeout, @config.options.connectTimeout)
connectTimeout: =>
message = "timeout : failed to connect to #{@config.server}:#{@config.options.port} in #{@config.options.connectTimeout}ms"
@debug.log(message)
@emit('connect', message)
@connectTimer = undefined
@dispatchEvent('connectTimeout')
clearConnectTimer: ->
if @connectTimer
clearTimeout(@connectTimer)
transitionTo: (newState) ->
if @state?.exit
@state.exit.apply(@)
@debug.log("State change: #{@state?.name} -> #{newState.name}")
@state = newState
if @state.enter
@state.enter.apply(@)
dispatchEvent: (eventName, args...) ->
if @state?.events[eventName]
eventFunction = @state.events[eventName].apply(@, args)
else
throw new Error("No event '#{eventName}' in state '#{@state.name}'")
socketError: (error) =>
message = "connection to #{@config.server}:#{@config.options.port} - failed #{error}"
@debug.log(message)
@dispatchEvent('socketError', error)
socketConnect: =>
@debug.log("connected to #{@config.server}:#{@config.options.port}")
@dispatchEvent('socketConnect')
socketClose: =>
@debug.log("connection to #{@config.server}:#{@config.options.port} closed")
@transitionTo(@STATE.FINAL)
sendPreLogin: ->
payload = new PreloginPayload({encrypt: @config.options.encrypt})
@messageIo.sendMessage(TYPE.PRELOGIN, payload.data)
@debug.payload(->
payload.toString(' ')
)
emptyMessageBuffer: ->
@messageBuffer = new Buffer(0)
addToMessageBuffer: (data) ->
@messageBuffer = Buffer.concat([@messageBuffer, data])
processPreLoginResponse: ->
preloginPayload = new PreloginPayload(@messageBuffer)
@debug.payload(->
preloginPayload.toString(' ')
)
if preloginPayload.encryptionString == 'ON'
@dispatchEvent('tls')
else
@dispatchEvent('noTls')
sendLogin7Packet: ->
loginData =
userName: @config.userName
password: <PASSWORD>
database: @config.options.database
appName: @config.options.appName
packetSize: @config.options.packetSize
tdsVersion: @config.options.tdsVersion
payload = new Login7Payload(loginData)
@messageIo.sendMessage(TYPE.LOGIN7, payload.data)
@debug.payload(->
payload.toString(' ')
)
initiateTlsSslHandshake: ->
@config.options.cryptoCredentialsDetails.ciphers ||= 'RC4-MD5'
credentials = crypto.createCredentials(@config.options.cryptoCredentialsDetails)
@securePair = tls.createSecurePair(credentials)
@securePair.on('secure', =>
cipher = @securePair.cleartext.getCipher()
@debug.log("TLS negotiated (#{cipher.name}, #{cipher.version})")
# console.log cipher
# console.log @securePair.cleartext.getPeerCertificate()
@emit('secure', @securePair.cleartext)
@messageIo.encryptAllFutureTraffic()
@dispatchEvent('tlsNegotiated')
)
@securePair.encrypted.on('data', (data) =>
@messageIo.sendMessage(TYPE.PRELOGIN, data)
)
@messageIo.tlsNegotiationStarting(@securePair)
sendDataToTokenStreamParser: (data) ->
@tokenStreamParser.addBuffer(data)
sendInitialSql: ->
payload = new SqlBatchPayload(@getInitialSql(), @currentTransactionDescriptor())
@messageIo.sendMessage(TYPE.SQL_BATCH, payload.data)
getInitialSql: ->
'set textsize ' + @config.options.textsize + '''
set quoted_identifier on
set arithabort off
set numeric_roundabort off
set ansi_warnings on
set ansi_padding on
set ansi_nulls on
set concat_null_yields_null on
set cursor_close_on_commit off
set implicit_transactions off
set language us_english
set dateformat mdy
set datefirst 7
set transaction isolation level read committed'''
processedInitialSql: ->
@clearConnectTimer()
@emit('connect')
processLogin7Response: ->
if @loggedIn
@dispatchEvent('loggedIn')
else
@emit('connect', 'Login failed; one or more errorMessage events should have been emitted')
@dispatchEvent('loginFailed')
execSqlBatch: (request) ->
@makeRequest(request, TYPE.SQL_BATCH, new SqlBatchPayload(request.sqlTextOrProcedure, @currentTransactionDescriptor()))
execSql: (request) ->
request.transformIntoExecuteSqlRpc()
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
prepare: (request) ->
request.transformIntoPrepareRpc()
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
unprepare: (request) ->
request.transformIntoUnprepareRpc()
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
execute: (request, parameters) ->
request.transformIntoExecuteRpc(parameters)
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
callProcedure: (request) ->
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
beginTransaction: (callback, name, isolationLevel) ->
name ||= ''
isolationLevel ||= @config.options.isolationLevel
transaction = new Transaction(name, isolationLevel)
@transactions.push(transaction)
request = new Request(undefined, (err) =>
callback(err, @currentTransactionDescriptor())
)
@makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.beginPayload(@currentTransactionDescriptor()))
commitTransaction: (callback) ->
if @transactions.length == 0
throw new Error('No transaction in progress')
transaction = @transactions.pop()
request = new Request(undefined, callback)
@makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.commitPayload(@currentTransactionDescriptor()))
rollbackTransaction: (callback) ->
if @transactions.length == 0
throw new Error('No transaction in progress')
transaction = @transactions.pop()
request = new Request(undefined, callback)
@makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.rollbackPayload(@currentTransactionDescriptor()))
makeRequest: (request, packetType, payload) ->
if @state != @STATE.LOGGED_IN
message = "Invalid state; requests can only be made in the #{@STATE.LOGGED_IN.name} state, not the #{@state.name} state"
@debug.log(message)
request.callback(message)
else
@request = request
@request.rowCount = 0
@request.rows = []
@messageIo.sendMessage(packetType, payload.data, @resetConnectionOnNextRequest)
@resetConnectionOnNextRequest = false
@debug.payload(->
payload.toString(' ')
)
@transitionTo(@STATE.SENT_CLIENT_REQUEST)
reset: (callback) =>
request = new Request(@getInitialSql(), (err, rowCount, rows) ->
callback(err)
)
@resetConnectionOnNextRequest = true
@execSqlBatch(request)
currentTransactionDescriptor: ->
@transactionDescriptors[@transactionDescriptors.length - 1]
module.exports = Connection
| true | require('./buffertools')
Debug = require('./debug')
EventEmitter = require('events').EventEmitter
instanceLookup = require('./instance-lookup').instanceLookup
TYPE = require('./packet').TYPE
PreloginPayload = require('./prelogin-payload')
Login7Payload = require('./login7-payload')
Request = require('./request')
RpcRequestPayload = require('./rpcrequest-payload')
SqlBatchPayload = require('./sqlbatch-payload')
MessageIO = require('./message-io')
Socket = require('net').Socket
TokenStreamParser = require('./token/token-stream-parser').Parser
Transaction = require('./transaction').Transaction
ISOLATION_LEVEL = require('./transaction').ISOLATION_LEVEL
crypto = require('crypto')
tls = require('tls')
# A rather basic state machine for managing a connection.
# Implements something approximating s3.2.1.
KEEP_ALIVE_INITIAL_DELAY = 30 * 1000
DEFAULT_CONNECT_TIMEOUT = 15 * 1000
DEFAULT_CLIENT_REQUEST_TIMEOUT = 15 * 1000
DEFAULT_CANCEL_TIMEOUT = 5 * 1000
DEFAULT_PACKET_SIZE = 4 * 1024
DEFAULT_TEXTSIZE = '2147483647'
DEFAULT_PORT = 1433
DEFAULT_TDS_VERSION = '7_2'
class Connection extends EventEmitter
STATE:
CONNECTING:
name: 'Connecting'
enter: ->
@initialiseConnection()
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
socketConnect: ->
@sendPreLogin()
@transitionTo(@STATE.SENT_PRELOGIN)
SENT_PRELOGIN:
name: 'SentPrelogin'
enter: ->
@emptyMessageBuffer()
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@addToMessageBuffer(data)
message: ->
@processPreLoginResponse()
noTls: ->
@sendLogin7Packet()
@transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN)
tls: ->
@initiateTlsSslHandshake()
@sendLogin7Packet()
@transitionTo(@STATE.SENT_TLSSSLNEGOTIATION)
SENT_TLSSSLNEGOTIATION:
name: 'SentTLSSSLNegotiation'
enter: ->
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@securePair.encrypted.write(data)
tlsNegotiated: ->
@tlsNegotiationComplete = true
message: ->
if @tlsNegotiationComplete
@transitionTo(@STATE.SENT_LOGIN7_WITH_STANDARD_LOGIN)
else
SENT_LOGIN7_WITH_STANDARD_LOGIN:
name: 'SentLogin7WithStandardLogin'
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@sendDataToTokenStreamParser(data)
loggedIn: ->
@transitionTo(@STATE.LOGGED_IN_SENDING_INITIAL_SQL)
loginFailed: ->
@transitionTo(@STATE.FINAL)
message: ->
@processLogin7Response()
LOGGED_IN_SENDING_INITIAL_SQL:
name: 'LoggedInSendingInitialSql'
enter: ->
@sendInitialSql()
events:
connectTimeout: ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@sendDataToTokenStreamParser(data)
message: (error) ->
@transitionTo(@STATE.LOGGED_IN)
@processedInitialSql()
LOGGED_IN:
name: 'LoggedIn'
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
SENT_CLIENT_REQUEST:
name: 'SentClientRequest'
events:
socketError: (error) ->
@transitionTo(@STATE.FINAL)
data: (data) ->
@sendDataToTokenStreamParser(data)
message: ->
@transitionTo(@STATE.LOGGED_IN)
sqlRequest = @request
@request = undefined
sqlRequest.callback(sqlRequest.error, sqlRequest.rowCount, sqlRequest.rows)
FINAL:
name: 'Final'
enter: ->
@cleanupConnection()
events:
loginFailed: ->
# Do nothing. The connection was probably closed by the client code.
connectTimeout: ->
# Do nothing, as the timer should be cleaned up.
message: ->
# Do nothing
socketError: ->
# Do nothing
constructor: (@config) ->
@defaultConfig()
@createDebug()
@createTokenStreamParser()
@transactions = []
@transactionDescriptors = [new Buffer([0, 0, 0, 0, 0, 0, 0, 0])]
@transitionTo(@STATE.CONNECTING)
close: ->
@transitionTo(@STATE.FINAL)
initialiseConnection: ->
@connect()
@createConnectTimer()
cleanupConnection: ->
if !@closed
@clearConnectTimer()
@closeConnection()
@emit('end')
@closed = true
defaultConfig: ->
@config.options ||= {}
@config.options.textsize ||= DEFAULT_TEXTSIZE
@config.options.connectTimeout ||= DEFAULT_CONNECT_TIMEOUT
@config.options.requestTimeout ||= DEFAULT_CLIENT_REQUEST_TIMEOUT
@config.options.cancelTimeout ||= DEFAULT_CANCEL_TIMEOUT
@config.options.packetSize ||= DEFAULT_PACKET_SIZE
@config.options.tdsVersion ||= DEFAULT_TDS_VERSION
@config.options.isolationLevel ||= ISOLATION_LEVEL.READ_UNCOMMITTED
@config.options.encrypt ||= false
@config.options.cryptoCredentialsDetails ||= {}
if !@config.options.port && !@config.options.instanceName
@config.options.port = DEFAULT_PORT
else if @config.options.port && @config.options.instanceName
throw new Error("Port and instanceName are mutually exclusive, but #{config.options.port} and #{config.options.instanceName} provided")
createDebug: ->
@debug = new Debug(@config.options.debug)
@debug.on('debug', (message) =>
@emit('debug', message)
)
createTokenStreamParser: ->
@tokenStreamParser = new TokenStreamParser(@debug, undefined, @config.options.tdsVersion)
@tokenStreamParser.on('infoMessage', (token) =>
@emit('infoMessage', token)
)
@tokenStreamParser.on('errorMessage', (token) =>
@emit('errorMessage', token)
if @request
@request.error = token.message
)
@tokenStreamParser.on('databaseChange', (token) =>
@emit('databaseChange', token.newValue)
)
@tokenStreamParser.on('languageChange', (token) =>
@emit('languageChange', token.newValue)
)
@tokenStreamParser.on('charsetChange', (token) =>
@emit('charsetChange', token.newValue)
)
@tokenStreamParser.on('loginack', (token) =>
@loggedIn = true
)
@tokenStreamParser.on('packetSizeChange', (token) =>
@messageIo.packetSize(token.newValue)
)
@tokenStreamParser.on('beginTransaction', (token) =>
@transactionDescriptors.push(token.newValue)
)
@tokenStreamParser.on('commitTransaction', (token) =>
@transactionDescriptors.pop()
)
@tokenStreamParser.on('rollbackTransaction', (token) =>
@transactionDescriptors.pop()
)
@tokenStreamParser.on('columnMetadata', (token) =>
if @request
@request.emit('columnMetadata', token.columns)
else
throw new Error("Received 'columnMetadata' when no sqlRequest is in progress")
)
@tokenStreamParser.on('order', (token) =>
if @request
@request.emit('order', token.orderColumns)
else
throw new Error("Received 'order' when no sqlRequest is in progress")
)
@tokenStreamParser.on('row', (token) =>
if @request
if @config.options.rowCollectionOnRequestCompletion || @config.options.rowCollectionOnDone
@request.rows.push token.columns
@request.emit('row', token.columns)
else
throw new Error("Received 'row' when no sqlRequest is in progress")
)
@tokenStreamParser.on('returnStatus', (token) =>
if @request
# Keep value for passing in 'doneProc' event.
@procReturnStatusValue = token.value
)
@tokenStreamParser.on('returnValue', (token) =>
if @request
@request.emit('returnValue', token.paramName, token.value, token.metadata)
)
@tokenStreamParser.on('doneProc', (token) =>
if @request
@request.emit('doneProc', token.rowCount, token.more, @procReturnStatusValue, @request.rows)
@procReturnStatusValue = undefined
if token.rowCount != undefined
@request.rowCount += token.rowCount
if @config.options.rowCollectionOnDone
@request.rows = []
)
@tokenStreamParser.on('doneInProc', (token) =>
if @request
@request.emit('doneInProc', token.rowCount, token.more, @request.rows)
if token.rowCount != undefined
@request.rowCount += token.rowCount
if @config.options.rowCollectionOnDone
@request.rows = []
)
@tokenStreamParser.on('done', (token) =>
if @request
@request.emit('done', token.rowCount, token.more, @request.rows)
if token.rowCount != undefined
@request.rowCount += token.rowCount
if @config.options.rowCollectionOnDone
@request.rows = []
)
@tokenStreamParser.on('resetConnection', (token) =>
@emit('resetConnection')
)
connect: ->
if (@config.options.port)
@connectOnPort(@config.options.port)
else
instanceLookup(@config.server, @config.options.instanceName, (err, port) =>
if err
throw new Error(err)
else
@connectOnPort(port)
)
connectOnPort: (port) ->
@socket = new Socket({})
@socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY)
@socket.connect(port, @config.server)
@socket.on('error', @socketError)
@socket.on('connect', @socketConnect)
@socket.on('close', @socketClose)
@socket.on('end', @socketClose)
@messageIo = new MessageIO(@socket, @config.options.packetSize, @debug)
@messageIo.on('data', (data) =>
@dispatchEvent('data', data)
)
@messageIo.on('message', =>
@dispatchEvent('message')
)
closeConnection: ->
@socket.destroy()
createConnectTimer: ->
@connectTimer = setTimeout(@connectTimeout, @config.options.connectTimeout)
connectTimeout: =>
message = "timeout : failed to connect to #{@config.server}:#{@config.options.port} in #{@config.options.connectTimeout}ms"
@debug.log(message)
@emit('connect', message)
@connectTimer = undefined
@dispatchEvent('connectTimeout')
clearConnectTimer: ->
if @connectTimer
clearTimeout(@connectTimer)
transitionTo: (newState) ->
if @state?.exit
@state.exit.apply(@)
@debug.log("State change: #{@state?.name} -> #{newState.name}")
@state = newState
if @state.enter
@state.enter.apply(@)
dispatchEvent: (eventName, args...) ->
if @state?.events[eventName]
eventFunction = @state.events[eventName].apply(@, args)
else
throw new Error("No event '#{eventName}' in state '#{@state.name}'")
socketError: (error) =>
message = "connection to #{@config.server}:#{@config.options.port} - failed #{error}"
@debug.log(message)
@dispatchEvent('socketError', error)
socketConnect: =>
@debug.log("connected to #{@config.server}:#{@config.options.port}")
@dispatchEvent('socketConnect')
socketClose: =>
@debug.log("connection to #{@config.server}:#{@config.options.port} closed")
@transitionTo(@STATE.FINAL)
sendPreLogin: ->
payload = new PreloginPayload({encrypt: @config.options.encrypt})
@messageIo.sendMessage(TYPE.PRELOGIN, payload.data)
@debug.payload(->
payload.toString(' ')
)
emptyMessageBuffer: ->
@messageBuffer = new Buffer(0)
addToMessageBuffer: (data) ->
@messageBuffer = Buffer.concat([@messageBuffer, data])
processPreLoginResponse: ->
preloginPayload = new PreloginPayload(@messageBuffer)
@debug.payload(->
preloginPayload.toString(' ')
)
if preloginPayload.encryptionString == 'ON'
@dispatchEvent('tls')
else
@dispatchEvent('noTls')
sendLogin7Packet: ->
loginData =
userName: @config.userName
password: PI:PASSWORD:<PASSWORD>END_PI
database: @config.options.database
appName: @config.options.appName
packetSize: @config.options.packetSize
tdsVersion: @config.options.tdsVersion
payload = new Login7Payload(loginData)
@messageIo.sendMessage(TYPE.LOGIN7, payload.data)
@debug.payload(->
payload.toString(' ')
)
initiateTlsSslHandshake: ->
@config.options.cryptoCredentialsDetails.ciphers ||= 'RC4-MD5'
credentials = crypto.createCredentials(@config.options.cryptoCredentialsDetails)
@securePair = tls.createSecurePair(credentials)
@securePair.on('secure', =>
cipher = @securePair.cleartext.getCipher()
@debug.log("TLS negotiated (#{cipher.name}, #{cipher.version})")
# console.log cipher
# console.log @securePair.cleartext.getPeerCertificate()
@emit('secure', @securePair.cleartext)
@messageIo.encryptAllFutureTraffic()
@dispatchEvent('tlsNegotiated')
)
@securePair.encrypted.on('data', (data) =>
@messageIo.sendMessage(TYPE.PRELOGIN, data)
)
@messageIo.tlsNegotiationStarting(@securePair)
sendDataToTokenStreamParser: (data) ->
@tokenStreamParser.addBuffer(data)
sendInitialSql: ->
payload = new SqlBatchPayload(@getInitialSql(), @currentTransactionDescriptor())
@messageIo.sendMessage(TYPE.SQL_BATCH, payload.data)
getInitialSql: ->
'set textsize ' + @config.options.textsize + '''
set quoted_identifier on
set arithabort off
set numeric_roundabort off
set ansi_warnings on
set ansi_padding on
set ansi_nulls on
set concat_null_yields_null on
set cursor_close_on_commit off
set implicit_transactions off
set language us_english
set dateformat mdy
set datefirst 7
set transaction isolation level read committed'''
processedInitialSql: ->
@clearConnectTimer()
@emit('connect')
processLogin7Response: ->
if @loggedIn
@dispatchEvent('loggedIn')
else
@emit('connect', 'Login failed; one or more errorMessage events should have been emitted')
@dispatchEvent('loginFailed')
execSqlBatch: (request) ->
@makeRequest(request, TYPE.SQL_BATCH, new SqlBatchPayload(request.sqlTextOrProcedure, @currentTransactionDescriptor()))
execSql: (request) ->
request.transformIntoExecuteSqlRpc()
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
prepare: (request) ->
request.transformIntoPrepareRpc()
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
unprepare: (request) ->
request.transformIntoUnprepareRpc()
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
execute: (request, parameters) ->
request.transformIntoExecuteRpc(parameters)
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
callProcedure: (request) ->
@makeRequest(request, TYPE.RPC_REQUEST, new RpcRequestPayload(request, @currentTransactionDescriptor()))
beginTransaction: (callback, name, isolationLevel) ->
name ||= ''
isolationLevel ||= @config.options.isolationLevel
transaction = new Transaction(name, isolationLevel)
@transactions.push(transaction)
request = new Request(undefined, (err) =>
callback(err, @currentTransactionDescriptor())
)
@makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.beginPayload(@currentTransactionDescriptor()))
commitTransaction: (callback) ->
if @transactions.length == 0
throw new Error('No transaction in progress')
transaction = @transactions.pop()
request = new Request(undefined, callback)
@makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.commitPayload(@currentTransactionDescriptor()))
rollbackTransaction: (callback) ->
if @transactions.length == 0
throw new Error('No transaction in progress')
transaction = @transactions.pop()
request = new Request(undefined, callback)
@makeRequest(request, TYPE.TRANSACTION_MANAGER, transaction.rollbackPayload(@currentTransactionDescriptor()))
makeRequest: (request, packetType, payload) ->
if @state != @STATE.LOGGED_IN
message = "Invalid state; requests can only be made in the #{@STATE.LOGGED_IN.name} state, not the #{@state.name} state"
@debug.log(message)
request.callback(message)
else
@request = request
@request.rowCount = 0
@request.rows = []
@messageIo.sendMessage(packetType, payload.data, @resetConnectionOnNextRequest)
@resetConnectionOnNextRequest = false
@debug.payload(->
payload.toString(' ')
)
@transitionTo(@STATE.SENT_CLIENT_REQUEST)
reset: (callback) =>
request = new Request(@getInitialSql(), (err, rowCount, rows) ->
callback(err)
)
@resetConnectionOnNextRequest = true
@execSqlBatch(request)
currentTransactionDescriptor: ->
@transactionDescriptors[@transactionDescriptors.length - 1]
module.exports = Connection
|
[
{
"context": "->\n # A rule to validate input fields\n # @author Daniel Bartholomae\n class ValidatorRule\n # Create a new Validato",
"end": 326,
"score": 0.9998758435249329,
"start": 308,
"tag": "NAME",
"value": "Daniel Bartholomae"
}
] | src/rules/Rule.coffee | dbartholomae/node-validation-codes | 0 | ((modules, factory) ->
# Use define if amd compatible define function is defined
if typeof define is 'function' && define.amd
define modules, factory
# Use node require if not
else
module.exports = factory (require m for m in modules)...
)( [], ->
# A rule to validate input fields
# @author Daniel Bartholomae
class ValidatorRule
# Create a new ValidatorRule. When extending this constructor, set this.options to the default values
# and call super to overwrite all options given as a parameter.
#
# @param [Object] (options) An optional list of options
constructor: (options) ->
@options ?= {}
@setOptions options
# Set the options of this rule.
#
# @param [Object] (options) An optional list of options
setOptions: (options) ->
if options?
for own option, value of options
@options[option] = value
# Return all possible violation codes for this rule.
# @return [Array<String>] An array of all possible violation codes for this rule.
getViolationCodes: -> []
# Validate an object and return a list of codes for all rules it violates
#
# @param [Object] value The value to validate
# @return [Array<String>] [''] if the string is valid, an array of all rule violation codes if not
validate: (value) ->
return []
# Returns true if a given object is valid
#
# @param [Object] value The object to validate
# @return [Boolean] true if the object is valid, false otherwise
isValid: (value) -> @validate(value).length == 0
) | 172155 | ((modules, factory) ->
# Use define if amd compatible define function is defined
if typeof define is 'function' && define.amd
define modules, factory
# Use node require if not
else
module.exports = factory (require m for m in modules)...
)( [], ->
# A rule to validate input fields
# @author <NAME>
class ValidatorRule
# Create a new ValidatorRule. When extending this constructor, set this.options to the default values
# and call super to overwrite all options given as a parameter.
#
# @param [Object] (options) An optional list of options
constructor: (options) ->
@options ?= {}
@setOptions options
# Set the options of this rule.
#
# @param [Object] (options) An optional list of options
setOptions: (options) ->
if options?
for own option, value of options
@options[option] = value
# Return all possible violation codes for this rule.
# @return [Array<String>] An array of all possible violation codes for this rule.
getViolationCodes: -> []
# Validate an object and return a list of codes for all rules it violates
#
# @param [Object] value The value to validate
# @return [Array<String>] [''] if the string is valid, an array of all rule violation codes if not
validate: (value) ->
return []
# Returns true if a given object is valid
#
# @param [Object] value The object to validate
# @return [Boolean] true if the object is valid, false otherwise
isValid: (value) -> @validate(value).length == 0
) | true | ((modules, factory) ->
# Use define if amd compatible define function is defined
if typeof define is 'function' && define.amd
define modules, factory
# Use node require if not
else
module.exports = factory (require m for m in modules)...
)( [], ->
# A rule to validate input fields
# @author PI:NAME:<NAME>END_PI
class ValidatorRule
# Create a new ValidatorRule. When extending this constructor, set this.options to the default values
# and call super to overwrite all options given as a parameter.
#
# @param [Object] (options) An optional list of options
constructor: (options) ->
@options ?= {}
@setOptions options
# Set the options of this rule.
#
# @param [Object] (options) An optional list of options
setOptions: (options) ->
if options?
for own option, value of options
@options[option] = value
# Return all possible violation codes for this rule.
# @return [Array<String>] An array of all possible violation codes for this rule.
getViolationCodes: -> []
# Validate an object and return a list of codes for all rules it violates
#
# @param [Object] value The value to validate
# @return [Array<String>] [''] if the string is valid, an array of all rule violation codes if not
validate: (value) ->
return []
# Returns true if a given object is valid
#
# @param [Object] value The object to validate
# @return [Boolean] true if the object is valid, false otherwise
isValid: (value) -> @validate(value).length == 0
) |
[
{
"context": "ns) for touch devices\n Based on the touch demo by Seb Lee-Delisle <http://seb.ly/>\n \n @class bkcore.controllers.T",
"end": 102,
"score": 0.9983980059623718,
"start": 87,
"tag": "NAME",
"value": "Seb Lee-Delisle"
},
{
"context": "class bkcore.controllers.TouchContr... | webInterface/game/bkcore.coffee/controllers/TouchController.coffee | ploh007/design-project | 1,017 | ###
TouchController (stick + buttons) for touch devices
Based on the touch demo by Seb Lee-Delisle <http://seb.ly/>
@class bkcore.controllers.TouchController
@author Thibaut 'BKcore' Despoulain <http://bkcore.com>
###
class TouchController
@isCompatible: ->
return ('ontouchstart' of document.documentElement);
###
Creates a new TouchController
@param dom DOMElement The element that will listen to touch events
@param stickMargin int The left margin in px for stick detection
@param buttonCallback function Callback for non-stick touches
###
constructor: (@dom, @stickMargin=200, @buttonCallback=null) ->
@active = true
@touches = null
@stickID = -1
@stickPos = new Vec2(0, 0)
@stickStartPos = new Vec2(0, 0)
@stickVector = new Vec2(0, 0)
@dom.addEventListener('touchstart', ((e)=> @touchStart(e)), false)
@dom.addEventListener('touchmove', ((e)=> @touchMove(e)), false)
@dom.addEventListener('touchend', ((e)=> @touchEnd(e)), false)
###
@private
###
touchStart: (event) ->
return if not @active
for touch in event.changedTouches
if @stickID < 0 and touch.clientX < @stickMargin
@stickID = touch.identifier
@stickStartPos.set(touch.clientX, touch.clientY)
@stickPos.copy(@stickStartPos)
@stickVector.set(0, 0)
continue
else
@buttonCallback?(on, touch, event)
@touches = event.touches
false
###
@private
###
touchMove: (event) ->
event.preventDefault()
return if not @active
for touch in event.changedTouches
if @stickID is touch.identifier and touch.clientX < @stickMargin
@stickPos.set(touch.clientX, touch.clientY)
@stickVector.copy(@stickPos).substract(@stickStartPos)
break
@touches = event.touches
false
###
@private
###
touchEnd: (event) ->
return if not @active
@touches = event.touches
for touch in event.changedTouches
if @stickID is touch.identifier
@stickID = -1
@stickVector.set(0, 0)
break
else
@buttonCallback?(off, touch, event)
false
###
Internal class used for vector2
@class Vec2
@private
###
class Vec2
constructor: (@x = 0, @y = 0) ->
substract: (vec) ->
@x -= vec.x
@y -= vec.y
@
copy: (vec) ->
@x = vec.x
@y = vec.y
@
set: (x, y) ->
@x = x
@y = y
@
###
Exports
@package bkcore
###
exports = exports ? @
exports.bkcore ||= {}
exports.bkcore.controllers ||= {}
exports.bkcore.controllers.TouchController = TouchController | 80111 | ###
TouchController (stick + buttons) for touch devices
Based on the touch demo by <NAME> <http://seb.ly/>
@class bkcore.controllers.TouchController
@author <NAME> 'BKcore' <NAME> <http://bkcore.com>
###
class TouchController
@isCompatible: ->
return ('ontouchstart' of document.documentElement);
###
Creates a new TouchController
@param dom DOMElement The element that will listen to touch events
@param stickMargin int The left margin in px for stick detection
@param buttonCallback function Callback for non-stick touches
###
constructor: (@dom, @stickMargin=200, @buttonCallback=null) ->
@active = true
@touches = null
@stickID = -1
@stickPos = new Vec2(0, 0)
@stickStartPos = new Vec2(0, 0)
@stickVector = new Vec2(0, 0)
@dom.addEventListener('touchstart', ((e)=> @touchStart(e)), false)
@dom.addEventListener('touchmove', ((e)=> @touchMove(e)), false)
@dom.addEventListener('touchend', ((e)=> @touchEnd(e)), false)
###
@private
###
touchStart: (event) ->
return if not @active
for touch in event.changedTouches
if @stickID < 0 and touch.clientX < @stickMargin
@stickID = touch.identifier
@stickStartPos.set(touch.clientX, touch.clientY)
@stickPos.copy(@stickStartPos)
@stickVector.set(0, 0)
continue
else
@buttonCallback?(on, touch, event)
@touches = event.touches
false
###
@private
###
touchMove: (event) ->
event.preventDefault()
return if not @active
for touch in event.changedTouches
if @stickID is touch.identifier and touch.clientX < @stickMargin
@stickPos.set(touch.clientX, touch.clientY)
@stickVector.copy(@stickPos).substract(@stickStartPos)
break
@touches = event.touches
false
###
@private
###
touchEnd: (event) ->
return if not @active
@touches = event.touches
for touch in event.changedTouches
if @stickID is touch.identifier
@stickID = -1
@stickVector.set(0, 0)
break
else
@buttonCallback?(off, touch, event)
false
###
Internal class used for vector2
@class Vec2
@private
###
class Vec2
constructor: (@x = 0, @y = 0) ->
substract: (vec) ->
@x -= vec.x
@y -= vec.y
@
copy: (vec) ->
@x = vec.x
@y = vec.y
@
set: (x, y) ->
@x = x
@y = y
@
###
Exports
@package bkcore
###
exports = exports ? @
exports.bkcore ||= {}
exports.bkcore.controllers ||= {}
exports.bkcore.controllers.TouchController = TouchController | true | ###
TouchController (stick + buttons) for touch devices
Based on the touch demo by PI:NAME:<NAME>END_PI <http://seb.ly/>
@class bkcore.controllers.TouchController
@author PI:NAME:<NAME>END_PI 'BKcore' PI:NAME:<NAME>END_PI <http://bkcore.com>
###
class TouchController
@isCompatible: ->
return ('ontouchstart' of document.documentElement);
###
Creates a new TouchController
@param dom DOMElement The element that will listen to touch events
@param stickMargin int The left margin in px for stick detection
@param buttonCallback function Callback for non-stick touches
###
constructor: (@dom, @stickMargin=200, @buttonCallback=null) ->
@active = true
@touches = null
@stickID = -1
@stickPos = new Vec2(0, 0)
@stickStartPos = new Vec2(0, 0)
@stickVector = new Vec2(0, 0)
@dom.addEventListener('touchstart', ((e)=> @touchStart(e)), false)
@dom.addEventListener('touchmove', ((e)=> @touchMove(e)), false)
@dom.addEventListener('touchend', ((e)=> @touchEnd(e)), false)
###
@private
###
touchStart: (event) ->
return if not @active
for touch in event.changedTouches
if @stickID < 0 and touch.clientX < @stickMargin
@stickID = touch.identifier
@stickStartPos.set(touch.clientX, touch.clientY)
@stickPos.copy(@stickStartPos)
@stickVector.set(0, 0)
continue
else
@buttonCallback?(on, touch, event)
@touches = event.touches
false
###
@private
###
touchMove: (event) ->
event.preventDefault()
return if not @active
for touch in event.changedTouches
if @stickID is touch.identifier and touch.clientX < @stickMargin
@stickPos.set(touch.clientX, touch.clientY)
@stickVector.copy(@stickPos).substract(@stickStartPos)
break
@touches = event.touches
false
###
@private
###
touchEnd: (event) ->
return if not @active
@touches = event.touches
for touch in event.changedTouches
if @stickID is touch.identifier
@stickID = -1
@stickVector.set(0, 0)
break
else
@buttonCallback?(off, touch, event)
false
###
Internal class used for vector2
@class Vec2
@private
###
class Vec2
constructor: (@x = 0, @y = 0) ->
substract: (vec) ->
@x -= vec.x
@y -= vec.y
@
copy: (vec) ->
@x = vec.x
@y = vec.y
@
set: (x, y) ->
@x = x
@y = y
@
###
Exports
@package bkcore
###
exports = exports ? @
exports.bkcore ||= {}
exports.bkcore.controllers ||= {}
exports.bkcore.controllers.TouchController = TouchController |
[
{
"context": "ghlighting in JavaScript\n#Copyright (C) 2007, 2008 gnombat@users.sourceforge.net\n#License: http://shjs.sourceforge.net/doc/gplv3.h",
"end": 99,
"score": 0.9998972415924072,
"start": 70,
"tag": "EMAIL",
"value": "gnombat@users.sourceforge.net"
}
] | doc/sh_main.coffee | lxe/io.coffee | 0 | #
#SHJS - Syntax Highlighting in JavaScript
#Copyright (C) 2007, 2008 gnombat@users.sourceforge.net
#License: http://shjs.sourceforge.net/doc/gplv3.html
#
sh_isEmailAddress = (url) ->
return false if /^mailto:/.test(url)
url.indexOf("@") isnt -1
sh_setHref = (tags, numTags, inputString) ->
url = inputString.substring(tags[numTags - 2].pos, tags[numTags - 1].pos)
url = url.substr(1, url.length - 2) if url.length >= 2 and url.charAt(0) is "<" and url.charAt(url.length - 1) is ">"
url = "mailto:" + url if sh_isEmailAddress(url)
tags[numTags - 2].node.href = url
return
#
#Konqueror has a bug where the regular expression /$/g will not match at the end
#of a line more than once:
#
# var regex = /$/g;
# var match;
#
# var line = '1234567890';
# regex.lastIndex = 10;
# match = regex.exec(line);
#
# var line2 = 'abcde';
# regex.lastIndex = 5;
# match = regex.exec(line2); // fails
#
sh_konquerorExec = (s) ->
result = [""]
result.index = s.length
result.input = s
result
###*
Highlights all elements containing source code in a text string. The return
value is an array of objects, each representing an HTML start or end tag. Each
object has a property named pos, which is an integer representing the text
offset of the tag. Every start tag also has a property named node, which is the
DOM element started by the tag. End tags do not have this property.
@param inputString a text string
@param language a language definition object
@return an array of tag objects
###
sh_highlightString = (inputString, language) ->
if /Konqueror/.test(navigator.userAgent)
unless language.konquered
s = 0
while s < language.length
p = 0
while p < language[s].length
r = language[s][p][0]
r.exec = sh_konquerorExec if r.source is "$"
p++
s++
language.konquered = true
a = document.createElement("a")
span = document.createElement("span")
# the result
tags = []
numTags = 0
# each element is a pattern object from language
patternStack = []
# the current position within inputString
pos = 0
# the name of the current style, or null if there is no current style
currentStyle = null
output = (s, style) ->
length = s.length
# this is more than just an optimization - we don't want to output empty <span></span> elements
return if length is 0
unless style
stackLength = patternStack.length
if stackLength isnt 0
pattern = patternStack[stackLength - 1]
# check whether this is a state or an environment
# it's not a state - it's an environment; use the style for this environment
style = pattern[1] unless pattern[3]
if currentStyle isnt style
if currentStyle
tags[numTags++] = pos: pos
sh_setHref tags, numTags, inputString if currentStyle is "sh_url"
if style
clone = undefined
if style is "sh_url"
clone = a.cloneNode(false)
else
clone = span.cloneNode(false)
clone.className = style
tags[numTags++] =
node: clone
pos: pos
pos += length
currentStyle = style
return
endOfLinePattern = /\r\n|\r|\n/g
endOfLinePattern.lastIndex = 0
inputStringLength = inputString.length
while pos < inputStringLength
start = pos
end = undefined
startOfNextLine = undefined
endOfLineMatch = endOfLinePattern.exec(inputString)
if endOfLineMatch is null
end = inputStringLength
startOfNextLine = inputStringLength
else
end = endOfLineMatch.index
startOfNextLine = endOfLinePattern.lastIndex
line = inputString.substring(start, end)
matchCache = []
loop
posWithinLine = pos - start
stateIndex = undefined
stackLength = patternStack.length
if stackLength is 0
stateIndex = 0
else
# get the next state
stateIndex = patternStack[stackLength - 1][2]
state = language[stateIndex]
numPatterns = state.length
mc = matchCache[stateIndex]
mc = matchCache[stateIndex] = [] unless mc
bestMatch = null
bestPatternIndex = -1
i = 0
while i < numPatterns
match = undefined
if i < mc.length and (mc[i] is null or posWithinLine <= mc[i].index)
match = mc[i]
else
regex = state[i][0]
regex.lastIndex = posWithinLine
match = regex.exec(line)
mc[i] = match
if match isnt null and (bestMatch is null or match.index < bestMatch.index)
bestMatch = match
bestPatternIndex = i
break if match.index is posWithinLine
i++
if bestMatch is null
output line.substring(posWithinLine), null
break
else
# got a match
output line.substring(posWithinLine, bestMatch.index), null if bestMatch.index > posWithinLine
pattern = state[bestPatternIndex]
newStyle = pattern[1]
matchedString = undefined
if newStyle instanceof Array
subexpression = 0
while subexpression < newStyle.length
matchedString = bestMatch[subexpression + 1]
output matchedString, newStyle[subexpression]
subexpression++
else
matchedString = bestMatch[0]
output matchedString, newStyle
switch pattern[2]
# do nothing
when -1, -2
# exit
patternStack.pop()
when -3
# exitall
patternStack.length = 0
else
# this was the start of a delimited pattern or a state/environment
patternStack.push pattern
# end of the line
if currentStyle
tags[numTags++] = pos: pos
sh_setHref tags, numTags, inputString if currentStyle is "sh_url"
currentStyle = null
pos = startOfNextLine
tags
#//////////////////////////////////////////////////////////////////////////////
# DOM-dependent functions
sh_getClasses = (element) ->
result = []
htmlClass = element.className
if htmlClass and htmlClass.length > 0
htmlClasses = htmlClass.split(" ")
i = 0
while i < htmlClasses.length
result.push htmlClasses[i] if htmlClasses[i].length > 0
i++
result
sh_addClass = (element, name) ->
htmlClasses = sh_getClasses(element)
i = 0
while i < htmlClasses.length
return if name.toLowerCase() is htmlClasses[i].toLowerCase()
i++
htmlClasses.push name
element.className = htmlClasses.join(" ")
return
###*
Extracts the tags from an HTML DOM NodeList.
@param nodeList a DOM NodeList
@param result an object with text, tags and pos properties
###
sh_extractTagsFromNodeList = (nodeList, result) ->
length = nodeList.length
i = 0
while i < length
node = nodeList.item(i)
switch node.nodeType
when 1
if node.nodeName.toLowerCase() is "br"
terminator = undefined
if /MSIE/.test(navigator.userAgent)
terminator = "\r"
else
terminator = "\n"
result.text.push terminator
result.pos++
else
result.tags.push
node: node.cloneNode(false)
pos: result.pos
sh_extractTagsFromNodeList node.childNodes, result
result.tags.push pos: result.pos
when 3, 4
result.text.push node.data
result.pos += node.length
i++
return
###*
Extracts the tags from the text of an HTML element. The extracted tags will be
returned as an array of tag objects. See sh_highlightString for the format of
the tag objects.
@param element a DOM element
@param tags an empty array; the extracted tag objects will be returned in it
@return the text of the element
@see sh_highlightString
###
sh_extractTags = (element, tags) ->
result = {}
result.text = []
result.tags = tags
result.pos = 0
sh_extractTagsFromNodeList element.childNodes, result
result.text.join ""
###*
Merges the original tags from an element with the tags produced by highlighting.
@param originalTags an array containing the original tags
@param highlightTags an array containing the highlighting tags - these must not overlap
@result an array containing the merged tags
###
sh_mergeTags = (originalTags, highlightTags) ->
numOriginalTags = originalTags.length
return highlightTags if numOriginalTags is 0
numHighlightTags = highlightTags.length
return originalTags if numHighlightTags is 0
result = []
originalIndex = 0
highlightIndex = 0
while originalIndex < numOriginalTags and highlightIndex < numHighlightTags
originalTag = originalTags[originalIndex]
highlightTag = highlightTags[highlightIndex]
if originalTag.pos <= highlightTag.pos
result.push originalTag
originalIndex++
else
result.push highlightTag
if highlightTags[highlightIndex + 1].pos <= originalTag.pos
highlightIndex++
result.push highlightTags[highlightIndex]
highlightIndex++
else
# new end tag
result.push pos: originalTag.pos
# new start tag
highlightTags[highlightIndex] =
node: highlightTag.node.cloneNode(false)
pos: originalTag.pos
while originalIndex < numOriginalTags
result.push originalTags[originalIndex]
originalIndex++
while highlightIndex < numHighlightTags
result.push highlightTags[highlightIndex]
highlightIndex++
result
###*
Inserts tags into text.
@param tags an array of tag objects
@param text a string representing the text
@return a DOM DocumentFragment representing the resulting HTML
###
sh_insertTags = (tags, text) ->
doc = document
result = document.createDocumentFragment()
tagIndex = 0
numTags = tags.length
textPos = 0
textLength = text.length
currentNode = result
# output one tag or text node every iteration
while textPos < textLength or tagIndex < numTags
tag = undefined
tagPos = undefined
if tagIndex < numTags
tag = tags[tagIndex]
tagPos = tag.pos
else
tagPos = textLength
if tagPos <= textPos
# output the tag
if tag.node
# start tag
newNode = tag.node
currentNode.appendChild newNode
currentNode = newNode
else
# end tag
currentNode = currentNode.parentNode
tagIndex++
else
# output text
currentNode.appendChild doc.createTextNode(text.substring(textPos, tagPos))
textPos = tagPos
result
###*
Highlights an element containing source code. Upon completion of this function,
the element will have been placed in the "sh_sourceCode" class.
@param element a DOM <pre> element containing the source code to be highlighted
@param language a language definition object
###
sh_highlightElement = (element, language) ->
sh_addClass element, "sh_sourceCode"
originalTags = []
inputString = sh_extractTags(element, originalTags)
highlightTags = sh_highlightString(inputString, language)
tags = sh_mergeTags(originalTags, highlightTags)
documentFragment = sh_insertTags(tags, inputString)
element.removeChild element.firstChild while element.hasChildNodes()
element.appendChild documentFragment
return
sh_getXMLHttpRequest = ->
if window.ActiveXObject
return new ActiveXObject("Msxml2.XMLHTTP")
else return new XMLHttpRequest() if window.XMLHttpRequest
throw "No XMLHttpRequest implementation available"return
sh_load = (language, element, prefix, suffix) ->
if language of sh_requests
sh_requests[language].push element
return
sh_requests[language] = [element]
request = sh_getXMLHttpRequest()
url = prefix + "sh_" + language + suffix
request.open "GET", url, true
request.onreadystatechange = ->
if request.readyState is 4
try
if not request.status or request.status is 200
eval request.responseText
elements = sh_requests[language]
i = 0
while i < elements.length
sh_highlightElement elements[i], sh_languages[language]
i++
else
throw "HTTP error: status " + request.status
finally
request = null
return
request.send null
return
###*
Highlights all elements containing source code on the current page. Elements
containing source code must be "pre" elements with a "class" attribute of
"sh_LANGUAGE", where LANGUAGE is a valid language identifier; e.g., "sh_java"
identifies the element as containing "java" language source code.
###
highlight = (prefix, suffix, tag) ->
nodeList = document.getElementsByTagName(tag)
i = 0
while i < nodeList.length
element = nodeList.item(i)
htmlClasses = sh_getClasses(element)
highlighted = false
donthighlight = false
j = 0
while j < htmlClasses.length
htmlClass = htmlClasses[j].toLowerCase()
if htmlClass is "sh_none"
donthighlight = true
continue
if htmlClass.substr(0, 3) is "sh_"
language = htmlClass.substring(3)
if language of sh_languages
sh_highlightElement element, sh_languages[language]
highlighted = true
else if typeof (prefix) is "string" and typeof (suffix) is "string"
sh_load language, element, prefix, suffix
else
throw "Found <" + tag + "> element with class=\"" + htmlClass + "\", but no such language exists"
break
j++
sh_highlightElement element, sh_languages["javascript"] if highlighted is false and donthighlight is false
i++
return
sh_highlightDocument = (prefix, suffix) ->
highlight prefix, suffix, "tt"
highlight prefix, suffix, "code"
highlight prefix, suffix, "pre"
return
@sh_languages = {} unless @sh_languages
sh_requests = {}
| 22531 | #
#SHJS - Syntax Highlighting in JavaScript
#Copyright (C) 2007, 2008 <EMAIL>
#License: http://shjs.sourceforge.net/doc/gplv3.html
#
sh_isEmailAddress = (url) ->
return false if /^mailto:/.test(url)
url.indexOf("@") isnt -1
sh_setHref = (tags, numTags, inputString) ->
url = inputString.substring(tags[numTags - 2].pos, tags[numTags - 1].pos)
url = url.substr(1, url.length - 2) if url.length >= 2 and url.charAt(0) is "<" and url.charAt(url.length - 1) is ">"
url = "mailto:" + url if sh_isEmailAddress(url)
tags[numTags - 2].node.href = url
return
#
#Konqueror has a bug where the regular expression /$/g will not match at the end
#of a line more than once:
#
# var regex = /$/g;
# var match;
#
# var line = '1234567890';
# regex.lastIndex = 10;
# match = regex.exec(line);
#
# var line2 = 'abcde';
# regex.lastIndex = 5;
# match = regex.exec(line2); // fails
#
sh_konquerorExec = (s) ->
result = [""]
result.index = s.length
result.input = s
result
###*
Highlights all elements containing source code in a text string. The return
value is an array of objects, each representing an HTML start or end tag. Each
object has a property named pos, which is an integer representing the text
offset of the tag. Every start tag also has a property named node, which is the
DOM element started by the tag. End tags do not have this property.
@param inputString a text string
@param language a language definition object
@return an array of tag objects
###
sh_highlightString = (inputString, language) ->
if /Konqueror/.test(navigator.userAgent)
unless language.konquered
s = 0
while s < language.length
p = 0
while p < language[s].length
r = language[s][p][0]
r.exec = sh_konquerorExec if r.source is "$"
p++
s++
language.konquered = true
a = document.createElement("a")
span = document.createElement("span")
# the result
tags = []
numTags = 0
# each element is a pattern object from language
patternStack = []
# the current position within inputString
pos = 0
# the name of the current style, or null if there is no current style
currentStyle = null
output = (s, style) ->
length = s.length
# this is more than just an optimization - we don't want to output empty <span></span> elements
return if length is 0
unless style
stackLength = patternStack.length
if stackLength isnt 0
pattern = patternStack[stackLength - 1]
# check whether this is a state or an environment
# it's not a state - it's an environment; use the style for this environment
style = pattern[1] unless pattern[3]
if currentStyle isnt style
if currentStyle
tags[numTags++] = pos: pos
sh_setHref tags, numTags, inputString if currentStyle is "sh_url"
if style
clone = undefined
if style is "sh_url"
clone = a.cloneNode(false)
else
clone = span.cloneNode(false)
clone.className = style
tags[numTags++] =
node: clone
pos: pos
pos += length
currentStyle = style
return
endOfLinePattern = /\r\n|\r|\n/g
endOfLinePattern.lastIndex = 0
inputStringLength = inputString.length
while pos < inputStringLength
start = pos
end = undefined
startOfNextLine = undefined
endOfLineMatch = endOfLinePattern.exec(inputString)
if endOfLineMatch is null
end = inputStringLength
startOfNextLine = inputStringLength
else
end = endOfLineMatch.index
startOfNextLine = endOfLinePattern.lastIndex
line = inputString.substring(start, end)
matchCache = []
loop
posWithinLine = pos - start
stateIndex = undefined
stackLength = patternStack.length
if stackLength is 0
stateIndex = 0
else
# get the next state
stateIndex = patternStack[stackLength - 1][2]
state = language[stateIndex]
numPatterns = state.length
mc = matchCache[stateIndex]
mc = matchCache[stateIndex] = [] unless mc
bestMatch = null
bestPatternIndex = -1
i = 0
while i < numPatterns
match = undefined
if i < mc.length and (mc[i] is null or posWithinLine <= mc[i].index)
match = mc[i]
else
regex = state[i][0]
regex.lastIndex = posWithinLine
match = regex.exec(line)
mc[i] = match
if match isnt null and (bestMatch is null or match.index < bestMatch.index)
bestMatch = match
bestPatternIndex = i
break if match.index is posWithinLine
i++
if bestMatch is null
output line.substring(posWithinLine), null
break
else
# got a match
output line.substring(posWithinLine, bestMatch.index), null if bestMatch.index > posWithinLine
pattern = state[bestPatternIndex]
newStyle = pattern[1]
matchedString = undefined
if newStyle instanceof Array
subexpression = 0
while subexpression < newStyle.length
matchedString = bestMatch[subexpression + 1]
output matchedString, newStyle[subexpression]
subexpression++
else
matchedString = bestMatch[0]
output matchedString, newStyle
switch pattern[2]
# do nothing
when -1, -2
# exit
patternStack.pop()
when -3
# exitall
patternStack.length = 0
else
# this was the start of a delimited pattern or a state/environment
patternStack.push pattern
# end of the line
if currentStyle
tags[numTags++] = pos: pos
sh_setHref tags, numTags, inputString if currentStyle is "sh_url"
currentStyle = null
pos = startOfNextLine
tags
#//////////////////////////////////////////////////////////////////////////////
# DOM-dependent functions
sh_getClasses = (element) ->
result = []
htmlClass = element.className
if htmlClass and htmlClass.length > 0
htmlClasses = htmlClass.split(" ")
i = 0
while i < htmlClasses.length
result.push htmlClasses[i] if htmlClasses[i].length > 0
i++
result
sh_addClass = (element, name) ->
htmlClasses = sh_getClasses(element)
i = 0
while i < htmlClasses.length
return if name.toLowerCase() is htmlClasses[i].toLowerCase()
i++
htmlClasses.push name
element.className = htmlClasses.join(" ")
return
###*
Extracts the tags from an HTML DOM NodeList.
@param nodeList a DOM NodeList
@param result an object with text, tags and pos properties
###
sh_extractTagsFromNodeList = (nodeList, result) ->
length = nodeList.length
i = 0
while i < length
node = nodeList.item(i)
switch node.nodeType
when 1
if node.nodeName.toLowerCase() is "br"
terminator = undefined
if /MSIE/.test(navigator.userAgent)
terminator = "\r"
else
terminator = "\n"
result.text.push terminator
result.pos++
else
result.tags.push
node: node.cloneNode(false)
pos: result.pos
sh_extractTagsFromNodeList node.childNodes, result
result.tags.push pos: result.pos
when 3, 4
result.text.push node.data
result.pos += node.length
i++
return
###*
Extracts the tags from the text of an HTML element. The extracted tags will be
returned as an array of tag objects. See sh_highlightString for the format of
the tag objects.
@param element a DOM element
@param tags an empty array; the extracted tag objects will be returned in it
@return the text of the element
@see sh_highlightString
###
sh_extractTags = (element, tags) ->
result = {}
result.text = []
result.tags = tags
result.pos = 0
sh_extractTagsFromNodeList element.childNodes, result
result.text.join ""
###*
Merges the original tags from an element with the tags produced by highlighting.
@param originalTags an array containing the original tags
@param highlightTags an array containing the highlighting tags - these must not overlap
@result an array containing the merged tags
###
sh_mergeTags = (originalTags, highlightTags) ->
numOriginalTags = originalTags.length
return highlightTags if numOriginalTags is 0
numHighlightTags = highlightTags.length
return originalTags if numHighlightTags is 0
result = []
originalIndex = 0
highlightIndex = 0
while originalIndex < numOriginalTags and highlightIndex < numHighlightTags
originalTag = originalTags[originalIndex]
highlightTag = highlightTags[highlightIndex]
if originalTag.pos <= highlightTag.pos
result.push originalTag
originalIndex++
else
result.push highlightTag
if highlightTags[highlightIndex + 1].pos <= originalTag.pos
highlightIndex++
result.push highlightTags[highlightIndex]
highlightIndex++
else
# new end tag
result.push pos: originalTag.pos
# new start tag
highlightTags[highlightIndex] =
node: highlightTag.node.cloneNode(false)
pos: originalTag.pos
while originalIndex < numOriginalTags
result.push originalTags[originalIndex]
originalIndex++
while highlightIndex < numHighlightTags
result.push highlightTags[highlightIndex]
highlightIndex++
result
###*
Inserts tags into text.
@param tags an array of tag objects
@param text a string representing the text
@return a DOM DocumentFragment representing the resulting HTML
###
sh_insertTags = (tags, text) ->
doc = document
result = document.createDocumentFragment()
tagIndex = 0
numTags = tags.length
textPos = 0
textLength = text.length
currentNode = result
# output one tag or text node every iteration
while textPos < textLength or tagIndex < numTags
tag = undefined
tagPos = undefined
if tagIndex < numTags
tag = tags[tagIndex]
tagPos = tag.pos
else
tagPos = textLength
if tagPos <= textPos
# output the tag
if tag.node
# start tag
newNode = tag.node
currentNode.appendChild newNode
currentNode = newNode
else
# end tag
currentNode = currentNode.parentNode
tagIndex++
else
# output text
currentNode.appendChild doc.createTextNode(text.substring(textPos, tagPos))
textPos = tagPos
result
###*
Highlights an element containing source code. Upon completion of this function,
the element will have been placed in the "sh_sourceCode" class.
@param element a DOM <pre> element containing the source code to be highlighted
@param language a language definition object
###
sh_highlightElement = (element, language) ->
sh_addClass element, "sh_sourceCode"
originalTags = []
inputString = sh_extractTags(element, originalTags)
highlightTags = sh_highlightString(inputString, language)
tags = sh_mergeTags(originalTags, highlightTags)
documentFragment = sh_insertTags(tags, inputString)
element.removeChild element.firstChild while element.hasChildNodes()
element.appendChild documentFragment
return
sh_getXMLHttpRequest = ->
if window.ActiveXObject
return new ActiveXObject("Msxml2.XMLHTTP")
else return new XMLHttpRequest() if window.XMLHttpRequest
throw "No XMLHttpRequest implementation available"return
sh_load = (language, element, prefix, suffix) ->
if language of sh_requests
sh_requests[language].push element
return
sh_requests[language] = [element]
request = sh_getXMLHttpRequest()
url = prefix + "sh_" + language + suffix
request.open "GET", url, true
request.onreadystatechange = ->
if request.readyState is 4
try
if not request.status or request.status is 200
eval request.responseText
elements = sh_requests[language]
i = 0
while i < elements.length
sh_highlightElement elements[i], sh_languages[language]
i++
else
throw "HTTP error: status " + request.status
finally
request = null
return
request.send null
return
###*
Highlights all elements containing source code on the current page. Elements
containing source code must be "pre" elements with a "class" attribute of
"sh_LANGUAGE", where LANGUAGE is a valid language identifier; e.g., "sh_java"
identifies the element as containing "java" language source code.
###
highlight = (prefix, suffix, tag) ->
nodeList = document.getElementsByTagName(tag)
i = 0
while i < nodeList.length
element = nodeList.item(i)
htmlClasses = sh_getClasses(element)
highlighted = false
donthighlight = false
j = 0
while j < htmlClasses.length
htmlClass = htmlClasses[j].toLowerCase()
if htmlClass is "sh_none"
donthighlight = true
continue
if htmlClass.substr(0, 3) is "sh_"
language = htmlClass.substring(3)
if language of sh_languages
sh_highlightElement element, sh_languages[language]
highlighted = true
else if typeof (prefix) is "string" and typeof (suffix) is "string"
sh_load language, element, prefix, suffix
else
throw "Found <" + tag + "> element with class=\"" + htmlClass + "\", but no such language exists"
break
j++
sh_highlightElement element, sh_languages["javascript"] if highlighted is false and donthighlight is false
i++
return
sh_highlightDocument = (prefix, suffix) ->
highlight prefix, suffix, "tt"
highlight prefix, suffix, "code"
highlight prefix, suffix, "pre"
return
@sh_languages = {} unless @sh_languages
sh_requests = {}
| true | #
#SHJS - Syntax Highlighting in JavaScript
#Copyright (C) 2007, 2008 PI:EMAIL:<EMAIL>END_PI
#License: http://shjs.sourceforge.net/doc/gplv3.html
#
sh_isEmailAddress = (url) ->
return false if /^mailto:/.test(url)
url.indexOf("@") isnt -1
sh_setHref = (tags, numTags, inputString) ->
url = inputString.substring(tags[numTags - 2].pos, tags[numTags - 1].pos)
url = url.substr(1, url.length - 2) if url.length >= 2 and url.charAt(0) is "<" and url.charAt(url.length - 1) is ">"
url = "mailto:" + url if sh_isEmailAddress(url)
tags[numTags - 2].node.href = url
return
#
#Konqueror has a bug where the regular expression /$/g will not match at the end
#of a line more than once:
#
# var regex = /$/g;
# var match;
#
# var line = '1234567890';
# regex.lastIndex = 10;
# match = regex.exec(line);
#
# var line2 = 'abcde';
# regex.lastIndex = 5;
# match = regex.exec(line2); // fails
#
sh_konquerorExec = (s) ->
result = [""]
result.index = s.length
result.input = s
result
###*
Highlights all elements containing source code in a text string. The return
value is an array of objects, each representing an HTML start or end tag. Each
object has a property named pos, which is an integer representing the text
offset of the tag. Every start tag also has a property named node, which is the
DOM element started by the tag. End tags do not have this property.
@param inputString a text string
@param language a language definition object
@return an array of tag objects
###
sh_highlightString = (inputString, language) ->
if /Konqueror/.test(navigator.userAgent)
unless language.konquered
s = 0
while s < language.length
p = 0
while p < language[s].length
r = language[s][p][0]
r.exec = sh_konquerorExec if r.source is "$"
p++
s++
language.konquered = true
a = document.createElement("a")
span = document.createElement("span")
# the result
tags = []
numTags = 0
# each element is a pattern object from language
patternStack = []
# the current position within inputString
pos = 0
# the name of the current style, or null if there is no current style
currentStyle = null
output = (s, style) ->
length = s.length
# this is more than just an optimization - we don't want to output empty <span></span> elements
return if length is 0
unless style
stackLength = patternStack.length
if stackLength isnt 0
pattern = patternStack[stackLength - 1]
# check whether this is a state or an environment
# it's not a state - it's an environment; use the style for this environment
style = pattern[1] unless pattern[3]
if currentStyle isnt style
if currentStyle
tags[numTags++] = pos: pos
sh_setHref tags, numTags, inputString if currentStyle is "sh_url"
if style
clone = undefined
if style is "sh_url"
clone = a.cloneNode(false)
else
clone = span.cloneNode(false)
clone.className = style
tags[numTags++] =
node: clone
pos: pos
pos += length
currentStyle = style
return
endOfLinePattern = /\r\n|\r|\n/g
endOfLinePattern.lastIndex = 0
inputStringLength = inputString.length
while pos < inputStringLength
start = pos
end = undefined
startOfNextLine = undefined
endOfLineMatch = endOfLinePattern.exec(inputString)
if endOfLineMatch is null
end = inputStringLength
startOfNextLine = inputStringLength
else
end = endOfLineMatch.index
startOfNextLine = endOfLinePattern.lastIndex
line = inputString.substring(start, end)
matchCache = []
loop
posWithinLine = pos - start
stateIndex = undefined
stackLength = patternStack.length
if stackLength is 0
stateIndex = 0
else
# get the next state
stateIndex = patternStack[stackLength - 1][2]
state = language[stateIndex]
numPatterns = state.length
mc = matchCache[stateIndex]
mc = matchCache[stateIndex] = [] unless mc
bestMatch = null
bestPatternIndex = -1
i = 0
while i < numPatterns
match = undefined
if i < mc.length and (mc[i] is null or posWithinLine <= mc[i].index)
match = mc[i]
else
regex = state[i][0]
regex.lastIndex = posWithinLine
match = regex.exec(line)
mc[i] = match
if match isnt null and (bestMatch is null or match.index < bestMatch.index)
bestMatch = match
bestPatternIndex = i
break if match.index is posWithinLine
i++
if bestMatch is null
output line.substring(posWithinLine), null
break
else
# got a match
output line.substring(posWithinLine, bestMatch.index), null if bestMatch.index > posWithinLine
pattern = state[bestPatternIndex]
newStyle = pattern[1]
matchedString = undefined
if newStyle instanceof Array
subexpression = 0
while subexpression < newStyle.length
matchedString = bestMatch[subexpression + 1]
output matchedString, newStyle[subexpression]
subexpression++
else
matchedString = bestMatch[0]
output matchedString, newStyle
switch pattern[2]
# do nothing
when -1, -2
# exit
patternStack.pop()
when -3
# exitall
patternStack.length = 0
else
# this was the start of a delimited pattern or a state/environment
patternStack.push pattern
# end of the line
if currentStyle
tags[numTags++] = pos: pos
sh_setHref tags, numTags, inputString if currentStyle is "sh_url"
currentStyle = null
pos = startOfNextLine
tags
#//////////////////////////////////////////////////////////////////////////////
# DOM-dependent functions
sh_getClasses = (element) ->
result = []
htmlClass = element.className
if htmlClass and htmlClass.length > 0
htmlClasses = htmlClass.split(" ")
i = 0
while i < htmlClasses.length
result.push htmlClasses[i] if htmlClasses[i].length > 0
i++
result
sh_addClass = (element, name) ->
htmlClasses = sh_getClasses(element)
i = 0
while i < htmlClasses.length
return if name.toLowerCase() is htmlClasses[i].toLowerCase()
i++
htmlClasses.push name
element.className = htmlClasses.join(" ")
return
###*
Extracts the tags from an HTML DOM NodeList.
@param nodeList a DOM NodeList
@param result an object with text, tags and pos properties
###
sh_extractTagsFromNodeList = (nodeList, result) ->
length = nodeList.length
i = 0
while i < length
node = nodeList.item(i)
switch node.nodeType
when 1
if node.nodeName.toLowerCase() is "br"
terminator = undefined
if /MSIE/.test(navigator.userAgent)
terminator = "\r"
else
terminator = "\n"
result.text.push terminator
result.pos++
else
result.tags.push
node: node.cloneNode(false)
pos: result.pos
sh_extractTagsFromNodeList node.childNodes, result
result.tags.push pos: result.pos
when 3, 4
result.text.push node.data
result.pos += node.length
i++
return
###*
Extracts the tags from the text of an HTML element. The extracted tags will be
returned as an array of tag objects. See sh_highlightString for the format of
the tag objects.
@param element a DOM element
@param tags an empty array; the extracted tag objects will be returned in it
@return the text of the element
@see sh_highlightString
###
sh_extractTags = (element, tags) ->
result = {}
result.text = []
result.tags = tags
result.pos = 0
sh_extractTagsFromNodeList element.childNodes, result
result.text.join ""
###*
Merges the original tags from an element with the tags produced by highlighting.
@param originalTags an array containing the original tags
@param highlightTags an array containing the highlighting tags - these must not overlap
@result an array containing the merged tags
###
sh_mergeTags = (originalTags, highlightTags) ->
numOriginalTags = originalTags.length
return highlightTags if numOriginalTags is 0
numHighlightTags = highlightTags.length
return originalTags if numHighlightTags is 0
result = []
originalIndex = 0
highlightIndex = 0
while originalIndex < numOriginalTags and highlightIndex < numHighlightTags
originalTag = originalTags[originalIndex]
highlightTag = highlightTags[highlightIndex]
if originalTag.pos <= highlightTag.pos
result.push originalTag
originalIndex++
else
result.push highlightTag
if highlightTags[highlightIndex + 1].pos <= originalTag.pos
highlightIndex++
result.push highlightTags[highlightIndex]
highlightIndex++
else
# new end tag
result.push pos: originalTag.pos
# new start tag
highlightTags[highlightIndex] =
node: highlightTag.node.cloneNode(false)
pos: originalTag.pos
while originalIndex < numOriginalTags
result.push originalTags[originalIndex]
originalIndex++
while highlightIndex < numHighlightTags
result.push highlightTags[highlightIndex]
highlightIndex++
result
###*
Inserts tags into text.
@param tags an array of tag objects
@param text a string representing the text
@return a DOM DocumentFragment representing the resulting HTML
###
sh_insertTags = (tags, text) ->
doc = document
result = document.createDocumentFragment()
tagIndex = 0
numTags = tags.length
textPos = 0
textLength = text.length
currentNode = result
# output one tag or text node every iteration
while textPos < textLength or tagIndex < numTags
tag = undefined
tagPos = undefined
if tagIndex < numTags
tag = tags[tagIndex]
tagPos = tag.pos
else
tagPos = textLength
if tagPos <= textPos
# output the tag
if tag.node
# start tag
newNode = tag.node
currentNode.appendChild newNode
currentNode = newNode
else
# end tag
currentNode = currentNode.parentNode
tagIndex++
else
# output text
currentNode.appendChild doc.createTextNode(text.substring(textPos, tagPos))
textPos = tagPos
result
###*
Highlights an element containing source code. Upon completion of this function,
the element will have been placed in the "sh_sourceCode" class.
@param element a DOM <pre> element containing the source code to be highlighted
@param language a language definition object
###
sh_highlightElement = (element, language) ->
sh_addClass element, "sh_sourceCode"
originalTags = []
inputString = sh_extractTags(element, originalTags)
highlightTags = sh_highlightString(inputString, language)
tags = sh_mergeTags(originalTags, highlightTags)
documentFragment = sh_insertTags(tags, inputString)
element.removeChild element.firstChild while element.hasChildNodes()
element.appendChild documentFragment
return
sh_getXMLHttpRequest = ->
if window.ActiveXObject
return new ActiveXObject("Msxml2.XMLHTTP")
else return new XMLHttpRequest() if window.XMLHttpRequest
throw "No XMLHttpRequest implementation available"return
sh_load = (language, element, prefix, suffix) ->
if language of sh_requests
sh_requests[language].push element
return
sh_requests[language] = [element]
request = sh_getXMLHttpRequest()
url = prefix + "sh_" + language + suffix
request.open "GET", url, true
request.onreadystatechange = ->
if request.readyState is 4
try
if not request.status or request.status is 200
eval request.responseText
elements = sh_requests[language]
i = 0
while i < elements.length
sh_highlightElement elements[i], sh_languages[language]
i++
else
throw "HTTP error: status " + request.status
finally
request = null
return
request.send null
return
###*
Highlights all elements containing source code on the current page. Elements
containing source code must be "pre" elements with a "class" attribute of
"sh_LANGUAGE", where LANGUAGE is a valid language identifier; e.g., "sh_java"
identifies the element as containing "java" language source code.
###
highlight = (prefix, suffix, tag) ->
nodeList = document.getElementsByTagName(tag)
i = 0
while i < nodeList.length
element = nodeList.item(i)
htmlClasses = sh_getClasses(element)
highlighted = false
donthighlight = false
j = 0
while j < htmlClasses.length
htmlClass = htmlClasses[j].toLowerCase()
if htmlClass is "sh_none"
donthighlight = true
continue
if htmlClass.substr(0, 3) is "sh_"
language = htmlClass.substring(3)
if language of sh_languages
sh_highlightElement element, sh_languages[language]
highlighted = true
else if typeof (prefix) is "string" and typeof (suffix) is "string"
sh_load language, element, prefix, suffix
else
throw "Found <" + tag + "> element with class=\"" + htmlClass + "\", but no such language exists"
break
j++
sh_highlightElement element, sh_languages["javascript"] if highlighted is false and donthighlight is false
i++
return
sh_highlightDocument = (prefix, suffix) ->
highlight prefix, suffix, "tt"
highlight prefix, suffix, "code"
highlight prefix, suffix, "pre"
return
@sh_languages = {} unless @sh_languages
sh_requests = {}
|
[
{
"context": "#Copyright [2011] [Ali Ok - aliok AT apache org]\n#\n#Licensed under the Apac",
"end": 25,
"score": 0.9998403191566467,
"start": 19,
"tag": "NAME",
"value": "Ali Ok"
}
] | flashcards-ui/coffee/aliok/flashcards/flashcards.coffee | aliok/flashcards | 6 | #Copyright [2011] [Ali Ok - aliok AT apache org]
#
#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.
###
if there are no words yet, and the app is offline, then all buttons are shown!
show current set number on the ui
allow fetching a set by number
next word button, previous word button
score mode / training mode
###
class Context
#adding time in milliseconds for breaking the browser cache.
#we can of course do it with modifying JQuery.getJson function's options,
#but in that case we will lose the nice syntax of it and use JQuery.ajax instead
dataServiceUrl: () ->
key = localStorage['userKey']
time = new Date().getTime()
if key
val = "http://the-flashcards-data-service.appspot.com/data?userKey=#{ key }&time=#{ time }&callback=?"
else
val = "http://the-flashcards-data-service.appspot.com/data?time=#{ time }&callback=?"
class View
registerPageCreateHandler :(callback)->$('#mainPage' ).live 'pageinit', callback
registerAnswerDerButtonHandler :(callback)->$('#answerDer').bind 'click', callback
registerAnswerDieButtonHandler :(callback)->$('#answerDie').bind 'click', callback
registerAnswerDasButtonHandler :(callback)->$('#answerDas').bind 'click', callback
registerNextWordButtonHandler :(callback)->$('#nextWord' ).bind 'click', callback
registerNextSetButtonHandler : (callback)->$('#nextSet' ).bind 'click', ()=>
$('#nextSet').die 'click'
callback()
setWord :(word)-> $('#word').html word
setTranslation:(translation)-> $('#translation').html translation
setArticle :(article)-> $('#article').html article
setScore :(score)-> $('#score').html score
showLoadingDialog : ()-> $.mobile.showPageLoadingMsg()
hideLoadingDialog : ()-> $.mobile.hidePageLoadingMsg()
showResult : () ->
$('#answers').hide()
$('#article').show()
$('#translation').show()
$('#nextWordContainer').show()
showChoices : () ->
$('#answers').show()
$('#article').hide()
$('#translation').hide()
$('#nextWordContainer').hide()
setArticleColor : (correctAnswer)->
if correctAnswer
$('#article').attr 'class', 'correct'
else
$('#article').attr 'class', 'wrong'
goBackToIndex : (changeHash=false) =>
$.mobile.changePage( "index.html", {
transition: "pop",
reverse: true,
changeHash: changeHash
});
askToFetchNextSet : (callback) =>
$.mobile.changePage( "confirmFetchNextSet.html", {
transition: "pop",
reverse: false,
changeHash: false
});
$('#nextSetFetchConfirmationYesButton').live 'click', ()=>
$('#nextSetFetchConfirmationYesButton').die 'click'
callback true, @goBackToIndex()
$('#nextSetFetchConfirmationNoButton').live 'click', ()=>
$('#nextSetFetchConfirmationNoButton').die 'click'
callback false, @goBackToIndex()
alert : (text)-> window.alert text
alertConnectionProblem : ()=> @alert('Unable to connect server, please check your internet connection.')
alertShowingCurrentSet : ()=> @alert('New words could not be fetched, thus showing the same word set.')
alertNoWebsqlDatabase : ()=> @alert("Your browser doesn't support websql database, thus the application could not run.")
class Controller
constructor: (@view, @service) ->
@currentArticle = null
@currentTranslation = null
@score = 0
init:()=>
@view.registerAnswerDerButtonHandler @answerDer
@view.registerAnswerDieButtonHandler @answerDie
@view.registerAnswerDasButtonHandler @answerDas
@view.registerNextWordButtonHandler @nextWord
@view.registerNextSetButtonHandler @nextSet
@view.setScore 0
@nextWord()
answerDer:()=> @answer 'der'
answerDie:()=> @answer 'die'
answerDas:()=> @answer 'das'
answer:(article) =>
answerCorrect = (article==@currentArticle)
if answerCorrect
@score++
else
@score--
@view.setArticleColor answerCorrect
@view.setScore @score
@view.showResult()
_showNextWordFromUnshownWords : (callback)=>
@service.getNextWord (article, translation, word)=>
if word?
if(callback)
callback()
@currentArticle = article
@currentTranslation = translation
@view.showChoices()
@view.setWord word
@view.setTranslation @currentTranslation
@view.setArticle @currentArticle
@view.hideLoadingDialog()
else
if(callback)
callback()
@view.hideLoadingDialog()
@view.alertConnectionProblem()
nextWord:()=>
@view.showLoadingDialog()
setWordsAsNonShownAndShowNextWord = (callback)=>
@service.setWordsAsNonShown ()=>
@_showNextWordFromUnshownWords callback
@service.areThereWords (thereAreWords) =>
unless thereAreWords
@service.fetchNextSet (success)=>
if success
@_showNextWordFromUnshownWords()
else
@view.alertConnectionProblem()
else
@service.checkAllShown (allShown) =>
if allShown
@view.askToFetchNextSet (fetchNextSet, callback) =>
if fetchNextSet
@service.fetchNextSet (success)=>
if success
@_showNextWordFromUnshownWords callback
else
@view.alertConnectionProblem()
@view.alertShowingCurrentSet()
setWordsAsNonShownAndShowNextWord callback
else
setWordsAsNonShownAndShowNextWord callback
else
@_showNextWordFromUnshownWords()
nextSet: ()=>
@view.showLoadingDialog()
@service.fetchNextSet (success)=>
if success
@_showNextWordFromUnshownWords ()=>
@view.hideLoadingDialog()
@view.goBackToIndex(true)
else
@view.hideLoadingDialog()
@view.alertConnectionProblem()
start:()=>
@view.registerPageCreateHandler @init
unless Modernizr.websqldatabase
@view.alertNoWebsqlDatabase()
else
@service.initializeDatabase (constructed) =>
if not constructed
@view.alert ('Unable to construct the local database!')
class Service
constructor : (@context, @ajaxManager, @databaseManager) ->
initializeDatabase: (callback) =>
@databaseManager.initializeDatabase callback
getNextWord :(callback) =>
@databaseManager.getNextWord (article, translation, word)=>
@databaseManager.setWordAsShown word, ()=> callback article, translation, word
areThereWords: (callback) =>
@databaseManager.areThereWords callback
checkAllShown: (callback) =>
@databaseManager.checkAllShown callback
setWordsAsNonShown: (callback) =>
@databaseManager.setWordsAsNonShown callback
fetchNextSet: (callback) =>
@ajaxManager.fetchNextSet (data)=>
unless data
callback false
else
@constructWordStorage data, ()-> callback(true)
constructWordStorage : (data, callback) =>
@databaseManager.deleteAllWords (sqlError)=>
if sqlError
window.alert 'Unable to delete all words for reconstructing the word storage'
else
@databaseManager.addNewWordEntries data, callback
class AjaxManager
constructor : (@context) ->
fetchNextSet : (callback)=>
jqXHR = $.ajax({
url: @context.dataServiceUrl(),
dataType: 'json',
timeout: 10000
success: (data)=>
unless data
callback null
else
if data['userKey']
localStorage['userKey'] = data['userKey']
console.log('Received user key :' + data['userKey'])
callback data['entries']
});
jqXHR.error () ->
console.error 'Data call caused an error'
callback null
class DatabaseManager
constructor : ()->
initializeDatabase : (callback) =>
@database = openDatabase 'flashcards', '1.0', 'Flashcards Database', 2 * 1024 * 1024
@database.transaction(
(tx) -> tx.executeSql 'CREATE TABLE IF NOT EXISTS entry (number INTEGER NOT NULL, article TEXT NOT NULL, translation TEXT NOT NULL, word TEXT NOT NULL, shown BOOLEAN NOT NULL)',
(sqlError) -> callback false,
() -> callback true
)
areThereWords : (callback) =>
@database.transaction (tx) ->
tx.executeSql(
'select count(*) as wordCount from entry',
null,
((t,r) ->
wordCount = r.rows.item(0)['wordCount']
if wordCount
callback true
else
callback false
),
() ->
)
checkAllShown : (callback) =>
@database.transaction (tx) ->
tx.executeSql(
'select count(*) as notShownWordCount from entry where shown="false"',
null,
((t,r) ->
notShownWordCount = r.rows.item(0)['notShownWordCount']
unless notShownWordCount
callback true
else
callback false
),
() ->
)
getNextWord : (callback) =>
@database.transaction (tx) -> tx.executeSql(
'select article, translation, word from entry where shown="false" order by number limit 1',
null,
((t,r) ->
item = r.rows.item(0)
callback item['article'], item['translation'], item['word']
),
()->
)
addNewWordEntries : (words, callback) =>
escape = (str)-> str.replace "'", "''"
sql = "INSERT INTO entry "
i = 0
for obj in words
do (obj) =>
article = escape obj['a']
translation = escape obj['t']
word = escape obj['w']
if i==0
sql += "SELECT #{ i } as number, '#{ article }' as 'article', '#{ translation }' as 'translation', '#{ word }' as 'word', 'false' as 'shown' "
else
sql += "UNION SELECT #{ i }, '#{ article }', '#{ translation }', '#{ word }', 'false' "
i++
sql += ";"
@database.transaction(
(tx) -> tx.executeSql sql, null ,
((sqlError) ->
console.log(sqlError)
window.alert(sqlError)
),
() => callback() if callback
)
deleteAllWords : (callback) =>
@database.transaction(
(tx) -> tx.executeSql 'DELETE from entry' ,
(sqlError) -> callback sqlError ,
() =>
callback()
)
setWordAsShown : (word, callback) =>
@database.transaction(
(tx) -> tx.executeSql 'UPDATE entry set shown="true" where entry.word = ?', [word] ,
(sqlError) -> callback sqlError,
() -> callback()
)
setWordsAsNonShown: (callback) =>
@database.transaction(
(tx) -> tx.executeSql 'UPDATE entry set shown="false"', null ,
(sqlError) -> callback sqlError,
() -> callback()
)
context = new Context()
view = new View()
service = new Service context, new AjaxManager(context), new DatabaseManager()
controller = new Controller view, service
controller.start() | 102700 | #Copyright [2011] [<NAME> - aliok AT apache org]
#
#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.
###
if there are no words yet, and the app is offline, then all buttons are shown!
show current set number on the ui
allow fetching a set by number
next word button, previous word button
score mode / training mode
###
class Context
#adding time in milliseconds for breaking the browser cache.
#we can of course do it with modifying JQuery.getJson function's options,
#but in that case we will lose the nice syntax of it and use JQuery.ajax instead
dataServiceUrl: () ->
key = localStorage['userKey']
time = new Date().getTime()
if key
val = "http://the-flashcards-data-service.appspot.com/data?userKey=#{ key }&time=#{ time }&callback=?"
else
val = "http://the-flashcards-data-service.appspot.com/data?time=#{ time }&callback=?"
class View
registerPageCreateHandler :(callback)->$('#mainPage' ).live 'pageinit', callback
registerAnswerDerButtonHandler :(callback)->$('#answerDer').bind 'click', callback
registerAnswerDieButtonHandler :(callback)->$('#answerDie').bind 'click', callback
registerAnswerDasButtonHandler :(callback)->$('#answerDas').bind 'click', callback
registerNextWordButtonHandler :(callback)->$('#nextWord' ).bind 'click', callback
registerNextSetButtonHandler : (callback)->$('#nextSet' ).bind 'click', ()=>
$('#nextSet').die 'click'
callback()
setWord :(word)-> $('#word').html word
setTranslation:(translation)-> $('#translation').html translation
setArticle :(article)-> $('#article').html article
setScore :(score)-> $('#score').html score
showLoadingDialog : ()-> $.mobile.showPageLoadingMsg()
hideLoadingDialog : ()-> $.mobile.hidePageLoadingMsg()
showResult : () ->
$('#answers').hide()
$('#article').show()
$('#translation').show()
$('#nextWordContainer').show()
showChoices : () ->
$('#answers').show()
$('#article').hide()
$('#translation').hide()
$('#nextWordContainer').hide()
setArticleColor : (correctAnswer)->
if correctAnswer
$('#article').attr 'class', 'correct'
else
$('#article').attr 'class', 'wrong'
goBackToIndex : (changeHash=false) =>
$.mobile.changePage( "index.html", {
transition: "pop",
reverse: true,
changeHash: changeHash
});
askToFetchNextSet : (callback) =>
$.mobile.changePage( "confirmFetchNextSet.html", {
transition: "pop",
reverse: false,
changeHash: false
});
$('#nextSetFetchConfirmationYesButton').live 'click', ()=>
$('#nextSetFetchConfirmationYesButton').die 'click'
callback true, @goBackToIndex()
$('#nextSetFetchConfirmationNoButton').live 'click', ()=>
$('#nextSetFetchConfirmationNoButton').die 'click'
callback false, @goBackToIndex()
alert : (text)-> window.alert text
alertConnectionProblem : ()=> @alert('Unable to connect server, please check your internet connection.')
alertShowingCurrentSet : ()=> @alert('New words could not be fetched, thus showing the same word set.')
alertNoWebsqlDatabase : ()=> @alert("Your browser doesn't support websql database, thus the application could not run.")
class Controller
constructor: (@view, @service) ->
@currentArticle = null
@currentTranslation = null
@score = 0
init:()=>
@view.registerAnswerDerButtonHandler @answerDer
@view.registerAnswerDieButtonHandler @answerDie
@view.registerAnswerDasButtonHandler @answerDas
@view.registerNextWordButtonHandler @nextWord
@view.registerNextSetButtonHandler @nextSet
@view.setScore 0
@nextWord()
answerDer:()=> @answer 'der'
answerDie:()=> @answer 'die'
answerDas:()=> @answer 'das'
answer:(article) =>
answerCorrect = (article==@currentArticle)
if answerCorrect
@score++
else
@score--
@view.setArticleColor answerCorrect
@view.setScore @score
@view.showResult()
_showNextWordFromUnshownWords : (callback)=>
@service.getNextWord (article, translation, word)=>
if word?
if(callback)
callback()
@currentArticle = article
@currentTranslation = translation
@view.showChoices()
@view.setWord word
@view.setTranslation @currentTranslation
@view.setArticle @currentArticle
@view.hideLoadingDialog()
else
if(callback)
callback()
@view.hideLoadingDialog()
@view.alertConnectionProblem()
nextWord:()=>
@view.showLoadingDialog()
setWordsAsNonShownAndShowNextWord = (callback)=>
@service.setWordsAsNonShown ()=>
@_showNextWordFromUnshownWords callback
@service.areThereWords (thereAreWords) =>
unless thereAreWords
@service.fetchNextSet (success)=>
if success
@_showNextWordFromUnshownWords()
else
@view.alertConnectionProblem()
else
@service.checkAllShown (allShown) =>
if allShown
@view.askToFetchNextSet (fetchNextSet, callback) =>
if fetchNextSet
@service.fetchNextSet (success)=>
if success
@_showNextWordFromUnshownWords callback
else
@view.alertConnectionProblem()
@view.alertShowingCurrentSet()
setWordsAsNonShownAndShowNextWord callback
else
setWordsAsNonShownAndShowNextWord callback
else
@_showNextWordFromUnshownWords()
nextSet: ()=>
@view.showLoadingDialog()
@service.fetchNextSet (success)=>
if success
@_showNextWordFromUnshownWords ()=>
@view.hideLoadingDialog()
@view.goBackToIndex(true)
else
@view.hideLoadingDialog()
@view.alertConnectionProblem()
start:()=>
@view.registerPageCreateHandler @init
unless Modernizr.websqldatabase
@view.alertNoWebsqlDatabase()
else
@service.initializeDatabase (constructed) =>
if not constructed
@view.alert ('Unable to construct the local database!')
class Service
constructor : (@context, @ajaxManager, @databaseManager) ->
initializeDatabase: (callback) =>
@databaseManager.initializeDatabase callback
getNextWord :(callback) =>
@databaseManager.getNextWord (article, translation, word)=>
@databaseManager.setWordAsShown word, ()=> callback article, translation, word
areThereWords: (callback) =>
@databaseManager.areThereWords callback
checkAllShown: (callback) =>
@databaseManager.checkAllShown callback
setWordsAsNonShown: (callback) =>
@databaseManager.setWordsAsNonShown callback
fetchNextSet: (callback) =>
@ajaxManager.fetchNextSet (data)=>
unless data
callback false
else
@constructWordStorage data, ()-> callback(true)
constructWordStorage : (data, callback) =>
@databaseManager.deleteAllWords (sqlError)=>
if sqlError
window.alert 'Unable to delete all words for reconstructing the word storage'
else
@databaseManager.addNewWordEntries data, callback
class AjaxManager
constructor : (@context) ->
fetchNextSet : (callback)=>
jqXHR = $.ajax({
url: @context.dataServiceUrl(),
dataType: 'json',
timeout: 10000
success: (data)=>
unless data
callback null
else
if data['userKey']
localStorage['userKey'] = data['userKey']
console.log('Received user key :' + data['userKey'])
callback data['entries']
});
jqXHR.error () ->
console.error 'Data call caused an error'
callback null
class DatabaseManager
constructor : ()->
initializeDatabase : (callback) =>
@database = openDatabase 'flashcards', '1.0', 'Flashcards Database', 2 * 1024 * 1024
@database.transaction(
(tx) -> tx.executeSql 'CREATE TABLE IF NOT EXISTS entry (number INTEGER NOT NULL, article TEXT NOT NULL, translation TEXT NOT NULL, word TEXT NOT NULL, shown BOOLEAN NOT NULL)',
(sqlError) -> callback false,
() -> callback true
)
areThereWords : (callback) =>
@database.transaction (tx) ->
tx.executeSql(
'select count(*) as wordCount from entry',
null,
((t,r) ->
wordCount = r.rows.item(0)['wordCount']
if wordCount
callback true
else
callback false
),
() ->
)
checkAllShown : (callback) =>
@database.transaction (tx) ->
tx.executeSql(
'select count(*) as notShownWordCount from entry where shown="false"',
null,
((t,r) ->
notShownWordCount = r.rows.item(0)['notShownWordCount']
unless notShownWordCount
callback true
else
callback false
),
() ->
)
getNextWord : (callback) =>
@database.transaction (tx) -> tx.executeSql(
'select article, translation, word from entry where shown="false" order by number limit 1',
null,
((t,r) ->
item = r.rows.item(0)
callback item['article'], item['translation'], item['word']
),
()->
)
addNewWordEntries : (words, callback) =>
escape = (str)-> str.replace "'", "''"
sql = "INSERT INTO entry "
i = 0
for obj in words
do (obj) =>
article = escape obj['a']
translation = escape obj['t']
word = escape obj['w']
if i==0
sql += "SELECT #{ i } as number, '#{ article }' as 'article', '#{ translation }' as 'translation', '#{ word }' as 'word', 'false' as 'shown' "
else
sql += "UNION SELECT #{ i }, '#{ article }', '#{ translation }', '#{ word }', 'false' "
i++
sql += ";"
@database.transaction(
(tx) -> tx.executeSql sql, null ,
((sqlError) ->
console.log(sqlError)
window.alert(sqlError)
),
() => callback() if callback
)
deleteAllWords : (callback) =>
@database.transaction(
(tx) -> tx.executeSql 'DELETE from entry' ,
(sqlError) -> callback sqlError ,
() =>
callback()
)
setWordAsShown : (word, callback) =>
@database.transaction(
(tx) -> tx.executeSql 'UPDATE entry set shown="true" where entry.word = ?', [word] ,
(sqlError) -> callback sqlError,
() -> callback()
)
setWordsAsNonShown: (callback) =>
@database.transaction(
(tx) -> tx.executeSql 'UPDATE entry set shown="false"', null ,
(sqlError) -> callback sqlError,
() -> callback()
)
context = new Context()
view = new View()
service = new Service context, new AjaxManager(context), new DatabaseManager()
controller = new Controller view, service
controller.start() | true | #Copyright [2011] [PI:NAME:<NAME>END_PI - aliok AT apache org]
#
#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.
###
if there are no words yet, and the app is offline, then all buttons are shown!
show current set number on the ui
allow fetching a set by number
next word button, previous word button
score mode / training mode
###
class Context
#adding time in milliseconds for breaking the browser cache.
#we can of course do it with modifying JQuery.getJson function's options,
#but in that case we will lose the nice syntax of it and use JQuery.ajax instead
dataServiceUrl: () ->
key = localStorage['userKey']
time = new Date().getTime()
if key
val = "http://the-flashcards-data-service.appspot.com/data?userKey=#{ key }&time=#{ time }&callback=?"
else
val = "http://the-flashcards-data-service.appspot.com/data?time=#{ time }&callback=?"
class View
registerPageCreateHandler :(callback)->$('#mainPage' ).live 'pageinit', callback
registerAnswerDerButtonHandler :(callback)->$('#answerDer').bind 'click', callback
registerAnswerDieButtonHandler :(callback)->$('#answerDie').bind 'click', callback
registerAnswerDasButtonHandler :(callback)->$('#answerDas').bind 'click', callback
registerNextWordButtonHandler :(callback)->$('#nextWord' ).bind 'click', callback
registerNextSetButtonHandler : (callback)->$('#nextSet' ).bind 'click', ()=>
$('#nextSet').die 'click'
callback()
setWord :(word)-> $('#word').html word
setTranslation:(translation)-> $('#translation').html translation
setArticle :(article)-> $('#article').html article
setScore :(score)-> $('#score').html score
showLoadingDialog : ()-> $.mobile.showPageLoadingMsg()
hideLoadingDialog : ()-> $.mobile.hidePageLoadingMsg()
showResult : () ->
$('#answers').hide()
$('#article').show()
$('#translation').show()
$('#nextWordContainer').show()
showChoices : () ->
$('#answers').show()
$('#article').hide()
$('#translation').hide()
$('#nextWordContainer').hide()
setArticleColor : (correctAnswer)->
if correctAnswer
$('#article').attr 'class', 'correct'
else
$('#article').attr 'class', 'wrong'
goBackToIndex : (changeHash=false) =>
$.mobile.changePage( "index.html", {
transition: "pop",
reverse: true,
changeHash: changeHash
});
askToFetchNextSet : (callback) =>
$.mobile.changePage( "confirmFetchNextSet.html", {
transition: "pop",
reverse: false,
changeHash: false
});
$('#nextSetFetchConfirmationYesButton').live 'click', ()=>
$('#nextSetFetchConfirmationYesButton').die 'click'
callback true, @goBackToIndex()
$('#nextSetFetchConfirmationNoButton').live 'click', ()=>
$('#nextSetFetchConfirmationNoButton').die 'click'
callback false, @goBackToIndex()
alert : (text)-> window.alert text
alertConnectionProblem : ()=> @alert('Unable to connect server, please check your internet connection.')
alertShowingCurrentSet : ()=> @alert('New words could not be fetched, thus showing the same word set.')
alertNoWebsqlDatabase : ()=> @alert("Your browser doesn't support websql database, thus the application could not run.")
class Controller
constructor: (@view, @service) ->
@currentArticle = null
@currentTranslation = null
@score = 0
init:()=>
@view.registerAnswerDerButtonHandler @answerDer
@view.registerAnswerDieButtonHandler @answerDie
@view.registerAnswerDasButtonHandler @answerDas
@view.registerNextWordButtonHandler @nextWord
@view.registerNextSetButtonHandler @nextSet
@view.setScore 0
@nextWord()
answerDer:()=> @answer 'der'
answerDie:()=> @answer 'die'
answerDas:()=> @answer 'das'
answer:(article) =>
answerCorrect = (article==@currentArticle)
if answerCorrect
@score++
else
@score--
@view.setArticleColor answerCorrect
@view.setScore @score
@view.showResult()
_showNextWordFromUnshownWords : (callback)=>
@service.getNextWord (article, translation, word)=>
if word?
if(callback)
callback()
@currentArticle = article
@currentTranslation = translation
@view.showChoices()
@view.setWord word
@view.setTranslation @currentTranslation
@view.setArticle @currentArticle
@view.hideLoadingDialog()
else
if(callback)
callback()
@view.hideLoadingDialog()
@view.alertConnectionProblem()
nextWord:()=>
@view.showLoadingDialog()
setWordsAsNonShownAndShowNextWord = (callback)=>
@service.setWordsAsNonShown ()=>
@_showNextWordFromUnshownWords callback
@service.areThereWords (thereAreWords) =>
unless thereAreWords
@service.fetchNextSet (success)=>
if success
@_showNextWordFromUnshownWords()
else
@view.alertConnectionProblem()
else
@service.checkAllShown (allShown) =>
if allShown
@view.askToFetchNextSet (fetchNextSet, callback) =>
if fetchNextSet
@service.fetchNextSet (success)=>
if success
@_showNextWordFromUnshownWords callback
else
@view.alertConnectionProblem()
@view.alertShowingCurrentSet()
setWordsAsNonShownAndShowNextWord callback
else
setWordsAsNonShownAndShowNextWord callback
else
@_showNextWordFromUnshownWords()
nextSet: ()=>
@view.showLoadingDialog()
@service.fetchNextSet (success)=>
if success
@_showNextWordFromUnshownWords ()=>
@view.hideLoadingDialog()
@view.goBackToIndex(true)
else
@view.hideLoadingDialog()
@view.alertConnectionProblem()
start:()=>
@view.registerPageCreateHandler @init
unless Modernizr.websqldatabase
@view.alertNoWebsqlDatabase()
else
@service.initializeDatabase (constructed) =>
if not constructed
@view.alert ('Unable to construct the local database!')
class Service
constructor : (@context, @ajaxManager, @databaseManager) ->
initializeDatabase: (callback) =>
@databaseManager.initializeDatabase callback
getNextWord :(callback) =>
@databaseManager.getNextWord (article, translation, word)=>
@databaseManager.setWordAsShown word, ()=> callback article, translation, word
areThereWords: (callback) =>
@databaseManager.areThereWords callback
checkAllShown: (callback) =>
@databaseManager.checkAllShown callback
setWordsAsNonShown: (callback) =>
@databaseManager.setWordsAsNonShown callback
fetchNextSet: (callback) =>
@ajaxManager.fetchNextSet (data)=>
unless data
callback false
else
@constructWordStorage data, ()-> callback(true)
constructWordStorage : (data, callback) =>
@databaseManager.deleteAllWords (sqlError)=>
if sqlError
window.alert 'Unable to delete all words for reconstructing the word storage'
else
@databaseManager.addNewWordEntries data, callback
class AjaxManager
constructor : (@context) ->
fetchNextSet : (callback)=>
jqXHR = $.ajax({
url: @context.dataServiceUrl(),
dataType: 'json',
timeout: 10000
success: (data)=>
unless data
callback null
else
if data['userKey']
localStorage['userKey'] = data['userKey']
console.log('Received user key :' + data['userKey'])
callback data['entries']
});
jqXHR.error () ->
console.error 'Data call caused an error'
callback null
class DatabaseManager
constructor : ()->
initializeDatabase : (callback) =>
@database = openDatabase 'flashcards', '1.0', 'Flashcards Database', 2 * 1024 * 1024
@database.transaction(
(tx) -> tx.executeSql 'CREATE TABLE IF NOT EXISTS entry (number INTEGER NOT NULL, article TEXT NOT NULL, translation TEXT NOT NULL, word TEXT NOT NULL, shown BOOLEAN NOT NULL)',
(sqlError) -> callback false,
() -> callback true
)
areThereWords : (callback) =>
@database.transaction (tx) ->
tx.executeSql(
'select count(*) as wordCount from entry',
null,
((t,r) ->
wordCount = r.rows.item(0)['wordCount']
if wordCount
callback true
else
callback false
),
() ->
)
checkAllShown : (callback) =>
@database.transaction (tx) ->
tx.executeSql(
'select count(*) as notShownWordCount from entry where shown="false"',
null,
((t,r) ->
notShownWordCount = r.rows.item(0)['notShownWordCount']
unless notShownWordCount
callback true
else
callback false
),
() ->
)
getNextWord : (callback) =>
@database.transaction (tx) -> tx.executeSql(
'select article, translation, word from entry where shown="false" order by number limit 1',
null,
((t,r) ->
item = r.rows.item(0)
callback item['article'], item['translation'], item['word']
),
()->
)
addNewWordEntries : (words, callback) =>
escape = (str)-> str.replace "'", "''"
sql = "INSERT INTO entry "
i = 0
for obj in words
do (obj) =>
article = escape obj['a']
translation = escape obj['t']
word = escape obj['w']
if i==0
sql += "SELECT #{ i } as number, '#{ article }' as 'article', '#{ translation }' as 'translation', '#{ word }' as 'word', 'false' as 'shown' "
else
sql += "UNION SELECT #{ i }, '#{ article }', '#{ translation }', '#{ word }', 'false' "
i++
sql += ";"
@database.transaction(
(tx) -> tx.executeSql sql, null ,
((sqlError) ->
console.log(sqlError)
window.alert(sqlError)
),
() => callback() if callback
)
deleteAllWords : (callback) =>
@database.transaction(
(tx) -> tx.executeSql 'DELETE from entry' ,
(sqlError) -> callback sqlError ,
() =>
callback()
)
setWordAsShown : (word, callback) =>
@database.transaction(
(tx) -> tx.executeSql 'UPDATE entry set shown="true" where entry.word = ?', [word] ,
(sqlError) -> callback sqlError,
() -> callback()
)
setWordsAsNonShown: (callback) =>
@database.transaction(
(tx) -> tx.executeSql 'UPDATE entry set shown="false"', null ,
(sqlError) -> callback sqlError,
() -> callback()
)
context = new Context()
view = new View()
service = new Service context, new AjaxManager(context), new DatabaseManager()
controller = new Controller view, service
controller.start() |
[
{
"context": "oUrl: null,\n interactive: {id: 1, name: \"test\"},\n authInfo: {provider: \"fakeprovider\",",
"end": 3437,
"score": 0.8007350564002991,
"start": 3433,
"tag": "NAME",
"value": "test"
},
{
"context": "provider: \"fakeprovider\", loggedIn: true, email: \... | spec/javascripts/iframe_saver_spec.coffee | sciencelabshs/lara | 0 | success_response =
status: 200,
responseText: '{}'
# this spec is very out of date with the current code
describe 'IFrameSaver', () ->
saver = null
request = null
iframePhone = jasmine.mockIframePhone
beforeEach () ->
iframePhone.install()
iframePhone.autoConnect = false
loadFixtures "iframe-saver.html"
afterEach () ->
iframePhone.uninstall()
getSaver = ->
new IFrameSaver($('#interactive'), $('#interactive_data_div'), $('.delete_interactive_data'))
describe "with an interactive in in iframe", ->
fake_save_indicator = jasmine.createSpyObj('SaveIndicator',['showSaved','showSaving', 'showSaveFailed'])
beforeEach () ->
saver = getSaver()
saver.save_indicator = fake_save_indicator
describe "a sane testing environment", () ->
it 'has an instance of IFrameSaver defined', () ->
expect(saver).toBeDefined()
it 'has an iframe to work with', () ->
expect($("#interactive")[0]).toExist()
it 'has an interactive data element', () ->
expect($("#interactive_data_div")).toExist()
describe "constructor called in the correct context", () ->
it "should have a interactive run state url", () ->
expect(saver.interactive_run_state_url).toBe("foo/42")
describe "save", () ->
beforeEach () ->
saver.save()
it "invokes the correct message on the iframePhone", () ->
expect(iframePhone.messages.findType('getInteractiveState')).toBeTruthy()
describe "save_learner_state", () ->
beforeEach () ->
jasmine.Ajax.install()
saver.save_learner_state({foo:'bar'})
request = jasmine.Ajax.requests.mostRecent()
request.respondWith(success_response)
afterEach () ->
jasmine.Ajax.uninstall()
describe "a successful save", () ->
it "should display the show saved indicator", () ->
expect(fake_save_indicator.showSaveFailed).not.toHaveBeenCalled()
expect(fake_save_indicator.showSaving).toHaveBeenCalled()
expect(fake_save_indicator.showSaved).toHaveBeenCalled()
describe "interactive initialization", () ->
describe "when state saving is enabled", () ->
beforeEach () ->
jasmine.Ajax.install()
$("#interactive_data_div").data("enable-learner-state", true)
saver = getSaver()
iframePhone.connect()
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200,
responseText: JSON.stringify({
"raw_data": JSON.stringify({"interactiveState": 321}),
"created_at": "2017",
"updated_at": "2018",
"activity_name": "test act",
"page_name": "test page",
"page_number": 2
})
})
afterEach () ->
jasmine.Ajax.uninstall()
it "should post 'initInteractive'", () ->
expect(iframePhone.messages.findType('initInteractive').message.content).toEqual({
version: 1,
error: null,
mode: 'runtime',
authoredState: {test: 123},
interactiveState: {interactiveState: 321},
createdAt: '2017'
updatedAt: '2018'
globalInteractiveState: null,
interactiveStateUrl: 'foo/42',
collaboratorUrls: null,
classInfoUrl: null,
interactive: {id: 1, name: "test"},
authInfo: {provider: "fakeprovider", loggedIn: true, email: "user@example.com"}
pageNumber: 2
pageName: "test page"
activityName: "test act"
})
describe "when state saving is disabled", () ->
beforeEach () ->
$("#interactive_data_div").data("enable-learner-state", false)
saver = getSaver()
iframePhone.connect()
it "should post 'initInteractive'", () ->
expect(iframePhone.messages.findType('initInteractive').message.content).toEqual({
version: 1,
error: null,
mode: 'runtime',
authoredState: {test: 123},
interactiveState: null,
globalInteractiveState: null,
interactiveStateUrl: 'foo/42',
collaboratorUrls: null,
classInfoUrl: null,
interactive: {id: 1, name: "test"},
authInfo: {provider: "fakeprovider", loggedIn: true, email: "user@example.com"}
})
| 104788 | success_response =
status: 200,
responseText: '{}'
# this spec is very out of date with the current code
describe 'IFrameSaver', () ->
saver = null
request = null
iframePhone = jasmine.mockIframePhone
beforeEach () ->
iframePhone.install()
iframePhone.autoConnect = false
loadFixtures "iframe-saver.html"
afterEach () ->
iframePhone.uninstall()
getSaver = ->
new IFrameSaver($('#interactive'), $('#interactive_data_div'), $('.delete_interactive_data'))
describe "with an interactive in in iframe", ->
fake_save_indicator = jasmine.createSpyObj('SaveIndicator',['showSaved','showSaving', 'showSaveFailed'])
beforeEach () ->
saver = getSaver()
saver.save_indicator = fake_save_indicator
describe "a sane testing environment", () ->
it 'has an instance of IFrameSaver defined', () ->
expect(saver).toBeDefined()
it 'has an iframe to work with', () ->
expect($("#interactive")[0]).toExist()
it 'has an interactive data element', () ->
expect($("#interactive_data_div")).toExist()
describe "constructor called in the correct context", () ->
it "should have a interactive run state url", () ->
expect(saver.interactive_run_state_url).toBe("foo/42")
describe "save", () ->
beforeEach () ->
saver.save()
it "invokes the correct message on the iframePhone", () ->
expect(iframePhone.messages.findType('getInteractiveState')).toBeTruthy()
describe "save_learner_state", () ->
beforeEach () ->
jasmine.Ajax.install()
saver.save_learner_state({foo:'bar'})
request = jasmine.Ajax.requests.mostRecent()
request.respondWith(success_response)
afterEach () ->
jasmine.Ajax.uninstall()
describe "a successful save", () ->
it "should display the show saved indicator", () ->
expect(fake_save_indicator.showSaveFailed).not.toHaveBeenCalled()
expect(fake_save_indicator.showSaving).toHaveBeenCalled()
expect(fake_save_indicator.showSaved).toHaveBeenCalled()
describe "interactive initialization", () ->
describe "when state saving is enabled", () ->
beforeEach () ->
jasmine.Ajax.install()
$("#interactive_data_div").data("enable-learner-state", true)
saver = getSaver()
iframePhone.connect()
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200,
responseText: JSON.stringify({
"raw_data": JSON.stringify({"interactiveState": 321}),
"created_at": "2017",
"updated_at": "2018",
"activity_name": "test act",
"page_name": "test page",
"page_number": 2
})
})
afterEach () ->
jasmine.Ajax.uninstall()
it "should post 'initInteractive'", () ->
expect(iframePhone.messages.findType('initInteractive').message.content).toEqual({
version: 1,
error: null,
mode: 'runtime',
authoredState: {test: 123},
interactiveState: {interactiveState: 321},
createdAt: '2017'
updatedAt: '2018'
globalInteractiveState: null,
interactiveStateUrl: 'foo/42',
collaboratorUrls: null,
classInfoUrl: null,
interactive: {id: 1, name: "<NAME>"},
authInfo: {provider: "fakeprovider", loggedIn: true, email: "<EMAIL>"}
pageNumber: 2
pageName: "test page"
activityName: "test act"
})
describe "when state saving is disabled", () ->
beforeEach () ->
$("#interactive_data_div").data("enable-learner-state", false)
saver = getSaver()
iframePhone.connect()
it "should post 'initInteractive'", () ->
expect(iframePhone.messages.findType('initInteractive').message.content).toEqual({
version: 1,
error: null,
mode: 'runtime',
authoredState: {test: 123},
interactiveState: null,
globalInteractiveState: null,
interactiveStateUrl: 'foo/42',
collaboratorUrls: null,
classInfoUrl: null,
interactive: {id: 1, name: "test"},
authInfo: {provider: "fakeprovider", loggedIn: true, email: "<EMAIL>"}
})
| true | success_response =
status: 200,
responseText: '{}'
# this spec is very out of date with the current code
describe 'IFrameSaver', () ->
saver = null
request = null
iframePhone = jasmine.mockIframePhone
beforeEach () ->
iframePhone.install()
iframePhone.autoConnect = false
loadFixtures "iframe-saver.html"
afterEach () ->
iframePhone.uninstall()
getSaver = ->
new IFrameSaver($('#interactive'), $('#interactive_data_div'), $('.delete_interactive_data'))
describe "with an interactive in in iframe", ->
fake_save_indicator = jasmine.createSpyObj('SaveIndicator',['showSaved','showSaving', 'showSaveFailed'])
beforeEach () ->
saver = getSaver()
saver.save_indicator = fake_save_indicator
describe "a sane testing environment", () ->
it 'has an instance of IFrameSaver defined', () ->
expect(saver).toBeDefined()
it 'has an iframe to work with', () ->
expect($("#interactive")[0]).toExist()
it 'has an interactive data element', () ->
expect($("#interactive_data_div")).toExist()
describe "constructor called in the correct context", () ->
it "should have a interactive run state url", () ->
expect(saver.interactive_run_state_url).toBe("foo/42")
describe "save", () ->
beforeEach () ->
saver.save()
it "invokes the correct message on the iframePhone", () ->
expect(iframePhone.messages.findType('getInteractiveState')).toBeTruthy()
describe "save_learner_state", () ->
beforeEach () ->
jasmine.Ajax.install()
saver.save_learner_state({foo:'bar'})
request = jasmine.Ajax.requests.mostRecent()
request.respondWith(success_response)
afterEach () ->
jasmine.Ajax.uninstall()
describe "a successful save", () ->
it "should display the show saved indicator", () ->
expect(fake_save_indicator.showSaveFailed).not.toHaveBeenCalled()
expect(fake_save_indicator.showSaving).toHaveBeenCalled()
expect(fake_save_indicator.showSaved).toHaveBeenCalled()
describe "interactive initialization", () ->
describe "when state saving is enabled", () ->
beforeEach () ->
jasmine.Ajax.install()
$("#interactive_data_div").data("enable-learner-state", true)
saver = getSaver()
iframePhone.connect()
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200,
responseText: JSON.stringify({
"raw_data": JSON.stringify({"interactiveState": 321}),
"created_at": "2017",
"updated_at": "2018",
"activity_name": "test act",
"page_name": "test page",
"page_number": 2
})
})
afterEach () ->
jasmine.Ajax.uninstall()
it "should post 'initInteractive'", () ->
expect(iframePhone.messages.findType('initInteractive').message.content).toEqual({
version: 1,
error: null,
mode: 'runtime',
authoredState: {test: 123},
interactiveState: {interactiveState: 321},
createdAt: '2017'
updatedAt: '2018'
globalInteractiveState: null,
interactiveStateUrl: 'foo/42',
collaboratorUrls: null,
classInfoUrl: null,
interactive: {id: 1, name: "PI:NAME:<NAME>END_PI"},
authInfo: {provider: "fakeprovider", loggedIn: true, email: "PI:EMAIL:<EMAIL>END_PI"}
pageNumber: 2
pageName: "test page"
activityName: "test act"
})
describe "when state saving is disabled", () ->
beforeEach () ->
$("#interactive_data_div").data("enable-learner-state", false)
saver = getSaver()
iframePhone.connect()
it "should post 'initInteractive'", () ->
expect(iframePhone.messages.findType('initInteractive').message.content).toEqual({
version: 1,
error: null,
mode: 'runtime',
authoredState: {test: 123},
interactiveState: null,
globalInteractiveState: null,
interactiveStateUrl: 'foo/42',
collaboratorUrls: null,
classInfoUrl: null,
interactive: {id: 1, name: "test"},
authInfo: {provider: "fakeprovider", loggedIn: true, email: "PI:EMAIL:<EMAIL>END_PI"}
})
|
[
{
"context": "4fa'}\n\n @getDevice.yields null, {ipAddress: '192.168.1.1'}\n @updateDevice.yields null, @device\n ",
"end": 1151,
"score": 0.9996104836463928,
"start": 1140,
"tag": "IP_ADDRESS",
"value": "192.168.1.1"
},
{
"context": "iscoverWhitelist: [@fromDevice.uui... | test/lib/claimDevice-spec.coffee | Christopheraburns/projecttelemetry | 0 | describe 'claimDevice', ->
beforeEach ->
@updateDevice = sinon.stub()
@canConfigure = sinon.stub()
@getDevice = sinon.stub()
@canConfigure.returns true
@dependencies = {updateDevice: @updateDevice, canConfigure: @canConfigure, getDevice: @getDevice}
@sut = require '../../lib/claimDevice'
it 'should be a function', ->
expect(@sut).to.be.a 'function'
describe 'when called with a bunch of nothing', ->
beforeEach (done) ->
storeError = (@error) => done()
@sut null, null, storeError, @dependencies
it 'should callback with an error', ->
expect(@error).to.exist
describe 'when called with a some of nothing', ->
beforeEach (done) ->
storeError = (@error) => done()
@sut {uuid: 'something'}, null, storeError, @dependencies
it 'should callback with an error', ->
expect(@error).to.exist
describe 'when called with a bunch of something', ->
beforeEach (done) ->
@fromDevice = {uuid: '89e9cd5f-dfff-4771-b821-d35614b7a506'}
@device = {uuid: '07a4ed85-acc5-4495-b3d7-2d93439c04fa'}
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@updateDevice.yields null, @device
@sut @fromDevice, @device, done, @dependencies
it 'should call updateDevice with that uuid and name', ->
expect(@updateDevice).to.have.been.calledWith @device.uuid, {owner: @fromDevice.uuid, uuid: @device.uuid, discoverWhitelist: [@fromDevice.uuid], ipAddress: '192.168.1.1'}
describe 'when called with params other than uuid', ->
beforeEach (done) ->
@fromDevice = {uuid: '89e9cd5f-dfff-4771-b821-d35614b7a506'}
@device = {uuid: '07a4ed85-acc5-4495-b3d7-2d93439c04fa', name: 'Cookie Crisp'}
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@updateDevice.yields null, @device
@sut @fromDevice, @device, done, @dependencies
it 'should call updateDevice with that uuid and name', ->
expect(@updateDevice).to.have.been.calledWith @device.uuid, {owner: @fromDevice.uuid, name: 'Cookie Crisp', uuid: @device.uuid, discoverWhitelist: [@fromDevice.uuid], ipAddress: '192.168.1.1'}
describe 'when called with an owner param', ->
beforeEach (done) ->
@fromDevice = {uuid: 'e33c1844-6888-4698-852a-7be584327a1d'}
@device = {uuid: '9b97159e-63c2-4a71-9327-8fadad97f1e9', name: 'Fruit Loops', owner: 'wrong'}
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@updateDevice.yields null, @device
@sut @fromDevice, @device, done, @dependencies
it 'should call updateDevice with that uuid and name', ->
expect(@updateDevice).to.have.been.calledWith @device.uuid, {owner: @fromDevice.uuid, name: 'Fruit Loops', uuid: @device.uuid, discoverWhitelist: [@fromDevice.uuid], ipAddress: '192.168.1.1'}
describe 'when called by a non-authorized user', ->
beforeEach (done) ->
@fromDevice = {uuid: '1267b0fe-407a-4872-b09d-dd4853d59d76'}
@device = {uuid: '9b97159e-63c2-4a71-9327-8fadad97f1e9', name: 'Fruit Loops'}
storeError = (@error) => done()
@canConfigure.returns false
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@sut @fromDevice, @device, storeError, @dependencies
it 'should call canConfigure with fromDevice, device with the ipAddress mixed in', ->
expect(@canConfigure).to.have.been.calledWith @fromDevice, {
uuid: '9b97159e-63c2-4a71-9327-8fadad97f1e9'
ipAddress: '192.168.1.1'
name: 'Fruit Loops'
}
it 'should not call updateDevice with that uuid and name', ->
expect(@updateDevice).not.to.have.been.called
it 'should call the callback with an error', ->
expect(@error).to.exist
| 169338 | describe 'claimDevice', ->
beforeEach ->
@updateDevice = sinon.stub()
@canConfigure = sinon.stub()
@getDevice = sinon.stub()
@canConfigure.returns true
@dependencies = {updateDevice: @updateDevice, canConfigure: @canConfigure, getDevice: @getDevice}
@sut = require '../../lib/claimDevice'
it 'should be a function', ->
expect(@sut).to.be.a 'function'
describe 'when called with a bunch of nothing', ->
beforeEach (done) ->
storeError = (@error) => done()
@sut null, null, storeError, @dependencies
it 'should callback with an error', ->
expect(@error).to.exist
describe 'when called with a some of nothing', ->
beforeEach (done) ->
storeError = (@error) => done()
@sut {uuid: 'something'}, null, storeError, @dependencies
it 'should callback with an error', ->
expect(@error).to.exist
describe 'when called with a bunch of something', ->
beforeEach (done) ->
@fromDevice = {uuid: '89e9cd5f-dfff-4771-b821-d35614b7a506'}
@device = {uuid: '07a4ed85-acc5-4495-b3d7-2d93439c04fa'}
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@updateDevice.yields null, @device
@sut @fromDevice, @device, done, @dependencies
it 'should call updateDevice with that uuid and name', ->
expect(@updateDevice).to.have.been.calledWith @device.uuid, {owner: @fromDevice.uuid, uuid: @device.uuid, discoverWhitelist: [@fromDevice.uuid], ipAddress: '192.168.1.1'}
describe 'when called with params other than uuid', ->
beforeEach (done) ->
@fromDevice = {uuid: '89e9cd5f-dfff-4771-b821-d35614b7a506'}
@device = {uuid: '07a4ed85-acc5-4495-b3d7-2d93439c04fa', name: 'Cookie Crisp'}
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@updateDevice.yields null, @device
@sut @fromDevice, @device, done, @dependencies
it 'should call updateDevice with that uuid and name', ->
expect(@updateDevice).to.have.been.calledWith @device.uuid, {owner: @fromDevice.uuid, name: 'Cookie Crisp', uuid: @device.uuid, discoverWhitelist: [@fromDevice.uuid], ipAddress: '192.168.1.1'}
describe 'when called with an owner param', ->
beforeEach (done) ->
@fromDevice = {uuid: 'e33c1844-6888-4698-852a-7be584327a1d'}
@device = {uuid: '9b97159e-63c2-4a71-9327-8fadad97f1e9', name: '<NAME>', owner: 'wrong'}
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@updateDevice.yields null, @device
@sut @fromDevice, @device, done, @dependencies
it 'should call updateDevice with that uuid and name', ->
expect(@updateDevice).to.have.been.calledWith @device.uuid, {owner: @fromDevice.uuid, name: '<NAME>', uuid: @device.uuid, discoverWhitelist: [@fromDevice.uuid], ipAddress: '192.168.1.1'}
describe 'when called by a non-authorized user', ->
beforeEach (done) ->
@fromDevice = {uuid: '1267b0fe-407a-4872-b09d-dd4853d59d76'}
@device = {uuid: '9b97159e-63c2-4a71-9327-8fadad97f1e9', name: '<NAME>'}
storeError = (@error) => done()
@canConfigure.returns false
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@sut @fromDevice, @device, storeError, @dependencies
it 'should call canConfigure with fromDevice, device with the ipAddress mixed in', ->
expect(@canConfigure).to.have.been.calledWith @fromDevice, {
uuid: '9b97159e-63c2-4a71-9327-8fadad97f1e9'
ipAddress: '192.168.1.1'
name: '<NAME>'
}
it 'should not call updateDevice with that uuid and name', ->
expect(@updateDevice).not.to.have.been.called
it 'should call the callback with an error', ->
expect(@error).to.exist
| true | describe 'claimDevice', ->
beforeEach ->
@updateDevice = sinon.stub()
@canConfigure = sinon.stub()
@getDevice = sinon.stub()
@canConfigure.returns true
@dependencies = {updateDevice: @updateDevice, canConfigure: @canConfigure, getDevice: @getDevice}
@sut = require '../../lib/claimDevice'
it 'should be a function', ->
expect(@sut).to.be.a 'function'
describe 'when called with a bunch of nothing', ->
beforeEach (done) ->
storeError = (@error) => done()
@sut null, null, storeError, @dependencies
it 'should callback with an error', ->
expect(@error).to.exist
describe 'when called with a some of nothing', ->
beforeEach (done) ->
storeError = (@error) => done()
@sut {uuid: 'something'}, null, storeError, @dependencies
it 'should callback with an error', ->
expect(@error).to.exist
describe 'when called with a bunch of something', ->
beforeEach (done) ->
@fromDevice = {uuid: '89e9cd5f-dfff-4771-b821-d35614b7a506'}
@device = {uuid: '07a4ed85-acc5-4495-b3d7-2d93439c04fa'}
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@updateDevice.yields null, @device
@sut @fromDevice, @device, done, @dependencies
it 'should call updateDevice with that uuid and name', ->
expect(@updateDevice).to.have.been.calledWith @device.uuid, {owner: @fromDevice.uuid, uuid: @device.uuid, discoverWhitelist: [@fromDevice.uuid], ipAddress: '192.168.1.1'}
describe 'when called with params other than uuid', ->
beforeEach (done) ->
@fromDevice = {uuid: '89e9cd5f-dfff-4771-b821-d35614b7a506'}
@device = {uuid: '07a4ed85-acc5-4495-b3d7-2d93439c04fa', name: 'Cookie Crisp'}
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@updateDevice.yields null, @device
@sut @fromDevice, @device, done, @dependencies
it 'should call updateDevice with that uuid and name', ->
expect(@updateDevice).to.have.been.calledWith @device.uuid, {owner: @fromDevice.uuid, name: 'Cookie Crisp', uuid: @device.uuid, discoverWhitelist: [@fromDevice.uuid], ipAddress: '192.168.1.1'}
describe 'when called with an owner param', ->
beforeEach (done) ->
@fromDevice = {uuid: 'e33c1844-6888-4698-852a-7be584327a1d'}
@device = {uuid: '9b97159e-63c2-4a71-9327-8fadad97f1e9', name: 'PI:NAME:<NAME>END_PI', owner: 'wrong'}
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@updateDevice.yields null, @device
@sut @fromDevice, @device, done, @dependencies
it 'should call updateDevice with that uuid and name', ->
expect(@updateDevice).to.have.been.calledWith @device.uuid, {owner: @fromDevice.uuid, name: 'PI:NAME:<NAME>END_PI', uuid: @device.uuid, discoverWhitelist: [@fromDevice.uuid], ipAddress: '192.168.1.1'}
describe 'when called by a non-authorized user', ->
beforeEach (done) ->
@fromDevice = {uuid: '1267b0fe-407a-4872-b09d-dd4853d59d76'}
@device = {uuid: '9b97159e-63c2-4a71-9327-8fadad97f1e9', name: 'PI:NAME:<NAME>END_PI'}
storeError = (@error) => done()
@canConfigure.returns false
@getDevice.yields null, {ipAddress: '192.168.1.1'}
@sut @fromDevice, @device, storeError, @dependencies
it 'should call canConfigure with fromDevice, device with the ipAddress mixed in', ->
expect(@canConfigure).to.have.been.calledWith @fromDevice, {
uuid: '9b97159e-63c2-4a71-9327-8fadad97f1e9'
ipAddress: '192.168.1.1'
name: 'PI:NAME:<NAME>END_PI'
}
it 'should not call updateDevice with that uuid and name', ->
expect(@updateDevice).not.to.have.been.called
it 'should call the callback with an error', ->
expect(@error).to.exist
|
[
{
"context": "r the License.\n#\n\nclass MDNS\n @MDNS_ADDRESS = \"224.0.0.251\" #default ip\n @MDNS_PORT = 5353 #default p",
"end": 654,
"score": 0.9997417330741882,
"start": 643,
"tag": "IP_ADDRESS",
"value": "224.0.0.251"
}
] | lib/mdns/MDNSHelper.coffee | waitliu/flingd-coffee | 0 | #
# Copyright (C) 2013-2014, The OpenFlint Open Source Project
#
# 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.
#
class MDNS
@MDNS_ADDRESS = "224.0.0.251" #default ip
@MDNS_PORT = 5353 #default port
@MDNS_TTL = 20
@MDNS_LOOPBACK_MODE = true
@OPCODE_QUERY = 0
@OPCODE_INVERSE_QUERY = 1
@OPCODE_STATUS = 2
@RESPONSE_CODE_OK = 0
@RESPONSE_CODE_FORMAT_ERROR = 1
@RESPONSE_CODE_SERVER_ERROR = 2
@RESPONSE_CODE_NAME_ERROR = 3
@RESPONSE_CODE_NOT_IMPLEMENTED = 4
@RESPONSE_CODE_REFUSED = 5
@MAX_MSG_TYPICAL = 1460 # unused
@MAX_MSG_ABSOLUTE = 8972
@FLAGS_QR_MASK = 0x8000 # query response mask
@FLAGS_QR_QUERY = 0x0000 # query
@FLAGS_QR_RESPONSE = 0x8000 # response
@FLAGS_AA = 0x0400 # Authorative answer
@FLAGS_TC = 0x0200 # Truncated
@FLAGS_RD = 0x0100 # Recursion desired
@FLAGS_RA = 0x8000 # Recursion available
@FLAGS_Z = 0x0040 # Zero
@FLAGS_AD = 0x0020 # Authentic data
@FLAGS_CD = 0x0010 # Checking disabled
@CLASS_IN = 1
@CLASS_CS = 2
@CLASS_CH = 3
@CLASS_HS = 4
@CLASS_NONE = 254
@CLASS_ANY = 255
@CLASS_MASK = 0x7FFF
@CLASS_UNIQUE = 0x8000
@TYPE_A = 1 # host address
@TYPE_NS = 2
@TYPE_MD = 3
@TYPE_MF = 4
@TYPE_CNAME = 5
@TYPE_SOA = 6
@TYPE_MB = 7
@TYPE_MG = 8
@TYPE_MR = 9
@TYPE_NULL = 10
@TYPE_WKS = 11
@TYPE_PTR = 12
@TYPE_HINFO = 13
@TYPE_MINFO = 14
@TYPE_MX = 15
@TYPE_TXT = 16
@TYPE_AAAA = 28
@TYPE_SRV = 0x0021 # service location
@TYPE_NSEC = 0x002F # next secured
@TYPE_ANY = 255
@protocolHelperTcp: (string) ->
return "_"+string+"._tcp.local"
@protocolHelperUdp: (string) ->
return "_"+string+"._udp.local"
@stringToUtf8ByteArray: (string) ->
byteArray = []
for i in [0..string.length-1]
code = string.charCodeAt(i)
if code < 0x80
byteArray.push code
else if code < 0x800
byteArray.push 0xC0|((code >> 6) & 0x1F)
byteArray.push 0x80|(code & 0x3F)
else if code < 0x00010000
byteArray.push 0xE0|((code >> 12) & 0x0F)
byteArray.push 0x80|((code >> 6) & 0x3F)
byteArray.push 0x80|(code & 0x3F)
else
byteArray.push 0xF0|(code >> 18)
byteArray.push 0x80|((code >> 12) & 0x3F)
byteArray.push 0x80|((code >> 6) & 0x3F)
byteArray.push 0x80|(code & 0x3F)
return byteArray
@utf8ByteArrayToString: (byteArray) ->
bstr = ""
nOffset = 0
nRemainingBytes = byteArray.length
nTotalChars = byteArray.length
iCode = 0
iCode1 = 0
iCode2 = 0
iCode3 = 0
while nTotalChars > nOffset
iCode = byteArray[nOffset]
if (iCode & 0x80) == 0 # 1 byte
if nRemainingBytes < 1 # not enough data
break
bstr += String.fromCharCode iCode & 0x7F
nOffset++
nRemainingBytes -= 1
else if (iCode & 0xE0) == 0xC0 # 2 bytes
iCode1 = byteArray[nOffset + 1]
if nRemainingBytes < 2 || (iCode1 & 0xC0) != 0x80
break
bstr += String.fromCharCode ((iCode & 0x3F) << 6) | (iCode1 & 0x3F)
nOffset += 2
nRemainingBytes -= 2
else if (iCode & 0xF0) == 0xE0 # 3 bytes
iCode1 = byteArray[nOffset + 1]
iCode2 = byteArray[nOffset + 2]
if nRemainingBytes < 3 || (iCode1 & 0xC0) != 0x80 || (iCode2 & 0xC0) != 0x80
break
bstr += String.fromCharCode (iCode & 0x0F) << 12 | ((iCode1 & 0x3F) << 6) | (iCode2 & 0x3F)
nOffset += 3
nRemainingBytes -= 3
else # 4 bytes
iCode1 = byteArray[nOffset + 1]
iCode2 = byteArray[nOffset + 2]
iCode3 = byteArray[nOffset + 3]
if nRemainingBytes < 4 || (iCode1 & 0xC0) != 0x80 || (iCode2 & 0xC0) != 0x80 || (iCode3 & 0xC0) != 0x80
break
bstr += String.fromCharCode (iCode & 0x0F) << 18 | ((iCode1 & 0x0F) << 12) | ((iCode3 & 0x3F) << 6) | (iCode3 & 0x3F)
nOffset += 4
nRemainingBytes -= 4
return bstr
@pad: (num, n, base=10) ->
numStr = num.toString(base)
len = numStr.length
while(len < n)
numStr = "0" + numStr
len++
return numStr
@ipReverse: (ipStr) ->
ipArray = ipStr.split "."
ipArray.reverse()
return ipArray.join "."
@encodeMessage: (message) ->
data = []
textMapping = {}
writeByte = (b, pos = null) ->
if pos != null
data[pos] = b
else
data.push b
return 1
writeWord = (w, pos = null) ->
if pos != null
return writeByte(w >> 8, pos) + writeByte(w & 0xFF, pos + 1)
else
return writeByte(w >> 8) + writeByte(w & 0xFF)
writeDWord = (d) ->
return writeWord(d >> 16) + writeWord(d & 0xFFFF)
writeByteArray = (b) ->
bytesWritten = 0
if b.length > 0
for i in [0 .. b.length - 1]
bytesWritten += writeByte b[i]
return bytesWritten
writeIPAddress = (a) ->
parts = a.split(".")
bytesWritten = 0
if parts.length > 0
for i in [0 .. parts.length - 1]
bytesWritten += writeByte parseInt parts[i]
return bytesWritten
writeIP6Address = (a) ->
parts = a.split(":")
zeroCount = 8 - parts.length
for i in [0 .. parts.length - 1]
if parts[i]
writeWord parseInt parts[i], 16
else
while zeroCount >= 0
writeWord 0
zeroCount -= 1
return 16
writeStringArray = (parts, includeLastTerminator) ->
brokeEarly = false
bytesWritten = 0
if parts.length > 0
for i in [0 .. parts.length - 1]
remainingString = parts.slice(i).join("._-_.")
location = textMapping[remainingString]
if location
brokeEarly = true
bytesWritten += writeByte 0xC0
bytesWritten += writeByte location
break
if data.length < 256 # we can't ever shortcut to a position after the first 256 bytes
textMapping[remainingString] = data.length
part = parts[i]
# utf-8 byte array
part = MDNS.stringToUtf8ByteArray part
bytesWritten += writeByte part.length
if part.length > 0
for j in [0 .. part.length - 1]
bytesWritten += writeByte part[j]
if not brokeEarly and includeLastTerminator
bytesWritten += writeByte 0
return bytesWritten
writeDNSName = (n) ->
parts = n.split(".")
return writeStringArray(parts, true)
writeQuestion = (q) ->
writeDNSName q.name
writeWord q.type
if q.unicast
q.class |= MDNS.CLASS_UNIQUE
writeWord q.class
writeRecord = (r) ->
writeDNSName r.name
writeWord r.type
writeWord r.class #| if r.flushCache then 0x8000 else 0
writeDWord r.timeToLive
switch r.type
when MDNS.TYPE_NSEC
lengthPos = data.length
writeWord 0
length = writeDNSName r.nsec_domainName
length += writeByte 0 # offset (always 0)
r.nsec_types.sort()
bytesNeeded = Math.ceil r.nsec_types[r.nsec_types.length - 1] / 8
length += writeByte bytesNeeded
bitMapArray = new Uint8Array bytesNeeded
#bitMapArray block 0, bit 1 corresponds to RR type 1 (A), bit 2 corresponds to RR type 2 (NS), and so forth.
# look rfc4034
if r.nsec_types.length > 0
for i in [0 .. r.nsec_types.length - 1]
type = r.nsec_types[i]
byteNum = Math.floor type / 8
bitNum = type % 8
bitMapArray[byteNum] |= 1 << (7 - bitNum)
length += writeByteArray bitMapArray
writeWord length, lengthPos
when MDNS.TYPE_TXT
lengthPos = data.length
writeWord 0
length = writeStringArray r.txt_texts, false
writeWord length, lengthPos
when MDNS.TYPE_A
lengthPos = data.length
writeWord 0
length = writeIPAddress r.a_address
writeWord length, lengthPos
when MDNS.TYPE_AAAA
lengthPos = data.length
writeWord 0
length = writeIP6Address r.a_address
writeWord length, lengthPos
when MDNS.TYPE_SRV
lengthPos = data.length
writeWord 0
length = writeWord r.srv_priority
length += writeWord r.srv_weight
length += writeWord r.srv_port
length += writeDNSName r.srv_target
writeWord length, lengthPos
when MDNS.TYPE_PTR
lengthPos = data.length
writeWord 0
length = writeDNSName r.ptr_domainName
writeWord length, lengthPos
else
writeWord r.resourceData.length
writeByteArray r.resourceData
writeWord message.transactionID
flags = 0
if not message.isQuery then flags |= 0x8000
flags |= (message.opCode & 0xFF) << 11
if message.authoritativeAnswer then flags |= 0x400
if message.truncated then flags |= 0x200
if message.recursionDesired then flags |= 0x100
if message.recursionAvailable then flags |= 0x80
flags |= message.responseCode & 0xF
writeWord flags
writeWord message.questions.length
writeWord message.answers.length
writeWord message.autorityRecords.length
writeWord message.additionalRecords.length
if message.questions.length > 0
for i in [0 .. message.questions.length-1]
writeQuestion message.questions[i]
if message.answers.length > 0
for i in [0 .. message.answers.length-1]
writeRecord message.answers[i]
if message.autorityRecords.length > 0
for i in [0 .. message.autorityRecords.length-1]
writeRecord message.autorityRecords[i]
if message.additionalRecords.length > 0
for i in [0 .. message.additionalRecords.length-1]
writeRecord message.additionalRecords[i]
return data
@decodeMessage: (rawData) ->
position = 0
errored = false
consumeByte = ->
if position + 1 > rawData.length
if not errored
errored = true
return rawData[position++]
consumeWord = ->
return (consumeByte() << 8) | consumeByte()
consumeDWord = ->
return (consumeWord() << 16) | consumeWord()
consumeDNSName = ->
parts = []
while true
if position >= rawData.length then break
partLength = consumeByte()
if partLength == 0 then break
if partLength == 0xC0
bytePosition = consumeByte()
oldPosition = position
position = bytePosition
parts = parts.concat consumeDNSName().split(".")
position = oldPosition
break
if position + partLength > rawData.length
if not errored
errored = true
partLength = rawData.length - position
stringArray = []
while partLength-- > 0
stringArray.push consumeByte()
part = MDNS.utf8ByteArrayToString stringArray
parts.push part
return parts.join "."
consumeQuestion = ->
question = {}
question.name = consumeDNSName()
question.type = consumeWord()
question.class = consumeWord()
question.unicast = (question.class & 0x8000) != 0
question.class &= 0x7FFF
return question
consumeByteArray = (length) ->
length = Math.min length, rawData.length - position
if length <= 0
return ""
data = new Array length
for i in [0 .. length-1]
data[i] = consumeByte()
return MDNS.utf8ByteArrayToString data
consumeIPAddress = (length) ->
ipArr = []
for i in [0..length-1]
ipArr.push consumeByte()
return ipArr.join "."
consumeIP6Address = () ->
ipArr = []
for i in [0..7]
ipArr.push consumeWord()
return ipArr.join ":"
consumeResourceRecord = ->
resource = {}
resource.name = consumeDNSName()
resource.type = consumeWord()
resource.class = consumeWord()
resource.flushCache = (resource.class & 0x8000) != 0
resource.class &= 0x7FFF
resource.timeToLive = consumeDWord()
extraDataLength = consumeWord()
switch resource.type
when MDNS.TYPE_TXT
resourceData = []
totalLength = 0
while extraDataLength > totalLength
subLength = consumeByte()
totalLength += subLength + 1
tempStr = consumeByteArray subLength
resourceData.push tempStr
resource.resourceData = resourceData
when MDNS.TYPE_A
resource.resourceData = consumeIPAddress extraDataLength
when MDNS.TYPE_AAAA
resource.resourceData = consumeIP6Address()
when MDNS.TYPE_SRV
resourceData = {}
resourceData.srv_priority = consumeWord()
resourceData.srv_weight = consumeWord()
resourceData.srv_port = consumeWord()
resourceData.srv_target = consumeDNSName()
resource.resourceData = resourceData
when MDNS.TYPE_PTR
resource.resourceData = consumeDNSName()
else
if extraDataLength > 0
resource.resourceData = consumeByteArray extraDataLength
return resource
result = {}
result.transactionID = consumeWord()
flags = consumeWord()
result.isQuery = (flags & 0x8000) == 0
result.opCode = (flags >> 11) & 0xF
result.authoritativeAnswer = (flags & 0x400) != 0
result.truncated = (flags & 0x200) != 0
result.recursionDesired = (flags & 0x100) != 0
result.recursionAvailable = (flags & 0x80) != 0
result.responseCode = flags & 0xF
questionCount = consumeWord()
answerCount = consumeWord()
authorityRecordsCount = consumeWord()
additionalRecordsCount = consumeWord()
result.questions = []
result.answers = []
result.autorityRecords = []
result.additionalRecords = []
if questionCount > 0
for [1 .. questionCount]
result.questions.push consumeQuestion()
if answerCount > 0
for [1 .. answerCount]
result.answers.push consumeResourceRecord()
if authorityRecordsCount > 0
for [1 .. authorityRecordsCount]
result.autorityRecords.push consumeResourceRecord()
if additionalRecordsCount > 0
for [1 .. additionalRecordsCount]
result.additionalRecords.push consumeResourceRecord()
return result
@map2txt: (txtRecord) ->
txt_texts = []
for k,v of txtRecord
txt_texts.push k + "=" + v
return txt_texts
@creatDnsSdRequest: (transactionID, fullProtocol) ->
response =
transactionID: transactionID, # max 65535
isQuery: false,
opCode: 0,
authoritativeAnswer: true,
truncated: false,
recursionDesired: false,
recursionAvailable: false,
responseCode: MDNS.RESPONSE_CODE_OK,
questions: [],
answers: [],
additionalRecords: [],
autorityRecords: []
response.questions.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
unicast: false
return response
@creatDnsSdKeepResponse: (transactionID, fullProtocol, serverName, port, txtRecord, address, localName) ->
response =
transactionID: transactionID, # max 65535
isQuery: false,
opCode: 0,
authoritativeAnswer: true,
truncated: false,
recursionDesired: false,
recursionAvailable: false,
responseCode: MDNS.RESPONSE_CODE_OK,
questions: [],
answers: [],
additionalRecords: [],
autorityRecords: []
response.answers.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
ptr_domainName: serverName + "."+fullProtocol
response.answers.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_SRV,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
srv_priority: 0,
srv_weight: 0,
srv_port: port,
srv_target: localName + ".local"
response.answers.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_TXT,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
txt_texts: MDNS.map2txt txtRecord
response.answers.push
name: localName + ".local",
type: MDNS.TYPE_A,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
a_address: address.ipv4
response.answers.push
name: "_services._dns-sd._udp.local",
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 4500,
ptr_domainName: fullProtocol
return response
@creatDnsSdResponse: (transactionID, fullProtocol, serverName, port, txtRecord, address, localName) ->
response =
transactionID: transactionID, # max 65535
isQuery: false,
opCode: 0,
authoritativeAnswer: true,
truncated: false,
recursionDesired: false,
recursionAvailable: false,
responseCode: MDNS.RESPONSE_CODE_OK,
questions: [],
answers: [],
additionalRecords: [],
autorityRecords: []
response.questions.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
unicast: true
response.answers.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
ptr_domainName: serverName + "."+fullProtocol
response.additionalRecords.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_SRV,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
srv_priority: 0,
srv_weight: 0,
srv_port: port,
srv_target: localName + ".local"
if txtRecord
response.additionalRecords.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_TXT,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
txt_texts: MDNS.map2txt txtRecord
if address.ipv6
response.additionalRecords.push
name: localName + ".local",
type: MDNS.TYPE_AAAA,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
a_address: address.ipv6
response.additionalRecords.push
name: localName + ".local",
type: MDNS.TYPE_A,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
a_address: address.ipv4
return response
@parseDnsSdResponse : (response) ->
serverInfo = {}
for i of response.additionalRecords
tempRecode = response.additionalRecords[i]
if tempRecode.type == MDNS.TYPE_SRV
protocolArray = tempRecode.name.split "."
serverInfo.name = protocolArray[0]
serverInfo.protocol = protocolArray[1]
serverInfo.protocol_type = protocolArray[2]
serverInfo.srv_priority = tempRecode.resourceData.srv_priority
serverInfo.srv_weight = tempRecode.resourceData.srv_weight
serverInfo.srv_port = tempRecode.resourceData.srv_port
serverInfo.srv_target = tempRecode.resourceData.srv_target
else if tempRecode.type == MDNS.TYPE_TXT
tempMap = {}
for j of tempRecode.resourceData
tempArr = tempRecode.resourceData[j].split "="
tempMap[tempArr[0]] = tempArr[1]
serverInfo.txt_texts = tempMap
else if tempRecode.type == MDNS.TYPE_AAAA
serverInfo.ipv6 = tempRecode.resourceData
else if tempRecode.type == MDNS.TYPE_A
serverInfo.ipv4 = tempRecode.resourceData
return serverInfo
module.exports.MDNSHelper = MDNS
| 66153 | #
# Copyright (C) 2013-2014, The OpenFlint Open Source Project
#
# 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.
#
class MDNS
@MDNS_ADDRESS = "172.16.58.3" #default ip
@MDNS_PORT = 5353 #default port
@MDNS_TTL = 20
@MDNS_LOOPBACK_MODE = true
@OPCODE_QUERY = 0
@OPCODE_INVERSE_QUERY = 1
@OPCODE_STATUS = 2
@RESPONSE_CODE_OK = 0
@RESPONSE_CODE_FORMAT_ERROR = 1
@RESPONSE_CODE_SERVER_ERROR = 2
@RESPONSE_CODE_NAME_ERROR = 3
@RESPONSE_CODE_NOT_IMPLEMENTED = 4
@RESPONSE_CODE_REFUSED = 5
@MAX_MSG_TYPICAL = 1460 # unused
@MAX_MSG_ABSOLUTE = 8972
@FLAGS_QR_MASK = 0x8000 # query response mask
@FLAGS_QR_QUERY = 0x0000 # query
@FLAGS_QR_RESPONSE = 0x8000 # response
@FLAGS_AA = 0x0400 # Authorative answer
@FLAGS_TC = 0x0200 # Truncated
@FLAGS_RD = 0x0100 # Recursion desired
@FLAGS_RA = 0x8000 # Recursion available
@FLAGS_Z = 0x0040 # Zero
@FLAGS_AD = 0x0020 # Authentic data
@FLAGS_CD = 0x0010 # Checking disabled
@CLASS_IN = 1
@CLASS_CS = 2
@CLASS_CH = 3
@CLASS_HS = 4
@CLASS_NONE = 254
@CLASS_ANY = 255
@CLASS_MASK = 0x7FFF
@CLASS_UNIQUE = 0x8000
@TYPE_A = 1 # host address
@TYPE_NS = 2
@TYPE_MD = 3
@TYPE_MF = 4
@TYPE_CNAME = 5
@TYPE_SOA = 6
@TYPE_MB = 7
@TYPE_MG = 8
@TYPE_MR = 9
@TYPE_NULL = 10
@TYPE_WKS = 11
@TYPE_PTR = 12
@TYPE_HINFO = 13
@TYPE_MINFO = 14
@TYPE_MX = 15
@TYPE_TXT = 16
@TYPE_AAAA = 28
@TYPE_SRV = 0x0021 # service location
@TYPE_NSEC = 0x002F # next secured
@TYPE_ANY = 255
@protocolHelperTcp: (string) ->
return "_"+string+"._tcp.local"
@protocolHelperUdp: (string) ->
return "_"+string+"._udp.local"
@stringToUtf8ByteArray: (string) ->
byteArray = []
for i in [0..string.length-1]
code = string.charCodeAt(i)
if code < 0x80
byteArray.push code
else if code < 0x800
byteArray.push 0xC0|((code >> 6) & 0x1F)
byteArray.push 0x80|(code & 0x3F)
else if code < 0x00010000
byteArray.push 0xE0|((code >> 12) & 0x0F)
byteArray.push 0x80|((code >> 6) & 0x3F)
byteArray.push 0x80|(code & 0x3F)
else
byteArray.push 0xF0|(code >> 18)
byteArray.push 0x80|((code >> 12) & 0x3F)
byteArray.push 0x80|((code >> 6) & 0x3F)
byteArray.push 0x80|(code & 0x3F)
return byteArray
@utf8ByteArrayToString: (byteArray) ->
bstr = ""
nOffset = 0
nRemainingBytes = byteArray.length
nTotalChars = byteArray.length
iCode = 0
iCode1 = 0
iCode2 = 0
iCode3 = 0
while nTotalChars > nOffset
iCode = byteArray[nOffset]
if (iCode & 0x80) == 0 # 1 byte
if nRemainingBytes < 1 # not enough data
break
bstr += String.fromCharCode iCode & 0x7F
nOffset++
nRemainingBytes -= 1
else if (iCode & 0xE0) == 0xC0 # 2 bytes
iCode1 = byteArray[nOffset + 1]
if nRemainingBytes < 2 || (iCode1 & 0xC0) != 0x80
break
bstr += String.fromCharCode ((iCode & 0x3F) << 6) | (iCode1 & 0x3F)
nOffset += 2
nRemainingBytes -= 2
else if (iCode & 0xF0) == 0xE0 # 3 bytes
iCode1 = byteArray[nOffset + 1]
iCode2 = byteArray[nOffset + 2]
if nRemainingBytes < 3 || (iCode1 & 0xC0) != 0x80 || (iCode2 & 0xC0) != 0x80
break
bstr += String.fromCharCode (iCode & 0x0F) << 12 | ((iCode1 & 0x3F) << 6) | (iCode2 & 0x3F)
nOffset += 3
nRemainingBytes -= 3
else # 4 bytes
iCode1 = byteArray[nOffset + 1]
iCode2 = byteArray[nOffset + 2]
iCode3 = byteArray[nOffset + 3]
if nRemainingBytes < 4 || (iCode1 & 0xC0) != 0x80 || (iCode2 & 0xC0) != 0x80 || (iCode3 & 0xC0) != 0x80
break
bstr += String.fromCharCode (iCode & 0x0F) << 18 | ((iCode1 & 0x0F) << 12) | ((iCode3 & 0x3F) << 6) | (iCode3 & 0x3F)
nOffset += 4
nRemainingBytes -= 4
return bstr
@pad: (num, n, base=10) ->
numStr = num.toString(base)
len = numStr.length
while(len < n)
numStr = "0" + numStr
len++
return numStr
@ipReverse: (ipStr) ->
ipArray = ipStr.split "."
ipArray.reverse()
return ipArray.join "."
@encodeMessage: (message) ->
data = []
textMapping = {}
writeByte = (b, pos = null) ->
if pos != null
data[pos] = b
else
data.push b
return 1
writeWord = (w, pos = null) ->
if pos != null
return writeByte(w >> 8, pos) + writeByte(w & 0xFF, pos + 1)
else
return writeByte(w >> 8) + writeByte(w & 0xFF)
writeDWord = (d) ->
return writeWord(d >> 16) + writeWord(d & 0xFFFF)
writeByteArray = (b) ->
bytesWritten = 0
if b.length > 0
for i in [0 .. b.length - 1]
bytesWritten += writeByte b[i]
return bytesWritten
writeIPAddress = (a) ->
parts = a.split(".")
bytesWritten = 0
if parts.length > 0
for i in [0 .. parts.length - 1]
bytesWritten += writeByte parseInt parts[i]
return bytesWritten
writeIP6Address = (a) ->
parts = a.split(":")
zeroCount = 8 - parts.length
for i in [0 .. parts.length - 1]
if parts[i]
writeWord parseInt parts[i], 16
else
while zeroCount >= 0
writeWord 0
zeroCount -= 1
return 16
writeStringArray = (parts, includeLastTerminator) ->
brokeEarly = false
bytesWritten = 0
if parts.length > 0
for i in [0 .. parts.length - 1]
remainingString = parts.slice(i).join("._-_.")
location = textMapping[remainingString]
if location
brokeEarly = true
bytesWritten += writeByte 0xC0
bytesWritten += writeByte location
break
if data.length < 256 # we can't ever shortcut to a position after the first 256 bytes
textMapping[remainingString] = data.length
part = parts[i]
# utf-8 byte array
part = MDNS.stringToUtf8ByteArray part
bytesWritten += writeByte part.length
if part.length > 0
for j in [0 .. part.length - 1]
bytesWritten += writeByte part[j]
if not brokeEarly and includeLastTerminator
bytesWritten += writeByte 0
return bytesWritten
writeDNSName = (n) ->
parts = n.split(".")
return writeStringArray(parts, true)
writeQuestion = (q) ->
writeDNSName q.name
writeWord q.type
if q.unicast
q.class |= MDNS.CLASS_UNIQUE
writeWord q.class
writeRecord = (r) ->
writeDNSName r.name
writeWord r.type
writeWord r.class #| if r.flushCache then 0x8000 else 0
writeDWord r.timeToLive
switch r.type
when MDNS.TYPE_NSEC
lengthPos = data.length
writeWord 0
length = writeDNSName r.nsec_domainName
length += writeByte 0 # offset (always 0)
r.nsec_types.sort()
bytesNeeded = Math.ceil r.nsec_types[r.nsec_types.length - 1] / 8
length += writeByte bytesNeeded
bitMapArray = new Uint8Array bytesNeeded
#bitMapArray block 0, bit 1 corresponds to RR type 1 (A), bit 2 corresponds to RR type 2 (NS), and so forth.
# look rfc4034
if r.nsec_types.length > 0
for i in [0 .. r.nsec_types.length - 1]
type = r.nsec_types[i]
byteNum = Math.floor type / 8
bitNum = type % 8
bitMapArray[byteNum] |= 1 << (7 - bitNum)
length += writeByteArray bitMapArray
writeWord length, lengthPos
when MDNS.TYPE_TXT
lengthPos = data.length
writeWord 0
length = writeStringArray r.txt_texts, false
writeWord length, lengthPos
when MDNS.TYPE_A
lengthPos = data.length
writeWord 0
length = writeIPAddress r.a_address
writeWord length, lengthPos
when MDNS.TYPE_AAAA
lengthPos = data.length
writeWord 0
length = writeIP6Address r.a_address
writeWord length, lengthPos
when MDNS.TYPE_SRV
lengthPos = data.length
writeWord 0
length = writeWord r.srv_priority
length += writeWord r.srv_weight
length += writeWord r.srv_port
length += writeDNSName r.srv_target
writeWord length, lengthPos
when MDNS.TYPE_PTR
lengthPos = data.length
writeWord 0
length = writeDNSName r.ptr_domainName
writeWord length, lengthPos
else
writeWord r.resourceData.length
writeByteArray r.resourceData
writeWord message.transactionID
flags = 0
if not message.isQuery then flags |= 0x8000
flags |= (message.opCode & 0xFF) << 11
if message.authoritativeAnswer then flags |= 0x400
if message.truncated then flags |= 0x200
if message.recursionDesired then flags |= 0x100
if message.recursionAvailable then flags |= 0x80
flags |= message.responseCode & 0xF
writeWord flags
writeWord message.questions.length
writeWord message.answers.length
writeWord message.autorityRecords.length
writeWord message.additionalRecords.length
if message.questions.length > 0
for i in [0 .. message.questions.length-1]
writeQuestion message.questions[i]
if message.answers.length > 0
for i in [0 .. message.answers.length-1]
writeRecord message.answers[i]
if message.autorityRecords.length > 0
for i in [0 .. message.autorityRecords.length-1]
writeRecord message.autorityRecords[i]
if message.additionalRecords.length > 0
for i in [0 .. message.additionalRecords.length-1]
writeRecord message.additionalRecords[i]
return data
@decodeMessage: (rawData) ->
position = 0
errored = false
consumeByte = ->
if position + 1 > rawData.length
if not errored
errored = true
return rawData[position++]
consumeWord = ->
return (consumeByte() << 8) | consumeByte()
consumeDWord = ->
return (consumeWord() << 16) | consumeWord()
consumeDNSName = ->
parts = []
while true
if position >= rawData.length then break
partLength = consumeByte()
if partLength == 0 then break
if partLength == 0xC0
bytePosition = consumeByte()
oldPosition = position
position = bytePosition
parts = parts.concat consumeDNSName().split(".")
position = oldPosition
break
if position + partLength > rawData.length
if not errored
errored = true
partLength = rawData.length - position
stringArray = []
while partLength-- > 0
stringArray.push consumeByte()
part = MDNS.utf8ByteArrayToString stringArray
parts.push part
return parts.join "."
consumeQuestion = ->
question = {}
question.name = consumeDNSName()
question.type = consumeWord()
question.class = consumeWord()
question.unicast = (question.class & 0x8000) != 0
question.class &= 0x7FFF
return question
consumeByteArray = (length) ->
length = Math.min length, rawData.length - position
if length <= 0
return ""
data = new Array length
for i in [0 .. length-1]
data[i] = consumeByte()
return MDNS.utf8ByteArrayToString data
consumeIPAddress = (length) ->
ipArr = []
for i in [0..length-1]
ipArr.push consumeByte()
return ipArr.join "."
consumeIP6Address = () ->
ipArr = []
for i in [0..7]
ipArr.push consumeWord()
return ipArr.join ":"
consumeResourceRecord = ->
resource = {}
resource.name = consumeDNSName()
resource.type = consumeWord()
resource.class = consumeWord()
resource.flushCache = (resource.class & 0x8000) != 0
resource.class &= 0x7FFF
resource.timeToLive = consumeDWord()
extraDataLength = consumeWord()
switch resource.type
when MDNS.TYPE_TXT
resourceData = []
totalLength = 0
while extraDataLength > totalLength
subLength = consumeByte()
totalLength += subLength + 1
tempStr = consumeByteArray subLength
resourceData.push tempStr
resource.resourceData = resourceData
when MDNS.TYPE_A
resource.resourceData = consumeIPAddress extraDataLength
when MDNS.TYPE_AAAA
resource.resourceData = consumeIP6Address()
when MDNS.TYPE_SRV
resourceData = {}
resourceData.srv_priority = consumeWord()
resourceData.srv_weight = consumeWord()
resourceData.srv_port = consumeWord()
resourceData.srv_target = consumeDNSName()
resource.resourceData = resourceData
when MDNS.TYPE_PTR
resource.resourceData = consumeDNSName()
else
if extraDataLength > 0
resource.resourceData = consumeByteArray extraDataLength
return resource
result = {}
result.transactionID = consumeWord()
flags = consumeWord()
result.isQuery = (flags & 0x8000) == 0
result.opCode = (flags >> 11) & 0xF
result.authoritativeAnswer = (flags & 0x400) != 0
result.truncated = (flags & 0x200) != 0
result.recursionDesired = (flags & 0x100) != 0
result.recursionAvailable = (flags & 0x80) != 0
result.responseCode = flags & 0xF
questionCount = consumeWord()
answerCount = consumeWord()
authorityRecordsCount = consumeWord()
additionalRecordsCount = consumeWord()
result.questions = []
result.answers = []
result.autorityRecords = []
result.additionalRecords = []
if questionCount > 0
for [1 .. questionCount]
result.questions.push consumeQuestion()
if answerCount > 0
for [1 .. answerCount]
result.answers.push consumeResourceRecord()
if authorityRecordsCount > 0
for [1 .. authorityRecordsCount]
result.autorityRecords.push consumeResourceRecord()
if additionalRecordsCount > 0
for [1 .. additionalRecordsCount]
result.additionalRecords.push consumeResourceRecord()
return result
@map2txt: (txtRecord) ->
txt_texts = []
for k,v of txtRecord
txt_texts.push k + "=" + v
return txt_texts
@creatDnsSdRequest: (transactionID, fullProtocol) ->
response =
transactionID: transactionID, # max 65535
isQuery: false,
opCode: 0,
authoritativeAnswer: true,
truncated: false,
recursionDesired: false,
recursionAvailable: false,
responseCode: MDNS.RESPONSE_CODE_OK,
questions: [],
answers: [],
additionalRecords: [],
autorityRecords: []
response.questions.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
unicast: false
return response
@creatDnsSdKeepResponse: (transactionID, fullProtocol, serverName, port, txtRecord, address, localName) ->
response =
transactionID: transactionID, # max 65535
isQuery: false,
opCode: 0,
authoritativeAnswer: true,
truncated: false,
recursionDesired: false,
recursionAvailable: false,
responseCode: MDNS.RESPONSE_CODE_OK,
questions: [],
answers: [],
additionalRecords: [],
autorityRecords: []
response.answers.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
ptr_domainName: serverName + "."+fullProtocol
response.answers.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_SRV,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
srv_priority: 0,
srv_weight: 0,
srv_port: port,
srv_target: localName + ".local"
response.answers.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_TXT,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
txt_texts: MDNS.map2txt txtRecord
response.answers.push
name: localName + ".local",
type: MDNS.TYPE_A,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
a_address: address.ipv4
response.answers.push
name: "_services._dns-sd._udp.local",
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 4500,
ptr_domainName: fullProtocol
return response
@creatDnsSdResponse: (transactionID, fullProtocol, serverName, port, txtRecord, address, localName) ->
response =
transactionID: transactionID, # max 65535
isQuery: false,
opCode: 0,
authoritativeAnswer: true,
truncated: false,
recursionDesired: false,
recursionAvailable: false,
responseCode: MDNS.RESPONSE_CODE_OK,
questions: [],
answers: [],
additionalRecords: [],
autorityRecords: []
response.questions.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
unicast: true
response.answers.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
ptr_domainName: serverName + "."+fullProtocol
response.additionalRecords.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_SRV,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
srv_priority: 0,
srv_weight: 0,
srv_port: port,
srv_target: localName + ".local"
if txtRecord
response.additionalRecords.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_TXT,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
txt_texts: MDNS.map2txt txtRecord
if address.ipv6
response.additionalRecords.push
name: localName + ".local",
type: MDNS.TYPE_AAAA,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
a_address: address.ipv6
response.additionalRecords.push
name: localName + ".local",
type: MDNS.TYPE_A,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
a_address: address.ipv4
return response
@parseDnsSdResponse : (response) ->
serverInfo = {}
for i of response.additionalRecords
tempRecode = response.additionalRecords[i]
if tempRecode.type == MDNS.TYPE_SRV
protocolArray = tempRecode.name.split "."
serverInfo.name = protocolArray[0]
serverInfo.protocol = protocolArray[1]
serverInfo.protocol_type = protocolArray[2]
serverInfo.srv_priority = tempRecode.resourceData.srv_priority
serverInfo.srv_weight = tempRecode.resourceData.srv_weight
serverInfo.srv_port = tempRecode.resourceData.srv_port
serverInfo.srv_target = tempRecode.resourceData.srv_target
else if tempRecode.type == MDNS.TYPE_TXT
tempMap = {}
for j of tempRecode.resourceData
tempArr = tempRecode.resourceData[j].split "="
tempMap[tempArr[0]] = tempArr[1]
serverInfo.txt_texts = tempMap
else if tempRecode.type == MDNS.TYPE_AAAA
serverInfo.ipv6 = tempRecode.resourceData
else if tempRecode.type == MDNS.TYPE_A
serverInfo.ipv4 = tempRecode.resourceData
return serverInfo
module.exports.MDNSHelper = MDNS
| true | #
# Copyright (C) 2013-2014, The OpenFlint Open Source Project
#
# 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.
#
class MDNS
@MDNS_ADDRESS = "PI:IP_ADDRESS:172.16.58.3END_PI" #default ip
@MDNS_PORT = 5353 #default port
@MDNS_TTL = 20
@MDNS_LOOPBACK_MODE = true
@OPCODE_QUERY = 0
@OPCODE_INVERSE_QUERY = 1
@OPCODE_STATUS = 2
@RESPONSE_CODE_OK = 0
@RESPONSE_CODE_FORMAT_ERROR = 1
@RESPONSE_CODE_SERVER_ERROR = 2
@RESPONSE_CODE_NAME_ERROR = 3
@RESPONSE_CODE_NOT_IMPLEMENTED = 4
@RESPONSE_CODE_REFUSED = 5
@MAX_MSG_TYPICAL = 1460 # unused
@MAX_MSG_ABSOLUTE = 8972
@FLAGS_QR_MASK = 0x8000 # query response mask
@FLAGS_QR_QUERY = 0x0000 # query
@FLAGS_QR_RESPONSE = 0x8000 # response
@FLAGS_AA = 0x0400 # Authorative answer
@FLAGS_TC = 0x0200 # Truncated
@FLAGS_RD = 0x0100 # Recursion desired
@FLAGS_RA = 0x8000 # Recursion available
@FLAGS_Z = 0x0040 # Zero
@FLAGS_AD = 0x0020 # Authentic data
@FLAGS_CD = 0x0010 # Checking disabled
@CLASS_IN = 1
@CLASS_CS = 2
@CLASS_CH = 3
@CLASS_HS = 4
@CLASS_NONE = 254
@CLASS_ANY = 255
@CLASS_MASK = 0x7FFF
@CLASS_UNIQUE = 0x8000
@TYPE_A = 1 # host address
@TYPE_NS = 2
@TYPE_MD = 3
@TYPE_MF = 4
@TYPE_CNAME = 5
@TYPE_SOA = 6
@TYPE_MB = 7
@TYPE_MG = 8
@TYPE_MR = 9
@TYPE_NULL = 10
@TYPE_WKS = 11
@TYPE_PTR = 12
@TYPE_HINFO = 13
@TYPE_MINFO = 14
@TYPE_MX = 15
@TYPE_TXT = 16
@TYPE_AAAA = 28
@TYPE_SRV = 0x0021 # service location
@TYPE_NSEC = 0x002F # next secured
@TYPE_ANY = 255
@protocolHelperTcp: (string) ->
return "_"+string+"._tcp.local"
@protocolHelperUdp: (string) ->
return "_"+string+"._udp.local"
@stringToUtf8ByteArray: (string) ->
byteArray = []
for i in [0..string.length-1]
code = string.charCodeAt(i)
if code < 0x80
byteArray.push code
else if code < 0x800
byteArray.push 0xC0|((code >> 6) & 0x1F)
byteArray.push 0x80|(code & 0x3F)
else if code < 0x00010000
byteArray.push 0xE0|((code >> 12) & 0x0F)
byteArray.push 0x80|((code >> 6) & 0x3F)
byteArray.push 0x80|(code & 0x3F)
else
byteArray.push 0xF0|(code >> 18)
byteArray.push 0x80|((code >> 12) & 0x3F)
byteArray.push 0x80|((code >> 6) & 0x3F)
byteArray.push 0x80|(code & 0x3F)
return byteArray
@utf8ByteArrayToString: (byteArray) ->
bstr = ""
nOffset = 0
nRemainingBytes = byteArray.length
nTotalChars = byteArray.length
iCode = 0
iCode1 = 0
iCode2 = 0
iCode3 = 0
while nTotalChars > nOffset
iCode = byteArray[nOffset]
if (iCode & 0x80) == 0 # 1 byte
if nRemainingBytes < 1 # not enough data
break
bstr += String.fromCharCode iCode & 0x7F
nOffset++
nRemainingBytes -= 1
else if (iCode & 0xE0) == 0xC0 # 2 bytes
iCode1 = byteArray[nOffset + 1]
if nRemainingBytes < 2 || (iCode1 & 0xC0) != 0x80
break
bstr += String.fromCharCode ((iCode & 0x3F) << 6) | (iCode1 & 0x3F)
nOffset += 2
nRemainingBytes -= 2
else if (iCode & 0xF0) == 0xE0 # 3 bytes
iCode1 = byteArray[nOffset + 1]
iCode2 = byteArray[nOffset + 2]
if nRemainingBytes < 3 || (iCode1 & 0xC0) != 0x80 || (iCode2 & 0xC0) != 0x80
break
bstr += String.fromCharCode (iCode & 0x0F) << 12 | ((iCode1 & 0x3F) << 6) | (iCode2 & 0x3F)
nOffset += 3
nRemainingBytes -= 3
else # 4 bytes
iCode1 = byteArray[nOffset + 1]
iCode2 = byteArray[nOffset + 2]
iCode3 = byteArray[nOffset + 3]
if nRemainingBytes < 4 || (iCode1 & 0xC0) != 0x80 || (iCode2 & 0xC0) != 0x80 || (iCode3 & 0xC0) != 0x80
break
bstr += String.fromCharCode (iCode & 0x0F) << 18 | ((iCode1 & 0x0F) << 12) | ((iCode3 & 0x3F) << 6) | (iCode3 & 0x3F)
nOffset += 4
nRemainingBytes -= 4
return bstr
@pad: (num, n, base=10) ->
numStr = num.toString(base)
len = numStr.length
while(len < n)
numStr = "0" + numStr
len++
return numStr
@ipReverse: (ipStr) ->
ipArray = ipStr.split "."
ipArray.reverse()
return ipArray.join "."
@encodeMessage: (message) ->
data = []
textMapping = {}
writeByte = (b, pos = null) ->
if pos != null
data[pos] = b
else
data.push b
return 1
writeWord = (w, pos = null) ->
if pos != null
return writeByte(w >> 8, pos) + writeByte(w & 0xFF, pos + 1)
else
return writeByte(w >> 8) + writeByte(w & 0xFF)
writeDWord = (d) ->
return writeWord(d >> 16) + writeWord(d & 0xFFFF)
writeByteArray = (b) ->
bytesWritten = 0
if b.length > 0
for i in [0 .. b.length - 1]
bytesWritten += writeByte b[i]
return bytesWritten
writeIPAddress = (a) ->
parts = a.split(".")
bytesWritten = 0
if parts.length > 0
for i in [0 .. parts.length - 1]
bytesWritten += writeByte parseInt parts[i]
return bytesWritten
writeIP6Address = (a) ->
parts = a.split(":")
zeroCount = 8 - parts.length
for i in [0 .. parts.length - 1]
if parts[i]
writeWord parseInt parts[i], 16
else
while zeroCount >= 0
writeWord 0
zeroCount -= 1
return 16
writeStringArray = (parts, includeLastTerminator) ->
brokeEarly = false
bytesWritten = 0
if parts.length > 0
for i in [0 .. parts.length - 1]
remainingString = parts.slice(i).join("._-_.")
location = textMapping[remainingString]
if location
brokeEarly = true
bytesWritten += writeByte 0xC0
bytesWritten += writeByte location
break
if data.length < 256 # we can't ever shortcut to a position after the first 256 bytes
textMapping[remainingString] = data.length
part = parts[i]
# utf-8 byte array
part = MDNS.stringToUtf8ByteArray part
bytesWritten += writeByte part.length
if part.length > 0
for j in [0 .. part.length - 1]
bytesWritten += writeByte part[j]
if not brokeEarly and includeLastTerminator
bytesWritten += writeByte 0
return bytesWritten
writeDNSName = (n) ->
parts = n.split(".")
return writeStringArray(parts, true)
writeQuestion = (q) ->
writeDNSName q.name
writeWord q.type
if q.unicast
q.class |= MDNS.CLASS_UNIQUE
writeWord q.class
writeRecord = (r) ->
writeDNSName r.name
writeWord r.type
writeWord r.class #| if r.flushCache then 0x8000 else 0
writeDWord r.timeToLive
switch r.type
when MDNS.TYPE_NSEC
lengthPos = data.length
writeWord 0
length = writeDNSName r.nsec_domainName
length += writeByte 0 # offset (always 0)
r.nsec_types.sort()
bytesNeeded = Math.ceil r.nsec_types[r.nsec_types.length - 1] / 8
length += writeByte bytesNeeded
bitMapArray = new Uint8Array bytesNeeded
#bitMapArray block 0, bit 1 corresponds to RR type 1 (A), bit 2 corresponds to RR type 2 (NS), and so forth.
# look rfc4034
if r.nsec_types.length > 0
for i in [0 .. r.nsec_types.length - 1]
type = r.nsec_types[i]
byteNum = Math.floor type / 8
bitNum = type % 8
bitMapArray[byteNum] |= 1 << (7 - bitNum)
length += writeByteArray bitMapArray
writeWord length, lengthPos
when MDNS.TYPE_TXT
lengthPos = data.length
writeWord 0
length = writeStringArray r.txt_texts, false
writeWord length, lengthPos
when MDNS.TYPE_A
lengthPos = data.length
writeWord 0
length = writeIPAddress r.a_address
writeWord length, lengthPos
when MDNS.TYPE_AAAA
lengthPos = data.length
writeWord 0
length = writeIP6Address r.a_address
writeWord length, lengthPos
when MDNS.TYPE_SRV
lengthPos = data.length
writeWord 0
length = writeWord r.srv_priority
length += writeWord r.srv_weight
length += writeWord r.srv_port
length += writeDNSName r.srv_target
writeWord length, lengthPos
when MDNS.TYPE_PTR
lengthPos = data.length
writeWord 0
length = writeDNSName r.ptr_domainName
writeWord length, lengthPos
else
writeWord r.resourceData.length
writeByteArray r.resourceData
writeWord message.transactionID
flags = 0
if not message.isQuery then flags |= 0x8000
flags |= (message.opCode & 0xFF) << 11
if message.authoritativeAnswer then flags |= 0x400
if message.truncated then flags |= 0x200
if message.recursionDesired then flags |= 0x100
if message.recursionAvailable then flags |= 0x80
flags |= message.responseCode & 0xF
writeWord flags
writeWord message.questions.length
writeWord message.answers.length
writeWord message.autorityRecords.length
writeWord message.additionalRecords.length
if message.questions.length > 0
for i in [0 .. message.questions.length-1]
writeQuestion message.questions[i]
if message.answers.length > 0
for i in [0 .. message.answers.length-1]
writeRecord message.answers[i]
if message.autorityRecords.length > 0
for i in [0 .. message.autorityRecords.length-1]
writeRecord message.autorityRecords[i]
if message.additionalRecords.length > 0
for i in [0 .. message.additionalRecords.length-1]
writeRecord message.additionalRecords[i]
return data
@decodeMessage: (rawData) ->
position = 0
errored = false
consumeByte = ->
if position + 1 > rawData.length
if not errored
errored = true
return rawData[position++]
consumeWord = ->
return (consumeByte() << 8) | consumeByte()
consumeDWord = ->
return (consumeWord() << 16) | consumeWord()
consumeDNSName = ->
parts = []
while true
if position >= rawData.length then break
partLength = consumeByte()
if partLength == 0 then break
if partLength == 0xC0
bytePosition = consumeByte()
oldPosition = position
position = bytePosition
parts = parts.concat consumeDNSName().split(".")
position = oldPosition
break
if position + partLength > rawData.length
if not errored
errored = true
partLength = rawData.length - position
stringArray = []
while partLength-- > 0
stringArray.push consumeByte()
part = MDNS.utf8ByteArrayToString stringArray
parts.push part
return parts.join "."
consumeQuestion = ->
question = {}
question.name = consumeDNSName()
question.type = consumeWord()
question.class = consumeWord()
question.unicast = (question.class & 0x8000) != 0
question.class &= 0x7FFF
return question
consumeByteArray = (length) ->
length = Math.min length, rawData.length - position
if length <= 0
return ""
data = new Array length
for i in [0 .. length-1]
data[i] = consumeByte()
return MDNS.utf8ByteArrayToString data
consumeIPAddress = (length) ->
ipArr = []
for i in [0..length-1]
ipArr.push consumeByte()
return ipArr.join "."
consumeIP6Address = () ->
ipArr = []
for i in [0..7]
ipArr.push consumeWord()
return ipArr.join ":"
consumeResourceRecord = ->
resource = {}
resource.name = consumeDNSName()
resource.type = consumeWord()
resource.class = consumeWord()
resource.flushCache = (resource.class & 0x8000) != 0
resource.class &= 0x7FFF
resource.timeToLive = consumeDWord()
extraDataLength = consumeWord()
switch resource.type
when MDNS.TYPE_TXT
resourceData = []
totalLength = 0
while extraDataLength > totalLength
subLength = consumeByte()
totalLength += subLength + 1
tempStr = consumeByteArray subLength
resourceData.push tempStr
resource.resourceData = resourceData
when MDNS.TYPE_A
resource.resourceData = consumeIPAddress extraDataLength
when MDNS.TYPE_AAAA
resource.resourceData = consumeIP6Address()
when MDNS.TYPE_SRV
resourceData = {}
resourceData.srv_priority = consumeWord()
resourceData.srv_weight = consumeWord()
resourceData.srv_port = consumeWord()
resourceData.srv_target = consumeDNSName()
resource.resourceData = resourceData
when MDNS.TYPE_PTR
resource.resourceData = consumeDNSName()
else
if extraDataLength > 0
resource.resourceData = consumeByteArray extraDataLength
return resource
result = {}
result.transactionID = consumeWord()
flags = consumeWord()
result.isQuery = (flags & 0x8000) == 0
result.opCode = (flags >> 11) & 0xF
result.authoritativeAnswer = (flags & 0x400) != 0
result.truncated = (flags & 0x200) != 0
result.recursionDesired = (flags & 0x100) != 0
result.recursionAvailable = (flags & 0x80) != 0
result.responseCode = flags & 0xF
questionCount = consumeWord()
answerCount = consumeWord()
authorityRecordsCount = consumeWord()
additionalRecordsCount = consumeWord()
result.questions = []
result.answers = []
result.autorityRecords = []
result.additionalRecords = []
if questionCount > 0
for [1 .. questionCount]
result.questions.push consumeQuestion()
if answerCount > 0
for [1 .. answerCount]
result.answers.push consumeResourceRecord()
if authorityRecordsCount > 0
for [1 .. authorityRecordsCount]
result.autorityRecords.push consumeResourceRecord()
if additionalRecordsCount > 0
for [1 .. additionalRecordsCount]
result.additionalRecords.push consumeResourceRecord()
return result
@map2txt: (txtRecord) ->
txt_texts = []
for k,v of txtRecord
txt_texts.push k + "=" + v
return txt_texts
@creatDnsSdRequest: (transactionID, fullProtocol) ->
response =
transactionID: transactionID, # max 65535
isQuery: false,
opCode: 0,
authoritativeAnswer: true,
truncated: false,
recursionDesired: false,
recursionAvailable: false,
responseCode: MDNS.RESPONSE_CODE_OK,
questions: [],
answers: [],
additionalRecords: [],
autorityRecords: []
response.questions.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
unicast: false
return response
@creatDnsSdKeepResponse: (transactionID, fullProtocol, serverName, port, txtRecord, address, localName) ->
response =
transactionID: transactionID, # max 65535
isQuery: false,
opCode: 0,
authoritativeAnswer: true,
truncated: false,
recursionDesired: false,
recursionAvailable: false,
responseCode: MDNS.RESPONSE_CODE_OK,
questions: [],
answers: [],
additionalRecords: [],
autorityRecords: []
response.answers.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
ptr_domainName: serverName + "."+fullProtocol
response.answers.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_SRV,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
srv_priority: 0,
srv_weight: 0,
srv_port: port,
srv_target: localName + ".local"
response.answers.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_TXT,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
txt_texts: MDNS.map2txt txtRecord
response.answers.push
name: localName + ".local",
type: MDNS.TYPE_A,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
a_address: address.ipv4
response.answers.push
name: "_services._dns-sd._udp.local",
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 4500,
ptr_domainName: fullProtocol
return response
@creatDnsSdResponse: (transactionID, fullProtocol, serverName, port, txtRecord, address, localName) ->
response =
transactionID: transactionID, # max 65535
isQuery: false,
opCode: 0,
authoritativeAnswer: true,
truncated: false,
recursionDesired: false,
recursionAvailable: false,
responseCode: MDNS.RESPONSE_CODE_OK,
questions: [],
answers: [],
additionalRecords: [],
autorityRecords: []
response.questions.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
unicast: true
response.answers.push
name: fullProtocol,
type: MDNS.TYPE_PTR,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
ptr_domainName: serverName + "."+fullProtocol
response.additionalRecords.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_SRV,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
srv_priority: 0,
srv_weight: 0,
srv_port: port,
srv_target: localName + ".local"
if txtRecord
response.additionalRecords.push
name: serverName + "." + fullProtocol,
type: MDNS.TYPE_TXT,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
txt_texts: MDNS.map2txt txtRecord
if address.ipv6
response.additionalRecords.push
name: localName + ".local",
type: MDNS.TYPE_AAAA,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
a_address: address.ipv6
response.additionalRecords.push
name: localName + ".local",
type: MDNS.TYPE_A,
class: MDNS.CLASS_IN,
flushCache: false,
timeToLive: 10,
a_address: address.ipv4
return response
@parseDnsSdResponse : (response) ->
serverInfo = {}
for i of response.additionalRecords
tempRecode = response.additionalRecords[i]
if tempRecode.type == MDNS.TYPE_SRV
protocolArray = tempRecode.name.split "."
serverInfo.name = protocolArray[0]
serverInfo.protocol = protocolArray[1]
serverInfo.protocol_type = protocolArray[2]
serverInfo.srv_priority = tempRecode.resourceData.srv_priority
serverInfo.srv_weight = tempRecode.resourceData.srv_weight
serverInfo.srv_port = tempRecode.resourceData.srv_port
serverInfo.srv_target = tempRecode.resourceData.srv_target
else if tempRecode.type == MDNS.TYPE_TXT
tempMap = {}
for j of tempRecode.resourceData
tempArr = tempRecode.resourceData[j].split "="
tempMap[tempArr[0]] = tempArr[1]
serverInfo.txt_texts = tempMap
else if tempRecode.type == MDNS.TYPE_AAAA
serverInfo.ipv6 = tempRecode.resourceData
else if tempRecode.type == MDNS.TYPE_A
serverInfo.ipv4 = tempRecode.resourceData
return serverInfo
module.exports.MDNSHelper = MDNS
|
[
{
"context": "###\n datepicker.js\n Copyright (C) by Nils Sommer, 2016\n https://github.com/nsommer/datepicker.js\n",
"end": 50,
"score": 0.9998887181282043,
"start": 39,
"tag": "NAME",
"value": "Nils Sommer"
},
{
"context": "ght (C) by Nils Sommer, 2016\n https://github.com/nsom... | coffee/banner.coffee | nsommer/datepicker.js | 0 | ###
datepicker.js
Copyright (C) by Nils Sommer, 2016
https://github.com/nsommer/datepicker.js
Released under the MIT license.
### | 197971 | ###
datepicker.js
Copyright (C) by <NAME>, 2016
https://github.com/nsommer/datepicker.js
Released under the MIT license.
### | true | ###
datepicker.js
Copyright (C) by PI:NAME:<NAME>END_PI, 2016
https://github.com/nsommer/datepicker.js
Released under the MIT license.
### |
[
{
"context": "alid\"\n input: \n token: \"testNewIdentifier\"\n starts: 33\n ends:",
"end": 1759,
"score": 0.8022050857543945,
"start": 1742,
"tag": "KEY",
"value": "testNewIdentifier"
},
{
"context": "fier\"\n input:... | src/coffee/validateNewIdentifier.spec.coffee | jameswilddev/influx7 | 1 | describe "validateNewIdentifier", ->
rewire = require "rewire"
describe "imports", ->
validateNewIdentifier = rewire "./validateNewIdentifier"
it "isIdentifier", -> (expect validateNewIdentifier.__get__ "isIdentifier").toBe require "./isIdentifier"
describe "on calling", ->
validateNewIdentifier = rewire "./validateNewIdentifier"
declarations =
testExistingIdentifierA: "test value"
testExistingIdentifierB: "test value"
testExistingIdentifierC: "test value"
run = (config) -> describe config.description, ->
inputCopy = declarationsCopy = undefined
beforeEach ->
inputCopy = JSON.parse JSON.stringify config.input
declarationsCopy = JSON.parse JSON.stringify declarations
validateNewIdentifier.__set__ "isIdentifier", (token) ->
(expect token).toEqual config.input.token
config.isIdentifier
if config.throws
it "throws the expected exception", -> (expect -> validateNewIdentifier inputCopy, declarationsCopy).toThrow config.throws
else
it "does nothing", -> validateNewIdentifier inputCopy, declarationsCopy
describe "then", ->
beforeEach ->
try
validateNewIdentifier inputCopy, declarationsCopy
catch e
it "does not modify the input", -> (expect inputCopy).toEqual config.input
it "does not modify the declarations", -> (expect declarationsCopy).toEqual declarations
run
description: "valid"
input:
token: "testNewIdentifier"
starts: 33
ends: 47
isIdentifier: true
run
description: "not a valid identifier"
input:
token: "testNewIdentifier"
starts: 33
ends: 47
isIdentifier: false
throws:
reason: "identifierInvalid"
starts: 33
ends: 47
run
description: "already defined"
input:
token: "testExistingIdentifierB"
starts: 33
ends: 47
isIdentifier: true
throws:
reason: "identifierNotUnique"
starts: 33
ends: 47 | 46675 | describe "validateNewIdentifier", ->
rewire = require "rewire"
describe "imports", ->
validateNewIdentifier = rewire "./validateNewIdentifier"
it "isIdentifier", -> (expect validateNewIdentifier.__get__ "isIdentifier").toBe require "./isIdentifier"
describe "on calling", ->
validateNewIdentifier = rewire "./validateNewIdentifier"
declarations =
testExistingIdentifierA: "test value"
testExistingIdentifierB: "test value"
testExistingIdentifierC: "test value"
run = (config) -> describe config.description, ->
inputCopy = declarationsCopy = undefined
beforeEach ->
inputCopy = JSON.parse JSON.stringify config.input
declarationsCopy = JSON.parse JSON.stringify declarations
validateNewIdentifier.__set__ "isIdentifier", (token) ->
(expect token).toEqual config.input.token
config.isIdentifier
if config.throws
it "throws the expected exception", -> (expect -> validateNewIdentifier inputCopy, declarationsCopy).toThrow config.throws
else
it "does nothing", -> validateNewIdentifier inputCopy, declarationsCopy
describe "then", ->
beforeEach ->
try
validateNewIdentifier inputCopy, declarationsCopy
catch e
it "does not modify the input", -> (expect inputCopy).toEqual config.input
it "does not modify the declarations", -> (expect declarationsCopy).toEqual declarations
run
description: "valid"
input:
token: "<KEY>"
starts: 33
ends: 47
isIdentifier: true
run
description: "not a valid identifier"
input:
token: "<KEY>"
starts: 33
ends: 47
isIdentifier: false
throws:
reason: "identifierInvalid"
starts: 33
ends: 47
run
description: "already defined"
input:
token: "<KEY>"
starts: 33
ends: 47
isIdentifier: true
throws:
reason: "identifierNotUnique"
starts: 33
ends: 47 | true | describe "validateNewIdentifier", ->
rewire = require "rewire"
describe "imports", ->
validateNewIdentifier = rewire "./validateNewIdentifier"
it "isIdentifier", -> (expect validateNewIdentifier.__get__ "isIdentifier").toBe require "./isIdentifier"
describe "on calling", ->
validateNewIdentifier = rewire "./validateNewIdentifier"
declarations =
testExistingIdentifierA: "test value"
testExistingIdentifierB: "test value"
testExistingIdentifierC: "test value"
run = (config) -> describe config.description, ->
inputCopy = declarationsCopy = undefined
beforeEach ->
inputCopy = JSON.parse JSON.stringify config.input
declarationsCopy = JSON.parse JSON.stringify declarations
validateNewIdentifier.__set__ "isIdentifier", (token) ->
(expect token).toEqual config.input.token
config.isIdentifier
if config.throws
it "throws the expected exception", -> (expect -> validateNewIdentifier inputCopy, declarationsCopy).toThrow config.throws
else
it "does nothing", -> validateNewIdentifier inputCopy, declarationsCopy
describe "then", ->
beforeEach ->
try
validateNewIdentifier inputCopy, declarationsCopy
catch e
it "does not modify the input", -> (expect inputCopy).toEqual config.input
it "does not modify the declarations", -> (expect declarationsCopy).toEqual declarations
run
description: "valid"
input:
token: "PI:KEY:<KEY>END_PI"
starts: 33
ends: 47
isIdentifier: true
run
description: "not a valid identifier"
input:
token: "PI:KEY:<KEY>END_PI"
starts: 33
ends: 47
isIdentifier: false
throws:
reason: "identifierInvalid"
starts: 33
ends: 47
run
description: "already defined"
input:
token: "PI:KEY:<KEY>END_PI"
starts: 33
ends: 47
isIdentifier: true
throws:
reason: "identifierNotUnique"
starts: 33
ends: 47 |
[
{
"context": "eentrant so I'm adding an assert there\n # - Gabe, July 9 2018\n assert -> depToVersion['reac",
"end": 2685,
"score": 0.9828007221221924,
"start": 2681,
"tag": "NAME",
"value": "Gabe"
},
{
"context": " # in the middle of a forceUpdate\n # - Gab... | test/repo/lint-package-json.coffee | mehrdad-shokri/pagedraw | 3,213 | #!/usr/bin/env coffee
# Fails if any package.json deps start with an ^
# The ^ makes npm pick a version that number or higher, which
# can cause confusing bugs between team members
_l = require 'lodash'
chai = require 'chai'
assert = (condition) ->
chai.assert(condition(), condition.toString())
expect_has_no_unfrozen_deps = (pkg) ->
depToVersion = _l.extend {}, pkg.dependencies, pkg.devDependencies
nonFrozenDeps = _l.keys _l.pickBy depToVersion, (version) ->
_l.startsWith version, '^'
chai.expect(nonFrozenDeps).to.be.empty
describe "Lint package.json", ->
pkg = require '../../package'
depToVersion = _l.extend {}, pkg.dependencies, pkg.devDependencies
nonFrozenDeps = _l.keys _l.pickBy depToVersion, (version) ->
_l.startsWith version, '^'
it 'has no unfrozen dependencies', ->
expect_has_no_unfrozen_deps(pkg)
it 'ReactDOM.render is synchronous for TextBlock.getGeometryFromContent', ->
# TextBlock.getGeometryFromContent relies on ReactDOM.render being synchronous.
# As of React@0.14.5, ReactDOM.render is synchronous, so we're good. In future
# versions of React, ReactDOM.render is not guarenteed to be synchronous, and
# the React team has said it is intended to be used asynchronously. If React changes
# and ReactDOM.render is asynchronous, TextBlock.getGeometryFromContent will break.
# If you're trying to upgrade React, read the docs to make sure ReactDOM.render is
# still synchronous in the new version. If it is, change the update the version numbers
# below to your new version where ReactDOM.render is still synchronous. If your new
# version of React has an asyncrhonous ReactDOM.render, change the implementation of
# TextBlock.getGeometryFromContent before removing this test.
#
# Updated to React 16.4.1. I read React's code at that version to guarantee that
# ReactDOM.render is still synchronous. It actually stopped being synchronous wrt React 15 only
# in reentrant calls (when ReactDOM.render is called from within another render function). You can
# see this in react-dom.development.js:16334 function requestWork. This is also true in prod.
# In non reentrant calls it's synchronous per react-dom.development.js:17232 function legacyCreateRootFromDOMContainer.
# Once React starts favoring unstable_createRootFromDOMContainer in favor of the legacy version, this will
# probably start being async but for now we're good.
# Now it's crucial that handleDocChanged is not reentrant so I'm adding an assert there
# - Gabe, July 9 2018
assert -> depToVersion['react'] == '16.4.1'
assert -> depToVersion['react-dom'] == '16.4.1'
it 'ReactComponent.forceUpdate(callback) calls its callback as part of the same task', ->
# https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
# ReactComponent.forceUpdate() takes a callback because it can be "async". In 15.4.2
# this appears limited to batching multiple nested React transactions. We're giving
# a callback/promise to be called when forceUpdate finishes so we know we can clean up
# after the render. We're using Promises, but that's okay because they're microtasks.
# This logic WILL CHANGE with React16. I'm not leaving a better note because we're going
# to rethink this soon anyway. If you're seeing this and have no idea what I'm talking
# about, come find me and hope I remember why in React@15.4.2, ReactComponent.forceUpdate
# takes a callback. -JRP, 10/13/17
# Updated to React 16.4.1. I read React's code at that version and I *believe* forceUpdate is still synchronous
# but I'm not 100% positive. If it's not synchronous our cache is f*ed because we might be making mutations while in readonly mode.
# We should understand this better but I'm pushing this upgrade for now and adding an assert that there are no mutations of the doc
# in the middle of a forceUpdate
# - Gabe, July 9 2018
assert -> depToVersion['react'] == '16.4.1'
assert -> depToVersion['react-dom'] == '16.4.1'
describe 'cli/package.json', ->
cli_pkg = require('../../cli/package')
it 'has no unfrozen dependencies', ->
expect_has_no_unfrozen_deps(cli_pkg)
| 161419 | #!/usr/bin/env coffee
# Fails if any package.json deps start with an ^
# The ^ makes npm pick a version that number or higher, which
# can cause confusing bugs between team members
_l = require 'lodash'
chai = require 'chai'
assert = (condition) ->
chai.assert(condition(), condition.toString())
expect_has_no_unfrozen_deps = (pkg) ->
depToVersion = _l.extend {}, pkg.dependencies, pkg.devDependencies
nonFrozenDeps = _l.keys _l.pickBy depToVersion, (version) ->
_l.startsWith version, '^'
chai.expect(nonFrozenDeps).to.be.empty
describe "Lint package.json", ->
pkg = require '../../package'
depToVersion = _l.extend {}, pkg.dependencies, pkg.devDependencies
nonFrozenDeps = _l.keys _l.pickBy depToVersion, (version) ->
_l.startsWith version, '^'
it 'has no unfrozen dependencies', ->
expect_has_no_unfrozen_deps(pkg)
it 'ReactDOM.render is synchronous for TextBlock.getGeometryFromContent', ->
# TextBlock.getGeometryFromContent relies on ReactDOM.render being synchronous.
# As of React@0.14.5, ReactDOM.render is synchronous, so we're good. In future
# versions of React, ReactDOM.render is not guarenteed to be synchronous, and
# the React team has said it is intended to be used asynchronously. If React changes
# and ReactDOM.render is asynchronous, TextBlock.getGeometryFromContent will break.
# If you're trying to upgrade React, read the docs to make sure ReactDOM.render is
# still synchronous in the new version. If it is, change the update the version numbers
# below to your new version where ReactDOM.render is still synchronous. If your new
# version of React has an asyncrhonous ReactDOM.render, change the implementation of
# TextBlock.getGeometryFromContent before removing this test.
#
# Updated to React 16.4.1. I read React's code at that version to guarantee that
# ReactDOM.render is still synchronous. It actually stopped being synchronous wrt React 15 only
# in reentrant calls (when ReactDOM.render is called from within another render function). You can
# see this in react-dom.development.js:16334 function requestWork. This is also true in prod.
# In non reentrant calls it's synchronous per react-dom.development.js:17232 function legacyCreateRootFromDOMContainer.
# Once React starts favoring unstable_createRootFromDOMContainer in favor of the legacy version, this will
# probably start being async but for now we're good.
# Now it's crucial that handleDocChanged is not reentrant so I'm adding an assert there
# - <NAME>, July 9 2018
assert -> depToVersion['react'] == '16.4.1'
assert -> depToVersion['react-dom'] == '16.4.1'
it 'ReactComponent.forceUpdate(callback) calls its callback as part of the same task', ->
# https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
# ReactComponent.forceUpdate() takes a callback because it can be "async". In 15.4.2
# this appears limited to batching multiple nested React transactions. We're giving
# a callback/promise to be called when forceUpdate finishes so we know we can clean up
# after the render. We're using Promises, but that's okay because they're microtasks.
# This logic WILL CHANGE with React16. I'm not leaving a better note because we're going
# to rethink this soon anyway. If you're seeing this and have no idea what I'm talking
# about, come find me and hope I remember why in React@15.4.2, ReactComponent.forceUpdate
# takes a callback. -JRP, 10/13/17
# Updated to React 16.4.1. I read React's code at that version and I *believe* forceUpdate is still synchronous
# but I'm not 100% positive. If it's not synchronous our cache is f*ed because we might be making mutations while in readonly mode.
# We should understand this better but I'm pushing this upgrade for now and adding an assert that there are no mutations of the doc
# in the middle of a forceUpdate
# - <NAME>, July 9 2018
assert -> depToVersion['react'] == '16.4.1'
assert -> depToVersion['react-dom'] == '16.4.1'
describe 'cli/package.json', ->
cli_pkg = require('../../cli/package')
it 'has no unfrozen dependencies', ->
expect_has_no_unfrozen_deps(cli_pkg)
| true | #!/usr/bin/env coffee
# Fails if any package.json deps start with an ^
# The ^ makes npm pick a version that number or higher, which
# can cause confusing bugs between team members
_l = require 'lodash'
chai = require 'chai'
assert = (condition) ->
chai.assert(condition(), condition.toString())
expect_has_no_unfrozen_deps = (pkg) ->
depToVersion = _l.extend {}, pkg.dependencies, pkg.devDependencies
nonFrozenDeps = _l.keys _l.pickBy depToVersion, (version) ->
_l.startsWith version, '^'
chai.expect(nonFrozenDeps).to.be.empty
describe "Lint package.json", ->
pkg = require '../../package'
depToVersion = _l.extend {}, pkg.dependencies, pkg.devDependencies
nonFrozenDeps = _l.keys _l.pickBy depToVersion, (version) ->
_l.startsWith version, '^'
it 'has no unfrozen dependencies', ->
expect_has_no_unfrozen_deps(pkg)
it 'ReactDOM.render is synchronous for TextBlock.getGeometryFromContent', ->
# TextBlock.getGeometryFromContent relies on ReactDOM.render being synchronous.
# As of React@0.14.5, ReactDOM.render is synchronous, so we're good. In future
# versions of React, ReactDOM.render is not guarenteed to be synchronous, and
# the React team has said it is intended to be used asynchronously. If React changes
# and ReactDOM.render is asynchronous, TextBlock.getGeometryFromContent will break.
# If you're trying to upgrade React, read the docs to make sure ReactDOM.render is
# still synchronous in the new version. If it is, change the update the version numbers
# below to your new version where ReactDOM.render is still synchronous. If your new
# version of React has an asyncrhonous ReactDOM.render, change the implementation of
# TextBlock.getGeometryFromContent before removing this test.
#
# Updated to React 16.4.1. I read React's code at that version to guarantee that
# ReactDOM.render is still synchronous. It actually stopped being synchronous wrt React 15 only
# in reentrant calls (when ReactDOM.render is called from within another render function). You can
# see this in react-dom.development.js:16334 function requestWork. This is also true in prod.
# In non reentrant calls it's synchronous per react-dom.development.js:17232 function legacyCreateRootFromDOMContainer.
# Once React starts favoring unstable_createRootFromDOMContainer in favor of the legacy version, this will
# probably start being async but for now we're good.
# Now it's crucial that handleDocChanged is not reentrant so I'm adding an assert there
# - PI:NAME:<NAME>END_PI, July 9 2018
assert -> depToVersion['react'] == '16.4.1'
assert -> depToVersion['react-dom'] == '16.4.1'
it 'ReactComponent.forceUpdate(callback) calls its callback as part of the same task', ->
# https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
# ReactComponent.forceUpdate() takes a callback because it can be "async". In 15.4.2
# this appears limited to batching multiple nested React transactions. We're giving
# a callback/promise to be called when forceUpdate finishes so we know we can clean up
# after the render. We're using Promises, but that's okay because they're microtasks.
# This logic WILL CHANGE with React16. I'm not leaving a better note because we're going
# to rethink this soon anyway. If you're seeing this and have no idea what I'm talking
# about, come find me and hope I remember why in React@15.4.2, ReactComponent.forceUpdate
# takes a callback. -JRP, 10/13/17
# Updated to React 16.4.1. I read React's code at that version and I *believe* forceUpdate is still synchronous
# but I'm not 100% positive. If it's not synchronous our cache is f*ed because we might be making mutations while in readonly mode.
# We should understand this better but I'm pushing this upgrade for now and adding an assert that there are no mutations of the doc
# in the middle of a forceUpdate
# - PI:NAME:<NAME>END_PI, July 9 2018
assert -> depToVersion['react'] == '16.4.1'
assert -> depToVersion['react-dom'] == '16.4.1'
describe 'cli/package.json', ->
cli_pkg = require('../../cli/package')
it 'has no unfrozen dependencies', ->
expect_has_no_unfrozen_deps(cli_pkg)
|
[
{
"context": "은 [**폴인 사이트**][2]에서 구매할 수 있다. \n \n 정선언 기자 jng.sunean@joongang.co.kr \n \n [1]: https:\\\\\\\\news.joins.com\\\\article\\\\2",
"end": 3993,
"score": 0.9998980164527893,
"start": 3968,
"tag": "EMAIL",
"value": "jng.sunean@joongang.co.kr"
}
] | _posts/notes/8ca5dd06-baa1-46b0-89ea-40386eaa8136.cson | rpblic/rpblic.github.io | 0 | createdAt: "2018-09-11T10:31:24.558Z"
updatedAt: "2018-09-27T05:14:37.578Z"
type: "MARKDOWN_NOTE"
folder: "5ccab513127047f4eb61"
title: ""
content: '''
---
layout: post
title: "회사도 인생도, 마지막을 결정하는 건 꿈의 크기" 유니콘 감별사 VC 김한준, 일의 의미를 말하다
category: Article
tags: ['Article', 'Passion', 'Insight']
---
[출처: 중앙일보](https:\\\\news.joins.com\\article\\22942860)
개인적 참조를 위한 복사로, [중앙일보의 저작권 정책](http:\\\\bbs.joins.com\\app\\myjoins_policy\\163116)을 확인하고 준수하였습니다.
창업가들은 종종 창업을 "똥더미를 치우는 일 같다"고 표현한다. 일은 산더미고, 매일매일 새로운 문제가 터진다. 그런 것들을 처리하다 보면 '왜 창업했는지' 같은 큰 그림과 방향성은 잊히게 마련이다. 그런 사소한 일상 속에서 교훈을 얻고, 계속해서 방향을 바꾸며 앞으로 나아간다는 점에서 창업은 인생과 닮았다. 창업도, 인생도 한두 번 실패했다고 해서 포기할 수 없다는 점도 비슷하다.
창업이 인생과 비슷하다면, 인생에 대한 조언도 어쩌면 창업 코치가 잘해줄 수 있지 않을까. 국내 대표 VC(벤처캐피털리스트) 김한준 알토스벤처스 대표가 라는 다소 엉뚱해보이는 제목의 컨퍼런스에 선다. 일의 의미를 찾는 직장인들에게 자신이 생각하는 꿈의 정의를 들려주기 위해서다. 지식 콘텐츠 플랫폼 폴인(fol:in)이 준비한 9월의 스튜디오다.
김한준 대표는 '유니콘 감별사'로 불린다. 배틀그라운드로 전 세계 게이머를 사로잡은 블루홀, e커머스 업계 신흥 강자 쿠팡, 푸드 테크 선두 기업이 된 배달의 민족까지, 그가 투자한 회사들이 4~5년 사이 '유니콘 스타트업'이 됐다. 송금 서비스에서 종합 금융 서비스로 도약 중인 토스, 원룸에서 아파트로 사업을 확장 중인 직방, 글로벌 서비스로 떠오른 아자르 등 '넥스트 유니콘'으로 불리며 떠오르고 있는 스타트업에도 투자했다.
그는 스타트업 창업가들에게 늘 같은 주문을 한다.
"더, 더, 더!"
그의 메신저 프로필 상태 메시지와 페이스북에서 늘 볼 수 있는 문구다.
창업가들은 꿈을 가진 사람들이에요. 그 꿈을 실현하기 위해 창업한 거죠. 그런데 그 꿈이 그 회사와 서비스의 마지막을 결정하는 것 같아요. 더 큰 꿈을 가지고, 그걸 향해 나아가라는 게 제 주문이에요. 그리고 이건 저에 대한 주문이기도 하죠.
그에게 꿈과 일의 의미에 대해 질문했다. 다음은 일문일답.
**관련 기사 : [폴인 9월 컨퍼런스 '왜 일하는가' 열려][1]**
** **

대표님은 왜 스타트업에 투자하는 일을 하시는 건가요? 돈을 벌기 위해서라면 부동산이나 주식같이 다른 데 투자를 할 수도 있을 텐데요.
많은 사람이 학벌·외모·가정환경 같은 다양한 이유로 자신의 삶을 제한해버려요. 그런데 스타트업계는 그렇지 않은 사람이 많습니다. 이 바닥에선 누구나 스펙을 다 떼고 온전히 자신의 능력으로 세상에 없던 제품과 서비스를 만들어 내고, 그걸로 소비자의 마음을 사고, 투자자의 자본을 얻죠. 그런 사람이 많아지면 사회 전체가 역동적이고 건강해지는 거잖아요.
미디어가 성공한 창업가를 주로 다루다 보니 창업이 화려해 보이는 것 같아요. 하지만 실제 창업가들의 일상은 아주 작고 의미 없는 '삽질'로 채워지는 것 같습니다. 그런데도 왜 점점 더 많은 사람들이 창업에 뛰어드는 걸까요?
'이 문제만큼은 해결해보겠다'라거나 '이 서비스를 통해 변화를 만들어내고 싶다'는 식의 꿈이 있어요. 그 꿈을 이루기 위해 한 걸음 한 걸음 나아가는 과정에 엄청난 성취감과 만족감이 있고요. 바로 그 성취감·만족감 때문에 연쇄 창업가가 되는 사람도 많아요.
그리고 그런 창업가를 지지하고 돕는 과정에서 대표님도 만족감과 성취감을 느끼시는 거겠죠?
"그게 제가 다른 투자가 아닌 스타트업 투자에 투신한 이유겠죠."
김한준 대표의 이력은 여느 창업가 못지않게 화려하다. 초등학교 때 가족과 함께 이민을 간 그는 미국의 육군사관학교인 웨스트포인트에 입학해 군인으로 일했다. 한국이나 미국이나 군 엘리트를 키우는 사관학교 출신은 큰 이변이 없는 한 안정적으로 살 수 있다. 하지만 김 대표는 그 길을 마다하고 전역해 스탠퍼드 MBA를 거쳐 1996년 벤처기업에 투자하는 벤처캐피탈(VC) 알토스벤처스를 창업했다.
이력 중 웨스트포인트 진학이 눈에 띕니다. 왜 군인이 되셨나요?
제 부모님의 시계는 이민 간 1976년에 멈췄어요. 보수주의자셨죠. 반면 저는 미국의 민주적이고 자유로운 문화에 충격을 받았어요. 무슨 의견에 대해서도 반대 의견을 말할 수 있는 자유가 놀라웠습니다. 민주주의는 지킬만한 가치가 있다고 생각했고, 그래서 그 가치를 지키는 군인이 되고 싶었어요.
그런데 왜 전역하신 건가요?
위계가 강하고 엄격한 군 조직문화가 잘 맞진 않았어요. 졸업 후 4년쯤 됐을 때 베를린 장벽이 무너졌는데, 그게 결정적이었어요. 공산주의가 없어졌으니 더는 군에 남을 이유가 없었어요.
전역 후 MBA에 진학한 것도 이유가 있을 것 같아요.
왜 공산주의와 그에 기반을 둔 경제 체제는 역사 속으로 사라졌고, 민주주의와 거기에 기초한 경제 체제(자본주의)는 살아남았을까 오래 고민했어요. 공산주의는 성선설 위에 있다면, 자본주의는 인간은 선하지도 악하지도 않다고 가정하고 욕망을 최대한 보장하되 최소한의 수준으로 규제하자고 생각하는 것 같았죠. 저 역시 그게 맞다고 생각했고, 그래서 비즈니스 영역에서 일하고 싶었어요.
다양한 비즈니스 영역 중 스타트업 투자라는 곳에 뿌리내린 건 왜인가요?
미 동부의 대학들이 금융 산업과 가깝고 보수적이라면, 서부 특히 스탠퍼드대는 정보기술(IT) 산업과 창업계에 가깝고 진취적이에요. 그건 지금도 마찬가지고요. 제가 VC가 된 건 그런 학풍의 영향일 거예요. 교수님 소개로 벤처 투자에 관심이 많은 기업인을 만난 게 구체적인 계기가 됐어요. 그 덕에 뜻이 맞는 친구들과 알토스벤처스를 창업했어요.
김한준 대표는 성공한 창업가를 비교적 초기부터 가까이에서 보아왔다. 그런 그가 꼽은 '안 가본 길을 가는 사람' 그리고 그 중 성공한 이들의 특징은 뭘까.
창업가마다 도드라지는 특징이 있어요. 어떤 창업가는 몰입하는 능력이 뛰어나고, 어떤 창업가는 실행력이 압도적이고요. 그런데도 모든 창업가를 관통하는 특징이 있는데, 제 생각엔 경험을 통해 끊임없이 배워나간다는 것 같아요.
김한준 대표가 투자한 창업가 중엔 앞선 사업을 실패한 이들이 적지 않다. 김 대표가 "실패했다는 사실은 중요하지 않다. 거기서 배운 게 있다면, 그리하여 성장했다면 그는 더 좋은 창업가"라고 말하는 것 역시 같은 맥락이다.
김 대표가 연사로 나서는 이번 컨퍼런스는 오는 20일 오후 7시 서울 성수동 카페 월 닷 서울(구 레필로소피)에서 열린다. 티켓은 [**폴인 사이트**][2]에서 구매할 수 있다.
정선언 기자 jng.sunean@joongang.co.kr
[1]: https:\\\\news.joins.com\\article\\22942694
[2]: https:\\\\www.folin.co\\studio\\4\\view
'''
tags: []
isStarred: false
isTrashed: false
| 147422 | createdAt: "2018-09-11T10:31:24.558Z"
updatedAt: "2018-09-27T05:14:37.578Z"
type: "MARKDOWN_NOTE"
folder: "5ccab513127047f4eb61"
title: ""
content: '''
---
layout: post
title: "회사도 인생도, 마지막을 결정하는 건 꿈의 크기" 유니콘 감별사 VC 김한준, 일의 의미를 말하다
category: Article
tags: ['Article', 'Passion', 'Insight']
---
[출처: 중앙일보](https:\\\\news.joins.com\\article\\22942860)
개인적 참조를 위한 복사로, [중앙일보의 저작권 정책](http:\\\\bbs.joins.com\\app\\myjoins_policy\\163116)을 확인하고 준수하였습니다.
창업가들은 종종 창업을 "똥더미를 치우는 일 같다"고 표현한다. 일은 산더미고, 매일매일 새로운 문제가 터진다. 그런 것들을 처리하다 보면 '왜 창업했는지' 같은 큰 그림과 방향성은 잊히게 마련이다. 그런 사소한 일상 속에서 교훈을 얻고, 계속해서 방향을 바꾸며 앞으로 나아간다는 점에서 창업은 인생과 닮았다. 창업도, 인생도 한두 번 실패했다고 해서 포기할 수 없다는 점도 비슷하다.
창업이 인생과 비슷하다면, 인생에 대한 조언도 어쩌면 창업 코치가 잘해줄 수 있지 않을까. 국내 대표 VC(벤처캐피털리스트) 김한준 알토스벤처스 대표가 라는 다소 엉뚱해보이는 제목의 컨퍼런스에 선다. 일의 의미를 찾는 직장인들에게 자신이 생각하는 꿈의 정의를 들려주기 위해서다. 지식 콘텐츠 플랫폼 폴인(fol:in)이 준비한 9월의 스튜디오다.
김한준 대표는 '유니콘 감별사'로 불린다. 배틀그라운드로 전 세계 게이머를 사로잡은 블루홀, e커머스 업계 신흥 강자 쿠팡, 푸드 테크 선두 기업이 된 배달의 민족까지, 그가 투자한 회사들이 4~5년 사이 '유니콘 스타트업'이 됐다. 송금 서비스에서 종합 금융 서비스로 도약 중인 토스, 원룸에서 아파트로 사업을 확장 중인 직방, 글로벌 서비스로 떠오른 아자르 등 '넥스트 유니콘'으로 불리며 떠오르고 있는 스타트업에도 투자했다.
그는 스타트업 창업가들에게 늘 같은 주문을 한다.
"더, 더, 더!"
그의 메신저 프로필 상태 메시지와 페이스북에서 늘 볼 수 있는 문구다.
창업가들은 꿈을 가진 사람들이에요. 그 꿈을 실현하기 위해 창업한 거죠. 그런데 그 꿈이 그 회사와 서비스의 마지막을 결정하는 것 같아요. 더 큰 꿈을 가지고, 그걸 향해 나아가라는 게 제 주문이에요. 그리고 이건 저에 대한 주문이기도 하죠.
그에게 꿈과 일의 의미에 대해 질문했다. 다음은 일문일답.
**관련 기사 : [폴인 9월 컨퍼런스 '왜 일하는가' 열려][1]**
** **

대표님은 왜 스타트업에 투자하는 일을 하시는 건가요? 돈을 벌기 위해서라면 부동산이나 주식같이 다른 데 투자를 할 수도 있을 텐데요.
많은 사람이 학벌·외모·가정환경 같은 다양한 이유로 자신의 삶을 제한해버려요. 그런데 스타트업계는 그렇지 않은 사람이 많습니다. 이 바닥에선 누구나 스펙을 다 떼고 온전히 자신의 능력으로 세상에 없던 제품과 서비스를 만들어 내고, 그걸로 소비자의 마음을 사고, 투자자의 자본을 얻죠. 그런 사람이 많아지면 사회 전체가 역동적이고 건강해지는 거잖아요.
미디어가 성공한 창업가를 주로 다루다 보니 창업이 화려해 보이는 것 같아요. 하지만 실제 창업가들의 일상은 아주 작고 의미 없는 '삽질'로 채워지는 것 같습니다. 그런데도 왜 점점 더 많은 사람들이 창업에 뛰어드는 걸까요?
'이 문제만큼은 해결해보겠다'라거나 '이 서비스를 통해 변화를 만들어내고 싶다'는 식의 꿈이 있어요. 그 꿈을 이루기 위해 한 걸음 한 걸음 나아가는 과정에 엄청난 성취감과 만족감이 있고요. 바로 그 성취감·만족감 때문에 연쇄 창업가가 되는 사람도 많아요.
그리고 그런 창업가를 지지하고 돕는 과정에서 대표님도 만족감과 성취감을 느끼시는 거겠죠?
"그게 제가 다른 투자가 아닌 스타트업 투자에 투신한 이유겠죠."
김한준 대표의 이력은 여느 창업가 못지않게 화려하다. 초등학교 때 가족과 함께 이민을 간 그는 미국의 육군사관학교인 웨스트포인트에 입학해 군인으로 일했다. 한국이나 미국이나 군 엘리트를 키우는 사관학교 출신은 큰 이변이 없는 한 안정적으로 살 수 있다. 하지만 김 대표는 그 길을 마다하고 전역해 스탠퍼드 MBA를 거쳐 1996년 벤처기업에 투자하는 벤처캐피탈(VC) 알토스벤처스를 창업했다.
이력 중 웨스트포인트 진학이 눈에 띕니다. 왜 군인이 되셨나요?
제 부모님의 시계는 이민 간 1976년에 멈췄어요. 보수주의자셨죠. 반면 저는 미국의 민주적이고 자유로운 문화에 충격을 받았어요. 무슨 의견에 대해서도 반대 의견을 말할 수 있는 자유가 놀라웠습니다. 민주주의는 지킬만한 가치가 있다고 생각했고, 그래서 그 가치를 지키는 군인이 되고 싶었어요.
그런데 왜 전역하신 건가요?
위계가 강하고 엄격한 군 조직문화가 잘 맞진 않았어요. 졸업 후 4년쯤 됐을 때 베를린 장벽이 무너졌는데, 그게 결정적이었어요. 공산주의가 없어졌으니 더는 군에 남을 이유가 없었어요.
전역 후 MBA에 진학한 것도 이유가 있을 것 같아요.
왜 공산주의와 그에 기반을 둔 경제 체제는 역사 속으로 사라졌고, 민주주의와 거기에 기초한 경제 체제(자본주의)는 살아남았을까 오래 고민했어요. 공산주의는 성선설 위에 있다면, 자본주의는 인간은 선하지도 악하지도 않다고 가정하고 욕망을 최대한 보장하되 최소한의 수준으로 규제하자고 생각하는 것 같았죠. 저 역시 그게 맞다고 생각했고, 그래서 비즈니스 영역에서 일하고 싶었어요.
다양한 비즈니스 영역 중 스타트업 투자라는 곳에 뿌리내린 건 왜인가요?
미 동부의 대학들이 금융 산업과 가깝고 보수적이라면, 서부 특히 스탠퍼드대는 정보기술(IT) 산업과 창업계에 가깝고 진취적이에요. 그건 지금도 마찬가지고요. 제가 VC가 된 건 그런 학풍의 영향일 거예요. 교수님 소개로 벤처 투자에 관심이 많은 기업인을 만난 게 구체적인 계기가 됐어요. 그 덕에 뜻이 맞는 친구들과 알토스벤처스를 창업했어요.
김한준 대표는 성공한 창업가를 비교적 초기부터 가까이에서 보아왔다. 그런 그가 꼽은 '안 가본 길을 가는 사람' 그리고 그 중 성공한 이들의 특징은 뭘까.
창업가마다 도드라지는 특징이 있어요. 어떤 창업가는 몰입하는 능력이 뛰어나고, 어떤 창업가는 실행력이 압도적이고요. 그런데도 모든 창업가를 관통하는 특징이 있는데, 제 생각엔 경험을 통해 끊임없이 배워나간다는 것 같아요.
김한준 대표가 투자한 창업가 중엔 앞선 사업을 실패한 이들이 적지 않다. 김 대표가 "실패했다는 사실은 중요하지 않다. 거기서 배운 게 있다면, 그리하여 성장했다면 그는 더 좋은 창업가"라고 말하는 것 역시 같은 맥락이다.
김 대표가 연사로 나서는 이번 컨퍼런스는 오는 20일 오후 7시 서울 성수동 카페 월 닷 서울(구 레필로소피)에서 열린다. 티켓은 [**폴인 사이트**][2]에서 구매할 수 있다.
정선언 기자 <EMAIL>
[1]: https:\\\\news.joins.com\\article\\22942694
[2]: https:\\\\www.folin.co\\studio\\4\\view
'''
tags: []
isStarred: false
isTrashed: false
| true | createdAt: "2018-09-11T10:31:24.558Z"
updatedAt: "2018-09-27T05:14:37.578Z"
type: "MARKDOWN_NOTE"
folder: "5ccab513127047f4eb61"
title: ""
content: '''
---
layout: post
title: "회사도 인생도, 마지막을 결정하는 건 꿈의 크기" 유니콘 감별사 VC 김한준, 일의 의미를 말하다
category: Article
tags: ['Article', 'Passion', 'Insight']
---
[출처: 중앙일보](https:\\\\news.joins.com\\article\\22942860)
개인적 참조를 위한 복사로, [중앙일보의 저작권 정책](http:\\\\bbs.joins.com\\app\\myjoins_policy\\163116)을 확인하고 준수하였습니다.
창업가들은 종종 창업을 "똥더미를 치우는 일 같다"고 표현한다. 일은 산더미고, 매일매일 새로운 문제가 터진다. 그런 것들을 처리하다 보면 '왜 창업했는지' 같은 큰 그림과 방향성은 잊히게 마련이다. 그런 사소한 일상 속에서 교훈을 얻고, 계속해서 방향을 바꾸며 앞으로 나아간다는 점에서 창업은 인생과 닮았다. 창업도, 인생도 한두 번 실패했다고 해서 포기할 수 없다는 점도 비슷하다.
창업이 인생과 비슷하다면, 인생에 대한 조언도 어쩌면 창업 코치가 잘해줄 수 있지 않을까. 국내 대표 VC(벤처캐피털리스트) 김한준 알토스벤처스 대표가 라는 다소 엉뚱해보이는 제목의 컨퍼런스에 선다. 일의 의미를 찾는 직장인들에게 자신이 생각하는 꿈의 정의를 들려주기 위해서다. 지식 콘텐츠 플랫폼 폴인(fol:in)이 준비한 9월의 스튜디오다.
김한준 대표는 '유니콘 감별사'로 불린다. 배틀그라운드로 전 세계 게이머를 사로잡은 블루홀, e커머스 업계 신흥 강자 쿠팡, 푸드 테크 선두 기업이 된 배달의 민족까지, 그가 투자한 회사들이 4~5년 사이 '유니콘 스타트업'이 됐다. 송금 서비스에서 종합 금융 서비스로 도약 중인 토스, 원룸에서 아파트로 사업을 확장 중인 직방, 글로벌 서비스로 떠오른 아자르 등 '넥스트 유니콘'으로 불리며 떠오르고 있는 스타트업에도 투자했다.
그는 스타트업 창업가들에게 늘 같은 주문을 한다.
"더, 더, 더!"
그의 메신저 프로필 상태 메시지와 페이스북에서 늘 볼 수 있는 문구다.
창업가들은 꿈을 가진 사람들이에요. 그 꿈을 실현하기 위해 창업한 거죠. 그런데 그 꿈이 그 회사와 서비스의 마지막을 결정하는 것 같아요. 더 큰 꿈을 가지고, 그걸 향해 나아가라는 게 제 주문이에요. 그리고 이건 저에 대한 주문이기도 하죠.
그에게 꿈과 일의 의미에 대해 질문했다. 다음은 일문일답.
**관련 기사 : [폴인 9월 컨퍼런스 '왜 일하는가' 열려][1]**
** **

대표님은 왜 스타트업에 투자하는 일을 하시는 건가요? 돈을 벌기 위해서라면 부동산이나 주식같이 다른 데 투자를 할 수도 있을 텐데요.
많은 사람이 학벌·외모·가정환경 같은 다양한 이유로 자신의 삶을 제한해버려요. 그런데 스타트업계는 그렇지 않은 사람이 많습니다. 이 바닥에선 누구나 스펙을 다 떼고 온전히 자신의 능력으로 세상에 없던 제품과 서비스를 만들어 내고, 그걸로 소비자의 마음을 사고, 투자자의 자본을 얻죠. 그런 사람이 많아지면 사회 전체가 역동적이고 건강해지는 거잖아요.
미디어가 성공한 창업가를 주로 다루다 보니 창업이 화려해 보이는 것 같아요. 하지만 실제 창업가들의 일상은 아주 작고 의미 없는 '삽질'로 채워지는 것 같습니다. 그런데도 왜 점점 더 많은 사람들이 창업에 뛰어드는 걸까요?
'이 문제만큼은 해결해보겠다'라거나 '이 서비스를 통해 변화를 만들어내고 싶다'는 식의 꿈이 있어요. 그 꿈을 이루기 위해 한 걸음 한 걸음 나아가는 과정에 엄청난 성취감과 만족감이 있고요. 바로 그 성취감·만족감 때문에 연쇄 창업가가 되는 사람도 많아요.
그리고 그런 창업가를 지지하고 돕는 과정에서 대표님도 만족감과 성취감을 느끼시는 거겠죠?
"그게 제가 다른 투자가 아닌 스타트업 투자에 투신한 이유겠죠."
김한준 대표의 이력은 여느 창업가 못지않게 화려하다. 초등학교 때 가족과 함께 이민을 간 그는 미국의 육군사관학교인 웨스트포인트에 입학해 군인으로 일했다. 한국이나 미국이나 군 엘리트를 키우는 사관학교 출신은 큰 이변이 없는 한 안정적으로 살 수 있다. 하지만 김 대표는 그 길을 마다하고 전역해 스탠퍼드 MBA를 거쳐 1996년 벤처기업에 투자하는 벤처캐피탈(VC) 알토스벤처스를 창업했다.
이력 중 웨스트포인트 진학이 눈에 띕니다. 왜 군인이 되셨나요?
제 부모님의 시계는 이민 간 1976년에 멈췄어요. 보수주의자셨죠. 반면 저는 미국의 민주적이고 자유로운 문화에 충격을 받았어요. 무슨 의견에 대해서도 반대 의견을 말할 수 있는 자유가 놀라웠습니다. 민주주의는 지킬만한 가치가 있다고 생각했고, 그래서 그 가치를 지키는 군인이 되고 싶었어요.
그런데 왜 전역하신 건가요?
위계가 강하고 엄격한 군 조직문화가 잘 맞진 않았어요. 졸업 후 4년쯤 됐을 때 베를린 장벽이 무너졌는데, 그게 결정적이었어요. 공산주의가 없어졌으니 더는 군에 남을 이유가 없었어요.
전역 후 MBA에 진학한 것도 이유가 있을 것 같아요.
왜 공산주의와 그에 기반을 둔 경제 체제는 역사 속으로 사라졌고, 민주주의와 거기에 기초한 경제 체제(자본주의)는 살아남았을까 오래 고민했어요. 공산주의는 성선설 위에 있다면, 자본주의는 인간은 선하지도 악하지도 않다고 가정하고 욕망을 최대한 보장하되 최소한의 수준으로 규제하자고 생각하는 것 같았죠. 저 역시 그게 맞다고 생각했고, 그래서 비즈니스 영역에서 일하고 싶었어요.
다양한 비즈니스 영역 중 스타트업 투자라는 곳에 뿌리내린 건 왜인가요?
미 동부의 대학들이 금융 산업과 가깝고 보수적이라면, 서부 특히 스탠퍼드대는 정보기술(IT) 산업과 창업계에 가깝고 진취적이에요. 그건 지금도 마찬가지고요. 제가 VC가 된 건 그런 학풍의 영향일 거예요. 교수님 소개로 벤처 투자에 관심이 많은 기업인을 만난 게 구체적인 계기가 됐어요. 그 덕에 뜻이 맞는 친구들과 알토스벤처스를 창업했어요.
김한준 대표는 성공한 창업가를 비교적 초기부터 가까이에서 보아왔다. 그런 그가 꼽은 '안 가본 길을 가는 사람' 그리고 그 중 성공한 이들의 특징은 뭘까.
창업가마다 도드라지는 특징이 있어요. 어떤 창업가는 몰입하는 능력이 뛰어나고, 어떤 창업가는 실행력이 압도적이고요. 그런데도 모든 창업가를 관통하는 특징이 있는데, 제 생각엔 경험을 통해 끊임없이 배워나간다는 것 같아요.
김한준 대표가 투자한 창업가 중엔 앞선 사업을 실패한 이들이 적지 않다. 김 대표가 "실패했다는 사실은 중요하지 않다. 거기서 배운 게 있다면, 그리하여 성장했다면 그는 더 좋은 창업가"라고 말하는 것 역시 같은 맥락이다.
김 대표가 연사로 나서는 이번 컨퍼런스는 오는 20일 오후 7시 서울 성수동 카페 월 닷 서울(구 레필로소피)에서 열린다. 티켓은 [**폴인 사이트**][2]에서 구매할 수 있다.
정선언 기자 PI:EMAIL:<EMAIL>END_PI
[1]: https:\\\\news.joins.com\\article\\22942694
[2]: https:\\\\www.folin.co\\studio\\4\\view
'''
tags: []
isStarred: false
isTrashed: false
|
[
{
"context": "\t\t@user = {\n\t\t\t_id: \"user-id-123\"\n\t\t\tfirst_name: \"Joe\"\n\t\t\tlast_name: \"Bloggs\"\n\t\t\temail: \"joe@example.co",
"end": 1002,
"score": 0.9998042583465576,
"start": 999,
"tag": "NAME",
"value": "Joe"
},
{
"context": "\"user-id-123\"\n\t\t\tfirst_name: \... | test/UnitTests/coffee/ConnectedUsers/ConnectedUsersManagerTests.coffee | ukasiu/web-sharelatex | 0 |
should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/ConnectedUsers/ConnectedUsersManager"
expect = require("chai").expect
tk = require("timekeeper")
describe "ConnectedUsersManager", ->
beforeEach ->
@settings =
redis:
web:{}
@rClient =
auth:->
setex:sinon.stub()
sadd:sinon.stub()
get: sinon.stub()
srem:sinon.stub()
del:sinon.stub()
smembers:sinon.stub()
expire:sinon.stub()
hset:sinon.stub()
hgetall:sinon.stub()
exec:sinon.stub()
multi: => return @rClient
tk.freeze(new Date())
@ConnectedUsersManager = SandboxedModule.require modulePath, requires:
"settings-sharelatex":@settings
"logger-sharelatex": log:->
"redis": createClient:=>
return @rClient
@client_id = "32132132"
@project_id = "dskjh2u21321"
@user = {
_id: "user-id-123"
first_name: "Joe"
last_name: "Bloggs"
email: "joe@example.com"
}
@cursorData = { row: 12, column: 9, doc_id: '53c3b8c85fee64000023dc6e' }
afterEach ->
tk.reset()
describe "updateUserPosition", ->
beforeEach ->
@rClient.exec.callsArgWith(0)
it "should set a key with the date and give it a ttl", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "last_updated_at", Date.now()).should.equal true
done()
it "should set a key with the user_id", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "user_id", @user._id).should.equal true
done()
it "should set a key with the first_name", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "first_name", @user.first_name).should.equal true
done()
it "should set a key with the last_name", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "last_name", @user.last_name).should.equal true
done()
it "should set a key with the email", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "email", @user.email).should.equal true
done()
it "should push the client_id on to the project list", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.sadd.calledWith("clients_in_project:#{@project_id}", @client_id).should.equal true
done()
it "should add a ttl to the project set so it stays clean", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.expire.calledWith("clients_in_project:#{@project_id}", 24 * 4 * 60 * 60).should.equal true
done()
it "should add a ttl to the connected user so it stays clean", (done) ->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.expire.calledWith("connected_user:#{@project_id}:#{@client_id}", 60 * 15).should.equal true
done()
it "should set the cursor position when provided", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, @cursorData, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "cursorData", JSON.stringify(@cursorData)).should.equal true
done()
describe "markUserAsDisconnected", ->
beforeEach ->
@rClient.exec.callsArgWith(0)
it "should remove the user from the set", (done)->
@ConnectedUsersManager.markUserAsDisconnected @project_id, @client_id, (err)=>
@rClient.srem.calledWith("clients_in_project:#{@project_id}", @client_id).should.equal true
done()
it "should delete the connected_user string", (done)->
@ConnectedUsersManager.markUserAsDisconnected @project_id, @client_id, (err)=>
@rClient.del.calledWith("connected_user:#{@project_id}:#{@client_id}").should.equal true
done()
it "should add a ttl to the connected user set so it stays clean", (done)->
@ConnectedUsersManager.markUserAsDisconnected @project_id, @client_id, (err)=>
@rClient.expire.calledWith("clients_in_project:#{@project_id}", 24 * 4 * 60 * 60).should.equal true
done()
describe "_getConnectedUser", ->
it "should get the user returning connected if there is a value", (done)->
cursorData = JSON.stringify(cursorData:{row:1})
@rClient.hgetall.callsArgWith(1, null, {connected_at:new Date(), cursorData})
@ConnectedUsersManager._getConnectedUser @project_id, @client_id, (err, result)=>
result.connected.should.equal true
result.client_id.should.equal @client_id
done()
it "should get the user returning connected if there is a value", (done)->
@rClient.hgetall.callsArgWith(1)
@ConnectedUsersManager._getConnectedUser @project_id, @client_id, (err, result)=>
result.connected.should.equal false
result.client_id.should.equal @client_id
done()
describe "getConnectedUsers", ->
beforeEach ->
@users = ["1234", "5678", "9123"]
@rClient.smembers.callsArgWith(1, null, @users)
@ConnectedUsersManager._getConnectedUser = sinon.stub()
@ConnectedUsersManager._getConnectedUser.withArgs(@project_id, @users[0]).callsArgWith(2, null, {connected:true, client_id:@users[0]})
@ConnectedUsersManager._getConnectedUser.withArgs(@project_id, @users[1]).callsArgWith(2, null, {connected:false, client_id:@users[1]})
@ConnectedUsersManager._getConnectedUser.withArgs(@project_id, @users[2]).callsArgWith(2, null, {connected:true, client_id:@users[2]})
it "should only return the users in the list which are still in redis", (done)->
@ConnectedUsersManager.getConnectedUsers @project_id, (err, users)=>
users.length.should.equal 2
users[0].should.deep.equal {client_id:@users[0], connected:true}
users[1].should.deep.equal {client_id:@users[2], connected:true}
done()
| 26281 |
should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/ConnectedUsers/ConnectedUsersManager"
expect = require("chai").expect
tk = require("timekeeper")
describe "ConnectedUsersManager", ->
beforeEach ->
@settings =
redis:
web:{}
@rClient =
auth:->
setex:sinon.stub()
sadd:sinon.stub()
get: sinon.stub()
srem:sinon.stub()
del:sinon.stub()
smembers:sinon.stub()
expire:sinon.stub()
hset:sinon.stub()
hgetall:sinon.stub()
exec:sinon.stub()
multi: => return @rClient
tk.freeze(new Date())
@ConnectedUsersManager = SandboxedModule.require modulePath, requires:
"settings-sharelatex":@settings
"logger-sharelatex": log:->
"redis": createClient:=>
return @rClient
@client_id = "32132132"
@project_id = "dskjh2u21321"
@user = {
_id: "user-id-123"
first_name: "<NAME>"
last_name: "<NAME>"
email: "<EMAIL>"
}
@cursorData = { row: 12, column: 9, doc_id: '53c3b8c85fee64000023dc6e' }
afterEach ->
tk.reset()
describe "updateUserPosition", ->
beforeEach ->
@rClient.exec.callsArgWith(0)
it "should set a key with the date and give it a ttl", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "last_updated_at", Date.now()).should.equal true
done()
it "should set a key with the user_id", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "user_id", @user._id).should.equal true
done()
it "should set a key with the first_name", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "first_name", @user.first_name).should.equal true
done()
it "should set a key with the last_name", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "last_name", @user.last_name).should.equal true
done()
it "should set a key with the email", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "email", @user.email).should.equal true
done()
it "should push the client_id on to the project list", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.sadd.calledWith("clients_in_project:#{@project_id}", @client_id).should.equal true
done()
it "should add a ttl to the project set so it stays clean", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.expire.calledWith("clients_in_project:#{@project_id}", 24 * 4 * 60 * 60).should.equal true
done()
it "should add a ttl to the connected user so it stays clean", (done) ->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.expire.calledWith("connected_user:#{@project_id}:#{@client_id}", 60 * 15).should.equal true
done()
it "should set the cursor position when provided", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, @cursorData, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "cursorData", JSON.stringify(@cursorData)).should.equal true
done()
describe "markUserAsDisconnected", ->
beforeEach ->
@rClient.exec.callsArgWith(0)
it "should remove the user from the set", (done)->
@ConnectedUsersManager.markUserAsDisconnected @project_id, @client_id, (err)=>
@rClient.srem.calledWith("clients_in_project:#{@project_id}", @client_id).should.equal true
done()
it "should delete the connected_user string", (done)->
@ConnectedUsersManager.markUserAsDisconnected @project_id, @client_id, (err)=>
@rClient.del.calledWith("connected_user:#{@project_id}:#{@client_id}").should.equal true
done()
it "should add a ttl to the connected user set so it stays clean", (done)->
@ConnectedUsersManager.markUserAsDisconnected @project_id, @client_id, (err)=>
@rClient.expire.calledWith("clients_in_project:#{@project_id}", 24 * 4 * 60 * 60).should.equal true
done()
describe "_getConnectedUser", ->
it "should get the user returning connected if there is a value", (done)->
cursorData = JSON.stringify(cursorData:{row:1})
@rClient.hgetall.callsArgWith(1, null, {connected_at:new Date(), cursorData})
@ConnectedUsersManager._getConnectedUser @project_id, @client_id, (err, result)=>
result.connected.should.equal true
result.client_id.should.equal @client_id
done()
it "should get the user returning connected if there is a value", (done)->
@rClient.hgetall.callsArgWith(1)
@ConnectedUsersManager._getConnectedUser @project_id, @client_id, (err, result)=>
result.connected.should.equal false
result.client_id.should.equal @client_id
done()
describe "getConnectedUsers", ->
beforeEach ->
@users = ["1234", "5678", "9123"]
@rClient.smembers.callsArgWith(1, null, @users)
@ConnectedUsersManager._getConnectedUser = sinon.stub()
@ConnectedUsersManager._getConnectedUser.withArgs(@project_id, @users[0]).callsArgWith(2, null, {connected:true, client_id:@users[0]})
@ConnectedUsersManager._getConnectedUser.withArgs(@project_id, @users[1]).callsArgWith(2, null, {connected:false, client_id:@users[1]})
@ConnectedUsersManager._getConnectedUser.withArgs(@project_id, @users[2]).callsArgWith(2, null, {connected:true, client_id:@users[2]})
it "should only return the users in the list which are still in redis", (done)->
@ConnectedUsersManager.getConnectedUsers @project_id, (err, users)=>
users.length.should.equal 2
users[0].should.deep.equal {client_id:@users[0], connected:true}
users[1].should.deep.equal {client_id:@users[2], connected: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/ConnectedUsers/ConnectedUsersManager"
expect = require("chai").expect
tk = require("timekeeper")
describe "ConnectedUsersManager", ->
beforeEach ->
@settings =
redis:
web:{}
@rClient =
auth:->
setex:sinon.stub()
sadd:sinon.stub()
get: sinon.stub()
srem:sinon.stub()
del:sinon.stub()
smembers:sinon.stub()
expire:sinon.stub()
hset:sinon.stub()
hgetall:sinon.stub()
exec:sinon.stub()
multi: => return @rClient
tk.freeze(new Date())
@ConnectedUsersManager = SandboxedModule.require modulePath, requires:
"settings-sharelatex":@settings
"logger-sharelatex": log:->
"redis": createClient:=>
return @rClient
@client_id = "32132132"
@project_id = "dskjh2u21321"
@user = {
_id: "user-id-123"
first_name: "PI:NAME:<NAME>END_PI"
last_name: "PI:NAME:<NAME>END_PI"
email: "PI:EMAIL:<EMAIL>END_PI"
}
@cursorData = { row: 12, column: 9, doc_id: '53c3b8c85fee64000023dc6e' }
afterEach ->
tk.reset()
describe "updateUserPosition", ->
beforeEach ->
@rClient.exec.callsArgWith(0)
it "should set a key with the date and give it a ttl", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "last_updated_at", Date.now()).should.equal true
done()
it "should set a key with the user_id", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "user_id", @user._id).should.equal true
done()
it "should set a key with the first_name", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "first_name", @user.first_name).should.equal true
done()
it "should set a key with the last_name", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "last_name", @user.last_name).should.equal true
done()
it "should set a key with the email", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "email", @user.email).should.equal true
done()
it "should push the client_id on to the project list", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.sadd.calledWith("clients_in_project:#{@project_id}", @client_id).should.equal true
done()
it "should add a ttl to the project set so it stays clean", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.expire.calledWith("clients_in_project:#{@project_id}", 24 * 4 * 60 * 60).should.equal true
done()
it "should add a ttl to the connected user so it stays clean", (done) ->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, null, (err)=>
@rClient.expire.calledWith("connected_user:#{@project_id}:#{@client_id}", 60 * 15).should.equal true
done()
it "should set the cursor position when provided", (done)->
@ConnectedUsersManager.updateUserPosition @project_id, @client_id, @user, @cursorData, (err)=>
@rClient.hset.calledWith("connected_user:#{@project_id}:#{@client_id}", "cursorData", JSON.stringify(@cursorData)).should.equal true
done()
describe "markUserAsDisconnected", ->
beforeEach ->
@rClient.exec.callsArgWith(0)
it "should remove the user from the set", (done)->
@ConnectedUsersManager.markUserAsDisconnected @project_id, @client_id, (err)=>
@rClient.srem.calledWith("clients_in_project:#{@project_id}", @client_id).should.equal true
done()
it "should delete the connected_user string", (done)->
@ConnectedUsersManager.markUserAsDisconnected @project_id, @client_id, (err)=>
@rClient.del.calledWith("connected_user:#{@project_id}:#{@client_id}").should.equal true
done()
it "should add a ttl to the connected user set so it stays clean", (done)->
@ConnectedUsersManager.markUserAsDisconnected @project_id, @client_id, (err)=>
@rClient.expire.calledWith("clients_in_project:#{@project_id}", 24 * 4 * 60 * 60).should.equal true
done()
describe "_getConnectedUser", ->
it "should get the user returning connected if there is a value", (done)->
cursorData = JSON.stringify(cursorData:{row:1})
@rClient.hgetall.callsArgWith(1, null, {connected_at:new Date(), cursorData})
@ConnectedUsersManager._getConnectedUser @project_id, @client_id, (err, result)=>
result.connected.should.equal true
result.client_id.should.equal @client_id
done()
it "should get the user returning connected if there is a value", (done)->
@rClient.hgetall.callsArgWith(1)
@ConnectedUsersManager._getConnectedUser @project_id, @client_id, (err, result)=>
result.connected.should.equal false
result.client_id.should.equal @client_id
done()
describe "getConnectedUsers", ->
beforeEach ->
@users = ["1234", "5678", "9123"]
@rClient.smembers.callsArgWith(1, null, @users)
@ConnectedUsersManager._getConnectedUser = sinon.stub()
@ConnectedUsersManager._getConnectedUser.withArgs(@project_id, @users[0]).callsArgWith(2, null, {connected:true, client_id:@users[0]})
@ConnectedUsersManager._getConnectedUser.withArgs(@project_id, @users[1]).callsArgWith(2, null, {connected:false, client_id:@users[1]})
@ConnectedUsersManager._getConnectedUser.withArgs(@project_id, @users[2]).callsArgWith(2, null, {connected:true, client_id:@users[2]})
it "should only return the users in the list which are still in redis", (done)->
@ConnectedUsersManager.getConnectedUsers @project_id, (err, users)=>
users.length.should.equal 2
users[0].should.deep.equal {client_id:@users[0], connected:true}
users[1].should.deep.equal {client_id:@users[2], connected:true}
done()
|
[
{
"context": "my'\n steamapi: 'dummy'\n aws_access_key_id: 'dummy'\n aws_secret_access_key: 'dummy'\n",
"end": 205,
"score": 0.5723594427108765,
"start": 200,
"tag": "KEY",
"value": "dummy"
},
{
"context": "ccess_key_id: 'dummy'\n aws_secret_access_key: 'dummy'\n",
"e... | config/test.coffee | SizzlingStats/sizzlingstats.com | 9 | module.exports =
cfg:
ENV: 'test'
mongo_url: process.env.MONGO_URL || 'mongodb://localhost/sizzlingstats-test'
secrets:
session: 'dummy'
steamapi: 'dummy'
aws_access_key_id: 'dummy'
aws_secret_access_key: 'dummy'
| 133263 | module.exports =
cfg:
ENV: 'test'
mongo_url: process.env.MONGO_URL || 'mongodb://localhost/sizzlingstats-test'
secrets:
session: 'dummy'
steamapi: 'dummy'
aws_access_key_id: '<KEY>'
aws_secret_access_key: '<KEY>'
| true | module.exports =
cfg:
ENV: 'test'
mongo_url: process.env.MONGO_URL || 'mongodb://localhost/sizzlingstats-test'
secrets:
session: 'dummy'
steamapi: 'dummy'
aws_access_key_id: 'PI:KEY:<KEY>END_PI'
aws_secret_access_key: 'PI:KEY:<KEY>END_PI'
|
[
{
"context": " keybox = self\n done null\n\n username = 'test'\n email = 'test@test.com'\n password = 'this is ",
"end": 308,
"score": 0.999133825302124,
"start": 304,
"tag": "USERNAME",
"value": "test"
},
{
"context": " done null\n\n username = 'test'\n email = ... | test/keybox.coffee | yinso/keybox | 1 | Keybox = require '../src/keybox'
fs = require 'fs'
describe 'keybox test', ->
keybox = null
filePath = './test.kbx'
it 'can init', (done) ->
Keybox.initialize {filePath: filePath}, (err, self) ->
if err
done err
else
keybox = self
done null
username = 'test'
email = 'test@test.com'
password = 'this is a test password'
user = null
it 'can create user', (done) ->
keybox.createUser username, password, { email: email }, (err, val) ->
if err
done err
else
user = val
done null
it 'can login', (done) ->
keybox.login username, password, (err, val) ->
if err
done err
else
user = val
done null
newPassword = 'this is the new password try it'
it 'can change password', (done) ->
keybox.changePasswordAsync username, password, newPassword, newPassword
.then ->
keybox.loginAsync username, password
.then ->
throw new Error("old password still works!")
.catch (err) ->
return
.then ->
keybox.loginAsync username, newPassword
.then ->
user = keybox.currentUser
done null
.catch done
it 'can remove file', (done) ->
fs.unlink filePath, done
| 21613 | Keybox = require '../src/keybox'
fs = require 'fs'
describe 'keybox test', ->
keybox = null
filePath = './test.kbx'
it 'can init', (done) ->
Keybox.initialize {filePath: filePath}, (err, self) ->
if err
done err
else
keybox = self
done null
username = 'test'
email = '<EMAIL>'
password = '<PASSWORD>'
user = null
it 'can create user', (done) ->
keybox.createUser username, password, { email: email }, (err, val) ->
if err
done err
else
user = val
done null
it 'can login', (done) ->
keybox.login username, password, (err, val) ->
if err
done err
else
user = val
done null
newPassword = '<PASSWORD>'
it 'can change password', (done) ->
keybox.changePasswordAsync username, password, newPassword, newPassword
.then ->
keybox.loginAsync username, password
.then ->
throw new Error("old password still works!")
.catch (err) ->
return
.then ->
keybox.loginAsync username, newPassword
.then ->
user = keybox.currentUser
done null
.catch done
it 'can remove file', (done) ->
fs.unlink filePath, done
| true | Keybox = require '../src/keybox'
fs = require 'fs'
describe 'keybox test', ->
keybox = null
filePath = './test.kbx'
it 'can init', (done) ->
Keybox.initialize {filePath: filePath}, (err, self) ->
if err
done err
else
keybox = self
done null
username = 'test'
email = 'PI:EMAIL:<EMAIL>END_PI'
password = 'PI:PASSWORD:<PASSWORD>END_PI'
user = null
it 'can create user', (done) ->
keybox.createUser username, password, { email: email }, (err, val) ->
if err
done err
else
user = val
done null
it 'can login', (done) ->
keybox.login username, password, (err, val) ->
if err
done err
else
user = val
done null
newPassword = 'PI:PASSWORD:<PASSWORD>END_PI'
it 'can change password', (done) ->
keybox.changePasswordAsync username, password, newPassword, newPassword
.then ->
keybox.loginAsync username, password
.then ->
throw new Error("old password still works!")
.catch (err) ->
return
.then ->
keybox.loginAsync username, newPassword
.then ->
user = keybox.currentUser
done null
.catch done
it 'can remove file', (done) ->
fs.unlink filePath, done
|
[
{
"context": "ath.random = (->\n seed = 49734321\n ->\n \n # Robert Jenkins' 32 bit integer hash function.\n seed = ((seed ",
"end": 3442,
"score": 0.9996160268783569,
"start": 3428,
"tag": "NAME",
"value": "Robert Jenkins"
}
] | deps/v8/benchmarks/base.coffee | lxe/io.coffee | 0 | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Simple framework for running the benchmark suites and
# computing a score based on the timing measurements.
# A benchmark has a name (string) and a function that will be run to
# do the performance measurement. The optional setup and tearDown
# arguments are functions that will be invoked before and after
# running the benchmark, but the running time of these functions will
# not be accounted for in the benchmark score.
Benchmark = (name, run, setup, tearDown) ->
@name = name
@run = run
@Setup = (if setup then setup else ->
)
@TearDown = (if tearDown then tearDown else ->
)
return
# Benchmark results hold the benchmark and the measured time used to
# run the benchmark. The benchmark score is computed later once a
# full benchmark suite has run to completion.
BenchmarkResult = (benchmark, time) ->
@benchmark = benchmark
@time = time
return
# Automatically convert results to numbers. Used by the geometric
# mean computation.
# Suites of benchmarks consist of a name and the set of benchmarks in
# addition to the reference timing that the final score will be based
# on. This way, all scores are relative to a reference run and higher
# scores implies better performance.
BenchmarkSuite = (name, reference, benchmarks) ->
@name = name
@reference = reference
@benchmarks = benchmarks
BenchmarkSuite.suites.push this
return
BenchmarkResult::valueOf = ->
@time
# Keep track of all declared benchmark suites.
BenchmarkSuite.suites = []
# Scores are not comparable across versions. Bump the version if
# you're making changes that will affect that scores, e.g. if you add
# a new benchmark or change an existing one.
BenchmarkSuite.version = "7"
# To make the benchmark results predictable, we replace Math.random
# with a 100% deterministic alternative.
Math.random = (->
seed = 49734321
->
# Robert Jenkins' 32 bit integer hash function.
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff
(seed & 0xfffffff) / 0x10000000
)()
# Runs all registered benchmark suites and optionally yields between
# each individual benchmark to avoid running for too long in the
# context of browsers. Once done, the final score is reported to the
# runner.
BenchmarkSuite.RunSuites = (runner) ->
RunStep = ->
while continuation or index < length
if continuation
continuation = continuation()
else
suite = suites[index++]
runner.NotifyStart suite.name if runner.NotifyStart
continuation = suite.RunStep(runner)
if continuation and typeof window isnt "undefined" and window.setTimeout
window.setTimeout RunStep, 25
return
if runner.NotifyScore
score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores)
formatted = BenchmarkSuite.FormatScore(100 * score)
runner.NotifyScore formatted
return
continuation = null
suites = BenchmarkSuite.suites
length = suites.length
BenchmarkSuite.scores = []
index = 0
RunStep()
return
# Counts the total number of registered benchmarks. Useful for
# showing progress as a percentage.
BenchmarkSuite.CountBenchmarks = ->
result = 0
suites = BenchmarkSuite.suites
i = 0
while i < suites.length
result += suites[i].benchmarks.length
i++
result
# Computes the geometric mean of a set of numbers.
BenchmarkSuite.GeometricMean = (numbers) ->
log = 0
i = 0
while i < numbers.length
log += Math.log(numbers[i])
i++
Math.pow Math.E, log / numbers.length
# Converts a score value to a string with at least three significant
# digits.
BenchmarkSuite.FormatScore = (value) ->
if value > 100
value.toFixed 0
else
value.toPrecision 3
# Notifies the runner that we're done running a single benchmark in
# the benchmark suite. This can be useful to report progress.
BenchmarkSuite::NotifyStep = (result) ->
@results.push result
@runner.NotifyStep result.benchmark.name if @runner.NotifyStep
return
# Notifies the runner that we're done with running a suite and that
# we have a result which can be reported to the user if needed.
BenchmarkSuite::NotifyResult = ->
mean = BenchmarkSuite.GeometricMean(@results)
score = @reference / mean
BenchmarkSuite.scores.push score
if @runner.NotifyResult
formatted = BenchmarkSuite.FormatScore(100 * score)
@runner.NotifyResult @name, formatted
return
# Notifies the runner that running a benchmark resulted in an error.
BenchmarkSuite::NotifyError = (error) ->
@runner.NotifyError @name, error if @runner.NotifyError
@runner.NotifyStep @name if @runner.NotifyStep
return
# Runs a single benchmark for at least a second and computes the
# average time it takes to run a single iteration.
BenchmarkSuite::RunSingleBenchmark = (benchmark, data) ->
Measure = (data) ->
elapsed = 0
start = new Date()
n = 0
while elapsed < 1000
benchmark.run()
elapsed = new Date() - start
n++
if data?
data.runs += n
data.elapsed += elapsed
return
unless data?
# Measure the benchmark once for warm up and throw the result
# away. Return a fresh data object.
Measure null
runs: 0
elapsed: 0
else
Measure data
# If we've run too few iterations, we continue for another second.
return data if data.runs < 32
usec = (data.elapsed * 1000) / data.runs
@NotifyStep new BenchmarkResult(benchmark, usec)
null
# This function starts running a suite, but stops between each
# individual benchmark in the suite and returns a continuation
# function which can be invoked to run the next benchmark. Once the
# last benchmark has been executed, null is returned.
BenchmarkSuite::RunStep = (runner) ->
# Run the setup, the actual benchmark, and the tear down in three
# separate steps to allow the framework to yield between any of the
# steps.
RunNextSetup = ->
if index < length
try
suite.benchmarks[index].Setup()
catch e
suite.NotifyError e
return null
return RunNextBenchmark
suite.NotifyResult()
null
RunNextBenchmark = ->
try
data = suite.RunSingleBenchmark(suite.benchmarks[index], data)
catch e
suite.NotifyError e
return null
# If data is null, we're done with this benchmark.
(if (not (data?)) then RunNextTearDown else RunNextBenchmark())
RunNextTearDown = ->
try
suite.benchmarks[index++].TearDown()
catch e
suite.NotifyError e
return null
RunNextSetup
@results = []
@runner = runner
length = @benchmarks.length
index = 0
suite = this
data = undefined
# Start out running the setup.
RunNextSetup()
| 28213 | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Simple framework for running the benchmark suites and
# computing a score based on the timing measurements.
# A benchmark has a name (string) and a function that will be run to
# do the performance measurement. The optional setup and tearDown
# arguments are functions that will be invoked before and after
# running the benchmark, but the running time of these functions will
# not be accounted for in the benchmark score.
Benchmark = (name, run, setup, tearDown) ->
@name = name
@run = run
@Setup = (if setup then setup else ->
)
@TearDown = (if tearDown then tearDown else ->
)
return
# Benchmark results hold the benchmark and the measured time used to
# run the benchmark. The benchmark score is computed later once a
# full benchmark suite has run to completion.
BenchmarkResult = (benchmark, time) ->
@benchmark = benchmark
@time = time
return
# Automatically convert results to numbers. Used by the geometric
# mean computation.
# Suites of benchmarks consist of a name and the set of benchmarks in
# addition to the reference timing that the final score will be based
# on. This way, all scores are relative to a reference run and higher
# scores implies better performance.
BenchmarkSuite = (name, reference, benchmarks) ->
@name = name
@reference = reference
@benchmarks = benchmarks
BenchmarkSuite.suites.push this
return
BenchmarkResult::valueOf = ->
@time
# Keep track of all declared benchmark suites.
BenchmarkSuite.suites = []
# Scores are not comparable across versions. Bump the version if
# you're making changes that will affect that scores, e.g. if you add
# a new benchmark or change an existing one.
BenchmarkSuite.version = "7"
# To make the benchmark results predictable, we replace Math.random
# with a 100% deterministic alternative.
Math.random = (->
seed = 49734321
->
# <NAME>' 32 bit integer hash function.
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff
(seed & 0xfffffff) / 0x10000000
)()
# Runs all registered benchmark suites and optionally yields between
# each individual benchmark to avoid running for too long in the
# context of browsers. Once done, the final score is reported to the
# runner.
BenchmarkSuite.RunSuites = (runner) ->
RunStep = ->
while continuation or index < length
if continuation
continuation = continuation()
else
suite = suites[index++]
runner.NotifyStart suite.name if runner.NotifyStart
continuation = suite.RunStep(runner)
if continuation and typeof window isnt "undefined" and window.setTimeout
window.setTimeout RunStep, 25
return
if runner.NotifyScore
score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores)
formatted = BenchmarkSuite.FormatScore(100 * score)
runner.NotifyScore formatted
return
continuation = null
suites = BenchmarkSuite.suites
length = suites.length
BenchmarkSuite.scores = []
index = 0
RunStep()
return
# Counts the total number of registered benchmarks. Useful for
# showing progress as a percentage.
BenchmarkSuite.CountBenchmarks = ->
result = 0
suites = BenchmarkSuite.suites
i = 0
while i < suites.length
result += suites[i].benchmarks.length
i++
result
# Computes the geometric mean of a set of numbers.
BenchmarkSuite.GeometricMean = (numbers) ->
log = 0
i = 0
while i < numbers.length
log += Math.log(numbers[i])
i++
Math.pow Math.E, log / numbers.length
# Converts a score value to a string with at least three significant
# digits.
BenchmarkSuite.FormatScore = (value) ->
if value > 100
value.toFixed 0
else
value.toPrecision 3
# Notifies the runner that we're done running a single benchmark in
# the benchmark suite. This can be useful to report progress.
BenchmarkSuite::NotifyStep = (result) ->
@results.push result
@runner.NotifyStep result.benchmark.name if @runner.NotifyStep
return
# Notifies the runner that we're done with running a suite and that
# we have a result which can be reported to the user if needed.
BenchmarkSuite::NotifyResult = ->
mean = BenchmarkSuite.GeometricMean(@results)
score = @reference / mean
BenchmarkSuite.scores.push score
if @runner.NotifyResult
formatted = BenchmarkSuite.FormatScore(100 * score)
@runner.NotifyResult @name, formatted
return
# Notifies the runner that running a benchmark resulted in an error.
BenchmarkSuite::NotifyError = (error) ->
@runner.NotifyError @name, error if @runner.NotifyError
@runner.NotifyStep @name if @runner.NotifyStep
return
# Runs a single benchmark for at least a second and computes the
# average time it takes to run a single iteration.
BenchmarkSuite::RunSingleBenchmark = (benchmark, data) ->
Measure = (data) ->
elapsed = 0
start = new Date()
n = 0
while elapsed < 1000
benchmark.run()
elapsed = new Date() - start
n++
if data?
data.runs += n
data.elapsed += elapsed
return
unless data?
# Measure the benchmark once for warm up and throw the result
# away. Return a fresh data object.
Measure null
runs: 0
elapsed: 0
else
Measure data
# If we've run too few iterations, we continue for another second.
return data if data.runs < 32
usec = (data.elapsed * 1000) / data.runs
@NotifyStep new BenchmarkResult(benchmark, usec)
null
# This function starts running a suite, but stops between each
# individual benchmark in the suite and returns a continuation
# function which can be invoked to run the next benchmark. Once the
# last benchmark has been executed, null is returned.
BenchmarkSuite::RunStep = (runner) ->
# Run the setup, the actual benchmark, and the tear down in three
# separate steps to allow the framework to yield between any of the
# steps.
RunNextSetup = ->
if index < length
try
suite.benchmarks[index].Setup()
catch e
suite.NotifyError e
return null
return RunNextBenchmark
suite.NotifyResult()
null
RunNextBenchmark = ->
try
data = suite.RunSingleBenchmark(suite.benchmarks[index], data)
catch e
suite.NotifyError e
return null
# If data is null, we're done with this benchmark.
(if (not (data?)) then RunNextTearDown else RunNextBenchmark())
RunNextTearDown = ->
try
suite.benchmarks[index++].TearDown()
catch e
suite.NotifyError e
return null
RunNextSetup
@results = []
@runner = runner
length = @benchmarks.length
index = 0
suite = this
data = undefined
# Start out running the setup.
RunNextSetup()
| true | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Simple framework for running the benchmark suites and
# computing a score based on the timing measurements.
# A benchmark has a name (string) and a function that will be run to
# do the performance measurement. The optional setup and tearDown
# arguments are functions that will be invoked before and after
# running the benchmark, but the running time of these functions will
# not be accounted for in the benchmark score.
Benchmark = (name, run, setup, tearDown) ->
@name = name
@run = run
@Setup = (if setup then setup else ->
)
@TearDown = (if tearDown then tearDown else ->
)
return
# Benchmark results hold the benchmark and the measured time used to
# run the benchmark. The benchmark score is computed later once a
# full benchmark suite has run to completion.
BenchmarkResult = (benchmark, time) ->
@benchmark = benchmark
@time = time
return
# Automatically convert results to numbers. Used by the geometric
# mean computation.
# Suites of benchmarks consist of a name and the set of benchmarks in
# addition to the reference timing that the final score will be based
# on. This way, all scores are relative to a reference run and higher
# scores implies better performance.
BenchmarkSuite = (name, reference, benchmarks) ->
@name = name
@reference = reference
@benchmarks = benchmarks
BenchmarkSuite.suites.push this
return
BenchmarkResult::valueOf = ->
@time
# Keep track of all declared benchmark suites.
BenchmarkSuite.suites = []
# Scores are not comparable across versions. Bump the version if
# you're making changes that will affect that scores, e.g. if you add
# a new benchmark or change an existing one.
BenchmarkSuite.version = "7"
# To make the benchmark results predictable, we replace Math.random
# with a 100% deterministic alternative.
Math.random = (->
seed = 49734321
->
# PI:NAME:<NAME>END_PI' 32 bit integer hash function.
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff
(seed & 0xfffffff) / 0x10000000
)()
# Runs all registered benchmark suites and optionally yields between
# each individual benchmark to avoid running for too long in the
# context of browsers. Once done, the final score is reported to the
# runner.
BenchmarkSuite.RunSuites = (runner) ->
RunStep = ->
while continuation or index < length
if continuation
continuation = continuation()
else
suite = suites[index++]
runner.NotifyStart suite.name if runner.NotifyStart
continuation = suite.RunStep(runner)
if continuation and typeof window isnt "undefined" and window.setTimeout
window.setTimeout RunStep, 25
return
if runner.NotifyScore
score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores)
formatted = BenchmarkSuite.FormatScore(100 * score)
runner.NotifyScore formatted
return
continuation = null
suites = BenchmarkSuite.suites
length = suites.length
BenchmarkSuite.scores = []
index = 0
RunStep()
return
# Counts the total number of registered benchmarks. Useful for
# showing progress as a percentage.
BenchmarkSuite.CountBenchmarks = ->
result = 0
suites = BenchmarkSuite.suites
i = 0
while i < suites.length
result += suites[i].benchmarks.length
i++
result
# Computes the geometric mean of a set of numbers.
BenchmarkSuite.GeometricMean = (numbers) ->
log = 0
i = 0
while i < numbers.length
log += Math.log(numbers[i])
i++
Math.pow Math.E, log / numbers.length
# Converts a score value to a string with at least three significant
# digits.
BenchmarkSuite.FormatScore = (value) ->
if value > 100
value.toFixed 0
else
value.toPrecision 3
# Notifies the runner that we're done running a single benchmark in
# the benchmark suite. This can be useful to report progress.
BenchmarkSuite::NotifyStep = (result) ->
@results.push result
@runner.NotifyStep result.benchmark.name if @runner.NotifyStep
return
# Notifies the runner that we're done with running a suite and that
# we have a result which can be reported to the user if needed.
BenchmarkSuite::NotifyResult = ->
mean = BenchmarkSuite.GeometricMean(@results)
score = @reference / mean
BenchmarkSuite.scores.push score
if @runner.NotifyResult
formatted = BenchmarkSuite.FormatScore(100 * score)
@runner.NotifyResult @name, formatted
return
# Notifies the runner that running a benchmark resulted in an error.
BenchmarkSuite::NotifyError = (error) ->
@runner.NotifyError @name, error if @runner.NotifyError
@runner.NotifyStep @name if @runner.NotifyStep
return
# Runs a single benchmark for at least a second and computes the
# average time it takes to run a single iteration.
BenchmarkSuite::RunSingleBenchmark = (benchmark, data) ->
Measure = (data) ->
elapsed = 0
start = new Date()
n = 0
while elapsed < 1000
benchmark.run()
elapsed = new Date() - start
n++
if data?
data.runs += n
data.elapsed += elapsed
return
unless data?
# Measure the benchmark once for warm up and throw the result
# away. Return a fresh data object.
Measure null
runs: 0
elapsed: 0
else
Measure data
# If we've run too few iterations, we continue for another second.
return data if data.runs < 32
usec = (data.elapsed * 1000) / data.runs
@NotifyStep new BenchmarkResult(benchmark, usec)
null
# This function starts running a suite, but stops between each
# individual benchmark in the suite and returns a continuation
# function which can be invoked to run the next benchmark. Once the
# last benchmark has been executed, null is returned.
BenchmarkSuite::RunStep = (runner) ->
# Run the setup, the actual benchmark, and the tear down in three
# separate steps to allow the framework to yield between any of the
# steps.
RunNextSetup = ->
if index < length
try
suite.benchmarks[index].Setup()
catch e
suite.NotifyError e
return null
return RunNextBenchmark
suite.NotifyResult()
null
RunNextBenchmark = ->
try
data = suite.RunSingleBenchmark(suite.benchmarks[index], data)
catch e
suite.NotifyError e
return null
# If data is null, we're done with this benchmark.
(if (not (data?)) then RunNextTearDown else RunNextBenchmark())
RunNextTearDown = ->
try
suite.benchmarks[index++].TearDown()
catch e
suite.NotifyError e
return null
RunNextSetup
@results = []
@runner = runner
length = @benchmarks.length
index = 0
suite = this
data = undefined
# Start out running the setup.
RunNextSetup()
|
[
{
"context": "led = false\n renderables = [{\n name: \"Alice\"\n $renderers: [{renderer: 'hbs', options: ",
"end": 2692,
"score": 0.9998360872268677,
"start": 2687,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ntent: \"{{name}}\"\n },\n {\n nam... | tests/renderers_test.coffee | bahiamartins/stacktic | 1 | Renderers = require('../lib/Renderers')
HandlebarsRenderingEngine = require('../plugins/hbs/HandlebarsRenderingEngine')
HandlebarsRenderingEngine.configure({src: 'tests/_fixtures'}, {})
class GreeterRenderer
render: (content, context, done) ->
done(null, "Hi #{content}")
describe "Renderers", ->
describe "#registerEngine", ->
it "should register an engine", ->
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
(renderers.engines.hbs is HandlebarsRenderingEngine).should.be.true
describe "#resolveEngine", ->
it "should instantiate an engine if exists", ->
instanceOptions = {a: 1}
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
eng = renderers.resolveEngine('hbs', instanceOptions)
eng.should.be.instanceOf(HandlebarsRenderingEngine)
describe "#setDefaultEngines", ->
it "should setup default engines", ->
renderers = new Renderers()
renderers.setDefaultEngines(['hbs', 'md'], {hbs: {layout: 'app'}})
renderers.defaultEngines.should.eql([
{renderer: 'hbs', options: {layout: 'app'}}
{renderer: 'md', options: {}}
])
it "should not throw if no options are provided", ->
renderers = new Renderers()
(->
renderers.setDefaultEngines(['hbs', 'md'])
).should.not.throw()
describe "#render", ->
it 'should render renderables', ->
called = false
renderables = [{
a: 1,
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{a}}"
}]
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
renderers.render renderables, (err, objects, x) ->
called = true
objects.should.be.an.Array
objects[0].$rendered.should.equal('1')
called.should.be.true
it 'should render many renderables', ->
called = false
renderables = [{
a: 1,
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{a}}"
},
{
a: 2,
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{a}}"
}]
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
renderers.render renderables, (err, objects, x) ->
called = true
objects.should.be.an.Array
objects.length.should.equal(2)
objects[1].$rendered.should.equal('2')
called.should.be.true
it 'should compose engines', ->
called = false
renderables = [{
name: "Alice"
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{name}}"
},
{
name: "Bob"
$renderers: [{renderer: 'hbs', options: {}}, {renderer: 'greeter', options: {}}]
$current:
$content: "{{name}}"
}]
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
renderers.registerEngine('greeter', GreeterRenderer)
renderers.render renderables, (err, objects, x) ->
called = true
objects.should.be.an.Array
objects.length.should.equal(2)
objects[0].$rendered.should.equal('Alice')
objects[1].$rendered.should.equal('Hi Bob')
called.should.be.true
| 52471 | Renderers = require('../lib/Renderers')
HandlebarsRenderingEngine = require('../plugins/hbs/HandlebarsRenderingEngine')
HandlebarsRenderingEngine.configure({src: 'tests/_fixtures'}, {})
class GreeterRenderer
render: (content, context, done) ->
done(null, "Hi #{content}")
describe "Renderers", ->
describe "#registerEngine", ->
it "should register an engine", ->
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
(renderers.engines.hbs is HandlebarsRenderingEngine).should.be.true
describe "#resolveEngine", ->
it "should instantiate an engine if exists", ->
instanceOptions = {a: 1}
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
eng = renderers.resolveEngine('hbs', instanceOptions)
eng.should.be.instanceOf(HandlebarsRenderingEngine)
describe "#setDefaultEngines", ->
it "should setup default engines", ->
renderers = new Renderers()
renderers.setDefaultEngines(['hbs', 'md'], {hbs: {layout: 'app'}})
renderers.defaultEngines.should.eql([
{renderer: 'hbs', options: {layout: 'app'}}
{renderer: 'md', options: {}}
])
it "should not throw if no options are provided", ->
renderers = new Renderers()
(->
renderers.setDefaultEngines(['hbs', 'md'])
).should.not.throw()
describe "#render", ->
it 'should render renderables', ->
called = false
renderables = [{
a: 1,
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{a}}"
}]
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
renderers.render renderables, (err, objects, x) ->
called = true
objects.should.be.an.Array
objects[0].$rendered.should.equal('1')
called.should.be.true
it 'should render many renderables', ->
called = false
renderables = [{
a: 1,
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{a}}"
},
{
a: 2,
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{a}}"
}]
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
renderers.render renderables, (err, objects, x) ->
called = true
objects.should.be.an.Array
objects.length.should.equal(2)
objects[1].$rendered.should.equal('2')
called.should.be.true
it 'should compose engines', ->
called = false
renderables = [{
name: "<NAME>"
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{name}}"
},
{
name: "<NAME>"
$renderers: [{renderer: 'hbs', options: {}}, {renderer: 'greeter', options: {}}]
$current:
$content: "{{name}}"
}]
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
renderers.registerEngine('greeter', GreeterRenderer)
renderers.render renderables, (err, objects, x) ->
called = true
objects.should.be.an.Array
objects.length.should.equal(2)
objects[0].$rendered.should.equal('<NAME>')
objects[1].$rendered.should.equal('Hi <NAME>')
called.should.be.true
| true | Renderers = require('../lib/Renderers')
HandlebarsRenderingEngine = require('../plugins/hbs/HandlebarsRenderingEngine')
HandlebarsRenderingEngine.configure({src: 'tests/_fixtures'}, {})
class GreeterRenderer
render: (content, context, done) ->
done(null, "Hi #{content}")
describe "Renderers", ->
describe "#registerEngine", ->
it "should register an engine", ->
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
(renderers.engines.hbs is HandlebarsRenderingEngine).should.be.true
describe "#resolveEngine", ->
it "should instantiate an engine if exists", ->
instanceOptions = {a: 1}
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
eng = renderers.resolveEngine('hbs', instanceOptions)
eng.should.be.instanceOf(HandlebarsRenderingEngine)
describe "#setDefaultEngines", ->
it "should setup default engines", ->
renderers = new Renderers()
renderers.setDefaultEngines(['hbs', 'md'], {hbs: {layout: 'app'}})
renderers.defaultEngines.should.eql([
{renderer: 'hbs', options: {layout: 'app'}}
{renderer: 'md', options: {}}
])
it "should not throw if no options are provided", ->
renderers = new Renderers()
(->
renderers.setDefaultEngines(['hbs', 'md'])
).should.not.throw()
describe "#render", ->
it 'should render renderables', ->
called = false
renderables = [{
a: 1,
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{a}}"
}]
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
renderers.render renderables, (err, objects, x) ->
called = true
objects.should.be.an.Array
objects[0].$rendered.should.equal('1')
called.should.be.true
it 'should render many renderables', ->
called = false
renderables = [{
a: 1,
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{a}}"
},
{
a: 2,
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{a}}"
}]
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
renderers.render renderables, (err, objects, x) ->
called = true
objects.should.be.an.Array
objects.length.should.equal(2)
objects[1].$rendered.should.equal('2')
called.should.be.true
it 'should compose engines', ->
called = false
renderables = [{
name: "PI:NAME:<NAME>END_PI"
$renderers: [{renderer: 'hbs', options: {}}]
$current:
$content: "{{name}}"
},
{
name: "PI:NAME:<NAME>END_PI"
$renderers: [{renderer: 'hbs', options: {}}, {renderer: 'greeter', options: {}}]
$current:
$content: "{{name}}"
}]
renderers = new Renderers()
renderers.registerEngine('hbs', HandlebarsRenderingEngine)
renderers.registerEngine('greeter', GreeterRenderer)
renderers.render renderables, (err, objects, x) ->
called = true
objects.should.be.an.Array
objects.length.should.equal(2)
objects[0].$rendered.should.equal('PI:NAME:<NAME>END_PI')
objects[1].$rendered.should.equal('Hi PI:NAME:<NAME>END_PI')
called.should.be.true
|
[
{
"context": "->\n\tif cfg is '' then cfg={host:'localhost',user:'scott',password:'kaylie',database:'hapi'}\n\tmysql = requ",
"end": 86,
"score": 0.9815781116485596,
"start": 81,
"tag": "USERNAME",
"value": "scott"
},
{
"context": "then cfg={host:'localhost',user:'scott',password:'ka... | chapters/chapter4/libs/db.coffee | scotthathaway/hapifw | 4 | query = (sql,log=false,cfg='') ->
if cfg is '' then cfg={host:'localhost',user:'scott',password:'kaylie',database:'hapi'}
mysql = require("promise-mysql")
_ = require("lodash")
mysql.createConnection(cfg).then((conn) ->
conn.query(sql).then((rows) ->
if rows==[]
return []
else
keys = _.keys(rows[0])
rs = []
for i,row of rows
rs[i] = {}
for key in keys
rs[i][key] = row[key]
return rs
).catch((error) ->
return []
)
)
module.exports.query = query
| 168029 | query = (sql,log=false,cfg='') ->
if cfg is '' then cfg={host:'localhost',user:'scott',password:'<PASSWORD>',database:'hapi'}
mysql = require("promise-mysql")
_ = require("lodash")
mysql.createConnection(cfg).then((conn) ->
conn.query(sql).then((rows) ->
if rows==[]
return []
else
keys = _.keys(rows[0])
rs = []
for i,row of rows
rs[i] = {}
for key in keys
rs[i][key] = row[key]
return rs
).catch((error) ->
return []
)
)
module.exports.query = query
| true | query = (sql,log=false,cfg='') ->
if cfg is '' then cfg={host:'localhost',user:'scott',password:'PI:PASSWORD:<PASSWORD>END_PI',database:'hapi'}
mysql = require("promise-mysql")
_ = require("lodash")
mysql.createConnection(cfg).then((conn) ->
conn.query(sql).then((rows) ->
if rows==[]
return []
else
keys = _.keys(rows[0])
rs = []
for i,row of rows
rs[i] = {}
for key in keys
rs[i][key] = row[key]
return rs
).catch((error) ->
return []
)
)
module.exports.query = query
|
[
{
"context": "tional programming\n# style.\n#\n# Copyright (c) 2011 Olaf Delgado-Friedrichs (odf@github.com)\n# ------------------------------",
"end": 197,
"score": 0.9998899698257446,
"start": 174,
"tag": "NAME",
"value": "Olaf Delgado-Friedrichs"
},
{
"context": ".\n#\n# Copyright... | lib/functional.coffee | odf/pazy.js | 0 | # --------------------------------------------------------------------
# Various useful short functions that support a functional programming
# style.
#
# Copyright (c) 2011 Olaf Delgado-Friedrichs (odf@github.com)
# --------------------------------------------------------------------
exports = module?.exports or this.pazy ?= {}
# --------------------------------------------------------------------
# An implementation of the suspend/force paradigm of lazy evaluation
# via simple function memoization.
#
# Only the first call to the returned function will evaluate the given
# code; the remaining ones will return a cached result.
# --------------------------------------------------------------------
exports.suspend = (code) ->
f = -> val = code(); (f = -> val)()
-> f()
# --------------------------------------------------------------------
# A function to simulate tail call optimization.
# --------------------------------------------------------------------
exports.bounce = (val) -> val = val() while typeof val == 'function'; val
# --------------------------------------------------------------------
# This function simulates a local scope.
# --------------------------------------------------------------------
exports.scope = (args, f) -> f(args...)
| 179487 | # --------------------------------------------------------------------
# Various useful short functions that support a functional programming
# style.
#
# Copyright (c) 2011 <NAME> (<EMAIL>)
# --------------------------------------------------------------------
exports = module?.exports or this.pazy ?= {}
# --------------------------------------------------------------------
# An implementation of the suspend/force paradigm of lazy evaluation
# via simple function memoization.
#
# Only the first call to the returned function will evaluate the given
# code; the remaining ones will return a cached result.
# --------------------------------------------------------------------
exports.suspend = (code) ->
f = -> val = code(); (f = -> val)()
-> f()
# --------------------------------------------------------------------
# A function to simulate tail call optimization.
# --------------------------------------------------------------------
exports.bounce = (val) -> val = val() while typeof val == 'function'; val
# --------------------------------------------------------------------
# This function simulates a local scope.
# --------------------------------------------------------------------
exports.scope = (args, f) -> f(args...)
| true | # --------------------------------------------------------------------
# Various useful short functions that support a functional programming
# style.
#
# Copyright (c) 2011 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# --------------------------------------------------------------------
exports = module?.exports or this.pazy ?= {}
# --------------------------------------------------------------------
# An implementation of the suspend/force paradigm of lazy evaluation
# via simple function memoization.
#
# Only the first call to the returned function will evaluate the given
# code; the remaining ones will return a cached result.
# --------------------------------------------------------------------
exports.suspend = (code) ->
f = -> val = code(); (f = -> val)()
-> f()
# --------------------------------------------------------------------
# A function to simulate tail call optimization.
# --------------------------------------------------------------------
exports.bounce = (val) -> val = val() while typeof val == 'function'; val
# --------------------------------------------------------------------
# This function simulates a local scope.
# --------------------------------------------------------------------
exports.scope = (args, f) -> f(args...)
|
[
{
"context": "/rest/v3'\napp.constant 'ALLOCINE_PARTNER_TOKEN', 'yW5kcm9pZC12M3M'\n\napp.config (\n $locationProvider\n $stateProvid",
"end": 331,
"score": 0.8818044662475586,
"start": 316,
"tag": "PASSWORD",
"value": "yW5kcm9pZC12M3M"
},
{
"context": "herwise '/map'\n\n ParseProv... | src-public/app.coffee | nicgirault/allo-art-et-essai | 0 | 'use strict'
app = angular.module 'alloArtEtEssai', [
'ng'
'ngResource'
'ui.router'
'ui.bootstrap'
'app.templates'
'Parse'
'angulartics'
'angulartics.google.analytics'
'uiGmapgoogle-maps'
]
app.constant 'ALLOCINE_API_URL', 'http://api.allocine.fr/rest/v3'
app.constant 'ALLOCINE_PARTNER_TOKEN', 'yW5kcm9pZC12M3M'
app.config (
$locationProvider
$stateProvider
$urlRouterProvider
ParseProvider
uiGmapGoogleMapApiProvider
) ->
$locationProvider.hashPrefix '!'
$stateProvider
.state 'map',
url: '/map'
controller: 'mapCtrl'
templateUrl: 'map.html'
.state 'admin-cinema',
url: '/admin/cinema'
controller: 'adminCinemaCtrl'
templateUrl: 'admin-cinema.html'
.state 'cinema',
url: '/cinema'
controller: 'cinemaCtrl'
templateUrl: 'cinema.html'
.state 'about',
url: '/about'
templateUrl: 'about.html'
.state 'showtime',
url: '/cinema/:cinemaId/showtime'
controller: 'showtimeCtrl'
templateUrl: 'showtime.html'
resolve:
cinemaData: (AlloCine, $stateParams) ->
return AlloCine.getCinemaData $stateParams.cinemaId
$urlRouterProvider.otherwise '/map'
ParseProvider.initialize(
"2Y3JhneedL6TfTswvBgPfJbZ0qxQRJHj8jg0GqEU", # Application ID
"w1ek8EuSk7dD8bEBDSN5J8XTyXlGuOgx8mv7q7MD" # REST API Key
)
uiGmapGoogleMapApiProvider.configure {
#key: 'AIzaSyDXUwacxRBdrqDyJ0x7kqqD9DuvVxJjngI'
v: '3.20'
libraries: ''
}
app.run ($rootScope, $state) ->
$rootScope.$state = $state
| 10548 | 'use strict'
app = angular.module 'alloArtEtEssai', [
'ng'
'ngResource'
'ui.router'
'ui.bootstrap'
'app.templates'
'Parse'
'angulartics'
'angulartics.google.analytics'
'uiGmapgoogle-maps'
]
app.constant 'ALLOCINE_API_URL', 'http://api.allocine.fr/rest/v3'
app.constant 'ALLOCINE_PARTNER_TOKEN', '<PASSWORD>'
app.config (
$locationProvider
$stateProvider
$urlRouterProvider
ParseProvider
uiGmapGoogleMapApiProvider
) ->
$locationProvider.hashPrefix '!'
$stateProvider
.state 'map',
url: '/map'
controller: 'mapCtrl'
templateUrl: 'map.html'
.state 'admin-cinema',
url: '/admin/cinema'
controller: 'adminCinemaCtrl'
templateUrl: 'admin-cinema.html'
.state 'cinema',
url: '/cinema'
controller: 'cinemaCtrl'
templateUrl: 'cinema.html'
.state 'about',
url: '/about'
templateUrl: 'about.html'
.state 'showtime',
url: '/cinema/:cinemaId/showtime'
controller: 'showtimeCtrl'
templateUrl: 'showtime.html'
resolve:
cinemaData: (AlloCine, $stateParams) ->
return AlloCine.getCinemaData $stateParams.cinemaId
$urlRouterProvider.otherwise '/map'
ParseProvider.initialize(
"2<KEY>", # Application ID
"w1ek8EuSk7dD8bEBDSN5J8XTyXlGuOgx8mv7<KEY>7MD" # REST API Key
)
uiGmapGoogleMapApiProvider.configure {
#key: '<KEY>'
v: '3.20'
libraries: ''
}
app.run ($rootScope, $state) ->
$rootScope.$state = $state
| true | 'use strict'
app = angular.module 'alloArtEtEssai', [
'ng'
'ngResource'
'ui.router'
'ui.bootstrap'
'app.templates'
'Parse'
'angulartics'
'angulartics.google.analytics'
'uiGmapgoogle-maps'
]
app.constant 'ALLOCINE_API_URL', 'http://api.allocine.fr/rest/v3'
app.constant 'ALLOCINE_PARTNER_TOKEN', 'PI:PASSWORD:<PASSWORD>END_PI'
app.config (
$locationProvider
$stateProvider
$urlRouterProvider
ParseProvider
uiGmapGoogleMapApiProvider
) ->
$locationProvider.hashPrefix '!'
$stateProvider
.state 'map',
url: '/map'
controller: 'mapCtrl'
templateUrl: 'map.html'
.state 'admin-cinema',
url: '/admin/cinema'
controller: 'adminCinemaCtrl'
templateUrl: 'admin-cinema.html'
.state 'cinema',
url: '/cinema'
controller: 'cinemaCtrl'
templateUrl: 'cinema.html'
.state 'about',
url: '/about'
templateUrl: 'about.html'
.state 'showtime',
url: '/cinema/:cinemaId/showtime'
controller: 'showtimeCtrl'
templateUrl: 'showtime.html'
resolve:
cinemaData: (AlloCine, $stateParams) ->
return AlloCine.getCinemaData $stateParams.cinemaId
$urlRouterProvider.otherwise '/map'
ParseProvider.initialize(
"2PI:KEY:<KEY>END_PI", # Application ID
"w1ek8EuSk7dD8bEBDSN5J8XTyXlGuOgx8mv7PI:KEY:<KEY>END_PI7MD" # REST API Key
)
uiGmapGoogleMapApiProvider.configure {
#key: 'PI:KEY:<KEY>END_PI'
v: '3.20'
libraries: ''
}
app.run ($rootScope, $state) ->
$rootScope.$state = $state
|
[
{
"context": "Algorithm API for JavaScript\n# https://github.com/kzokm/ga.js\n#\n# Copyright (c) 2014 OKAMURA, Kazuhide\n#\n",
"end": 69,
"score": 0.9996663928031921,
"start": 64,
"tag": "USERNAME",
"value": "kzokm"
},
{
"context": "ps://github.com/kzokm/ga.js\n#\n# Copyright (c) 201... | lib/mutation_operator.coffee | kzokm/ga.js | 4 | ###
# Genetic Algorithm API for JavaScript
# https://github.com/kzokm/ga.js
#
# Copyright (c) 2014 OKAMURA, Kazuhide
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
###
{randomInt} = require './utils'
deprecated = require 'deprecated'
class MutationOperator
randomLocusOf = (c)-> randomInt c.length
@booleanInversion: ->
@substitution (gene)-> !gene
@binaryInversion: ->
@substitution (gene)-> 1 - gene
@substitution: (alleles)-> (chromosome)->
p = randomLocusOf chromosome
chromosome[p] = alleles chromosome[p]
chromosome
@swap: -> (chromosome)->
p1 = randomLocusOf chromosome
p2 = randomLocusOf chromosome
swap chromosome, p1, p2
chromosome
swap = (c, p1, p2)->
temp = c[p1]; c[p1] = c[p2]; c[p2] = temp
@inversion: -> (chromosome)->
p1 = randomLocusOf chromosome
p2 = randomLocusOf chromosome
c1 = chromosome.splice 0, Math.min p1, p2
c2 = chromosome.splice 0, (Math.abs p1 - p2) + 1
c3 = chromosome
c1.concat c2.reverse(), c3
@reverse: deprecated.method 'Mutation.reverse is deprecated, Use inversion instead',
console.log, @inversion
module.exports = MutationOperator
| 59281 | ###
# Genetic Algorithm API for JavaScript
# https://github.com/kzokm/ga.js
#
# Copyright (c) 2014 <NAME>, <NAME>
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
###
{randomInt} = require './utils'
deprecated = require 'deprecated'
class MutationOperator
randomLocusOf = (c)-> randomInt c.length
@booleanInversion: ->
@substitution (gene)-> !gene
@binaryInversion: ->
@substitution (gene)-> 1 - gene
@substitution: (alleles)-> (chromosome)->
p = randomLocusOf chromosome
chromosome[p] = alleles chromosome[p]
chromosome
@swap: -> (chromosome)->
p1 = randomLocusOf chromosome
p2 = randomLocusOf chromosome
swap chromosome, p1, p2
chromosome
swap = (c, p1, p2)->
temp = c[p1]; c[p1] = c[p2]; c[p2] = temp
@inversion: -> (chromosome)->
p1 = randomLocusOf chromosome
p2 = randomLocusOf chromosome
c1 = chromosome.splice 0, Math.min p1, p2
c2 = chromosome.splice 0, (Math.abs p1 - p2) + 1
c3 = chromosome
c1.concat c2.reverse(), c3
@reverse: deprecated.method 'Mutation.reverse is deprecated, Use inversion instead',
console.log, @inversion
module.exports = MutationOperator
| true | ###
# Genetic Algorithm API for JavaScript
# https://github.com/kzokm/ga.js
#
# Copyright (c) 2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
###
{randomInt} = require './utils'
deprecated = require 'deprecated'
class MutationOperator
randomLocusOf = (c)-> randomInt c.length
@booleanInversion: ->
@substitution (gene)-> !gene
@binaryInversion: ->
@substitution (gene)-> 1 - gene
@substitution: (alleles)-> (chromosome)->
p = randomLocusOf chromosome
chromosome[p] = alleles chromosome[p]
chromosome
@swap: -> (chromosome)->
p1 = randomLocusOf chromosome
p2 = randomLocusOf chromosome
swap chromosome, p1, p2
chromosome
swap = (c, p1, p2)->
temp = c[p1]; c[p1] = c[p2]; c[p2] = temp
@inversion: -> (chromosome)->
p1 = randomLocusOf chromosome
p2 = randomLocusOf chromosome
c1 = chromosome.splice 0, Math.min p1, p2
c2 = chromosome.splice 0, (Math.abs p1 - p2) + 1
c3 = chromosome
c1.concat c2.reverse(), c3
@reverse: deprecated.method 'Mutation.reverse is deprecated, Use inversion instead',
console.log, @inversion
module.exports = MutationOperator
|
[
{
"context": "###\nThe MIT License\n\nCopyright (c) 2015 Michalis Korakakis, Inc. https://github.com/mkorakakis.\n\nPermission ",
"end": 58,
"score": 0.9998841881752014,
"start": 40,
"tag": "NAME",
"value": "Michalis Korakakis"
},
{
"context": " 2015 Michalis Korakakis, Inc. https://... | lib/compare.coffee | davidferguson/drivelist-scanner | 0 | ###
The MIT License
Copyright (c) 2015 Michalis Korakakis, Inc. https://github.com/mkorakakis.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
###
_ = require('lodash')
containsDeep = (array, item) ->
return _.any(_.map(array, _.partial(_.isEqual, item)))
differenceDeep = (x, y) ->
return _.filter(x, _.partial(_.negate(containsDeep), y))
createDiffOperation = (type, element) ->
return {
type: type
drive: element
}
###*
# @summary Detect changes regarding connected drives between intervals
# @function
# @protected
#
# @param {Array} - previous drive list
# @param {Array} - current drive list
# @returns {Object[]} - current drive list, differences with previous list
#
# @example
# compare(previousDrives, currentDrives)
###
module.exports = (previous, current) ->
additions = differenceDeep(current, previous)
removals = differenceDeep(previous, current)
mappingAdditions = _.map(additions, _.partial(createDiffOperation, 'add'))
mappingRemovals = _.map(removals, _.partial(createDiffOperation, 'remove'))
return {
drives: current
diff: _.union(mappingAdditions, mappingRemovals)
}
| 158995 | ###
The MIT License
Copyright (c) 2015 <NAME>, Inc. https://github.com/mkorakakis.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
###
_ = require('lodash')
containsDeep = (array, item) ->
return _.any(_.map(array, _.partial(_.isEqual, item)))
differenceDeep = (x, y) ->
return _.filter(x, _.partial(_.negate(containsDeep), y))
createDiffOperation = (type, element) ->
return {
type: type
drive: element
}
###*
# @summary Detect changes regarding connected drives between intervals
# @function
# @protected
#
# @param {Array} - previous drive list
# @param {Array} - current drive list
# @returns {Object[]} - current drive list, differences with previous list
#
# @example
# compare(previousDrives, currentDrives)
###
module.exports = (previous, current) ->
additions = differenceDeep(current, previous)
removals = differenceDeep(previous, current)
mappingAdditions = _.map(additions, _.partial(createDiffOperation, 'add'))
mappingRemovals = _.map(removals, _.partial(createDiffOperation, 'remove'))
return {
drives: current
diff: _.union(mappingAdditions, mappingRemovals)
}
| true | ###
The MIT License
Copyright (c) 2015 PI:NAME:<NAME>END_PI, Inc. https://github.com/mkorakakis.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
###
_ = require('lodash')
containsDeep = (array, item) ->
return _.any(_.map(array, _.partial(_.isEqual, item)))
differenceDeep = (x, y) ->
return _.filter(x, _.partial(_.negate(containsDeep), y))
createDiffOperation = (type, element) ->
return {
type: type
drive: element
}
###*
# @summary Detect changes regarding connected drives between intervals
# @function
# @protected
#
# @param {Array} - previous drive list
# @param {Array} - current drive list
# @returns {Object[]} - current drive list, differences with previous list
#
# @example
# compare(previousDrives, currentDrives)
###
module.exports = (previous, current) ->
additions = differenceDeep(current, previous)
removals = differenceDeep(previous, current)
mappingAdditions = _.map(additions, _.partial(createDiffOperation, 'add'))
mappingRemovals = _.map(removals, _.partial(createDiffOperation, 'remove'))
return {
drives: current
diff: _.union(mappingAdditions, mappingRemovals)
}
|
[
{
"context": "gramming for microcontrollers\n# Copyright (c) 2013 Jon Nordby <jononor@gmail.com>\n# MicroFlo may be freely dist",
"end": 90,
"score": 0.9998355507850647,
"start": 80,
"tag": "NAME",
"value": "Jon Nordby"
},
{
"context": "microcontrollers\n# Copyright (c) 2013 Jon Nord... | test/componentlib.coffee | microflo/microflo | 136 | ### MicroFlo - Flow-Based Programming for microcontrollers
# Copyright (c) 2013 Jon Nordby <jononor@gmail.com>
# MicroFlo may be freely distributed under the MIT license
###
isBrowser = -> return typeof process != 'undefined' and process.execPath and process.execPath.indexOf('node') != -1
componentlib = null
if isBrowser()
chai = require 'chai'
componentlib = require '../lib/componentlib'
else
componentlib = require 'microflo/lib/componentlib'
describe 'ComponentLibrary', ->
componentLib = null
beforeEach ->
componentLib = new componentlib.ComponentLibrary
testComponents = ['DigitalWrite', 'Forward', 'Split', 'Timer', 'ToggleBoolean' ]
describe 'passing directory', ->
it 'loads all components in directory', (done) ->
paths = ['test/components']
componentLib.loadPaths paths, {}, (err) ->
return done err if err
c = componentLib.listComponents()
chai.expect(c).to.include.members testComponents
chai.expect(c).to.have.length testComponents.length
return done()
describe 'passing non-existent directory', ->
it 'should error', (done) ->
paths = ['test/components/bogus22', 'examples/embedding.cpp']
componentLib.loadPaths paths, {}, (err) ->
chai.expect(err).to.exist
chai.expect(err.message).to.include 'ENOENT'
chai.expect(err.message).to.include 'bogus22'
return done()
describe 'passing dir and files', ->
it 'loads both', (done) ->
paths = ['test/components', 'examples/embedding.cpp']
componentLib.loadPaths paths, {}, (err) ->
return done err if err
c = componentLib.listComponents()
chai.expect(c).to.include.members testComponents
chai.expect(c).to.include.members ['PlusOne', 'PrintInteger']
return done()
describe 'passing ignoreFiles and ignoreComponents', ->
it 'loads everything but listed', (done) ->
paths = ['test/components', 'examples/embedding.cpp']
options =
ignoreFiles: ['test/components/Split.hpp']
ignoreComponents: ['ToggleBoolean']
componentLib.loadPaths paths, options, (err) ->
return done err if err
c = componentLib.listComponents()
chai.expect(c).to.include.members ['PlusOne', 'Forward']
chai.expect(c).to.not.include.members ['Split', 'ToggleBoolean']
return done()
describe 'listing internal components', ->
normal = []
all = []
skipped = []
defs = {}
before (done) ->
paths = ['./test/components/']
componentLib.loadPaths paths, {}, (err) ->
chai.expect(err).to.be.a 'null'
normal = componentLib.listComponents(false, true)
all = componentLib.listComponents(true, true)
skipped = all.filter (n) -> normal.indexOf(n) == -1
defs = componentLib.getComponents true
done()
it 'Max,Invalid should be skipped', ->
chai.expect(normal).to.not.contain '_Max'
chai.expect(normal).to.not.contain 'Invalid'
it 'Split,Forward should be available', ->
chai.expect(normal).to.contain 'Split'
chai.expect(normal).to.contain 'Forward'
chai.expect(skipped).to.not.contain 'Split'
chai.expect(skipped).to.not.contain 'Forward'
it 'no components have same id', ->
i = 0
while i < all.length
j = 0
while j < all.length
I = all[i]
J = all[j]
if I == J
j++
continue
msg = I + ' has same ID as ' + J + ' : ' + defs[I].id
chai.expect(defs[I].id).to.not.equal defs[J].id, msg
j++
i++
| 67883 | ### MicroFlo - Flow-Based Programming for microcontrollers
# Copyright (c) 2013 <NAME> <<EMAIL>>
# MicroFlo may be freely distributed under the MIT license
###
isBrowser = -> return typeof process != 'undefined' and process.execPath and process.execPath.indexOf('node') != -1
componentlib = null
if isBrowser()
chai = require 'chai'
componentlib = require '../lib/componentlib'
else
componentlib = require 'microflo/lib/componentlib'
describe 'ComponentLibrary', ->
componentLib = null
beforeEach ->
componentLib = new componentlib.ComponentLibrary
testComponents = ['DigitalWrite', 'Forward', 'Split', 'Timer', 'ToggleBoolean' ]
describe 'passing directory', ->
it 'loads all components in directory', (done) ->
paths = ['test/components']
componentLib.loadPaths paths, {}, (err) ->
return done err if err
c = componentLib.listComponents()
chai.expect(c).to.include.members testComponents
chai.expect(c).to.have.length testComponents.length
return done()
describe 'passing non-existent directory', ->
it 'should error', (done) ->
paths = ['test/components/bogus22', 'examples/embedding.cpp']
componentLib.loadPaths paths, {}, (err) ->
chai.expect(err).to.exist
chai.expect(err.message).to.include 'ENOENT'
chai.expect(err.message).to.include 'bogus22'
return done()
describe 'passing dir and files', ->
it 'loads both', (done) ->
paths = ['test/components', 'examples/embedding.cpp']
componentLib.loadPaths paths, {}, (err) ->
return done err if err
c = componentLib.listComponents()
chai.expect(c).to.include.members testComponents
chai.expect(c).to.include.members ['PlusOne', 'PrintInteger']
return done()
describe 'passing ignoreFiles and ignoreComponents', ->
it 'loads everything but listed', (done) ->
paths = ['test/components', 'examples/embedding.cpp']
options =
ignoreFiles: ['test/components/Split.hpp']
ignoreComponents: ['ToggleBoolean']
componentLib.loadPaths paths, options, (err) ->
return done err if err
c = componentLib.listComponents()
chai.expect(c).to.include.members ['PlusOne', 'Forward']
chai.expect(c).to.not.include.members ['Split', 'ToggleBoolean']
return done()
describe 'listing internal components', ->
normal = []
all = []
skipped = []
defs = {}
before (done) ->
paths = ['./test/components/']
componentLib.loadPaths paths, {}, (err) ->
chai.expect(err).to.be.a 'null'
normal = componentLib.listComponents(false, true)
all = componentLib.listComponents(true, true)
skipped = all.filter (n) -> normal.indexOf(n) == -1
defs = componentLib.getComponents true
done()
it 'Max,Invalid should be skipped', ->
chai.expect(normal).to.not.contain '_Max'
chai.expect(normal).to.not.contain 'Invalid'
it 'Split,Forward should be available', ->
chai.expect(normal).to.contain 'Split'
chai.expect(normal).to.contain 'Forward'
chai.expect(skipped).to.not.contain 'Split'
chai.expect(skipped).to.not.contain 'Forward'
it 'no components have same id', ->
i = 0
while i < all.length
j = 0
while j < all.length
I = all[i]
J = all[j]
if I == J
j++
continue
msg = I + ' has same ID as ' + J + ' : ' + defs[I].id
chai.expect(defs[I].id).to.not.equal defs[J].id, msg
j++
i++
| true | ### MicroFlo - Flow-Based Programming for microcontrollers
# Copyright (c) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# MicroFlo may be freely distributed under the MIT license
###
isBrowser = -> return typeof process != 'undefined' and process.execPath and process.execPath.indexOf('node') != -1
componentlib = null
if isBrowser()
chai = require 'chai'
componentlib = require '../lib/componentlib'
else
componentlib = require 'microflo/lib/componentlib'
describe 'ComponentLibrary', ->
componentLib = null
beforeEach ->
componentLib = new componentlib.ComponentLibrary
testComponents = ['DigitalWrite', 'Forward', 'Split', 'Timer', 'ToggleBoolean' ]
describe 'passing directory', ->
it 'loads all components in directory', (done) ->
paths = ['test/components']
componentLib.loadPaths paths, {}, (err) ->
return done err if err
c = componentLib.listComponents()
chai.expect(c).to.include.members testComponents
chai.expect(c).to.have.length testComponents.length
return done()
describe 'passing non-existent directory', ->
it 'should error', (done) ->
paths = ['test/components/bogus22', 'examples/embedding.cpp']
componentLib.loadPaths paths, {}, (err) ->
chai.expect(err).to.exist
chai.expect(err.message).to.include 'ENOENT'
chai.expect(err.message).to.include 'bogus22'
return done()
describe 'passing dir and files', ->
it 'loads both', (done) ->
paths = ['test/components', 'examples/embedding.cpp']
componentLib.loadPaths paths, {}, (err) ->
return done err if err
c = componentLib.listComponents()
chai.expect(c).to.include.members testComponents
chai.expect(c).to.include.members ['PlusOne', 'PrintInteger']
return done()
describe 'passing ignoreFiles and ignoreComponents', ->
it 'loads everything but listed', (done) ->
paths = ['test/components', 'examples/embedding.cpp']
options =
ignoreFiles: ['test/components/Split.hpp']
ignoreComponents: ['ToggleBoolean']
componentLib.loadPaths paths, options, (err) ->
return done err if err
c = componentLib.listComponents()
chai.expect(c).to.include.members ['PlusOne', 'Forward']
chai.expect(c).to.not.include.members ['Split', 'ToggleBoolean']
return done()
describe 'listing internal components', ->
normal = []
all = []
skipped = []
defs = {}
before (done) ->
paths = ['./test/components/']
componentLib.loadPaths paths, {}, (err) ->
chai.expect(err).to.be.a 'null'
normal = componentLib.listComponents(false, true)
all = componentLib.listComponents(true, true)
skipped = all.filter (n) -> normal.indexOf(n) == -1
defs = componentLib.getComponents true
done()
it 'Max,Invalid should be skipped', ->
chai.expect(normal).to.not.contain '_Max'
chai.expect(normal).to.not.contain 'Invalid'
it 'Split,Forward should be available', ->
chai.expect(normal).to.contain 'Split'
chai.expect(normal).to.contain 'Forward'
chai.expect(skipped).to.not.contain 'Split'
chai.expect(skipped).to.not.contain 'Forward'
it 'no components have same id', ->
i = 0
while i < all.length
j = 0
while j < all.length
I = all[i]
J = all[j]
if I == J
j++
continue
msg = I + ' has same ID as ' + J + ' : ' + defs[I].id
chai.expect(defs[I].id).to.not.equal defs[J].id, msg
j++
i++
|
[
{
"context": "s.thangNames = thangNames =\n \"Soldier M\": [\n \"William\"\n \"Lucas\"\n \"Marcus\"\n \"Robert\"\n \"Gordo",
"end": 70,
"score": 0.9997826218605042,
"start": 63,
"tag": "NAME",
"value": "William"
},
{
"context": " thangNames =\n \"Soldier M\": [\n ... | app/lib/world/names.coffee | TamoghnaGhosh/https-github.com-sidharth-codecombat | 1 | module.exports.thangNames = thangNames =
"Soldier M": [
"William"
"Lucas"
"Marcus"
"Robert"
"Gordon"
"Kirin"
"Theo"
"Roger"
"Roderick"
"Samson"
"Silas"
"Richard"
"Max"
"Jax"
"Dax"
"Mischa"
"Ronald"
"Tyrone"
"Thelonious"
"Miles"
"Bill"
"Kumar"
"Ricardo"
"Maxwell"
"Jonah"
"Leopold"
"Phineas"
"Ferb"
"Felix"
"Arthur"
"Galahad"
"Ezra"
"Lucian"
"Augustus"
"Ronan"
"Pierce"
"Harry"
"Hirium"
"Hugo"
"Cecil"
"Barron"
"Huburt"
"Sterling"
"Alistair"
"Cid"
"Remy"
"Stormy"
"Halle"
"Sage"
]
"Soldier F": [
"Sarah"
"Alexandra"
"Holly"
"Trinity"
"Nikita"
"Alana"
"Lana"
"Joan"
"Helga"
"Annie"
]
"Peasant": [
"Yorik"
"Hector"
"Thad"
"Victor"
"Lyle"
"Charles"
"Mary"
"Brandy"
"Gwendolin"
"Tabitha"
"Regan"
"Yusef"
"Hingle"
"Azgot"
"Piers"
"Carlton"
"Giselle"
"Bernadette"
"Hershell"
"Gawain"
]
"Archer F": [
"Phoebe"
"Mira"
"Agapi"
"Cecily"
"Tansy"
"Ivy"
"Gemma"
"Keturah"
"Korra"
"Kim"
"Odette"
"Orly"
"Mercedes"
"Rosaline"
"Vesper"
"Beverly"
"Natalie"
"Clare"
"Rowan"
"Omar"
"Alden"
"Cairn"
"Jensen"
]
"Archer M": [
"Brian"
"Cole"
"Roman"
"Hunter"
"Simon"
"Robin"
"Quinn"
]
"Ogre Munchkin M": [
"Brack"
"Gort"
"Weeb"
"Nerph"
"Kratt"
"Smerk"
"Raack"
"Dobo"
"Draff"
"Zozo"
"Kogpole"
"Leerer"
"Skoggen"
"Treg"
"Goreball"
"Gert"
"Thabt"
"Snortt"
"Kog"
]
"Ogre Munchkin F": [
"Iyert"
"Palt"
"Shmeal"
"Gurzunn"
"Yugark"
]
"Ogre M": [
"Krogg"
"Dronck"
"Trogdor"
"Kulgor"
"Skrungt"
"Mak Fod"
"Trung"
"Axe Ox"
"Vargutt"
"Grumus"
"Gug"
]
"Ogre F": [
"Nareng"
"Morthrug"
"Glonc"
"Marghurk"
"Martha"
]
"Ogre Brawler": [
"Grul'thock"
"Boz"
"Trod"
"Muul"
"Grumoll"
"Burobb"
"Arelt"
"Zagurk"
"Zeredd"
"Borgag"
"Grognar"
"Ironjaw"
]
"Ogre Fangrider": [
"Dreek"
"Flarsho"
"Mizzy"
"Secka"
"Arizard"
"Secka"
"Arizard"
"Morzgret"
"Doralt"
"Geggret"
"Gurzthrot"
"Murgark"
"Muttin"
]
"Ogre Shaman": [
"Sham'uk"
"Il'Du'duka"
"Ahst'durante"
"Poult"
"Aolian'Tak"
"Tuzell"
"Yamizeb"
"Yerong"
"Tuzang"
"Varreth"
"Yugargen"
"Turann"
"Ugoki"
"Zulabar"
"Zo'Goroth"
"Mogadishu"
"Nazgareth"
]
"Ogre Thrower": [
"Kyrgg"
"Durnath"
"Kraggan"
"Rasha"
"Moza"
"Vujii"
"Esha"
"Zara"
"Hamedi"
"Jinjin"
"Yetu"
"Makas"
"Rakash"
"Drumbaa"
]
| 20633 | module.exports.thangNames = thangNames =
"Soldier M": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Soldier F": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Peasant": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Archer F": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"<NAME> M": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Ogre Munchkin M": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Ogre Munchkin F": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Ogre M": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Ogre F": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Ogre Brawler": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Ogre Fangrider": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Ogre Shaman": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
"Ogre Thrower": [
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
"<NAME>"
]
| true | module.exports.thangNames = thangNames =
"Soldier M": [
"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"
"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"
"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"
"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"
"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"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
"Soldier F": [
"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"
"PI:NAME:<NAME>END_PI"
]
"Peasant": [
"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"
"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"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
"Archer F": [
"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"
"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"
"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 M": [
"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"
]
"Ogre Munchkin M": [
"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"
"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"
"PI:NAME:<NAME>END_PI"
]
"Ogre Munchkin F": [
"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"
]
"Ogre M": [
"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"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
"Ogre F": [
"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"
]
"Ogre Brawler": [
"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"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
"Ogre Fangrider": [
"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"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
]
"Ogre Shaman": [
"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"
"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"
]
"Ogre Thrower": [
"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"
"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"
]
|
[
{
"context": "}\r\n {\r\n name: '7am'\r\n time: 7\r\n }\r",
"end": 2695,
"score": 0.6775099039077759,
"start": 2693,
"tag": "NAME",
"value": "am"
},
{
"context": "}\r\n {\r\n name: '... | js/coffee/drm-calendar/drm-calendar.coffee | elr-utilities/elr-utilities | 0 | ###############################################################################
# Interactive JS Calendar
###############################################################################
# needs support for events with start and end dates and times
# needs support for events that recur a limited number of times
# needs edit view
"use strict"
$ = jQuery
class @ElrCalendar
constructor: (@calendarClass = 'elr-calendar', @view = 'month', @addHolidays = yes, @currentDate = 'today', @newEvents = []) ->
self = @
@calendar = $ ".#{@calendarClass}"
if @calendar.length isnt 0
@body = $ 'body'
@daysPerWeek = 7
@now = new Date()
@today =
month: @now.getMonth()
date: @now.getDate()
year: @now.getFullYear()
@calendarInnerClass = "elr-calendar-#{@view}-view"
@eventClass = 'elr-events'
@classes =
weekend: 'elr-cal-weekend'
muted: 'elr-cal-muted'
holiday: 'elr-cal-holiday'
today: 'elr-cal-today'
month: 'elr-month'
week: 'elr-week'
date: 'elr-date'
@months = [
'January'
'February'
'March'
'April'
'May'
'June'
'July'
'August'
'September'
'October'
'November'
'December']
@days = [
'Sunday'
'Monday'
'Tuesday'
'Wednesday'
'Thursday'
'Friday'
'Saturday']
@hours = [
{
name: 'All Day Event'
time: null
}
{
name: '12am'
time: 0
}
{
name: '1am'
time: 1
}
{
name: '2am'
time: 2
}
{
name: '3am'
time: 3
}
{
name: '4am'
time: 4
}
{
name: '5am'
time: 5
}
{
name: '6am'
time: 6
}
{
name: '7am'
time: 7
}
{
name: '8am'
time: 8
}
{
name: '9am'
time: 9
}
{
name: '10am'
time: 10
}
{
name: '11am'
time: 11
}
{
name: '12pm'
time: 12
}
{
name: '1pm'
time: 13
}
{
name: '2pm'
time: 14
}
{
name: '3pm'
time: 15
}
{
name: '4pm'
time: 16
}
{
name: '5pm'
time: 17
}
{
name: '6pm'
time: 18
}
{
name: '7pm'
time: 19
}
{
name: '8pm'
time: 20
}
{
name: '9pm'
time: 21
}
{
name: '10pm'
time: 22
}
{
name: '11pm'
time: 23
}
]
@holidays = [
{
name: "New Year's Day"
month: "January"
eventDate: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "Martin Luther King's Birthday"
month: "January"
day: ["Monday"]
dayNum: 3
type: "holiday"
recurrance: "yearly"
}
{
name: "Groundhog Day"
month: "February"
eventDate: 2
type: "holiday"
recurrance: "yearly"
}
{
name: "Valentine's Day"
month: "February"
eventDate: 14
type: "holiday"
recurrance: "yearly"
}
{
name: "President's Day"
month: "February"
day: ["Monday"]
dayNum: 3
type: "holiday"
recurrance: "yearly"
}
{
name: "St. Patrick's Day"
month: "March"
eventDate: 17
type: "holiday"
recurrance: "yearly"
}
{
name: "April Fool's Day"
month: "April"
eventDate: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "Earth Day"
month: "April"
eventDate: 22
type: "holiday"
recurrance: "yearly"
}
{
name: "Arbor Day"
month: "April"
day: ["Friday"]
dayNum: "last"
type: "holiday"
recurrance: "yearly"
}
{
name: "May Day"
month: "May"
eventDate: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "Cinco De Mayo"
month: "May"
eventDate: 5
type: "holiday"
recurrance: "yearly"
}
{
name: "Mother's Day"
month: "May"
day: ["Sunday"]
dayNum: 2
type: "holiday"
recurrance: "yearly"
}
{
name: "Memorial Day"
month: "May"
day: ["Monday"]
dayNum: "last"
type: "holiday"
recurrance: "yearly"
}
{
name: "Flag Day"
month: "June"
eventDate: 14
type: "holiday"
recurrance: "yearly"
}
{
name: "Father's Day"
month: "June"
day: ["Sunday"]
type: "holiday"
recurrance: "yearly"
dayNum: 3
}
{
name: "Independence Day"
month: "July"
eventDate: 4
type: "holiday"
recurrance: "yearly"
}
{
name: "Labor Day"
month: "September"
day: ["Monday"]
dayNum: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "Patroit Day"
month: "September"
eventDate: 11
type: "holiday"
recurrance: "yearly"
}
{
name: "Columbus Day"
month: "October"
day: ["Monday"]
dayNum: 2
type: "holiday"
recurrance: "yearly"
}
{
name: "Halloween"
month: "October"
eventDate: 31
type: "holiday"
recurrance: "yearly"
}
{
name: "Veteran's Day"
month: "November"
eventDate: 11
type: "holiday"
recurrance: "yearly"
}
{
name: "Thanksgiving"
month: "November"
day: ["Thursday"]
dayNum: 4
type: "holiday"
recurrance: "yearly"
}
{
name: "Pearl Harbor Day"
month: "December"
eventDate: 7
type: "holiday"
recurrance: "yearly"
}
{
name: "Festivus"
month: "December"
eventDate: 23
type: "holiday"
recurrance: "yearly"
}
{
name: "Christmas Eve"
month: "December"
eventDate: 24
type: "holiday"
recurrance: "yearly"
}
{
name: "Christmas"
month: "December"
eventDate: 25
type: "holiday"
recurrance: "yearly"
}
{
name: "Boxing Day"
month: "December"
eventDate: 26
type: "holiday"
recurrance: "yearly"
}
{
name: "New Year's Eve"
month: "December"
eventDate: 31
type: "holiday"
recurrance: "yearly"
}
]
# calendar navigation
@calendarNav = $ '.elr-calendar-nav'
@calendarSelect = $ '.elr-calendar-select'
@calendarSelectButton = @calendarSelect.find 'button[type=submit]'
@addEventForm = @calendar.find('form.elr-calendar-new-event').hide()
@showEventFormButton = @calendar.find 'button.elr-show-event-form'
@calendarViewActiveButton = @calendar.find(".elr-calendar-view-nav button[data-view=#{@view}]").addClass 'active'
@calendar.each ->
that = $ @
#extract arguments
_view = if !that.data('view') then self.view else that.data('view')
_addHolidays = if that.data('holidays')? then that.data('holidays') else self.addHolidays
_currentDate = if !that.data('month') then 'today' else {month: $.inArray(that.data('month'), self.months), date: that.data('date'), year: that.data('year')}
events =
if !that.data('event-name')
self.newEvents
else
[{
name: if that.data('event-name')? then that.data('event-name') else null
recurrance: if that.data('event-recurrance')? then that.data('event-recurrance').toLowerCase() else null
month: if that.data('event-month')? then that.data('event-month') else null
year: if that.data('event-year')? then that.data('event-year') else null
eventDate: if that.data('event-date')? then that.data('event-date') else null
time: if that.data('event-time')? then that.data('event-time') else null
day: if that.data('event-day')? then that.data('event-day') else null
dayNum: if that.data('event-day-num')? then that.data('event-day-num') else null
type: if that.data('event-type')? then that.data('event-type').toLowerCase() else null
notes: if that.data('event-notes')? then that.data('event-notes') else null
}]
if _addHolidays is yes
$.each self.holidays, ->
self.createEvent @, events, that
if _currentDate is 'today'
_currentDate = self.today
self.createCalendar {month: self.today.month, date: self.today.date, year: self.today.year}, that, events
else
self.createCalendar {month: _currentDate.month, date: _currentDate.date, year: _currentDate.year}, that, events
that.on 'click', '.elr-calendar-view-nav button', (e) ->
# change calendar view
e.preventDefault()
_that = $ @
_that.addClass 'active'
calendar = _that.closest '.elr-calendar'
calendar.find(".elr-calendar-view-nav button.active").removeClass 'active'
view = _that.data 'view'
self.changeCalendarView view, events, calendar
that.on 'click', '.elr-calendar-date-prev, .elr-calendar-date-next', ->
# skip date forward or backward
_that = $ @
calendar = _that.closest '.elr-calendar'
direction = $(@).data 'dir'
self.advanceDate.call @, direction, events, calendar
that.on 'click', '.elr-calendar-week-prev, .elr-calendar-week-next', ->
# skip week forward or backward
_that = $ @
direction = $(@).data 'dir'
calendar = _that.closest '.elr-calendar'
self.advanceWeek.call @, direction, events, calendar
that.on 'click', '.elr-calendar-month-prev, .elr-calendar-month-next', ->
# skip month forward or backward
_that = $ @
calendar = _that.closest '.elr-calendar'
direction = _that.data 'dir'
self.advanceMonth.call @, direction, events, calendar
return
that.on 'click', '.elr-calendar-year-prev, .elr-calendar-year-next', ->
# skip year forward or backward
_that = $ @
direction = $(@).data 'dir'
calendar = _that.closest '.elr-calendar'
self.advanceYear.call @, direction, events, calendar
that.on 'click', '.elr-calendar-current', ->
# go to today's date
_that = $ @
calendar = _that.closest '.elr-calendar'
self.changeCalendar.call @, {month: self.today.month, date: self.today.date, year: self.today.year}, events, calendar
that.on 'click', '.elr-calendar-select button[type=submit]', (e) ->
# go to a specific date
e.preventDefault()
_that = $ @
calendar = _that.closest '.elr-calendar'
fields = _that.parent().find(':input').not 'button[type=submit]'
newDate =
month: _that.parent().find('#month').val()
date: _that.parent().find('#date').val()
year: _that.parent().find('#year').val()
# clear form
self.clearForm fields
# parse form data
$.each newDate, ->
parseInt @, 10
# change calendar view
self.changeCalendar.call self, newDate, events, calendar
that.on 'click', 'button.elr-show-event-form', ->
# show add event form
_that = $ @
if self.addEventForm.is(':hidden')
self.addEventForm.slideDown()
_that.text 'Hide Form'
else
self.addEventForm.slideUp()
_that.text 'Add New Event'
that.on 'click', 'form.elr-calendar-new-event button.addEvent', (e) ->
# add an new event to the events object
# this code should be moved to its own method
# write a method to get the form data and send the object to the createEvent method
e.preventDefault()
newEvent = self.getFormData self.addEventForm
currentMonth = $(".#{self.calendarInnerClass}").data 'month'
self.createEvent newEvent
newMonth = if newEvent.month? then $.inArray newEvent.month, self.months else self.today.month
if newMonth isnt currentMonth
newDate =
month: newMonth
date: newEvent.eventDate
year: self.today.year
self.changeCalendar.call @, newDate
# reset form
fields = self.addEventForm.find(':input').not('button[type=submit]').val ''
self.clearForm fields
that.on 'click', ".elr-date", ->
# show event form and fill out date infomation when a date is clicked
_that = $ @
if self.addEventForm.is ':hidden'
self.addEventForm.slideDown()
self.showEventFormButton.text 'Hide Form'
month: self.addEventForm.find('#month').val self.months[_that.data('month')]
year: self.addEventForm.find('#year').val _that.data('year')
eventDate: self.addEventForm.find('#eventDate').val _that.data('date')
time: self.addEventForm.find('#time').val _that.data('hour')
that.on 'click', "ul.#{self.eventClass} a", (e) ->
# show event details
_that = $ @
day = _that.closest '.elr-date'
eventId = _that.data 'event'
fullDate =
month: self.months[day.data('month')]
date: day.data 'date'
year: day.data 'year'
e.preventDefault()
e.stopPropagation()
self.readEvent eventId, fullDate
@body.on 'click', 'div.elr-calendar-event-details', (e) ->
e.stopPropagation()
@body.on 'click', 'div.elr-calendar-event-details button.elr-event-edit', (e) ->
e.preventDefault()
_that = $ @
eventId = _that.data 'event'
index = self.getEventIndex eventId
self.editEvent()
@body.on 'click', 'div.elr-calendar-event-details button.elr-event-delete', (e) ->
e.preventDefault()
_that = $ @
eventId = _that.data 'event'
index = self.getEventIndex eventId
self.destroyEvent eventId, index
self.closeEvent e
@body.on 'click', 'div.elr-calendar-event-details button.elr-event-close', @closeEvent
# utilities
capitalize: (str) ->
str.toLowerCase().replace /^.|\s\S/g, (a) -> a.toUpperCase()
cleanString: (str, re) ->
re = new RegExp "#{re}", 'i'
return $.trim str.replace re, ''
getFormData: (form) ->
# get form data and return an object
# need to remove dashes from ids
formInput = {}
_fields = form.find(':input').not('button').not ':checkbox'
_checkboxes = form.find 'input:checked'
if _checkboxes.length isnt 0
_boxIds = []
_checkboxes.each ->
_boxIds.push $(@).attr 'id'
_boxIds = $.unique boxIds
$.each _boxIds, ->
_checkboxValues = []
_boxes = form.find "input:checked##{@}"
_boxes.each ->
checkboxValues.push $.trim($(@).val())
formInput["#{@}"] = checkboxValues
return
$.each _fields, ->
_that = $ @
_id = _that.attr 'id'
_input = if $.trim(_that.val()) is '' then null else $.trim(_that.val())
if _input? then formInput["#{_id}"] = _input
return
formInput
clearForm: (fields) ->
fields.each ->
_that = $ @
if _that.attr('type') is 'checkbox' then _that.prop 'checked', false else _that.val ''
# calendar utilities
getDaysInMonth: (month, year) ->
# returns the number of days in a month
_month = month + 1
return new Date(year, _month, 0).getDate()
getDayOfWeek: (month, date, year) ->
# returns the day of the week for a specific date
_day = new Date year, month, date
return _day.getDay()
getWeeksInMonth: (month, year) ->
# gets the number of weeks in a month
_firstDay = @getDayOfWeek month, 1, year
_numberDays = @getDaysInMonth month, year
_dayShift = if _firstDay is @daysPerWeek then 0 else _firstDay
Math.ceil (_numberDays + _dayShift) / @daysPerWeek
getMonthWeekNum: (dayNum, day, month, year) ->
# gets the week of the month which an event occurs
_weeks = @calendar.find("div.#{@calendarInnerClass}").find '.elr-week'
_firstDay = @getDayOfWeek month, 1, year
_dayShift = if _firstDay is @daysPerWeek then 0 else _firstDay
_numberWeeks = @getWeeksInMonth month, year
_lastWeekLength = _weeks.eq(_numberWeeks).length
if dayNum is 'last' and _dayShift <= day
eventWeekNum = if _lastWeekLength < day then (_numberWeeks - 2) else _numberWeeks - 1
else if dayNum is 'last' and _dayShift > day
eventWeekNum = _numberWeeks - 2
else
eventWeekNum = parseInt(dayNum, 10) - 1
return if _dayShift <= day then eventWeekNum else eventWeekNum + 1
getDatesInWeek: (month, newDate, year) ->
_firstDay = @getDayOfWeek month, 1, year
_numberDays = @getDaysInMonth month, year
_dayShift = if _firstDay is @daysPerWeek then 0 else _firstDay
_currentDay = @getDayOfWeek month, newDate, year
_numberWeeks = @getWeeksInMonth month, year
weekInfo = {}
weekInfo.datesInWeek = []
_firstWeek = []
_lastWeek = []
_daysInFirstWeek = @daysPerWeek - _dayShift
_i = 1
# get the number of dates in each week
while _i <= _numberWeeks
dates = []
if _i is 1
# first week of the month
_j = 0
while _j < _daysInFirstWeek
_j = _j + 1
dates.push _j
# middle weeks
else if _i < _numberWeeks
if _i is 2 then _date = _daysInFirstWeek
_j = 0
while _j < @daysPerWeek
_j = _j + 1
_date = _date + 1
dates.push _date
else if _i is _numberWeeks
# last week in month
while _date < _numberDays
_date = _date + 1
dates.push _date
# get the week number
if newDate in dates
weekInfo.weekNum = _i - 1
weekInfo.datesInWeek = dates
_i = _i + 1
weekInfo
getWeekNumber: (month, newDate, year) ->
self = @
_weekNum = 1
weekNums = []
_weekInfo = self.getDatesInWeek month, newDate, year
$.each self.months, (key) ->
_numberDays = self.getDaysInMonth key, year
_firstDay = self.getDayOfWeek key, 1, year
_dayShift = if _firstDay is self.daysPerWeek then 0 else _firstDay
_numberWeeks = self.getWeeksInMonth month, year
_week = 1
if $.isNumeric _numberWeeks
while _week <= _numberWeeks
if _week is 1 and _firstDay isnt 0
_weekNum = _weekNum
else
_weekNum = _weekNum + 1
_week = _week + 1
if month is key
weekNums.push _weekNum
weekNums[_weekInfo.weekNum]
# event utilities
getEventIndex: (eventId) ->
# gets the index of an event so we can keep track after events are removed
index = null
$.each @events, (key, value) ->
if value.id is eventId then index = key
index
index
closeEvent: (e) ->
$('div.elr-blackout').fadeOut 300, ->
$(@).remove()
e.preventDefault()
createEvent: (newEvent, events, calendar) ->
if events
_id = events.length
obj =
id: _id
name: if newEvent.name? then newEvent.name else null
recurrance: if newEvent.recurrance? then newEvent.recurrance.toLowerCase() else 'none'
month: if newEvent.month? then newEvent.month else null
year: if newEvent.year? then parseInt(newEvent.year, 10) else null
eventDate: if newEvent.eventDate? then parseInt(newEvent.eventDate, 10) else null
time: if newEvent.time? then newEvent.time else null
day: if newEvent.day? then newEvent.day else null
dayNum: if newEvent.dayNum? then newEvent.dayNum else null
type: if newEvent.type? then newEvent.type.toLowerCase() else null
notes: if newEvent.notes? then newEvent.notes else null
events.push obj
@addEventsToCalendar events[obj.id], calendar
destroyEvent: (eventId, index) ->
events = @calendar.find "ul.#{@eventClass} a[data-event=#{eventId}]"
events.remove()
@events.splice index, 1
editEvent: ->
self = @
eventDetailList = $('.elr-event-detail-list')
eventDetails = eventDetailList.find 'li'
# change event details to form fields and populate with text
eventFormHtml = ''
$.each eventDetails, ->
_that = $ @
label = $.trim(_that.find('span.elr-event-label').text()).toLowerCase()
label = self.cleanString label, ':'
value = $.trim _that.find('span.elr-event-detail').text()
eventFormHtml += "<label for='#{label}'>#{self.capitalize(label)}: </label>
<input type='text' value='#{value}' id='#{label}' name='#{label}'>"
return eventFormHtml
editEventForm = $ '<form></form>',
class: 'elr-calendar-event-edit'
html: eventFormHtml
eventDetailList.empty().append editEventForm
return
updateEvent: (eventId, index) ->
console.log "#{eventId}, #{index}"
readEvent: (eventId, fullDate) ->
self = @
_index = self.getEventIndex eventId
_events = self.events[_index]
_eventDate = "#{fullDate.month} #{fullDate.date}, #{fullDate.year}"
_eventFrequency = do ->
if _events.recurrance is 'yearly' and _events.dayNum?
"Every #{_events.dayNum} #{_events.day} of #{_events.month}"
else if _events.recurrance is 'yearly'
"Every #{_events.eventDate} of #{_events.month}"
else if _events.recurrance is 'monthly' and _events.dayNum?
"Every #{_events.dayNum} #{_events.day} of the month"
else if _events.recurrance is 'monthly'
"Every #{_events.eventDate} of the month"
else if _events.recurrance is 'biweekly'
"Every other #{_events.day}"
else if _events.recurrance is 'weekly'
"Every #{_events.day}"
else if _events.recurrance is 'daily'
"Every Day"
else
"One Time Event"
_eventDetails =
date: _eventDate
time: _events.time
type: _events.type
frequency: _eventFrequency
repeat: _events.recurrance
notes: _events.notes
_eventHolder = $ '<div></div>',
class: 'elr-calendar-event-details'
html: "<h1 class='elr-calendar-header'>#{_events.name}</h1>"
_closeButton = $ '<button></button>',
class: 'elr-event-close'
text: 'Close'
type: 'button'
_editButton = $ "<button></button>",
class: 'elr-event-edit'
'data-event': _events.id
text: 'Edit'
type: 'button'
_deleteButton = $ "<button></button>",
class: 'elr-event-delete'
'data-event': _events.id
text: 'Delete'
type: 'button'
_eventDetailList = $ '<ul></ul>',
class: 'elr-event-detail-list'
_close = $ '<button></button>',
class: 'close'
text: 'x'
_lightboxHtml = $ '<div></div>',
class: 'elr-blackout'
html: _close + _eventHolder
_lightboxHtml.hide().appendTo('body').fadeIn 300, ->
_eventHolder.appendTo _lightboxHtml
_eventDetailList.appendTo _eventHolder
$.each _eventDetails, (key, value) ->
if value?
_title = self.capitalize key
_listItem = $ '<li></li>',
html: "<span class='elr-bold elr-event-label'>#{_title}: </span><span class='elr-event-detail'>#{value}</span>"
_listItem.appendTo _eventDetailList
_closeButton.insertAfter _eventDetailList
_deleteButton.insertAfter _eventDetailList
_editButton.insertAfter _eventDetailList
return
# calendar creation utilities
addEventsToCalendar: (events, calendar) ->
self = @
calendarInner = calendar.find "div.#{@calendarInnerClass}"
eventMonth = calendarInner.data 'month'
eventYear = calendarInner.data 'year'
month = $.inArray events.month, self.months
weeks = calendarInner.find '.elr-week'
eventDates = []
addEvents =
addYearlyEvents: (events, eventDates) ->
# add yearly events
if events.day
$.each events.day, ->
_day = $.inArray @, self.days
_eventWeekNum = self.getMonthWeekNum events.dayNum, _day, eventMonth, eventYear
if eventMonth is month
weeks.each ->
_that = $ @
_firstDate = _that.find(".#{self.classes.date}").first().data 'date'
_weekInfo = self.getDatesInWeek eventMonth, _firstDate, eventYear
if _eventWeekNum is _weekInfo.weekNum
eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data 'date'
else
eventDates.push parseInt(events.eventDate, 10)
addMonthlyEvents: (events, eventDates) ->
# add monthly events
if events.day
$.each events.day, ->
day = $.inArray @, self.days
_eventWeekNum = self.getMonthWeekNum events.dayNum, day, eventMonth, eventYear
weeks.each ->
_that = $ @
_firstDate = _that.find(".#{self.classes.date}").first().data 'date'
_weekInfo = self.getDatesInWeek eventMonth, _firstDate, eventYear
if _eventWeekNum is _weekInfo.weekNum
eventDates.push _that.find(".#{self.classes.date}[data-day=#{day}]").data 'date'
else
eventDates.push parseInt(events.eventDate, 10)
addBiWeeklyEvents: (events, eventDates) ->
# events _that occur every 2 weeks
if events.day
_weekInfo = self.getDatesInWeek eventMonth, events.eventDate, eventYear
$.each events.day, ->
_day = $.inArray @, self.days
_length = weeks.length
_weekPattern = if _weekInfo.weekNum % 2 is 0 then 'even' else 'odd'
_eventWeeks = calendarInner.find ".#{_weekPattern}-week"
$.each _eventWeeks, ->
_that = $ @
_weekLength = _that.find(".elr-date").length
eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
addWeeklyEvents: (events, eventDates) ->
# weekly events
_firstDay = self.getDayOfWeek eventMonth, 1, eventYear
_dayShift = if _firstDay is self.daysPerWeek then 0 else _firstDay
if events.day
$.each events.day, (key, value) ->
_day = $.inArray value, self.days
_length = weeks.length
$.each weeks, ->
_that = $ @
_days = if self.view is 'month'
_that.find ".#{self.classes.date}"
else
_that.find ".#{self.classes.date}[data-hour='All Day Event']"
_weekLength = _days.length
if key is 0 and _length isnt 1
if _dayShift <= _day then eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
else if key is (_length - 1) and _length isnt 1
if _day < _weekLength then eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
else
eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
eventDates
addDailyEvents: (events, eventDates) ->
_days = if self.view is 'month'
calendarInner.find ".#{self.classes.date}"
else
calendarInner.find ".#{self.classes.date}[data-hour='All Day Event']"
_days.each ->
eventDates.push $(@).data 'date'
addOneTimeEvents: (events, eventDates) ->
eventDates.push parseInt(events.eventDate, 10)
eventDates
_addCalendarEvent = (events, dates) ->
# create event html
if self.view is 'month'
_calendarItem = calendarInner.find ".elr-date[data-date=#{dates}]"
else if !events.time?
_calendarItem = calendarInner.find ".elr-date[data-date=#{dates}][data-hour='All Day Event']"
else
# find hour td element
re = new RegExp '^0?','gi'
re2 = new RegExp ':[0-9]{2}', 'gi'
hour = events.time.replace re, ''
hour = hour.replace re2, ''
_calendarItem = calendarInner.find ".elr-date[data-date=#{dates}][data-hour=#{hour}]"
_eventList = _calendarItem.find "ul.#{self.eventClass}"
_eventContent =
if events.time?
"<span class='elr-time'>#{events.time}: </span><span class='elr-event'>#{events.name}</span>"
else
"<span class='elr-event elr-all-day-event'>#{events.name}</span>"
_eventHtml = $ '<a></a>',
href: '#'
'data-event': events.id
html: _eventContent
if _eventList.length is 0
_eventList = $ '<ul></ul>',
class: "#{self.eventClass}"
_eventList.appendTo _calendarItem
_item = $ '<li></li>',
html: _eventHtml
_item.appendTo _eventList
if events.type is 'holiday' then _eventList.find("a:contains(#{events.name})").addClass self.classes.holiday
if events.recurrance is 'yearly' and eventMonth is month
addEvents.addYearlyEvents events, eventDates
else if events.recurrance is 'monthly'
addEvents.addMonthlyEvents events, eventDates
else if events.recurrance is 'biweekly'
addEvents.addBiWeeklyEvents events, eventDates
else if events.recurrance is 'weekly'
addEvents.addWeeklyEvents events, eventDates
else if events.recurrance is 'daily'
addEvents.addDailyEvents events, eventDates
else if events.recurrance is 'none' and eventMonth is month and eventYear is parseInt(events.year, 10)
addEvents.addOneTimeEvents events, eventDates
if eventDates.length > 0
$.each eventDates, (key, date) ->
# add css classes here
_addCalendarEvent events, date
advanceDate: (direction, events, calendar) =>
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
date: _calendarInner.find(".#{@classes.date}").data 'date'
year: _calendarInner.data 'year'
_nextYear = newDate.year + 1
_lastYear = newDate.year - 1
_nextMonth = if newDate.month is 11 then 0 else newDate.month + 1
lastMonth = if newDate.month is 0 then 11 else newDate.month - 1
if direction is 'prev'
_lastDayOfPrevMonth = @getDaysInMonth lastMonth, newDate.year
if newDate.date is 1
newDate.date = _lastDayOfPrevMonth
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else
newDate.date = newDate.date - 1
else if direction is 'next'
_lastDayOfMonth = @getDaysInMonth newDate.month, newDate.year
if newDate.date is _lastDayOfMonth
newDate.date = 1
newDate.year = if newDate.month is 11 then _nextYear else newDate.year
newDate.month = _nextMonth
else
newDate.date = newDate.date + 1
if @view is 'date' then @changeCalendar newDate, events, calendar
advanceWeek: (direction, events, calendar) =>
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
date: 1
year: _calendarInner.data 'year'
_nextYear = newDate.year + 1
_lastYear = newDate.year - 1
_nextMonth = if newDate.month is 11 then 0 else newDate.month + 1
lastMonth = if newDate.month is 0 then 11 else newDate.month - 1
if direction is 'prev'
_firstDay = _calendarInner.find(".#{@classes.date}").first().data 'date'
_lastDayOfPrevMonth = @getDaysInMonth lastMonth, newDate.year
if _firstDay is 1 and @view is 'week'
newDate.date = _lastDayOfPrevMonth
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else if _firstDay < 7 and @view is 'week'
newDate.date = _firstDay - 1
else if _firstDay is 1 and @view is 'date'
newDate.date = _lastDayOfPrevMonth - 6 # 30 - 6 1 24
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else if _firstDay < 7 and @view is 'date'
newDate.date = _lastDayOfPrevMonth - (7 - _firstDay) # 31 - (7 - 3) = 27 27 28 - (7 - 6) = 27 6 27
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else
newDate.date = _firstDay - 7
else if direction is 'next'
_lastDay = _calendarInner.find(".#{@classes.date}").last().data 'date'
_lastDayOfMonth = @getDaysInMonth newDate.month, newDate.year
if _lastDay is _lastDayOfMonth and @view is 'week'
newDate.date = 1
newDate.year = if newDate.month is 11 then _nextYear else newDate.year
newDate.month = _nextMonth
else if (_lastDay + 7 > _lastDayOfMonth) and @view is 'week'
newDate.date = _lastDayOfMonth
else if (_lastDay + 7 > _lastDayOfMonth) and @view is 'date'
newDate.date = 7 - (_lastDayOfMonth - _lastDay) # 31 - 29 = 2 then 7 - 2 = 5
newDate.year = if newDate.month is 11 then _nextYear else newDate.year
newDate.month = _nextMonth
else
newDate.date = _lastDay + 7
if @view is 'date' or @view is 'week' then @changeCalendar newDate, events, calendar
advanceMonth: (direction, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
date: if @month is self.today.month then self.today.date else 1
year: _calendarInner.data 'year'
if direction is 'prev'
newDate.month = if newDate.month is 0 then 11 else newDate.month - 1
newDate.year = if newDate.month is 11 then newDate.year - 1 else newDate.year
else if direction is 'next'
newDate.month = if newDate.month is 11 then 0 else newDate.month + 1
newDate.year = if newDate.month is 0 then newDate.year + 1 else newDate.year
@changeCalendar newDate, events, calendar
advanceYear: (direction, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
year: _calendarInner.data 'year'
newDate.date = if newDate.month is self.today.month then self.today.date else 1
newDate.year = if direction is 'prev' then newDate.year - 1 else newDate.year + 1
@changeCalendar newDate, events, calendar
changeCalendarView: (view, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
year: _calendarInner.data 'year'
newDate.date = if newDate.month is self.today.month then self.today.date else 1
# update view
@view = view
@changeCalendar newDate, events, calendar
# change calendar class
@calendarInnerClass = "elr-calendar-#{view}-view"
return
changeCalendar: (newDate, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{self.calendarInnerClass}"
_calendarInner.fadeOut(300).queue (next) ->
_that = $ @
$.when(_that.remove()).then(self.createCalendar(newDate, calendar, events))
next()
createCalendar: (newDate, calendar, events) ->
self = @
nextYear = newDate.year + 1
lastYear = newDate.year - 1
nextMonth = if newDate.month is 11 then 0 else newDate.month + 1
lastMonth = if newDate.month is 0 then 11 else newDate.month - 1
firstDay = self.getDayOfWeek newDate.month, 1, newDate.year
dayShift = if firstDay is self.daysPerWeek then 0 else firstDay
numberDays = self.getDaysInMonth newDate.month, newDate.year
numberWeeks = self.getWeeksInMonth newDate.month, newDate.year
prevMonthNumberDays = self.getDaysInMonth lastMonth, newDate.year
weekInfo = self.getDatesInWeek newDate.month, newDate.date, newDate.year
datesInWeek = weekInfo.datesInWeek
weekNumber = self.getWeekNumber newDate.month, newDate.date, newDate.year
weekClass = if weekNumber % 2 is 0 then 'even-week' else 'odd-week'
day = self.getDayOfWeek newDate.month, newDate.date, newDate.year
utilities =
highlightWeekends: ->
_calendarInner = calendar.find "div.#{self.calendarInnerClass}"
_weeks = _calendarInner.find '.elr-week'
weekends = [0, 6]
$.each _weeks, ->
_that = $ @
$.each weekends, ->
_weekend = _that.find(".#{self.classes.date}[data-day=#{@}]")
.not ".#{self.classes.muted}, .#{self.classes.today}, .#{self.classes.holiday}"
_weekend.addClass self.classes.weekend
highlightToday: ->
_calendarInner = calendar.find "div.#{self.calendarInnerClass}"
_month = _calendarInner.data 'month'
_year = _calendarInner.data 'year'
if _month is parseInt(newDate.month, 10) and _year is parseInt(newDate.year, 10)
_calendarInner.find(".elr-date[data-date=#{newDate.date}]").addClass self.classes.today
addWeekNumbers: ->
_weeks = calendar.find("div.#{self.calendarInnerClass}").find '.elr-week'
$.each _weeks, ->
_that = $ @
_firstDateInWeek = _that.find('.elr-date').first().data 'date'
_weekNumber = self.getWeekNumber newDate.month, _firstDateInWeek, newDate.year
if _weekNumber % 2 is 0
_that.addClass 'even-week'
else
_that.addClass 'odd-week'
_that.attr 'data-week', _weekNumber
getDates: (datesInWeek, key) ->
dates = {}
# if its the first week of the month
if datesInWeek.length < self.daysPerWeek and datesInWeek[0] is 1
if key is firstDay
dates.date = 1
dates.month = newDate.month
else if key > firstDay
dates.date = (key - firstDay) + 1
dates.month = newDate.month
else
dates.date = prevMonthNumberDays - (firstDay - (key + 1))
dates.month = lastMonth
else if datesInWeek.length is self.daysPerWeek
dates.date = datesInWeek[key]
dates.month = newDate.month
# if its the last week of the month
else if datesInWeek.length < self.daysPerWeek and datesInWeek[0] isnt 1
if key < datesInWeek.length
dates.date = datesInWeek[key]
dates.month = newDate.month
else
dates.date = Math.abs (datesInWeek.length - (key + 1))
dates.month = nextMonth
dates
views =
createMonth: (newDate, calendar) ->
_newDate = {month: newDate.month, date: newDate.date, year: newDate.year}
createWeekdays = ->
weekdays = "<div class='#{self.calendarInnerClass}' data-month='#{_newDate.month}' data-year='#{_newDate.year}'><table><thead><tr>"
$.each self.days, ->
weekdays += "<th>#{@}</th>"
weekdays += '</tr></thead>'
return weekdays
createFirstWeek = ->
# add cells for the previous month until we get to the first day
_lastMonthDays = 1
_prevDays = (prevMonthNumberDays - dayShift) + 1
firstWeekHtml = ''
$.each self.days, (key) ->
if _lastMonthDays <= dayShift
firstWeekHtml += "<td class='#{self.classes.muted}' data-day='#{key}'>#{_prevDays}</td>"
_prevDays += 1
_lastMonthDays += 1
else
# start adding cells for the current month
firstWeekHtml += "<td class='#{self.classes.date}' data-month='#{_newDate.month}' data-date='#{_newDate.date}'
data-year='#{_newDate.year}' data-day='#{key}'>#{_newDate.date}</td>"
_newDate.date += 1
return firstWeekHtml
createLastWeek = ->
_nextDates = 1
lastWeekHtml = ''
$.each self.days, (key) ->
# finish adding cells for the current month
if _newDate.date <= numberDays
lastWeekHtml += "<td class='#{self.classes.date}' data-month='#{_newDate.month}' data-date='#{_newDate.date}'
data-year='#{_newDate.year}' data-day='#{key}'>#{_newDate.date}</td>"
# start adding cells for next month
else
lastWeekHtml += "<td class='#{self.classes.muted}' data-day='#{key}'>#{_nextDates}</td>"
_nextDates += 1
_newDate.date += 1
return lastWeekHtml
createMiddleWeeks = ->
middleWeeksHtml = ''
$.each self.days, (key) ->
middleWeeksHtml += "<td class='#{self.classes.date}' data-month='#{_newDate.month}' data-date='#{_newDate.date}'
data-year='#{_newDate.year}' data-day='#{key}'>#{_newDate.date}</td>"
_newDate.date += 1
return middleWeeksHtml
createWeeks = ->
weekCount = 1
_newDate.date = 1
weeks = "<tbody class='#{self.classes.month}'>"
while weekCount <= numberWeeks
weeks += "<tr class='#{self.classes.week}'>"
# if we are in week 1 we need to shift to the correct day of the week
if weekCount is 1 and firstDay isnt 0
weeks += createFirstWeek()
# if we are in the last week of the month we need to add blank cells for next month
else if weekCount is numberWeeks
weeks += createLastWeek()
else
# if we are in the middle of the month add cells for the current month
weeks += createMiddleWeeks()
weeks += '</tr>'
weekCount += 1
weeks += '</tbody></table></div>'
return weeks
createCalendarHtml = ->
# create html
return createWeekdays() + createWeeks()
# add to DOM
addCalendar = (calendar) ->
_calendarHtml = createCalendarHtml()
_heading = $ '<h1></h1>',
class: 'elr-calendar-header'
text: "#{self.months[newDate.month]} #{newDate.year}"
calendar.append _calendarHtml
_calenderInner = calendar.find ".#{self.calendarInnerClass}"
_heading.prependTo _calenderInner
# style weeks
utilities.highlightToday()
utilities.highlightWeekends()
utilities.addWeekNumbers()
# add events to calendar
$.each events, ->
self.addEventsToCalendar @, calendar
# add and remove navigation buttons
$('.elr-calendar-year-prev').text lastYear
$('.elr-calendar-year-next').text nextYear
$('.elr-calendar-month-prev').text self.months[lastMonth]
$('.elr-calendar-month-next').text self.months[nextMonth]
$('.elr-calendar-week-prev, .elr-calendar-week-next').hide()
$('.elr-calendar-date-prev, .elr-calendar-date-next').hide()
addCalendar calendar
createWeek: (newDate, calendar) ->
weekdaysHtml = "<thead><tr><th></th>"
$.each self.days, (key, value) ->
_dates = utilities.getDates datesInWeek, key
weekdaysHtml += "<th>#{value}<br>#{self.months[_dates.month]} #{_dates.date}</th>"
weekdaysHtml += '</tr></thead>'
weekHtml = "<tbody class='#{self.classes.week} #{weekClass}' data-week='#{weekNumber}'>"
$.each self.hours, ->
_hour = @name
weekHtml += "<tr><td><span class='hour'>#{_hour}</span></td>"
$.each self.days, (key) ->
dates = utilities.getDates datesInWeek, key
weekHtml += "<td class='#{self.classes.date}' data-month='#{dates.month}' data-date='#{dates.date}'
data-year='#{newDate.year}' data-day='#{key}' data-hour='#{_hour}'></td>"
weekHtml += '</tr>'
weekHtml += '</tbody>'
_weekView = $ '<table></table>',
html: weekdaysHtml + weekHtml
_calendar = $ '<div></div>',
class: self.calendarInnerClass
html: _weekView
'data-month': newDate.month
'data-year': newDate.year
_weekDates = if datesInWeek.length > 1
"#{datesInWeek[0]} - #{datesInWeek[datesInWeek.length - 1]}"
else
"#{datesInWeek[0]}"
_heading = $ '<h1></h1>',
class: 'elr-calendar-header'
text: "#{self.months[newDate.month]} #{_weekDates}: Week #{weekNumber} of #{newDate.year}"
_calendar.appendTo calendar
_heading.prependTo calendar.find(".#{self.calendarInnerClass}")
$("div.#{self.calendarInnerClass}")
.find "tbody td[data-month=#{lastMonth}]"
.addClass self.classes.muted
.removeClass 'elr-date'
$("div.#{self.calendarInnerClass}")
.find "tbody td[data-month=#{nextMonth}]"
.addClass self.classes.muted
.removeClass 'elr-date'
utilities.highlightToday()
utilities.highlightWeekends()
$.each events, ->
self.addEventsToCalendar @, calendar
$('.elr-calendar-year-prev').text lastYear
$('.elr-calendar-year-next').text nextYear
$('.elr-calendar-month-prev').text self.months[lastMonth]
$('.elr-calendar-month-next').text self.months[nextMonth]
$('.elr-calendar-week-prev, .elr-calendar-week-next').show()
$('.elr-calendar-date-prev, .elr-calendar-date-next').hide()
createDate: (newDate, calendar) ->
dayListHtml = "<ul class='elr-week elr-day #{weekClass}' data-week='#{weekNumber}'>"
$.each self.hours, ->
_hour = @name
dayListHtml += "<li class='#{self.classes.date}' data-month='#{newDate.month}' data-date='#{newDate.date}'
data-year='#{newDate.year}' data-day='#{day}' data-hour='#{_hour}'><span class='hour'>#{_hour}</span></li>"
dayListHtml += '</ul>'
_calendar = $ '<div></div>',
class: self.calendarInnerClass
'data-month': newDate.month
'data-year': newDate.year
html: dayListHtml
_headingText =
if newDate.month is self.today.month and newDate is self.today.date and newDate.year is self.today.year
"Today, #{self.days[day]}, #{self.months[newDate.month]} #{newDate.date} #{newDate.year}"
else
"#{self.days[day]}, #{self.months[newDate.month]} #{newDate.date} #{newDate.year}"
_heading = $ '<h1></h1>',
class: 'elr-calendar-header'
text: _headingText
_calendar.appendTo calendar
_heading.prependTo calendar.find(".#{self.calendarInnerClass}")
$.each events, ->
self.addEventsToCalendar @, calendar
$('.elr-calendar-year-prev').text lastYear
$('.elr-calendar-year-next').text nextYear
$('.elr-calendar-month-prev').text self.months[lastMonth]
$('.elr-calendar-month-next').text self.months[nextMonth]
$('.elr-calendar-week-prev, .elr-calendar-week-next').show()
$('.elr-calendar-date-prev, .elr-calendar-date-next').show()
switch self.view
when 'month' then views.createMonth newDate, calendar
when 'week' then views.createWeek newDate, calendar
when 'date' then views.createDate newDate, calendar | 211333 | ###############################################################################
# Interactive JS Calendar
###############################################################################
# needs support for events with start and end dates and times
# needs support for events that recur a limited number of times
# needs edit view
"use strict"
$ = jQuery
class @ElrCalendar
constructor: (@calendarClass = 'elr-calendar', @view = 'month', @addHolidays = yes, @currentDate = 'today', @newEvents = []) ->
self = @
@calendar = $ ".#{@calendarClass}"
if @calendar.length isnt 0
@body = $ 'body'
@daysPerWeek = 7
@now = new Date()
@today =
month: @now.getMonth()
date: @now.getDate()
year: @now.getFullYear()
@calendarInnerClass = "elr-calendar-#{@view}-view"
@eventClass = 'elr-events'
@classes =
weekend: 'elr-cal-weekend'
muted: 'elr-cal-muted'
holiday: 'elr-cal-holiday'
today: 'elr-cal-today'
month: 'elr-month'
week: 'elr-week'
date: 'elr-date'
@months = [
'January'
'February'
'March'
'April'
'May'
'June'
'July'
'August'
'September'
'October'
'November'
'December']
@days = [
'Sunday'
'Monday'
'Tuesday'
'Wednesday'
'Thursday'
'Friday'
'Saturday']
@hours = [
{
name: 'All Day Event'
time: null
}
{
name: '12am'
time: 0
}
{
name: '1am'
time: 1
}
{
name: '2am'
time: 2
}
{
name: '3am'
time: 3
}
{
name: '4am'
time: 4
}
{
name: '5am'
time: 5
}
{
name: '6am'
time: 6
}
{
name: '7<NAME>'
time: 7
}
{
name: '8<NAME>'
time: 8
}
{
name: '9<NAME>'
time: 9
}
{
name: '<NAME>'
time: 10
}
{
name: '<NAME>'
time: 11
}
{
name: '<NAME>'
time: 12
}
{
name: '<NAME>'
time: 13
}
{
name: '<NAME>'
time: 14
}
{
name: '<NAME>'
time: 15
}
{
name: '<NAME>'
time: 16
}
{
name: '<NAME>'
time: 17
}
{
name: '<NAME>'
time: 18
}
{
name: '<NAME>'
time: 19
}
{
name: '<NAME>'
time: 20
}
{
name: '<NAME>'
time: 21
}
{
name: '<NAME>'
time: 22
}
{
name: '<NAME>1<NAME>'
time: 23
}
]
@holidays = [
{
name: "<NAME>"
month: "January"
eventDate: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "January"
day: ["Monday"]
dayNum: 3
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "February"
eventDate: 2
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "February"
eventDate: 14
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "February"
day: ["Monday"]
dayNum: 3
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "March"
eventDate: 17
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "April"
eventDate: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "April"
eventDate: 22
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "April"
day: ["Friday"]
dayNum: "last"
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "May"
eventDate: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "May"
eventDate: 5
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "May"
day: ["Sunday"]
dayNum: 2
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "May"
day: ["Monday"]
dayNum: "last"
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "June"
eventDate: 14
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "June"
day: ["Sunday"]
type: "holiday"
recurrance: "yearly"
dayNum: 3
}
{
name: "<NAME>dependence Day"
month: "July"
eventDate: 4
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "September"
day: ["Monday"]
dayNum: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "September"
eventDate: 11
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "October"
day: ["Monday"]
dayNum: 2
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "October"
eventDate: 31
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "November"
eventDate: 11
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "November"
day: ["Thursday"]
dayNum: 4
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "December"
eventDate: 7
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "December"
eventDate: 23
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "December"
eventDate: 24
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "December"
eventDate: 25
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "December"
eventDate: 26
type: "holiday"
recurrance: "yearly"
}
{
name: "<NAME>"
month: "December"
eventDate: 31
type: "holiday"
recurrance: "yearly"
}
]
# calendar navigation
@calendarNav = $ '.elr-calendar-nav'
@calendarSelect = $ '.elr-calendar-select'
@calendarSelectButton = @calendarSelect.find 'button[type=submit]'
@addEventForm = @calendar.find('form.elr-calendar-new-event').hide()
@showEventFormButton = @calendar.find 'button.elr-show-event-form'
@calendarViewActiveButton = @calendar.find(".elr-calendar-view-nav button[data-view=#{@view}]").addClass 'active'
@calendar.each ->
that = $ @
#extract arguments
_view = if !that.data('view') then self.view else that.data('view')
_addHolidays = if that.data('holidays')? then that.data('holidays') else self.addHolidays
_currentDate = if !that.data('month') then 'today' else {month: $.inArray(that.data('month'), self.months), date: that.data('date'), year: that.data('year')}
events =
if !that.data('event-name')
self.newEvents
else
[{
name: if that.data('event-name')? then that.data('event-name') else null
recurrance: if that.data('event-recurrance')? then that.data('event-recurrance').toLowerCase() else null
month: if that.data('event-month')? then that.data('event-month') else null
year: if that.data('event-year')? then that.data('event-year') else null
eventDate: if that.data('event-date')? then that.data('event-date') else null
time: if that.data('event-time')? then that.data('event-time') else null
day: if that.data('event-day')? then that.data('event-day') else null
dayNum: if that.data('event-day-num')? then that.data('event-day-num') else null
type: if that.data('event-type')? then that.data('event-type').toLowerCase() else null
notes: if that.data('event-notes')? then that.data('event-notes') else null
}]
if _addHolidays is yes
$.each self.holidays, ->
self.createEvent @, events, that
if _currentDate is 'today'
_currentDate = self.today
self.createCalendar {month: self.today.month, date: self.today.date, year: self.today.year}, that, events
else
self.createCalendar {month: _currentDate.month, date: _currentDate.date, year: _currentDate.year}, that, events
that.on 'click', '.elr-calendar-view-nav button', (e) ->
# change calendar view
e.preventDefault()
_that = $ @
_that.addClass 'active'
calendar = _that.closest '.elr-calendar'
calendar.find(".elr-calendar-view-nav button.active").removeClass 'active'
view = _that.data 'view'
self.changeCalendarView view, events, calendar
that.on 'click', '.elr-calendar-date-prev, .elr-calendar-date-next', ->
# skip date forward or backward
_that = $ @
calendar = _that.closest '.elr-calendar'
direction = $(@).data 'dir'
self.advanceDate.call @, direction, events, calendar
that.on 'click', '.elr-calendar-week-prev, .elr-calendar-week-next', ->
# skip week forward or backward
_that = $ @
direction = $(@).data 'dir'
calendar = _that.closest '.elr-calendar'
self.advanceWeek.call @, direction, events, calendar
that.on 'click', '.elr-calendar-month-prev, .elr-calendar-month-next', ->
# skip month forward or backward
_that = $ @
calendar = _that.closest '.elr-calendar'
direction = _that.data 'dir'
self.advanceMonth.call @, direction, events, calendar
return
that.on 'click', '.elr-calendar-year-prev, .elr-calendar-year-next', ->
# skip year forward or backward
_that = $ @
direction = $(@).data 'dir'
calendar = _that.closest '.elr-calendar'
self.advanceYear.call @, direction, events, calendar
that.on 'click', '.elr-calendar-current', ->
# go to today's date
_that = $ @
calendar = _that.closest '.elr-calendar'
self.changeCalendar.call @, {month: self.today.month, date: self.today.date, year: self.today.year}, events, calendar
that.on 'click', '.elr-calendar-select button[type=submit]', (e) ->
# go to a specific date
e.preventDefault()
_that = $ @
calendar = _that.closest '.elr-calendar'
fields = _that.parent().find(':input').not 'button[type=submit]'
newDate =
month: _that.parent().find('#month').val()
date: _that.parent().find('#date').val()
year: _that.parent().find('#year').val()
# clear form
self.clearForm fields
# parse form data
$.each newDate, ->
parseInt @, 10
# change calendar view
self.changeCalendar.call self, newDate, events, calendar
that.on 'click', 'button.elr-show-event-form', ->
# show add event form
_that = $ @
if self.addEventForm.is(':hidden')
self.addEventForm.slideDown()
_that.text 'Hide Form'
else
self.addEventForm.slideUp()
_that.text 'Add New Event'
that.on 'click', 'form.elr-calendar-new-event button.addEvent', (e) ->
# add an new event to the events object
# this code should be moved to its own method
# write a method to get the form data and send the object to the createEvent method
e.preventDefault()
newEvent = self.getFormData self.addEventForm
currentMonth = $(".#{self.calendarInnerClass}").data 'month'
self.createEvent newEvent
newMonth = if newEvent.month? then $.inArray newEvent.month, self.months else self.today.month
if newMonth isnt currentMonth
newDate =
month: newMonth
date: newEvent.eventDate
year: self.today.year
self.changeCalendar.call @, newDate
# reset form
fields = self.addEventForm.find(':input').not('button[type=submit]').val ''
self.clearForm fields
that.on 'click', ".elr-date", ->
# show event form and fill out date infomation when a date is clicked
_that = $ @
if self.addEventForm.is ':hidden'
self.addEventForm.slideDown()
self.showEventFormButton.text 'Hide Form'
month: self.addEventForm.find('#month').val self.months[_that.data('month')]
year: self.addEventForm.find('#year').val _that.data('year')
eventDate: self.addEventForm.find('#eventDate').val _that.data('date')
time: self.addEventForm.find('#time').val _that.data('hour')
that.on 'click', "ul.#{self.eventClass} a", (e) ->
# show event details
_that = $ @
day = _that.closest '.elr-date'
eventId = _that.data 'event'
fullDate =
month: self.months[day.data('month')]
date: day.data 'date'
year: day.data 'year'
e.preventDefault()
e.stopPropagation()
self.readEvent eventId, fullDate
@body.on 'click', 'div.elr-calendar-event-details', (e) ->
e.stopPropagation()
@body.on 'click', 'div.elr-calendar-event-details button.elr-event-edit', (e) ->
e.preventDefault()
_that = $ @
eventId = _that.data 'event'
index = self.getEventIndex eventId
self.editEvent()
@body.on 'click', 'div.elr-calendar-event-details button.elr-event-delete', (e) ->
e.preventDefault()
_that = $ @
eventId = _that.data 'event'
index = self.getEventIndex eventId
self.destroyEvent eventId, index
self.closeEvent e
@body.on 'click', 'div.elr-calendar-event-details button.elr-event-close', @closeEvent
# utilities
capitalize: (str) ->
str.toLowerCase().replace /^.|\s\S/g, (a) -> a.toUpperCase()
cleanString: (str, re) ->
re = new RegExp "#{re}", 'i'
return $.trim str.replace re, ''
getFormData: (form) ->
# get form data and return an object
# need to remove dashes from ids
formInput = {}
_fields = form.find(':input').not('button').not ':checkbox'
_checkboxes = form.find 'input:checked'
if _checkboxes.length isnt 0
_boxIds = []
_checkboxes.each ->
_boxIds.push $(@).attr 'id'
_boxIds = $.unique boxIds
$.each _boxIds, ->
_checkboxValues = []
_boxes = form.find "input:checked##{@}"
_boxes.each ->
checkboxValues.push $.trim($(@).val())
formInput["#{@}"] = checkboxValues
return
$.each _fields, ->
_that = $ @
_id = _that.attr 'id'
_input = if $.trim(_that.val()) is '' then null else $.trim(_that.val())
if _input? then formInput["#{_id}"] = _input
return
formInput
clearForm: (fields) ->
fields.each ->
_that = $ @
if _that.attr('type') is 'checkbox' then _that.prop 'checked', false else _that.val ''
# calendar utilities
getDaysInMonth: (month, year) ->
# returns the number of days in a month
_month = month + 1
return new Date(year, _month, 0).getDate()
getDayOfWeek: (month, date, year) ->
# returns the day of the week for a specific date
_day = new Date year, month, date
return _day.getDay()
getWeeksInMonth: (month, year) ->
# gets the number of weeks in a month
_firstDay = @getDayOfWeek month, 1, year
_numberDays = @getDaysInMonth month, year
_dayShift = if _firstDay is @daysPerWeek then 0 else _firstDay
Math.ceil (_numberDays + _dayShift) / @daysPerWeek
getMonthWeekNum: (dayNum, day, month, year) ->
# gets the week of the month which an event occurs
_weeks = @calendar.find("div.#{@calendarInnerClass}").find '.elr-week'
_firstDay = @getDayOfWeek month, 1, year
_dayShift = if _firstDay is @daysPerWeek then 0 else _firstDay
_numberWeeks = @getWeeksInMonth month, year
_lastWeekLength = _weeks.eq(_numberWeeks).length
if dayNum is 'last' and _dayShift <= day
eventWeekNum = if _lastWeekLength < day then (_numberWeeks - 2) else _numberWeeks - 1
else if dayNum is 'last' and _dayShift > day
eventWeekNum = _numberWeeks - 2
else
eventWeekNum = parseInt(dayNum, 10) - 1
return if _dayShift <= day then eventWeekNum else eventWeekNum + 1
getDatesInWeek: (month, newDate, year) ->
_firstDay = @getDayOfWeek month, 1, year
_numberDays = @getDaysInMonth month, year
_dayShift = if _firstDay is @daysPerWeek then 0 else _firstDay
_currentDay = @getDayOfWeek month, newDate, year
_numberWeeks = @getWeeksInMonth month, year
weekInfo = {}
weekInfo.datesInWeek = []
_firstWeek = []
_lastWeek = []
_daysInFirstWeek = @daysPerWeek - _dayShift
_i = 1
# get the number of dates in each week
while _i <= _numberWeeks
dates = []
if _i is 1
# first week of the month
_j = 0
while _j < _daysInFirstWeek
_j = _j + 1
dates.push _j
# middle weeks
else if _i < _numberWeeks
if _i is 2 then _date = _daysInFirstWeek
_j = 0
while _j < @daysPerWeek
_j = _j + 1
_date = _date + 1
dates.push _date
else if _i is _numberWeeks
# last week in month
while _date < _numberDays
_date = _date + 1
dates.push _date
# get the week number
if newDate in dates
weekInfo.weekNum = _i - 1
weekInfo.datesInWeek = dates
_i = _i + 1
weekInfo
getWeekNumber: (month, newDate, year) ->
self = @
_weekNum = 1
weekNums = []
_weekInfo = self.getDatesInWeek month, newDate, year
$.each self.months, (key) ->
_numberDays = self.getDaysInMonth key, year
_firstDay = self.getDayOfWeek key, 1, year
_dayShift = if _firstDay is self.daysPerWeek then 0 else _firstDay
_numberWeeks = self.getWeeksInMonth month, year
_week = 1
if $.isNumeric _numberWeeks
while _week <= _numberWeeks
if _week is 1 and _firstDay isnt 0
_weekNum = _weekNum
else
_weekNum = _weekNum + 1
_week = _week + 1
if month is key
weekNums.push _weekNum
weekNums[_weekInfo.weekNum]
# event utilities
getEventIndex: (eventId) ->
# gets the index of an event so we can keep track after events are removed
index = null
$.each @events, (key, value) ->
if value.id is eventId then index = key
index
index
closeEvent: (e) ->
$('div.elr-blackout').fadeOut 300, ->
$(@).remove()
e.preventDefault()
createEvent: (newEvent, events, calendar) ->
if events
_id = events.length
obj =
id: _id
name: if newEvent.name? then newEvent.name else null
recurrance: if newEvent.recurrance? then newEvent.recurrance.toLowerCase() else 'none'
month: if newEvent.month? then newEvent.month else null
year: if newEvent.year? then parseInt(newEvent.year, 10) else null
eventDate: if newEvent.eventDate? then parseInt(newEvent.eventDate, 10) else null
time: if newEvent.time? then newEvent.time else null
day: if newEvent.day? then newEvent.day else null
dayNum: if newEvent.dayNum? then newEvent.dayNum else null
type: if newEvent.type? then newEvent.type.toLowerCase() else null
notes: if newEvent.notes? then newEvent.notes else null
events.push obj
@addEventsToCalendar events[obj.id], calendar
destroyEvent: (eventId, index) ->
events = @calendar.find "ul.#{@eventClass} a[data-event=#{eventId}]"
events.remove()
@events.splice index, 1
editEvent: ->
self = @
eventDetailList = $('.elr-event-detail-list')
eventDetails = eventDetailList.find 'li'
# change event details to form fields and populate with text
eventFormHtml = ''
$.each eventDetails, ->
_that = $ @
label = $.trim(_that.find('span.elr-event-label').text()).toLowerCase()
label = self.cleanString label, ':'
value = $.trim _that.find('span.elr-event-detail').text()
eventFormHtml += "<label for='#{label}'>#{self.capitalize(label)}: </label>
<input type='text' value='#{value}' id='#{label}' name='#{label}'>"
return eventFormHtml
editEventForm = $ '<form></form>',
class: 'elr-calendar-event-edit'
html: eventFormHtml
eventDetailList.empty().append editEventForm
return
updateEvent: (eventId, index) ->
console.log "#{eventId}, #{index}"
readEvent: (eventId, fullDate) ->
self = @
_index = self.getEventIndex eventId
_events = self.events[_index]
_eventDate = "#{fullDate.month} #{fullDate.date}, #{fullDate.year}"
_eventFrequency = do ->
if _events.recurrance is 'yearly' and _events.dayNum?
"Every #{_events.dayNum} #{_events.day} of #{_events.month}"
else if _events.recurrance is 'yearly'
"Every #{_events.eventDate} of #{_events.month}"
else if _events.recurrance is 'monthly' and _events.dayNum?
"Every #{_events.dayNum} #{_events.day} of the month"
else if _events.recurrance is 'monthly'
"Every #{_events.eventDate} of the month"
else if _events.recurrance is 'biweekly'
"Every other #{_events.day}"
else if _events.recurrance is 'weekly'
"Every #{_events.day}"
else if _events.recurrance is 'daily'
"Every Day"
else
"One Time Event"
_eventDetails =
date: _eventDate
time: _events.time
type: _events.type
frequency: _eventFrequency
repeat: _events.recurrance
notes: _events.notes
_eventHolder = $ '<div></div>',
class: 'elr-calendar-event-details'
html: "<h1 class='elr-calendar-header'>#{_events.name}</h1>"
_closeButton = $ '<button></button>',
class: 'elr-event-close'
text: 'Close'
type: 'button'
_editButton = $ "<button></button>",
class: 'elr-event-edit'
'data-event': _events.id
text: 'Edit'
type: 'button'
_deleteButton = $ "<button></button>",
class: 'elr-event-delete'
'data-event': _events.id
text: 'Delete'
type: 'button'
_eventDetailList = $ '<ul></ul>',
class: 'elr-event-detail-list'
_close = $ '<button></button>',
class: 'close'
text: 'x'
_lightboxHtml = $ '<div></div>',
class: 'elr-blackout'
html: _close + _eventHolder
_lightboxHtml.hide().appendTo('body').fadeIn 300, ->
_eventHolder.appendTo _lightboxHtml
_eventDetailList.appendTo _eventHolder
$.each _eventDetails, (key, value) ->
if value?
_title = self.capitalize key
_listItem = $ '<li></li>',
html: "<span class='elr-bold elr-event-label'>#{_title}: </span><span class='elr-event-detail'>#{value}</span>"
_listItem.appendTo _eventDetailList
_closeButton.insertAfter _eventDetailList
_deleteButton.insertAfter _eventDetailList
_editButton.insertAfter _eventDetailList
return
# calendar creation utilities
addEventsToCalendar: (events, calendar) ->
self = @
calendarInner = calendar.find "div.#{@calendarInnerClass}"
eventMonth = calendarInner.data 'month'
eventYear = calendarInner.data 'year'
month = $.inArray events.month, self.months
weeks = calendarInner.find '.elr-week'
eventDates = []
addEvents =
addYearlyEvents: (events, eventDates) ->
# add yearly events
if events.day
$.each events.day, ->
_day = $.inArray @, self.days
_eventWeekNum = self.getMonthWeekNum events.dayNum, _day, eventMonth, eventYear
if eventMonth is month
weeks.each ->
_that = $ @
_firstDate = _that.find(".#{self.classes.date}").first().data 'date'
_weekInfo = self.getDatesInWeek eventMonth, _firstDate, eventYear
if _eventWeekNum is _weekInfo.weekNum
eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data 'date'
else
eventDates.push parseInt(events.eventDate, 10)
addMonthlyEvents: (events, eventDates) ->
# add monthly events
if events.day
$.each events.day, ->
day = $.inArray @, self.days
_eventWeekNum = self.getMonthWeekNum events.dayNum, day, eventMonth, eventYear
weeks.each ->
_that = $ @
_firstDate = _that.find(".#{self.classes.date}").first().data 'date'
_weekInfo = self.getDatesInWeek eventMonth, _firstDate, eventYear
if _eventWeekNum is _weekInfo.weekNum
eventDates.push _that.find(".#{self.classes.date}[data-day=#{day}]").data 'date'
else
eventDates.push parseInt(events.eventDate, 10)
addBiWeeklyEvents: (events, eventDates) ->
# events _that occur every 2 weeks
if events.day
_weekInfo = self.getDatesInWeek eventMonth, events.eventDate, eventYear
$.each events.day, ->
_day = $.inArray @, self.days
_length = weeks.length
_weekPattern = if _weekInfo.weekNum % 2 is 0 then 'even' else 'odd'
_eventWeeks = calendarInner.find ".#{_weekPattern}-week"
$.each _eventWeeks, ->
_that = $ @
_weekLength = _that.find(".elr-date").length
eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
addWeeklyEvents: (events, eventDates) ->
# weekly events
_firstDay = self.getDayOfWeek eventMonth, 1, eventYear
_dayShift = if _firstDay is self.daysPerWeek then 0 else _firstDay
if events.day
$.each events.day, (key, value) ->
_day = $.inArray value, self.days
_length = weeks.length
$.each weeks, ->
_that = $ @
_days = if self.view is 'month'
_that.find ".#{self.classes.date}"
else
_that.find ".#{self.classes.date}[data-hour='All Day Event']"
_weekLength = _days.length
if key is 0 and _length isnt 1
if _dayShift <= _day then eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
else if key is (_length - 1) and _length isnt 1
if _day < _weekLength then eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
else
eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
eventDates
addDailyEvents: (events, eventDates) ->
_days = if self.view is 'month'
calendarInner.find ".#{self.classes.date}"
else
calendarInner.find ".#{self.classes.date}[data-hour='All Day Event']"
_days.each ->
eventDates.push $(@).data 'date'
addOneTimeEvents: (events, eventDates) ->
eventDates.push parseInt(events.eventDate, 10)
eventDates
_addCalendarEvent = (events, dates) ->
# create event html
if self.view is 'month'
_calendarItem = calendarInner.find ".elr-date[data-date=#{dates}]"
else if !events.time?
_calendarItem = calendarInner.find ".elr-date[data-date=#{dates}][data-hour='All Day Event']"
else
# find hour td element
re = new RegExp '^0?','gi'
re2 = new RegExp ':[0-9]{2}', 'gi'
hour = events.time.replace re, ''
hour = hour.replace re2, ''
_calendarItem = calendarInner.find ".elr-date[data-date=#{dates}][data-hour=#{hour}]"
_eventList = _calendarItem.find "ul.#{self.eventClass}"
_eventContent =
if events.time?
"<span class='elr-time'>#{events.time}: </span><span class='elr-event'>#{events.name}</span>"
else
"<span class='elr-event elr-all-day-event'>#{events.name}</span>"
_eventHtml = $ '<a></a>',
href: '#'
'data-event': events.id
html: _eventContent
if _eventList.length is 0
_eventList = $ '<ul></ul>',
class: "#{self.eventClass}"
_eventList.appendTo _calendarItem
_item = $ '<li></li>',
html: _eventHtml
_item.appendTo _eventList
if events.type is 'holiday' then _eventList.find("a:contains(#{events.name})").addClass self.classes.holiday
if events.recurrance is 'yearly' and eventMonth is month
addEvents.addYearlyEvents events, eventDates
else if events.recurrance is 'monthly'
addEvents.addMonthlyEvents events, eventDates
else if events.recurrance is 'biweekly'
addEvents.addBiWeeklyEvents events, eventDates
else if events.recurrance is 'weekly'
addEvents.addWeeklyEvents events, eventDates
else if events.recurrance is 'daily'
addEvents.addDailyEvents events, eventDates
else if events.recurrance is 'none' and eventMonth is month and eventYear is parseInt(events.year, 10)
addEvents.addOneTimeEvents events, eventDates
if eventDates.length > 0
$.each eventDates, (key, date) ->
# add css classes here
_addCalendarEvent events, date
advanceDate: (direction, events, calendar) =>
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
date: _calendarInner.find(".#{@classes.date}").data 'date'
year: _calendarInner.data 'year'
_nextYear = newDate.year + 1
_lastYear = newDate.year - 1
_nextMonth = if newDate.month is 11 then 0 else newDate.month + 1
lastMonth = if newDate.month is 0 then 11 else newDate.month - 1
if direction is 'prev'
_lastDayOfPrevMonth = @getDaysInMonth lastMonth, newDate.year
if newDate.date is 1
newDate.date = _lastDayOfPrevMonth
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else
newDate.date = newDate.date - 1
else if direction is 'next'
_lastDayOfMonth = @getDaysInMonth newDate.month, newDate.year
if newDate.date is _lastDayOfMonth
newDate.date = 1
newDate.year = if newDate.month is 11 then _nextYear else newDate.year
newDate.month = _nextMonth
else
newDate.date = newDate.date + 1
if @view is 'date' then @changeCalendar newDate, events, calendar
advanceWeek: (direction, events, calendar) =>
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
date: 1
year: _calendarInner.data 'year'
_nextYear = newDate.year + 1
_lastYear = newDate.year - 1
_nextMonth = if newDate.month is 11 then 0 else newDate.month + 1
lastMonth = if newDate.month is 0 then 11 else newDate.month - 1
if direction is 'prev'
_firstDay = _calendarInner.find(".#{@classes.date}").first().data 'date'
_lastDayOfPrevMonth = @getDaysInMonth lastMonth, newDate.year
if _firstDay is 1 and @view is 'week'
newDate.date = _lastDayOfPrevMonth
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else if _firstDay < 7 and @view is 'week'
newDate.date = _firstDay - 1
else if _firstDay is 1 and @view is 'date'
newDate.date = _lastDayOfPrevMonth - 6 # 30 - 6 1 24
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else if _firstDay < 7 and @view is 'date'
newDate.date = _lastDayOfPrevMonth - (7 - _firstDay) # 31 - (7 - 3) = 27 27 28 - (7 - 6) = 27 6 27
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else
newDate.date = _firstDay - 7
else if direction is 'next'
_lastDay = _calendarInner.find(".#{@classes.date}").last().data 'date'
_lastDayOfMonth = @getDaysInMonth newDate.month, newDate.year
if _lastDay is _lastDayOfMonth and @view is 'week'
newDate.date = 1
newDate.year = if newDate.month is 11 then _nextYear else newDate.year
newDate.month = _nextMonth
else if (_lastDay + 7 > _lastDayOfMonth) and @view is 'week'
newDate.date = _lastDayOfMonth
else if (_lastDay + 7 > _lastDayOfMonth) and @view is 'date'
newDate.date = 7 - (_lastDayOfMonth - _lastDay) # 31 - 29 = 2 then 7 - 2 = 5
newDate.year = if newDate.month is 11 then _nextYear else newDate.year
newDate.month = _nextMonth
else
newDate.date = _lastDay + 7
if @view is 'date' or @view is 'week' then @changeCalendar newDate, events, calendar
advanceMonth: (direction, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
date: if @month is self.today.month then self.today.date else 1
year: _calendarInner.data 'year'
if direction is 'prev'
newDate.month = if newDate.month is 0 then 11 else newDate.month - 1
newDate.year = if newDate.month is 11 then newDate.year - 1 else newDate.year
else if direction is 'next'
newDate.month = if newDate.month is 11 then 0 else newDate.month + 1
newDate.year = if newDate.month is 0 then newDate.year + 1 else newDate.year
@changeCalendar newDate, events, calendar
advanceYear: (direction, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
year: _calendarInner.data 'year'
newDate.date = if newDate.month is self.today.month then self.today.date else 1
newDate.year = if direction is 'prev' then newDate.year - 1 else newDate.year + 1
@changeCalendar newDate, events, calendar
changeCalendarView: (view, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
year: _calendarInner.data 'year'
newDate.date = if newDate.month is self.today.month then self.today.date else 1
# update view
@view = view
@changeCalendar newDate, events, calendar
# change calendar class
@calendarInnerClass = "elr-calendar-#{view}-view"
return
changeCalendar: (newDate, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{self.calendarInnerClass}"
_calendarInner.fadeOut(300).queue (next) ->
_that = $ @
$.when(_that.remove()).then(self.createCalendar(newDate, calendar, events))
next()
createCalendar: (newDate, calendar, events) ->
self = @
nextYear = newDate.year + 1
lastYear = newDate.year - 1
nextMonth = if newDate.month is 11 then 0 else newDate.month + 1
lastMonth = if newDate.month is 0 then 11 else newDate.month - 1
firstDay = self.getDayOfWeek newDate.month, 1, newDate.year
dayShift = if firstDay is self.daysPerWeek then 0 else firstDay
numberDays = self.getDaysInMonth newDate.month, newDate.year
numberWeeks = self.getWeeksInMonth newDate.month, newDate.year
prevMonthNumberDays = self.getDaysInMonth lastMonth, newDate.year
weekInfo = self.getDatesInWeek newDate.month, newDate.date, newDate.year
datesInWeek = weekInfo.datesInWeek
weekNumber = self.getWeekNumber newDate.month, newDate.date, newDate.year
weekClass = if weekNumber % 2 is 0 then 'even-week' else 'odd-week'
day = self.getDayOfWeek newDate.month, newDate.date, newDate.year
utilities =
highlightWeekends: ->
_calendarInner = calendar.find "div.#{self.calendarInnerClass}"
_weeks = _calendarInner.find '.elr-week'
weekends = [0, 6]
$.each _weeks, ->
_that = $ @
$.each weekends, ->
_weekend = _that.find(".#{self.classes.date}[data-day=#{@}]")
.not ".#{self.classes.muted}, .#{self.classes.today}, .#{self.classes.holiday}"
_weekend.addClass self.classes.weekend
highlightToday: ->
_calendarInner = calendar.find "div.#{self.calendarInnerClass}"
_month = _calendarInner.data 'month'
_year = _calendarInner.data 'year'
if _month is parseInt(newDate.month, 10) and _year is parseInt(newDate.year, 10)
_calendarInner.find(".elr-date[data-date=#{newDate.date}]").addClass self.classes.today
addWeekNumbers: ->
_weeks = calendar.find("div.#{self.calendarInnerClass}").find '.elr-week'
$.each _weeks, ->
_that = $ @
_firstDateInWeek = _that.find('.elr-date').first().data 'date'
_weekNumber = self.getWeekNumber newDate.month, _firstDateInWeek, newDate.year
if _weekNumber % 2 is 0
_that.addClass 'even-week'
else
_that.addClass 'odd-week'
_that.attr 'data-week', _weekNumber
getDates: (datesInWeek, key) ->
dates = {}
# if its the first week of the month
if datesInWeek.length < self.daysPerWeek and datesInWeek[0] is 1
if key is firstDay
dates.date = 1
dates.month = newDate.month
else if key > firstDay
dates.date = (key - firstDay) + 1
dates.month = newDate.month
else
dates.date = prevMonthNumberDays - (firstDay - (key + 1))
dates.month = lastMonth
else if datesInWeek.length is self.daysPerWeek
dates.date = datesInWeek[key]
dates.month = newDate.month
# if its the last week of the month
else if datesInWeek.length < self.daysPerWeek and datesInWeek[0] isnt 1
if key < datesInWeek.length
dates.date = datesInWeek[key]
dates.month = newDate.month
else
dates.date = Math.abs (datesInWeek.length - (key + 1))
dates.month = nextMonth
dates
views =
createMonth: (newDate, calendar) ->
_newDate = {month: newDate.month, date: newDate.date, year: newDate.year}
createWeekdays = ->
weekdays = "<div class='#{self.calendarInnerClass}' data-month='#{_newDate.month}' data-year='#{_newDate.year}'><table><thead><tr>"
$.each self.days, ->
weekdays += "<th>#{@}</th>"
weekdays += '</tr></thead>'
return weekdays
createFirstWeek = ->
# add cells for the previous month until we get to the first day
_lastMonthDays = 1
_prevDays = (prevMonthNumberDays - dayShift) + 1
firstWeekHtml = ''
$.each self.days, (key) ->
if _lastMonthDays <= dayShift
firstWeekHtml += "<td class='#{self.classes.muted}' data-day='#{key}'>#{_prevDays}</td>"
_prevDays += 1
_lastMonthDays += 1
else
# start adding cells for the current month
firstWeekHtml += "<td class='#{self.classes.date}' data-month='#{_newDate.month}' data-date='#{_newDate.date}'
data-year='#{_newDate.year}' data-day='#{key}'>#{_newDate.date}</td>"
_newDate.date += 1
return firstWeekHtml
createLastWeek = ->
_nextDates = 1
lastWeekHtml = ''
$.each self.days, (key) ->
# finish adding cells for the current month
if _newDate.date <= numberDays
lastWeekHtml += "<td class='#{self.classes.date}' data-month='#{_newDate.month}' data-date='#{_newDate.date}'
data-year='#{_newDate.year}' data-day='#{key}'>#{_newDate.date}</td>"
# start adding cells for next month
else
lastWeekHtml += "<td class='#{self.classes.muted}' data-day='#{key}'>#{_nextDates}</td>"
_nextDates += 1
_newDate.date += 1
return lastWeekHtml
createMiddleWeeks = ->
middleWeeksHtml = ''
$.each self.days, (key) ->
middleWeeksHtml += "<td class='#{self.classes.date}' data-month='#{_newDate.month}' data-date='#{_newDate.date}'
data-year='#{_newDate.year}' data-day='#{key}'>#{_newDate.date}</td>"
_newDate.date += 1
return middleWeeksHtml
createWeeks = ->
weekCount = 1
_newDate.date = 1
weeks = "<tbody class='#{self.classes.month}'>"
while weekCount <= numberWeeks
weeks += "<tr class='#{self.classes.week}'>"
# if we are in week 1 we need to shift to the correct day of the week
if weekCount is 1 and firstDay isnt 0
weeks += createFirstWeek()
# if we are in the last week of the month we need to add blank cells for next month
else if weekCount is numberWeeks
weeks += createLastWeek()
else
# if we are in the middle of the month add cells for the current month
weeks += createMiddleWeeks()
weeks += '</tr>'
weekCount += 1
weeks += '</tbody></table></div>'
return weeks
createCalendarHtml = ->
# create html
return createWeekdays() + createWeeks()
# add to DOM
addCalendar = (calendar) ->
_calendarHtml = createCalendarHtml()
_heading = $ '<h1></h1>',
class: 'elr-calendar-header'
text: "#{self.months[newDate.month]} #{newDate.year}"
calendar.append _calendarHtml
_calenderInner = calendar.find ".#{self.calendarInnerClass}"
_heading.prependTo _calenderInner
# style weeks
utilities.highlightToday()
utilities.highlightWeekends()
utilities.addWeekNumbers()
# add events to calendar
$.each events, ->
self.addEventsToCalendar @, calendar
# add and remove navigation buttons
$('.elr-calendar-year-prev').text lastYear
$('.elr-calendar-year-next').text nextYear
$('.elr-calendar-month-prev').text self.months[lastMonth]
$('.elr-calendar-month-next').text self.months[nextMonth]
$('.elr-calendar-week-prev, .elr-calendar-week-next').hide()
$('.elr-calendar-date-prev, .elr-calendar-date-next').hide()
addCalendar calendar
createWeek: (newDate, calendar) ->
weekdaysHtml = "<thead><tr><th></th>"
$.each self.days, (key, value) ->
_dates = utilities.getDates datesInWeek, key
weekdaysHtml += "<th>#{value}<br>#{self.months[_dates.month]} #{_dates.date}</th>"
weekdaysHtml += '</tr></thead>'
weekHtml = "<tbody class='#{self.classes.week} #{weekClass}' data-week='#{weekNumber}'>"
$.each self.hours, ->
_hour = @name
weekHtml += "<tr><td><span class='hour'>#{_hour}</span></td>"
$.each self.days, (key) ->
dates = utilities.getDates datesInWeek, key
weekHtml += "<td class='#{self.classes.date}' data-month='#{dates.month}' data-date='#{dates.date}'
data-year='#{newDate.year}' data-day='#{key}' data-hour='#{_hour}'></td>"
weekHtml += '</tr>'
weekHtml += '</tbody>'
_weekView = $ '<table></table>',
html: weekdaysHtml + weekHtml
_calendar = $ '<div></div>',
class: self.calendarInnerClass
html: _weekView
'data-month': newDate.month
'data-year': newDate.year
_weekDates = if datesInWeek.length > 1
"#{datesInWeek[0]} - #{datesInWeek[datesInWeek.length - 1]}"
else
"#{datesInWeek[0]}"
_heading = $ '<h1></h1>',
class: 'elr-calendar-header'
text: "#{self.months[newDate.month]} #{_weekDates}: Week #{weekNumber} of #{newDate.year}"
_calendar.appendTo calendar
_heading.prependTo calendar.find(".#{self.calendarInnerClass}")
$("div.#{self.calendarInnerClass}")
.find "tbody td[data-month=#{lastMonth}]"
.addClass self.classes.muted
.removeClass 'elr-date'
$("div.#{self.calendarInnerClass}")
.find "tbody td[data-month=#{nextMonth}]"
.addClass self.classes.muted
.removeClass 'elr-date'
utilities.highlightToday()
utilities.highlightWeekends()
$.each events, ->
self.addEventsToCalendar @, calendar
$('.elr-calendar-year-prev').text lastYear
$('.elr-calendar-year-next').text nextYear
$('.elr-calendar-month-prev').text self.months[lastMonth]
$('.elr-calendar-month-next').text self.months[nextMonth]
$('.elr-calendar-week-prev, .elr-calendar-week-next').show()
$('.elr-calendar-date-prev, .elr-calendar-date-next').hide()
createDate: (newDate, calendar) ->
dayListHtml = "<ul class='elr-week elr-day #{weekClass}' data-week='#{weekNumber}'>"
$.each self.hours, ->
_hour = @name
dayListHtml += "<li class='#{self.classes.date}' data-month='#{newDate.month}' data-date='#{newDate.date}'
data-year='#{newDate.year}' data-day='#{day}' data-hour='#{_hour}'><span class='hour'>#{_hour}</span></li>"
dayListHtml += '</ul>'
_calendar = $ '<div></div>',
class: self.calendarInnerClass
'data-month': newDate.month
'data-year': newDate.year
html: dayListHtml
_headingText =
if newDate.month is self.today.month and newDate is self.today.date and newDate.year is self.today.year
"Today, #{self.days[day]}, #{self.months[newDate.month]} #{newDate.date} #{newDate.year}"
else
"#{self.days[day]}, #{self.months[newDate.month]} #{newDate.date} #{newDate.year}"
_heading = $ '<h1></h1>',
class: 'elr-calendar-header'
text: _headingText
_calendar.appendTo calendar
_heading.prependTo calendar.find(".#{self.calendarInnerClass}")
$.each events, ->
self.addEventsToCalendar @, calendar
$('.elr-calendar-year-prev').text lastYear
$('.elr-calendar-year-next').text nextYear
$('.elr-calendar-month-prev').text self.months[lastMonth]
$('.elr-calendar-month-next').text self.months[nextMonth]
$('.elr-calendar-week-prev, .elr-calendar-week-next').show()
$('.elr-calendar-date-prev, .elr-calendar-date-next').show()
switch self.view
when 'month' then views.createMonth newDate, calendar
when 'week' then views.createWeek newDate, calendar
when 'date' then views.createDate newDate, calendar | true | ###############################################################################
# Interactive JS Calendar
###############################################################################
# needs support for events with start and end dates and times
# needs support for events that recur a limited number of times
# needs edit view
"use strict"
$ = jQuery
class @ElrCalendar
constructor: (@calendarClass = 'elr-calendar', @view = 'month', @addHolidays = yes, @currentDate = 'today', @newEvents = []) ->
self = @
@calendar = $ ".#{@calendarClass}"
if @calendar.length isnt 0
@body = $ 'body'
@daysPerWeek = 7
@now = new Date()
@today =
month: @now.getMonth()
date: @now.getDate()
year: @now.getFullYear()
@calendarInnerClass = "elr-calendar-#{@view}-view"
@eventClass = 'elr-events'
@classes =
weekend: 'elr-cal-weekend'
muted: 'elr-cal-muted'
holiday: 'elr-cal-holiday'
today: 'elr-cal-today'
month: 'elr-month'
week: 'elr-week'
date: 'elr-date'
@months = [
'January'
'February'
'March'
'April'
'May'
'June'
'July'
'August'
'September'
'October'
'November'
'December']
@days = [
'Sunday'
'Monday'
'Tuesday'
'Wednesday'
'Thursday'
'Friday'
'Saturday']
@hours = [
{
name: 'All Day Event'
time: null
}
{
name: '12am'
time: 0
}
{
name: '1am'
time: 1
}
{
name: '2am'
time: 2
}
{
name: '3am'
time: 3
}
{
name: '4am'
time: 4
}
{
name: '5am'
time: 5
}
{
name: '6am'
time: 6
}
{
name: '7PI:NAME:<NAME>END_PI'
time: 7
}
{
name: '8PI:NAME:<NAME>END_PI'
time: 8
}
{
name: '9PI:NAME:<NAME>END_PI'
time: 9
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 10
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 11
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 12
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 13
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 14
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 15
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 16
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 17
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 18
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 19
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 20
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 21
}
{
name: 'PI:NAME:<NAME>END_PI'
time: 22
}
{
name: 'PI:NAME:<NAME>END_PI1PI:NAME:<NAME>END_PI'
time: 23
}
]
@holidays = [
{
name: "PI:NAME:<NAME>END_PI"
month: "January"
eventDate: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "January"
day: ["Monday"]
dayNum: 3
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "February"
eventDate: 2
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "February"
eventDate: 14
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "February"
day: ["Monday"]
dayNum: 3
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "March"
eventDate: 17
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "April"
eventDate: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "April"
eventDate: 22
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "April"
day: ["Friday"]
dayNum: "last"
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "May"
eventDate: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "May"
eventDate: 5
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "May"
day: ["Sunday"]
dayNum: 2
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "May"
day: ["Monday"]
dayNum: "last"
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "June"
eventDate: 14
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "June"
day: ["Sunday"]
type: "holiday"
recurrance: "yearly"
dayNum: 3
}
{
name: "PI:NAME:<NAME>END_PIdependence Day"
month: "July"
eventDate: 4
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "September"
day: ["Monday"]
dayNum: 1
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "September"
eventDate: 11
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "October"
day: ["Monday"]
dayNum: 2
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "October"
eventDate: 31
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "November"
eventDate: 11
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "November"
day: ["Thursday"]
dayNum: 4
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "December"
eventDate: 7
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "December"
eventDate: 23
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "December"
eventDate: 24
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "December"
eventDate: 25
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "December"
eventDate: 26
type: "holiday"
recurrance: "yearly"
}
{
name: "PI:NAME:<NAME>END_PI"
month: "December"
eventDate: 31
type: "holiday"
recurrance: "yearly"
}
]
# calendar navigation
@calendarNav = $ '.elr-calendar-nav'
@calendarSelect = $ '.elr-calendar-select'
@calendarSelectButton = @calendarSelect.find 'button[type=submit]'
@addEventForm = @calendar.find('form.elr-calendar-new-event').hide()
@showEventFormButton = @calendar.find 'button.elr-show-event-form'
@calendarViewActiveButton = @calendar.find(".elr-calendar-view-nav button[data-view=#{@view}]").addClass 'active'
@calendar.each ->
that = $ @
#extract arguments
_view = if !that.data('view') then self.view else that.data('view')
_addHolidays = if that.data('holidays')? then that.data('holidays') else self.addHolidays
_currentDate = if !that.data('month') then 'today' else {month: $.inArray(that.data('month'), self.months), date: that.data('date'), year: that.data('year')}
events =
if !that.data('event-name')
self.newEvents
else
[{
name: if that.data('event-name')? then that.data('event-name') else null
recurrance: if that.data('event-recurrance')? then that.data('event-recurrance').toLowerCase() else null
month: if that.data('event-month')? then that.data('event-month') else null
year: if that.data('event-year')? then that.data('event-year') else null
eventDate: if that.data('event-date')? then that.data('event-date') else null
time: if that.data('event-time')? then that.data('event-time') else null
day: if that.data('event-day')? then that.data('event-day') else null
dayNum: if that.data('event-day-num')? then that.data('event-day-num') else null
type: if that.data('event-type')? then that.data('event-type').toLowerCase() else null
notes: if that.data('event-notes')? then that.data('event-notes') else null
}]
if _addHolidays is yes
$.each self.holidays, ->
self.createEvent @, events, that
if _currentDate is 'today'
_currentDate = self.today
self.createCalendar {month: self.today.month, date: self.today.date, year: self.today.year}, that, events
else
self.createCalendar {month: _currentDate.month, date: _currentDate.date, year: _currentDate.year}, that, events
that.on 'click', '.elr-calendar-view-nav button', (e) ->
# change calendar view
e.preventDefault()
_that = $ @
_that.addClass 'active'
calendar = _that.closest '.elr-calendar'
calendar.find(".elr-calendar-view-nav button.active").removeClass 'active'
view = _that.data 'view'
self.changeCalendarView view, events, calendar
that.on 'click', '.elr-calendar-date-prev, .elr-calendar-date-next', ->
# skip date forward or backward
_that = $ @
calendar = _that.closest '.elr-calendar'
direction = $(@).data 'dir'
self.advanceDate.call @, direction, events, calendar
that.on 'click', '.elr-calendar-week-prev, .elr-calendar-week-next', ->
# skip week forward or backward
_that = $ @
direction = $(@).data 'dir'
calendar = _that.closest '.elr-calendar'
self.advanceWeek.call @, direction, events, calendar
that.on 'click', '.elr-calendar-month-prev, .elr-calendar-month-next', ->
# skip month forward or backward
_that = $ @
calendar = _that.closest '.elr-calendar'
direction = _that.data 'dir'
self.advanceMonth.call @, direction, events, calendar
return
that.on 'click', '.elr-calendar-year-prev, .elr-calendar-year-next', ->
# skip year forward or backward
_that = $ @
direction = $(@).data 'dir'
calendar = _that.closest '.elr-calendar'
self.advanceYear.call @, direction, events, calendar
that.on 'click', '.elr-calendar-current', ->
# go to today's date
_that = $ @
calendar = _that.closest '.elr-calendar'
self.changeCalendar.call @, {month: self.today.month, date: self.today.date, year: self.today.year}, events, calendar
that.on 'click', '.elr-calendar-select button[type=submit]', (e) ->
# go to a specific date
e.preventDefault()
_that = $ @
calendar = _that.closest '.elr-calendar'
fields = _that.parent().find(':input').not 'button[type=submit]'
newDate =
month: _that.parent().find('#month').val()
date: _that.parent().find('#date').val()
year: _that.parent().find('#year').val()
# clear form
self.clearForm fields
# parse form data
$.each newDate, ->
parseInt @, 10
# change calendar view
self.changeCalendar.call self, newDate, events, calendar
that.on 'click', 'button.elr-show-event-form', ->
# show add event form
_that = $ @
if self.addEventForm.is(':hidden')
self.addEventForm.slideDown()
_that.text 'Hide Form'
else
self.addEventForm.slideUp()
_that.text 'Add New Event'
that.on 'click', 'form.elr-calendar-new-event button.addEvent', (e) ->
# add an new event to the events object
# this code should be moved to its own method
# write a method to get the form data and send the object to the createEvent method
e.preventDefault()
newEvent = self.getFormData self.addEventForm
currentMonth = $(".#{self.calendarInnerClass}").data 'month'
self.createEvent newEvent
newMonth = if newEvent.month? then $.inArray newEvent.month, self.months else self.today.month
if newMonth isnt currentMonth
newDate =
month: newMonth
date: newEvent.eventDate
year: self.today.year
self.changeCalendar.call @, newDate
# reset form
fields = self.addEventForm.find(':input').not('button[type=submit]').val ''
self.clearForm fields
that.on 'click', ".elr-date", ->
# show event form and fill out date infomation when a date is clicked
_that = $ @
if self.addEventForm.is ':hidden'
self.addEventForm.slideDown()
self.showEventFormButton.text 'Hide Form'
month: self.addEventForm.find('#month').val self.months[_that.data('month')]
year: self.addEventForm.find('#year').val _that.data('year')
eventDate: self.addEventForm.find('#eventDate').val _that.data('date')
time: self.addEventForm.find('#time').val _that.data('hour')
that.on 'click', "ul.#{self.eventClass} a", (e) ->
# show event details
_that = $ @
day = _that.closest '.elr-date'
eventId = _that.data 'event'
fullDate =
month: self.months[day.data('month')]
date: day.data 'date'
year: day.data 'year'
e.preventDefault()
e.stopPropagation()
self.readEvent eventId, fullDate
@body.on 'click', 'div.elr-calendar-event-details', (e) ->
e.stopPropagation()
@body.on 'click', 'div.elr-calendar-event-details button.elr-event-edit', (e) ->
e.preventDefault()
_that = $ @
eventId = _that.data 'event'
index = self.getEventIndex eventId
self.editEvent()
@body.on 'click', 'div.elr-calendar-event-details button.elr-event-delete', (e) ->
e.preventDefault()
_that = $ @
eventId = _that.data 'event'
index = self.getEventIndex eventId
self.destroyEvent eventId, index
self.closeEvent e
@body.on 'click', 'div.elr-calendar-event-details button.elr-event-close', @closeEvent
# utilities
capitalize: (str) ->
str.toLowerCase().replace /^.|\s\S/g, (a) -> a.toUpperCase()
cleanString: (str, re) ->
re = new RegExp "#{re}", 'i'
return $.trim str.replace re, ''
getFormData: (form) ->
# get form data and return an object
# need to remove dashes from ids
formInput = {}
_fields = form.find(':input').not('button').not ':checkbox'
_checkboxes = form.find 'input:checked'
if _checkboxes.length isnt 0
_boxIds = []
_checkboxes.each ->
_boxIds.push $(@).attr 'id'
_boxIds = $.unique boxIds
$.each _boxIds, ->
_checkboxValues = []
_boxes = form.find "input:checked##{@}"
_boxes.each ->
checkboxValues.push $.trim($(@).val())
formInput["#{@}"] = checkboxValues
return
$.each _fields, ->
_that = $ @
_id = _that.attr 'id'
_input = if $.trim(_that.val()) is '' then null else $.trim(_that.val())
if _input? then formInput["#{_id}"] = _input
return
formInput
clearForm: (fields) ->
fields.each ->
_that = $ @
if _that.attr('type') is 'checkbox' then _that.prop 'checked', false else _that.val ''
# calendar utilities
getDaysInMonth: (month, year) ->
# returns the number of days in a month
_month = month + 1
return new Date(year, _month, 0).getDate()
getDayOfWeek: (month, date, year) ->
# returns the day of the week for a specific date
_day = new Date year, month, date
return _day.getDay()
getWeeksInMonth: (month, year) ->
# gets the number of weeks in a month
_firstDay = @getDayOfWeek month, 1, year
_numberDays = @getDaysInMonth month, year
_dayShift = if _firstDay is @daysPerWeek then 0 else _firstDay
Math.ceil (_numberDays + _dayShift) / @daysPerWeek
getMonthWeekNum: (dayNum, day, month, year) ->
# gets the week of the month which an event occurs
_weeks = @calendar.find("div.#{@calendarInnerClass}").find '.elr-week'
_firstDay = @getDayOfWeek month, 1, year
_dayShift = if _firstDay is @daysPerWeek then 0 else _firstDay
_numberWeeks = @getWeeksInMonth month, year
_lastWeekLength = _weeks.eq(_numberWeeks).length
if dayNum is 'last' and _dayShift <= day
eventWeekNum = if _lastWeekLength < day then (_numberWeeks - 2) else _numberWeeks - 1
else if dayNum is 'last' and _dayShift > day
eventWeekNum = _numberWeeks - 2
else
eventWeekNum = parseInt(dayNum, 10) - 1
return if _dayShift <= day then eventWeekNum else eventWeekNum + 1
getDatesInWeek: (month, newDate, year) ->
_firstDay = @getDayOfWeek month, 1, year
_numberDays = @getDaysInMonth month, year
_dayShift = if _firstDay is @daysPerWeek then 0 else _firstDay
_currentDay = @getDayOfWeek month, newDate, year
_numberWeeks = @getWeeksInMonth month, year
weekInfo = {}
weekInfo.datesInWeek = []
_firstWeek = []
_lastWeek = []
_daysInFirstWeek = @daysPerWeek - _dayShift
_i = 1
# get the number of dates in each week
while _i <= _numberWeeks
dates = []
if _i is 1
# first week of the month
_j = 0
while _j < _daysInFirstWeek
_j = _j + 1
dates.push _j
# middle weeks
else if _i < _numberWeeks
if _i is 2 then _date = _daysInFirstWeek
_j = 0
while _j < @daysPerWeek
_j = _j + 1
_date = _date + 1
dates.push _date
else if _i is _numberWeeks
# last week in month
while _date < _numberDays
_date = _date + 1
dates.push _date
# get the week number
if newDate in dates
weekInfo.weekNum = _i - 1
weekInfo.datesInWeek = dates
_i = _i + 1
weekInfo
getWeekNumber: (month, newDate, year) ->
self = @
_weekNum = 1
weekNums = []
_weekInfo = self.getDatesInWeek month, newDate, year
$.each self.months, (key) ->
_numberDays = self.getDaysInMonth key, year
_firstDay = self.getDayOfWeek key, 1, year
_dayShift = if _firstDay is self.daysPerWeek then 0 else _firstDay
_numberWeeks = self.getWeeksInMonth month, year
_week = 1
if $.isNumeric _numberWeeks
while _week <= _numberWeeks
if _week is 1 and _firstDay isnt 0
_weekNum = _weekNum
else
_weekNum = _weekNum + 1
_week = _week + 1
if month is key
weekNums.push _weekNum
weekNums[_weekInfo.weekNum]
# event utilities
getEventIndex: (eventId) ->
# gets the index of an event so we can keep track after events are removed
index = null
$.each @events, (key, value) ->
if value.id is eventId then index = key
index
index
closeEvent: (e) ->
$('div.elr-blackout').fadeOut 300, ->
$(@).remove()
e.preventDefault()
createEvent: (newEvent, events, calendar) ->
if events
_id = events.length
obj =
id: _id
name: if newEvent.name? then newEvent.name else null
recurrance: if newEvent.recurrance? then newEvent.recurrance.toLowerCase() else 'none'
month: if newEvent.month? then newEvent.month else null
year: if newEvent.year? then parseInt(newEvent.year, 10) else null
eventDate: if newEvent.eventDate? then parseInt(newEvent.eventDate, 10) else null
time: if newEvent.time? then newEvent.time else null
day: if newEvent.day? then newEvent.day else null
dayNum: if newEvent.dayNum? then newEvent.dayNum else null
type: if newEvent.type? then newEvent.type.toLowerCase() else null
notes: if newEvent.notes? then newEvent.notes else null
events.push obj
@addEventsToCalendar events[obj.id], calendar
destroyEvent: (eventId, index) ->
events = @calendar.find "ul.#{@eventClass} a[data-event=#{eventId}]"
events.remove()
@events.splice index, 1
editEvent: ->
self = @
eventDetailList = $('.elr-event-detail-list')
eventDetails = eventDetailList.find 'li'
# change event details to form fields and populate with text
eventFormHtml = ''
$.each eventDetails, ->
_that = $ @
label = $.trim(_that.find('span.elr-event-label').text()).toLowerCase()
label = self.cleanString label, ':'
value = $.trim _that.find('span.elr-event-detail').text()
eventFormHtml += "<label for='#{label}'>#{self.capitalize(label)}: </label>
<input type='text' value='#{value}' id='#{label}' name='#{label}'>"
return eventFormHtml
editEventForm = $ '<form></form>',
class: 'elr-calendar-event-edit'
html: eventFormHtml
eventDetailList.empty().append editEventForm
return
updateEvent: (eventId, index) ->
console.log "#{eventId}, #{index}"
readEvent: (eventId, fullDate) ->
self = @
_index = self.getEventIndex eventId
_events = self.events[_index]
_eventDate = "#{fullDate.month} #{fullDate.date}, #{fullDate.year}"
_eventFrequency = do ->
if _events.recurrance is 'yearly' and _events.dayNum?
"Every #{_events.dayNum} #{_events.day} of #{_events.month}"
else if _events.recurrance is 'yearly'
"Every #{_events.eventDate} of #{_events.month}"
else if _events.recurrance is 'monthly' and _events.dayNum?
"Every #{_events.dayNum} #{_events.day} of the month"
else if _events.recurrance is 'monthly'
"Every #{_events.eventDate} of the month"
else if _events.recurrance is 'biweekly'
"Every other #{_events.day}"
else if _events.recurrance is 'weekly'
"Every #{_events.day}"
else if _events.recurrance is 'daily'
"Every Day"
else
"One Time Event"
_eventDetails =
date: _eventDate
time: _events.time
type: _events.type
frequency: _eventFrequency
repeat: _events.recurrance
notes: _events.notes
_eventHolder = $ '<div></div>',
class: 'elr-calendar-event-details'
html: "<h1 class='elr-calendar-header'>#{_events.name}</h1>"
_closeButton = $ '<button></button>',
class: 'elr-event-close'
text: 'Close'
type: 'button'
_editButton = $ "<button></button>",
class: 'elr-event-edit'
'data-event': _events.id
text: 'Edit'
type: 'button'
_deleteButton = $ "<button></button>",
class: 'elr-event-delete'
'data-event': _events.id
text: 'Delete'
type: 'button'
_eventDetailList = $ '<ul></ul>',
class: 'elr-event-detail-list'
_close = $ '<button></button>',
class: 'close'
text: 'x'
_lightboxHtml = $ '<div></div>',
class: 'elr-blackout'
html: _close + _eventHolder
_lightboxHtml.hide().appendTo('body').fadeIn 300, ->
_eventHolder.appendTo _lightboxHtml
_eventDetailList.appendTo _eventHolder
$.each _eventDetails, (key, value) ->
if value?
_title = self.capitalize key
_listItem = $ '<li></li>',
html: "<span class='elr-bold elr-event-label'>#{_title}: </span><span class='elr-event-detail'>#{value}</span>"
_listItem.appendTo _eventDetailList
_closeButton.insertAfter _eventDetailList
_deleteButton.insertAfter _eventDetailList
_editButton.insertAfter _eventDetailList
return
# calendar creation utilities
addEventsToCalendar: (events, calendar) ->
self = @
calendarInner = calendar.find "div.#{@calendarInnerClass}"
eventMonth = calendarInner.data 'month'
eventYear = calendarInner.data 'year'
month = $.inArray events.month, self.months
weeks = calendarInner.find '.elr-week'
eventDates = []
addEvents =
addYearlyEvents: (events, eventDates) ->
# add yearly events
if events.day
$.each events.day, ->
_day = $.inArray @, self.days
_eventWeekNum = self.getMonthWeekNum events.dayNum, _day, eventMonth, eventYear
if eventMonth is month
weeks.each ->
_that = $ @
_firstDate = _that.find(".#{self.classes.date}").first().data 'date'
_weekInfo = self.getDatesInWeek eventMonth, _firstDate, eventYear
if _eventWeekNum is _weekInfo.weekNum
eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data 'date'
else
eventDates.push parseInt(events.eventDate, 10)
addMonthlyEvents: (events, eventDates) ->
# add monthly events
if events.day
$.each events.day, ->
day = $.inArray @, self.days
_eventWeekNum = self.getMonthWeekNum events.dayNum, day, eventMonth, eventYear
weeks.each ->
_that = $ @
_firstDate = _that.find(".#{self.classes.date}").first().data 'date'
_weekInfo = self.getDatesInWeek eventMonth, _firstDate, eventYear
if _eventWeekNum is _weekInfo.weekNum
eventDates.push _that.find(".#{self.classes.date}[data-day=#{day}]").data 'date'
else
eventDates.push parseInt(events.eventDate, 10)
addBiWeeklyEvents: (events, eventDates) ->
# events _that occur every 2 weeks
if events.day
_weekInfo = self.getDatesInWeek eventMonth, events.eventDate, eventYear
$.each events.day, ->
_day = $.inArray @, self.days
_length = weeks.length
_weekPattern = if _weekInfo.weekNum % 2 is 0 then 'even' else 'odd'
_eventWeeks = calendarInner.find ".#{_weekPattern}-week"
$.each _eventWeeks, ->
_that = $ @
_weekLength = _that.find(".elr-date").length
eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
addWeeklyEvents: (events, eventDates) ->
# weekly events
_firstDay = self.getDayOfWeek eventMonth, 1, eventYear
_dayShift = if _firstDay is self.daysPerWeek then 0 else _firstDay
if events.day
$.each events.day, (key, value) ->
_day = $.inArray value, self.days
_length = weeks.length
$.each weeks, ->
_that = $ @
_days = if self.view is 'month'
_that.find ".#{self.classes.date}"
else
_that.find ".#{self.classes.date}[data-hour='All Day Event']"
_weekLength = _days.length
if key is 0 and _length isnt 1
if _dayShift <= _day then eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
else if key is (_length - 1) and _length isnt 1
if _day < _weekLength then eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
else
eventDates.push _that.find(".#{self.classes.date}[data-day=#{_day}]").data('date')
eventDates
addDailyEvents: (events, eventDates) ->
_days = if self.view is 'month'
calendarInner.find ".#{self.classes.date}"
else
calendarInner.find ".#{self.classes.date}[data-hour='All Day Event']"
_days.each ->
eventDates.push $(@).data 'date'
addOneTimeEvents: (events, eventDates) ->
eventDates.push parseInt(events.eventDate, 10)
eventDates
_addCalendarEvent = (events, dates) ->
# create event html
if self.view is 'month'
_calendarItem = calendarInner.find ".elr-date[data-date=#{dates}]"
else if !events.time?
_calendarItem = calendarInner.find ".elr-date[data-date=#{dates}][data-hour='All Day Event']"
else
# find hour td element
re = new RegExp '^0?','gi'
re2 = new RegExp ':[0-9]{2}', 'gi'
hour = events.time.replace re, ''
hour = hour.replace re2, ''
_calendarItem = calendarInner.find ".elr-date[data-date=#{dates}][data-hour=#{hour}]"
_eventList = _calendarItem.find "ul.#{self.eventClass}"
_eventContent =
if events.time?
"<span class='elr-time'>#{events.time}: </span><span class='elr-event'>#{events.name}</span>"
else
"<span class='elr-event elr-all-day-event'>#{events.name}</span>"
_eventHtml = $ '<a></a>',
href: '#'
'data-event': events.id
html: _eventContent
if _eventList.length is 0
_eventList = $ '<ul></ul>',
class: "#{self.eventClass}"
_eventList.appendTo _calendarItem
_item = $ '<li></li>',
html: _eventHtml
_item.appendTo _eventList
if events.type is 'holiday' then _eventList.find("a:contains(#{events.name})").addClass self.classes.holiday
if events.recurrance is 'yearly' and eventMonth is month
addEvents.addYearlyEvents events, eventDates
else if events.recurrance is 'monthly'
addEvents.addMonthlyEvents events, eventDates
else if events.recurrance is 'biweekly'
addEvents.addBiWeeklyEvents events, eventDates
else if events.recurrance is 'weekly'
addEvents.addWeeklyEvents events, eventDates
else if events.recurrance is 'daily'
addEvents.addDailyEvents events, eventDates
else if events.recurrance is 'none' and eventMonth is month and eventYear is parseInt(events.year, 10)
addEvents.addOneTimeEvents events, eventDates
if eventDates.length > 0
$.each eventDates, (key, date) ->
# add css classes here
_addCalendarEvent events, date
advanceDate: (direction, events, calendar) =>
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
date: _calendarInner.find(".#{@classes.date}").data 'date'
year: _calendarInner.data 'year'
_nextYear = newDate.year + 1
_lastYear = newDate.year - 1
_nextMonth = if newDate.month is 11 then 0 else newDate.month + 1
lastMonth = if newDate.month is 0 then 11 else newDate.month - 1
if direction is 'prev'
_lastDayOfPrevMonth = @getDaysInMonth lastMonth, newDate.year
if newDate.date is 1
newDate.date = _lastDayOfPrevMonth
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else
newDate.date = newDate.date - 1
else if direction is 'next'
_lastDayOfMonth = @getDaysInMonth newDate.month, newDate.year
if newDate.date is _lastDayOfMonth
newDate.date = 1
newDate.year = if newDate.month is 11 then _nextYear else newDate.year
newDate.month = _nextMonth
else
newDate.date = newDate.date + 1
if @view is 'date' then @changeCalendar newDate, events, calendar
advanceWeek: (direction, events, calendar) =>
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
date: 1
year: _calendarInner.data 'year'
_nextYear = newDate.year + 1
_lastYear = newDate.year - 1
_nextMonth = if newDate.month is 11 then 0 else newDate.month + 1
lastMonth = if newDate.month is 0 then 11 else newDate.month - 1
if direction is 'prev'
_firstDay = _calendarInner.find(".#{@classes.date}").first().data 'date'
_lastDayOfPrevMonth = @getDaysInMonth lastMonth, newDate.year
if _firstDay is 1 and @view is 'week'
newDate.date = _lastDayOfPrevMonth
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else if _firstDay < 7 and @view is 'week'
newDate.date = _firstDay - 1
else if _firstDay is 1 and @view is 'date'
newDate.date = _lastDayOfPrevMonth - 6 # 30 - 6 1 24
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else if _firstDay < 7 and @view is 'date'
newDate.date = _lastDayOfPrevMonth - (7 - _firstDay) # 31 - (7 - 3) = 27 27 28 - (7 - 6) = 27 6 27
newDate.year = if newDate.month is 0 then _lastYear else newDate.year
newDate.month = lastMonth
else
newDate.date = _firstDay - 7
else if direction is 'next'
_lastDay = _calendarInner.find(".#{@classes.date}").last().data 'date'
_lastDayOfMonth = @getDaysInMonth newDate.month, newDate.year
if _lastDay is _lastDayOfMonth and @view is 'week'
newDate.date = 1
newDate.year = if newDate.month is 11 then _nextYear else newDate.year
newDate.month = _nextMonth
else if (_lastDay + 7 > _lastDayOfMonth) and @view is 'week'
newDate.date = _lastDayOfMonth
else if (_lastDay + 7 > _lastDayOfMonth) and @view is 'date'
newDate.date = 7 - (_lastDayOfMonth - _lastDay) # 31 - 29 = 2 then 7 - 2 = 5
newDate.year = if newDate.month is 11 then _nextYear else newDate.year
newDate.month = _nextMonth
else
newDate.date = _lastDay + 7
if @view is 'date' or @view is 'week' then @changeCalendar newDate, events, calendar
advanceMonth: (direction, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
date: if @month is self.today.month then self.today.date else 1
year: _calendarInner.data 'year'
if direction is 'prev'
newDate.month = if newDate.month is 0 then 11 else newDate.month - 1
newDate.year = if newDate.month is 11 then newDate.year - 1 else newDate.year
else if direction is 'next'
newDate.month = if newDate.month is 11 then 0 else newDate.month + 1
newDate.year = if newDate.month is 0 then newDate.year + 1 else newDate.year
@changeCalendar newDate, events, calendar
advanceYear: (direction, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
year: _calendarInner.data 'year'
newDate.date = if newDate.month is self.today.month then self.today.date else 1
newDate.year = if direction is 'prev' then newDate.year - 1 else newDate.year + 1
@changeCalendar newDate, events, calendar
changeCalendarView: (view, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{@calendarInnerClass}"
newDate =
month: _calendarInner.data 'month'
year: _calendarInner.data 'year'
newDate.date = if newDate.month is self.today.month then self.today.date else 1
# update view
@view = view
@changeCalendar newDate, events, calendar
# change calendar class
@calendarInnerClass = "elr-calendar-#{view}-view"
return
changeCalendar: (newDate, events, calendar) =>
self = @
_calendarInner = calendar.find "div.#{self.calendarInnerClass}"
_calendarInner.fadeOut(300).queue (next) ->
_that = $ @
$.when(_that.remove()).then(self.createCalendar(newDate, calendar, events))
next()
createCalendar: (newDate, calendar, events) ->
self = @
nextYear = newDate.year + 1
lastYear = newDate.year - 1
nextMonth = if newDate.month is 11 then 0 else newDate.month + 1
lastMonth = if newDate.month is 0 then 11 else newDate.month - 1
firstDay = self.getDayOfWeek newDate.month, 1, newDate.year
dayShift = if firstDay is self.daysPerWeek then 0 else firstDay
numberDays = self.getDaysInMonth newDate.month, newDate.year
numberWeeks = self.getWeeksInMonth newDate.month, newDate.year
prevMonthNumberDays = self.getDaysInMonth lastMonth, newDate.year
weekInfo = self.getDatesInWeek newDate.month, newDate.date, newDate.year
datesInWeek = weekInfo.datesInWeek
weekNumber = self.getWeekNumber newDate.month, newDate.date, newDate.year
weekClass = if weekNumber % 2 is 0 then 'even-week' else 'odd-week'
day = self.getDayOfWeek newDate.month, newDate.date, newDate.year
utilities =
highlightWeekends: ->
_calendarInner = calendar.find "div.#{self.calendarInnerClass}"
_weeks = _calendarInner.find '.elr-week'
weekends = [0, 6]
$.each _weeks, ->
_that = $ @
$.each weekends, ->
_weekend = _that.find(".#{self.classes.date}[data-day=#{@}]")
.not ".#{self.classes.muted}, .#{self.classes.today}, .#{self.classes.holiday}"
_weekend.addClass self.classes.weekend
highlightToday: ->
_calendarInner = calendar.find "div.#{self.calendarInnerClass}"
_month = _calendarInner.data 'month'
_year = _calendarInner.data 'year'
if _month is parseInt(newDate.month, 10) and _year is parseInt(newDate.year, 10)
_calendarInner.find(".elr-date[data-date=#{newDate.date}]").addClass self.classes.today
addWeekNumbers: ->
_weeks = calendar.find("div.#{self.calendarInnerClass}").find '.elr-week'
$.each _weeks, ->
_that = $ @
_firstDateInWeek = _that.find('.elr-date').first().data 'date'
_weekNumber = self.getWeekNumber newDate.month, _firstDateInWeek, newDate.year
if _weekNumber % 2 is 0
_that.addClass 'even-week'
else
_that.addClass 'odd-week'
_that.attr 'data-week', _weekNumber
getDates: (datesInWeek, key) ->
dates = {}
# if its the first week of the month
if datesInWeek.length < self.daysPerWeek and datesInWeek[0] is 1
if key is firstDay
dates.date = 1
dates.month = newDate.month
else if key > firstDay
dates.date = (key - firstDay) + 1
dates.month = newDate.month
else
dates.date = prevMonthNumberDays - (firstDay - (key + 1))
dates.month = lastMonth
else if datesInWeek.length is self.daysPerWeek
dates.date = datesInWeek[key]
dates.month = newDate.month
# if its the last week of the month
else if datesInWeek.length < self.daysPerWeek and datesInWeek[0] isnt 1
if key < datesInWeek.length
dates.date = datesInWeek[key]
dates.month = newDate.month
else
dates.date = Math.abs (datesInWeek.length - (key + 1))
dates.month = nextMonth
dates
views =
createMonth: (newDate, calendar) ->
_newDate = {month: newDate.month, date: newDate.date, year: newDate.year}
createWeekdays = ->
weekdays = "<div class='#{self.calendarInnerClass}' data-month='#{_newDate.month}' data-year='#{_newDate.year}'><table><thead><tr>"
$.each self.days, ->
weekdays += "<th>#{@}</th>"
weekdays += '</tr></thead>'
return weekdays
createFirstWeek = ->
# add cells for the previous month until we get to the first day
_lastMonthDays = 1
_prevDays = (prevMonthNumberDays - dayShift) + 1
firstWeekHtml = ''
$.each self.days, (key) ->
if _lastMonthDays <= dayShift
firstWeekHtml += "<td class='#{self.classes.muted}' data-day='#{key}'>#{_prevDays}</td>"
_prevDays += 1
_lastMonthDays += 1
else
# start adding cells for the current month
firstWeekHtml += "<td class='#{self.classes.date}' data-month='#{_newDate.month}' data-date='#{_newDate.date}'
data-year='#{_newDate.year}' data-day='#{key}'>#{_newDate.date}</td>"
_newDate.date += 1
return firstWeekHtml
createLastWeek = ->
_nextDates = 1
lastWeekHtml = ''
$.each self.days, (key) ->
# finish adding cells for the current month
if _newDate.date <= numberDays
lastWeekHtml += "<td class='#{self.classes.date}' data-month='#{_newDate.month}' data-date='#{_newDate.date}'
data-year='#{_newDate.year}' data-day='#{key}'>#{_newDate.date}</td>"
# start adding cells for next month
else
lastWeekHtml += "<td class='#{self.classes.muted}' data-day='#{key}'>#{_nextDates}</td>"
_nextDates += 1
_newDate.date += 1
return lastWeekHtml
createMiddleWeeks = ->
middleWeeksHtml = ''
$.each self.days, (key) ->
middleWeeksHtml += "<td class='#{self.classes.date}' data-month='#{_newDate.month}' data-date='#{_newDate.date}'
data-year='#{_newDate.year}' data-day='#{key}'>#{_newDate.date}</td>"
_newDate.date += 1
return middleWeeksHtml
createWeeks = ->
weekCount = 1
_newDate.date = 1
weeks = "<tbody class='#{self.classes.month}'>"
while weekCount <= numberWeeks
weeks += "<tr class='#{self.classes.week}'>"
# if we are in week 1 we need to shift to the correct day of the week
if weekCount is 1 and firstDay isnt 0
weeks += createFirstWeek()
# if we are in the last week of the month we need to add blank cells for next month
else if weekCount is numberWeeks
weeks += createLastWeek()
else
# if we are in the middle of the month add cells for the current month
weeks += createMiddleWeeks()
weeks += '</tr>'
weekCount += 1
weeks += '</tbody></table></div>'
return weeks
createCalendarHtml = ->
# create html
return createWeekdays() + createWeeks()
# add to DOM
addCalendar = (calendar) ->
_calendarHtml = createCalendarHtml()
_heading = $ '<h1></h1>',
class: 'elr-calendar-header'
text: "#{self.months[newDate.month]} #{newDate.year}"
calendar.append _calendarHtml
_calenderInner = calendar.find ".#{self.calendarInnerClass}"
_heading.prependTo _calenderInner
# style weeks
utilities.highlightToday()
utilities.highlightWeekends()
utilities.addWeekNumbers()
# add events to calendar
$.each events, ->
self.addEventsToCalendar @, calendar
# add and remove navigation buttons
$('.elr-calendar-year-prev').text lastYear
$('.elr-calendar-year-next').text nextYear
$('.elr-calendar-month-prev').text self.months[lastMonth]
$('.elr-calendar-month-next').text self.months[nextMonth]
$('.elr-calendar-week-prev, .elr-calendar-week-next').hide()
$('.elr-calendar-date-prev, .elr-calendar-date-next').hide()
addCalendar calendar
createWeek: (newDate, calendar) ->
weekdaysHtml = "<thead><tr><th></th>"
$.each self.days, (key, value) ->
_dates = utilities.getDates datesInWeek, key
weekdaysHtml += "<th>#{value}<br>#{self.months[_dates.month]} #{_dates.date}</th>"
weekdaysHtml += '</tr></thead>'
weekHtml = "<tbody class='#{self.classes.week} #{weekClass}' data-week='#{weekNumber}'>"
$.each self.hours, ->
_hour = @name
weekHtml += "<tr><td><span class='hour'>#{_hour}</span></td>"
$.each self.days, (key) ->
dates = utilities.getDates datesInWeek, key
weekHtml += "<td class='#{self.classes.date}' data-month='#{dates.month}' data-date='#{dates.date}'
data-year='#{newDate.year}' data-day='#{key}' data-hour='#{_hour}'></td>"
weekHtml += '</tr>'
weekHtml += '</tbody>'
_weekView = $ '<table></table>',
html: weekdaysHtml + weekHtml
_calendar = $ '<div></div>',
class: self.calendarInnerClass
html: _weekView
'data-month': newDate.month
'data-year': newDate.year
_weekDates = if datesInWeek.length > 1
"#{datesInWeek[0]} - #{datesInWeek[datesInWeek.length - 1]}"
else
"#{datesInWeek[0]}"
_heading = $ '<h1></h1>',
class: 'elr-calendar-header'
text: "#{self.months[newDate.month]} #{_weekDates}: Week #{weekNumber} of #{newDate.year}"
_calendar.appendTo calendar
_heading.prependTo calendar.find(".#{self.calendarInnerClass}")
$("div.#{self.calendarInnerClass}")
.find "tbody td[data-month=#{lastMonth}]"
.addClass self.classes.muted
.removeClass 'elr-date'
$("div.#{self.calendarInnerClass}")
.find "tbody td[data-month=#{nextMonth}]"
.addClass self.classes.muted
.removeClass 'elr-date'
utilities.highlightToday()
utilities.highlightWeekends()
$.each events, ->
self.addEventsToCalendar @, calendar
$('.elr-calendar-year-prev').text lastYear
$('.elr-calendar-year-next').text nextYear
$('.elr-calendar-month-prev').text self.months[lastMonth]
$('.elr-calendar-month-next').text self.months[nextMonth]
$('.elr-calendar-week-prev, .elr-calendar-week-next').show()
$('.elr-calendar-date-prev, .elr-calendar-date-next').hide()
createDate: (newDate, calendar) ->
dayListHtml = "<ul class='elr-week elr-day #{weekClass}' data-week='#{weekNumber}'>"
$.each self.hours, ->
_hour = @name
dayListHtml += "<li class='#{self.classes.date}' data-month='#{newDate.month}' data-date='#{newDate.date}'
data-year='#{newDate.year}' data-day='#{day}' data-hour='#{_hour}'><span class='hour'>#{_hour}</span></li>"
dayListHtml += '</ul>'
_calendar = $ '<div></div>',
class: self.calendarInnerClass
'data-month': newDate.month
'data-year': newDate.year
html: dayListHtml
_headingText =
if newDate.month is self.today.month and newDate is self.today.date and newDate.year is self.today.year
"Today, #{self.days[day]}, #{self.months[newDate.month]} #{newDate.date} #{newDate.year}"
else
"#{self.days[day]}, #{self.months[newDate.month]} #{newDate.date} #{newDate.year}"
_heading = $ '<h1></h1>',
class: 'elr-calendar-header'
text: _headingText
_calendar.appendTo calendar
_heading.prependTo calendar.find(".#{self.calendarInnerClass}")
$.each events, ->
self.addEventsToCalendar @, calendar
$('.elr-calendar-year-prev').text lastYear
$('.elr-calendar-year-next').text nextYear
$('.elr-calendar-month-prev').text self.months[lastMonth]
$('.elr-calendar-month-next').text self.months[nextMonth]
$('.elr-calendar-week-prev, .elr-calendar-week-next').show()
$('.elr-calendar-date-prev, .elr-calendar-date-next').show()
switch self.view
when 'month' then views.createMonth newDate, calendar
when 'week' then views.createWeek newDate, calendar
when 'date' then views.createDate newDate, calendar |
[
{
"context": "\t\tuserData =\n\t\t\temail: formData.email\n\t\t\tpassword: formData.pass\n\n\t\tuserId = Accounts.createUser userData\n\n\t\tRocke",
"end": 565,
"score": 0.999019205570221,
"start": 552,
"tag": "PASSWORD",
"value": "formData.pass"
},
{
"context": "hUserName: (formData... | rocketchat/server/methods/registerUser.coffee | Ritesh1991/mobile_app_server | 0 | Meteor.methods
registerUser: (formData) ->
if RocketChat.settings.get('Accounts_RegistrationForm') is 'Disabled'
throw new Meteor.Error 'registration-disabled', 'User registration is disabled'
else if RocketChat.settings.get('Accounts_RegistrationForm') is 'Secret URL' and (not formData.secretURL or formData.secretURL isnt RocketChat.settings.get('Accounts_RegistrationForm_SecretURL'))
throw new Meteor.Error 'registration-disabled', 'User registration is only allowed via Secret URL'
userData =
email: formData.email
password: formData.pass
userId = Accounts.createUser userData
RocketChat.models.Users.setName userId, formData.name
if userData.email
Accounts.sendVerificationEmail(userId, userData.email);
return userId
registerUserWithUserName: (formData) ->
userData =
username: formData.username
password: formData.password
name: formData.name
userId = Accounts.createUser userData
Meteor.users.update({_id: userId}, {$set: {name: userData.name}})
#RocketChat.models.Users.setName userId, formData.name
#if userData.email
# Accounts.sendVerificationEmail(userId, userData.email);
return userId
| 219516 | Meteor.methods
registerUser: (formData) ->
if RocketChat.settings.get('Accounts_RegistrationForm') is 'Disabled'
throw new Meteor.Error 'registration-disabled', 'User registration is disabled'
else if RocketChat.settings.get('Accounts_RegistrationForm') is 'Secret URL' and (not formData.secretURL or formData.secretURL isnt RocketChat.settings.get('Accounts_RegistrationForm_SecretURL'))
throw new Meteor.Error 'registration-disabled', 'User registration is only allowed via Secret URL'
userData =
email: formData.email
password: <PASSWORD>
userId = Accounts.createUser userData
RocketChat.models.Users.setName userId, formData.name
if userData.email
Accounts.sendVerificationEmail(userId, userData.email);
return userId
registerUserWithUserName: (formData) ->
userData =
username: formData.username
password: <PASSWORD>
name: formData.name
userId = Accounts.createUser userData
Meteor.users.update({_id: userId}, {$set: {name: userData.name}})
#RocketChat.models.Users.setName userId, formData.name
#if userData.email
# Accounts.sendVerificationEmail(userId, userData.email);
return userId
| true | Meteor.methods
registerUser: (formData) ->
if RocketChat.settings.get('Accounts_RegistrationForm') is 'Disabled'
throw new Meteor.Error 'registration-disabled', 'User registration is disabled'
else if RocketChat.settings.get('Accounts_RegistrationForm') is 'Secret URL' and (not formData.secretURL or formData.secretURL isnt RocketChat.settings.get('Accounts_RegistrationForm_SecretURL'))
throw new Meteor.Error 'registration-disabled', 'User registration is only allowed via Secret URL'
userData =
email: formData.email
password: PI:PASSWORD:<PASSWORD>END_PI
userId = Accounts.createUser userData
RocketChat.models.Users.setName userId, formData.name
if userData.email
Accounts.sendVerificationEmail(userId, userData.email);
return userId
registerUserWithUserName: (formData) ->
userData =
username: formData.username
password: PI:PASSWORD:<PASSWORD>END_PI
name: formData.name
userId = Accounts.createUser userData
Meteor.users.update({_id: userId}, {$set: {name: userData.name}})
#RocketChat.models.Users.setName userId, formData.name
#if userData.email
# Accounts.sendVerificationEmail(userId, userData.email);
return userId
|
[
{
"context": " the string return this:\n #\n # Sender Name <email@sender.com>\n displayAddress: (address, full = false) ->\n ",
"end": 656,
"score": 0.9999080896377563,
"start": 640,
"tag": "EMAIL",
"value": "email@sender.com"
},
{
"context": "s either the email adress eithe... | client/app/utils/message_utils.coffee | cozy-labs/emails | 58 | {ComposeActions} = require '../constants/app_constants'
ContactStore = require '../stores/contact_store'
QUOTE_STYLE = "margin-left: 0.8ex; padding-left: 1ex; border-left: 3px solid #34A6FF;"
# Style is required to clean pre and p styling in compose editor.
# It is removed by the visulasation iframe that's why we need to put
# style at the p level too.
COMPOSE_STYLE = """
<style>
pre {background: transparent; border: 0}
</style>
"""
module.exports = MessageUtils =
# Build string showing address from an `adress` object. If a mail is given
# in the `address` object, the string return this:
#
# Sender Name <email@sender.com>
displayAddress: (address, full = false) ->
if full
if address.name? and address.name isnt ""
return "\"#{address.name}\" <#{address.address}>"
else
return "#{address.address}"
else
if address.name? and address.name isnt ""
return address.name
else
return address.address.split('@')[0]
# Build a string from a list of `adress` objects. Addresses are
# separated by a coma. An address is either the email adress either this:
#
# Sender Name <email@sender.com>
displayAddresses: (addresses, full = false) ->
if not addresses?
return ""
else
res = []
for item in addresses
if not item?
break
res.push(MessageUtils.displayAddress item, full)
return res.join ", "
# From a text, build an `address` object (name and address).
# Add a isValid field if the given email is well formed.
parseAddress: (text) ->
text = text.trim()
if match = text.match /"{0,1}(.*)"{0,1} <(.*)>/
address =
name: match[1]
address: match[2]
else
address =
address: text.replace(/^\s*/, '')
# Test email validity
emailRe = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
address.isValid = address.address.match emailRe
address
# Extract a reply address from a `message` object.
getReplyToAddress: (message) ->
reply = message.get 'replyTo'
from = message.get 'from'
if (reply? and reply.length isnt 0)
return reply
else
return from
# Add signature at the end of the message
addSignature: (message, signature) ->
message.text += "\n\n-- \n#{signature}"
signatureHtml = signature.replace /\n/g, '<br>'
message.html += """
<p><br></p><p id="signature">-- \n<br>#{signatureHtml}</p>
<p><br></p>
"""
# Build message to put in the email composer depending on the context
# (reply, reply to all, forward or simple message).
# It add appropriate headers to the message. It adds style tags when
# required too.
# It adds signature at the end of the zone where the user will type.
makeReplyMessage: (myAddress, inReplyTo, action, inHTML, signature) ->
message =
composeInHTML: inHTML
attachments: Immutable.Vector.empty()
if inReplyTo
message.accountID = inReplyTo.get 'accountID'
message.conversationID = inReplyTo.get 'conversationID'
dateHuman = @formatReplyDate inReplyTo.get 'createdAt'
sender = @displayAddresses inReplyTo.get 'from'
text = inReplyTo.get 'text'
html = inReplyTo.get 'html'
text = '' unless text? # Some message have no content, only attachements
if text? and not html? and inHTML
try
html = markdown.toHTML text
catch e
console.error "Error converting message to Markdown: #{e}"
html = "<div class='text'>#{text}</div>"
if html? and not text? and not inHTML
text = toMarkdown html
message.inReplyTo = [inReplyTo.get 'id']
message.references = inReplyTo.get('references') or []
message.references = message.references.concat message.inReplyTo
if signature? and signature.length > 0
isSignature = true
else
isSignature = false
options = {
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
}
switch action
when ComposeActions.REPLY
@setMessageAsReply options
when ComposeActions.REPLY_ALL
@setMessageAsReplyAll options
when ComposeActions.FORWARD
@setMessageAsForward options
when null
@setMessageAsDefault options
# remove my address from dests
notMe = (dest) -> return dest.address isnt myAddress
message.to = message.to.filter notMe
message.cc = message.cc.filter notMe
return message
# Build message to display in composer in case of a reply to a message:
# * set subject automatically (Re: previous subject)
# * Set recipient based on sender
# * add a style header for proper display
# * Add quote of the previous message at the beginning of the message
# * adds a signature at the message end.
setMessageAsReply: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
params = date: dateHuman, sender: sender
separator = t 'compose reply separator', params
message.to = @getReplyToAddress inReplyTo
message.cc = []
message.bcc = []
message.subject = @getReplySubject inReplyTo
message.text = separator + @generateReplyText(text) + "\n"
message.html = """
#{COMPOSE_STYLE}
<p><br></p>
"""
if isSignature
@addSignature message, signature
message.html += """
<p>#{separator}<span class="originalToggle"> … </span></p>
<blockquote style="#{QUOTE_STYLE}">#{html}</blockquote>
"""
# Build message to display in composer in case of a reply to all message:
# * set subject automatically (Re: previous subject)
# * Set recipients based on all people set in the conversation.
# * add a style header for proper display
# * Add quote of the previous message at the beginning of the message
# * adds a signature at the message end.
setMessageAsReplyAll: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
params = date: dateHuman, sender: sender
separator = t 'compose reply separator', params
message.to = @getReplyToAddress inReplyTo
# filter to don't have same address twice
toAddresses = message.to.map (dest) -> return dest.address
message.cc = [].concat(
inReplyTo.get('from'),
inReplyTo.get('to'),
inReplyTo.get('cc')
).filter (dest) ->
return dest? and toAddresses.indexOf(dest.address) is -1
message.bcc = []
message.subject = @getReplySubject inReplyTo
message.text = separator + @generateReplyText(text) + "\n"
message.html = """
#{COMPOSE_STYLE}
<p><br></p>
"""
if isSignature
@addSignature message, signature
message.html += """
<p>#{separator}<span class="originalToggle"> … </span></p>
<blockquote style="#{QUOTE_STYLE}">#{html}</blockquote>
<p><br></p>
"""
# Build message to display in composer in case of a message forwarding:
# * set subject automatically (fwd: previous subject)
# * add a style header for proper display
# * Add forward information at the beginning of the message
# We don't add signature here (see Thunderbird behavior)
setMessageAsForward: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
addresses = inReplyTo.get('to')
.map (address) -> address.address
.join ', '
senderInfos = @getReplyToAddress inReplyTo
senderName = ""
senderAddress =
if senderInfos.length > 0
senderName = senderInfos[0].name
senderAddress = senderInfos[0].address
if senderName.length > 0
fromField = "#{senderName} <#{senderAddress}>"
else
fromField = senderAddress
separator = """
----- #{t 'compose forward header'} ------
#{t 'compose forward subject'} #{inReplyTo.get 'subject'}
#{t 'compose forward date'} #{dateHuman}
#{t 'compose forward from'} #{fromField}
#{t 'compose forward to'} #{addresses}
"""
textSeparator = separator.replace('<', '<').replace('>', '>')
textSeparator = textSeparator.replace('<pre>', '').replace('</pre>', '')
htmlSeparator = separator.replace /(\n)+/g, '<br>'
@setMessageAsDefault options
message.subject = """
#{t 'compose forward prefix'}#{inReplyTo.get 'subject'}
"""
message.text = textSeparator + text
message.html = "#{COMPOSE_STYLE}"
if isSignature
@addSignature message, signature
message.html += """
<p>#{htmlSeparator}</p><p><br></p>#{html}
"""
message.attachments = inReplyTo.get 'attachments'
return message
# Clear all fields of the message object.
# Add signature if given.
setMessageAsDefault: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
message.to = []
message.cc = []
message.bcc = []
message.subject = ''
message.text = ''
message.html = "#{COMPOSE_STYLE}\n<p><br></p>"
if isSignature
@addSignature message, signature
return message
# Generate reply text by adding `>` before each line of the given text.
generateReplyText: (text) ->
text = text.split '\n'
res = []
text.forEach (line) ->
res.push "> #{line}"
return res.join "\n"
# Guess simple attachment type from mime type.
getAttachmentType: (type) ->
return null unless type
sub = type.split '/'
switch sub[0]
when 'audio', 'image', 'text', 'video'
return sub[0]
when "application"
switch sub[1]
when "vnd.ms-excel",\
"vnd.oasis.opendocument.spreadsheet",\
"vnd.openxmlformats-officedocument.spreadsheetml.sheet"
return "spreadsheet"
when "msword",\
"vnd.ms-word",\
"vnd.oasis.opendocument.text",\
"vnd.openxmlformats-officedocument.wordprocessingm" + \
"l.document"
return "word"
when "vns.ms-powerpoint",\
"vnd.oasis.opendocument.presentation",\
"vnd.openxmlformats-officedocument.presentationml." + \
"presentation"
return "presentation"
when "pdf" then return sub[1]
when "gzip", "zip" then return 'archive'
# Format date to a conventional format for reply headers.
formatReplyDate: (date) ->
date = moment() unless date?
date = moment date
date.format 'lll'
# Display date as a readable string.
# Make it shorter if compact is set to true.
formatDate: (date, compact) ->
unless date?
return null
else
today = moment()
date = moment date
if date.isBefore today, 'year'
formatter = 'DD/MM/YYYY'
else if date.isBefore today, 'day'
if compact? and compact
formatter = 'L'
else
formatter = 'MMM DD'
else
formatter = 'HH:mm'
return date.format formatter
# Return avatar corresponding to sender by matching his email address with
# addresses from existing contacts.
getAvatar: (message) ->
if message.get('from')[0]?
return ContactStore.getAvatar message.get('from')[0].address
else
return null
# Remove from given string:
# * html tags
# * extra spaces between reply markers and text
# * empty reply lines
cleanReplyText: (html) ->
# Convert HTML to markdown
try
result = html.replace /<(style>)[^\1]*\1/gim, ''
result = toMarkdown result
catch
if html?
result = html.replace /<(style>)[^\1]*\1/gim, ''
result = html.replace /<[^>]*>/gi, ''
# convert HTML entities
tmp = document.createElement 'div'
tmp.innerHTML = result
result = tmp.textContent
# Make citation more human readable.
result = result.replace />[ \t]+/ig, '> '
result = result.replace /(> \n)+/g, '> \n'
result
# Add additional html tags to HTML replies:
# * add style block to change the blockquotes styles.
# * make "pre" without background
# * remove margins to "p"
wrapReplyHtml: (html) ->
html = html.replace /<p>/g, '<p style="margin: 0">'
return """
<style type="text/css">
blockquote {
margin: 0.8ex;
padding-left: 1ex;
border-left: 3px solid #34A6FF;
}
p {margin: 0;}
pre {background: transparent; border: 0}
</style>
#{html}
"""
# Add a reply prefix to the current subject. Do not add it again if it's
# already there.
getReplySubject: (inReplyTo) ->
subject = inReplyTo.get('subject') or ''
replyPrefix = t 'compose reply prefix'
if subject.indexOf(replyPrefix) isnt 0
subject = "#{replyPrefix}#{subject}"
subject
# To keep HTML markup light, create the contact tooltip dynamicaly
# on mouse over
# options:
# - container : tooltip container
# - delay : nb of miliseconds to wait before displaying tooltip
# - showOnClick: set to true to display tooltip when clicking on element
tooltip: (node, address, onAdd, options) ->
options ?= {}
timeout = null
doAdd = (e) ->
e.preventDefault()
e.stopPropagation()
onAdd address
addTooltip = (e) ->
if node.dataset.tooltip
return
node.dataset.tooltip = true
contact = ContactStore.getByAddress address.address
avatar = contact?.get 'avatar'
add = ''
image = ''
if contact?
if avatar?
image = "<img class='avatar' src=#{avatar}>"
else
image = "<div class='no-avatar'>?</div>"
image = """
<div class="tooltip-avatar">
<a href="/#apps/contacts/contact/#{contact.get 'id'}" target="blank">
#{image}
</a>
</div>
"""
else
if onAdd?
add = """
<p class="tooltip-toolbar">
<button class="btn btn-cozy btn-add" type="button">
#{t 'contact button label'}
</button>
</p>
"""
template = """
<div class="tooltip" role="tooltip">
<div class="tooltip-arrow"></div>
<div class="tooltip-content">
#{image}
<div>
#{address.name}
#{if address.name then '<br>' else ''}
<#{address.address}>
</div>
#{add}
</div>
</div>'
"""
options =
title: address.address
template: template
trigger: 'manual'
placement: 'auto top'
container: options.container or node.parentNode
jQuery(node).tooltip(options).tooltip('show')
tooltipNode = jQuery(node).data('bs.tooltip').tip()[0]
if parseInt(tooltipNode.style.left, 10) < 0
tooltipNode.style.left = 0
rect = tooltipNode.getBoundingClientRect()
mask = document.createElement 'div'
mask.classList.add 'tooltip-mask'
mask.style.top = (rect.top - 8) + 'px'
mask.style.left = (rect.left - 8) + 'px'
mask.style.height = (rect.height + 32) + 'px'
mask.style.width = (rect.width + 16) + 'px'
document.body.appendChild mask
mask.addEventListener 'mouseout', (e) ->
if not ( rect.left < e.pageX < rect.right) or
not ( rect.top < e.pageY < rect.bottom)
mask.parentNode.removeChild mask
removeTooltip()
if onAdd?
addNode = tooltipNode.querySelector('.btn-add')
if addNode?
addNode.addEventListener 'click', doAdd
removeTooltip = ->
addNode = node.querySelector('.btn-add')
if addNode?
addNode.removeEventListener 'click', doAdd
delete node.dataset.tooltip
jQuery(node).tooltip('destroy')
node.addEventListener 'mouseover', ->
timeout = setTimeout ->
addTooltip()
, options.delay or 1000
node.addEventListener 'mouseout', ->
clearTimeout timeout
if options.showOnClick
node.addEventListener 'click', (event) ->
event.stopPropagation()
addTooltip()
| 131210 | {ComposeActions} = require '../constants/app_constants'
ContactStore = require '../stores/contact_store'
QUOTE_STYLE = "margin-left: 0.8ex; padding-left: 1ex; border-left: 3px solid #34A6FF;"
# Style is required to clean pre and p styling in compose editor.
# It is removed by the visulasation iframe that's why we need to put
# style at the p level too.
COMPOSE_STYLE = """
<style>
pre {background: transparent; border: 0}
</style>
"""
module.exports = MessageUtils =
# Build string showing address from an `adress` object. If a mail is given
# in the `address` object, the string return this:
#
# Sender Name <<EMAIL>>
displayAddress: (address, full = false) ->
if full
if address.name? and address.name isnt ""
return "\"#{address.name}\" <#{address.address}>"
else
return "#{address.address}"
else
if address.name? and address.name isnt ""
return address.name
else
return address.address.split('@')[0]
# Build a string from a list of `adress` objects. Addresses are
# separated by a coma. An address is either the email adress either this:
#
# <NAME> <<EMAIL>>
displayAddresses: (addresses, full = false) ->
if not addresses?
return ""
else
res = []
for item in addresses
if not item?
break
res.push(MessageUtils.displayAddress item, full)
return res.join ", "
# From a text, build an `address` object (name and address).
# Add a isValid field if the given email is well formed.
parseAddress: (text) ->
text = text.trim()
if match = text.match /"{0,1}(.*)"{0,1} <(.*)>/
address =
name: match[1]
address: match[2]
else
address =
address: text.replace(/^\s*/, '')
# Test email validity
emailRe = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
address.isValid = address.address.match emailRe
address
# Extract a reply address from a `message` object.
getReplyToAddress: (message) ->
reply = message.get 'replyTo'
from = message.get 'from'
if (reply? and reply.length isnt 0)
return reply
else
return from
# Add signature at the end of the message
addSignature: (message, signature) ->
message.text += "\n\n-- \n#{signature}"
signatureHtml = signature.replace /\n/g, '<br>'
message.html += """
<p><br></p><p id="signature">-- \n<br>#{signatureHtml}</p>
<p><br></p>
"""
# Build message to put in the email composer depending on the context
# (reply, reply to all, forward or simple message).
# It add appropriate headers to the message. It adds style tags when
# required too.
# It adds signature at the end of the zone where the user will type.
makeReplyMessage: (myAddress, inReplyTo, action, inHTML, signature) ->
message =
composeInHTML: inHTML
attachments: Immutable.Vector.empty()
if inReplyTo
message.accountID = inReplyTo.get 'accountID'
message.conversationID = inReplyTo.get 'conversationID'
dateHuman = @formatReplyDate inReplyTo.get 'createdAt'
sender = @displayAddresses inReplyTo.get 'from'
text = inReplyTo.get 'text'
html = inReplyTo.get 'html'
text = '' unless text? # Some message have no content, only attachements
if text? and not html? and inHTML
try
html = markdown.toHTML text
catch e
console.error "Error converting message to Markdown: #{e}"
html = "<div class='text'>#{text}</div>"
if html? and not text? and not inHTML
text = toMarkdown html
message.inReplyTo = [inReplyTo.get 'id']
message.references = inReplyTo.get('references') or []
message.references = message.references.concat message.inReplyTo
if signature? and signature.length > 0
isSignature = true
else
isSignature = false
options = {
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
}
switch action
when ComposeActions.REPLY
@setMessageAsReply options
when ComposeActions.REPLY_ALL
@setMessageAsReplyAll options
when ComposeActions.FORWARD
@setMessageAsForward options
when null
@setMessageAsDefault options
# remove my address from dests
notMe = (dest) -> return dest.address isnt myAddress
message.to = message.to.filter notMe
message.cc = message.cc.filter notMe
return message
# Build message to display in composer in case of a reply to a message:
# * set subject automatically (Re: previous subject)
# * Set recipient based on sender
# * add a style header for proper display
# * Add quote of the previous message at the beginning of the message
# * adds a signature at the message end.
setMessageAsReply: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
params = date: dateHuman, sender: sender
separator = t 'compose reply separator', params
message.to = @getReplyToAddress inReplyTo
message.cc = []
message.bcc = []
message.subject = @getReplySubject inReplyTo
message.text = separator + @generateReplyText(text) + "\n"
message.html = """
#{COMPOSE_STYLE}
<p><br></p>
"""
if isSignature
@addSignature message, signature
message.html += """
<p>#{separator}<span class="originalToggle"> … </span></p>
<blockquote style="#{QUOTE_STYLE}">#{html}</blockquote>
"""
# Build message to display in composer in case of a reply to all message:
# * set subject automatically (Re: previous subject)
# * Set recipients based on all people set in the conversation.
# * add a style header for proper display
# * Add quote of the previous message at the beginning of the message
# * adds a signature at the message end.
setMessageAsReplyAll: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
params = date: dateHuman, sender: sender
separator = t 'compose reply separator', params
message.to = @getReplyToAddress inReplyTo
# filter to don't have same address twice
toAddresses = message.to.map (dest) -> return dest.address
message.cc = [].concat(
inReplyTo.get('from'),
inReplyTo.get('to'),
inReplyTo.get('cc')
).filter (dest) ->
return dest? and toAddresses.indexOf(dest.address) is -1
message.bcc = []
message.subject = @getReplySubject inReplyTo
message.text = separator + @generateReplyText(text) + "\n"
message.html = """
#{COMPOSE_STYLE}
<p><br></p>
"""
if isSignature
@addSignature message, signature
message.html += """
<p>#{separator}<span class="originalToggle"> … </span></p>
<blockquote style="#{QUOTE_STYLE}">#{html}</blockquote>
<p><br></p>
"""
# Build message to display in composer in case of a message forwarding:
# * set subject automatically (fwd: previous subject)
# * add a style header for proper display
# * Add forward information at the beginning of the message
# We don't add signature here (see Thunderbird behavior)
setMessageAsForward: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
addresses = inReplyTo.get('to')
.map (address) -> address.address
.join ', '
senderInfos = @getReplyToAddress inReplyTo
senderName = ""
senderAddress =
if senderInfos.length > 0
senderName = senderInfos[0].name
senderAddress = senderInfos[0].address
if senderName.length > 0
fromField = "#{senderName} <#{senderAddress}>"
else
fromField = senderAddress
separator = """
----- #{t 'compose forward header'} ------
#{t 'compose forward subject'} #{inReplyTo.get 'subject'}
#{t 'compose forward date'} #{dateHuman}
#{t 'compose forward from'} #{fromField}
#{t 'compose forward to'} #{addresses}
"""
textSeparator = separator.replace('<', '<').replace('>', '>')
textSeparator = textSeparator.replace('<pre>', '').replace('</pre>', '')
htmlSeparator = separator.replace /(\n)+/g, '<br>'
@setMessageAsDefault options
message.subject = """
#{t 'compose forward prefix'}#{inReplyTo.get 'subject'}
"""
message.text = textSeparator + text
message.html = "#{COMPOSE_STYLE}"
if isSignature
@addSignature message, signature
message.html += """
<p>#{htmlSeparator}</p><p><br></p>#{html}
"""
message.attachments = inReplyTo.get 'attachments'
return message
# Clear all fields of the message object.
# Add signature if given.
setMessageAsDefault: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
message.to = []
message.cc = []
message.bcc = []
message.subject = ''
message.text = ''
message.html = "#{COMPOSE_STYLE}\n<p><br></p>"
if isSignature
@addSignature message, signature
return message
# Generate reply text by adding `>` before each line of the given text.
generateReplyText: (text) ->
text = text.split '\n'
res = []
text.forEach (line) ->
res.push "> #{line}"
return res.join "\n"
# Guess simple attachment type from mime type.
getAttachmentType: (type) ->
return null unless type
sub = type.split '/'
switch sub[0]
when 'audio', 'image', 'text', 'video'
return sub[0]
when "application"
switch sub[1]
when "vnd.ms-excel",\
"vnd.oasis.opendocument.spreadsheet",\
"vnd.openxmlformats-officedocument.spreadsheetml.sheet"
return "spreadsheet"
when "msword",\
"vnd.ms-word",\
"vnd.oasis.opendocument.text",\
"vnd.openxmlformats-officedocument.wordprocessingm" + \
"l.document"
return "word"
when "vns.ms-powerpoint",\
"vnd.oasis.opendocument.presentation",\
"vnd.openxmlformats-officedocument.presentationml." + \
"presentation"
return "presentation"
when "pdf" then return sub[1]
when "gzip", "zip" then return 'archive'
# Format date to a conventional format for reply headers.
formatReplyDate: (date) ->
date = moment() unless date?
date = moment date
date.format 'lll'
# Display date as a readable string.
# Make it shorter if compact is set to true.
formatDate: (date, compact) ->
unless date?
return null
else
today = moment()
date = moment date
if date.isBefore today, 'year'
formatter = 'DD/MM/YYYY'
else if date.isBefore today, 'day'
if compact? and compact
formatter = 'L'
else
formatter = 'MMM DD'
else
formatter = 'HH:mm'
return date.format formatter
# Return avatar corresponding to sender by matching his email address with
# addresses from existing contacts.
getAvatar: (message) ->
if message.get('from')[0]?
return ContactStore.getAvatar message.get('from')[0].address
else
return null
# Remove from given string:
# * html tags
# * extra spaces between reply markers and text
# * empty reply lines
cleanReplyText: (html) ->
# Convert HTML to markdown
try
result = html.replace /<(style>)[^\1]*\1/gim, ''
result = toMarkdown result
catch
if html?
result = html.replace /<(style>)[^\1]*\1/gim, ''
result = html.replace /<[^>]*>/gi, ''
# convert HTML entities
tmp = document.createElement 'div'
tmp.innerHTML = result
result = tmp.textContent
# Make citation more human readable.
result = result.replace />[ \t]+/ig, '> '
result = result.replace /(> \n)+/g, '> \n'
result
# Add additional html tags to HTML replies:
# * add style block to change the blockquotes styles.
# * make "pre" without background
# * remove margins to "p"
wrapReplyHtml: (html) ->
html = html.replace /<p>/g, '<p style="margin: 0">'
return """
<style type="text/css">
blockquote {
margin: 0.8ex;
padding-left: 1ex;
border-left: 3px solid #34A6FF;
}
p {margin: 0;}
pre {background: transparent; border: 0}
</style>
#{html}
"""
# Add a reply prefix to the current subject. Do not add it again if it's
# already there.
getReplySubject: (inReplyTo) ->
subject = inReplyTo.get('subject') or ''
replyPrefix = t 'compose reply prefix'
if subject.indexOf(replyPrefix) isnt 0
subject = "#{replyPrefix}#{subject}"
subject
# To keep HTML markup light, create the contact tooltip dynamicaly
# on mouse over
# options:
# - container : tooltip container
# - delay : nb of miliseconds to wait before displaying tooltip
# - showOnClick: set to true to display tooltip when clicking on element
tooltip: (node, address, onAdd, options) ->
options ?= {}
timeout = null
doAdd = (e) ->
e.preventDefault()
e.stopPropagation()
onAdd address
addTooltip = (e) ->
if node.dataset.tooltip
return
node.dataset.tooltip = true
contact = ContactStore.getByAddress address.address
avatar = contact?.get 'avatar'
add = ''
image = ''
if contact?
if avatar?
image = "<img class='avatar' src=#{avatar}>"
else
image = "<div class='no-avatar'>?</div>"
image = """
<div class="tooltip-avatar">
<a href="/#apps/contacts/contact/#{contact.get 'id'}" target="blank">
#{image}
</a>
</div>
"""
else
if onAdd?
add = """
<p class="tooltip-toolbar">
<button class="btn btn-cozy btn-add" type="button">
#{t 'contact button label'}
</button>
</p>
"""
template = """
<div class="tooltip" role="tooltip">
<div class="tooltip-arrow"></div>
<div class="tooltip-content">
#{image}
<div>
#{address.name}
#{if address.name then '<br>' else ''}
<#{address.address}>
</div>
#{add}
</div>
</div>'
"""
options =
title: address.address
template: template
trigger: 'manual'
placement: 'auto top'
container: options.container or node.parentNode
jQuery(node).tooltip(options).tooltip('show')
tooltipNode = jQuery(node).data('bs.tooltip').tip()[0]
if parseInt(tooltipNode.style.left, 10) < 0
tooltipNode.style.left = 0
rect = tooltipNode.getBoundingClientRect()
mask = document.createElement 'div'
mask.classList.add 'tooltip-mask'
mask.style.top = (rect.top - 8) + 'px'
mask.style.left = (rect.left - 8) + 'px'
mask.style.height = (rect.height + 32) + 'px'
mask.style.width = (rect.width + 16) + 'px'
document.body.appendChild mask
mask.addEventListener 'mouseout', (e) ->
if not ( rect.left < e.pageX < rect.right) or
not ( rect.top < e.pageY < rect.bottom)
mask.parentNode.removeChild mask
removeTooltip()
if onAdd?
addNode = tooltipNode.querySelector('.btn-add')
if addNode?
addNode.addEventListener 'click', doAdd
removeTooltip = ->
addNode = node.querySelector('.btn-add')
if addNode?
addNode.removeEventListener 'click', doAdd
delete node.dataset.tooltip
jQuery(node).tooltip('destroy')
node.addEventListener 'mouseover', ->
timeout = setTimeout ->
addTooltip()
, options.delay or 1000
node.addEventListener 'mouseout', ->
clearTimeout timeout
if options.showOnClick
node.addEventListener 'click', (event) ->
event.stopPropagation()
addTooltip()
| true | {ComposeActions} = require '../constants/app_constants'
ContactStore = require '../stores/contact_store'
QUOTE_STYLE = "margin-left: 0.8ex; padding-left: 1ex; border-left: 3px solid #34A6FF;"
# Style is required to clean pre and p styling in compose editor.
# It is removed by the visulasation iframe that's why we need to put
# style at the p level too.
COMPOSE_STYLE = """
<style>
pre {background: transparent; border: 0}
</style>
"""
module.exports = MessageUtils =
# Build string showing address from an `adress` object. If a mail is given
# in the `address` object, the string return this:
#
# Sender Name <PI:EMAIL:<EMAIL>END_PI>
displayAddress: (address, full = false) ->
if full
if address.name? and address.name isnt ""
return "\"#{address.name}\" <#{address.address}>"
else
return "#{address.address}"
else
if address.name? and address.name isnt ""
return address.name
else
return address.address.split('@')[0]
# Build a string from a list of `adress` objects. Addresses are
# separated by a coma. An address is either the email adress either this:
#
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
displayAddresses: (addresses, full = false) ->
if not addresses?
return ""
else
res = []
for item in addresses
if not item?
break
res.push(MessageUtils.displayAddress item, full)
return res.join ", "
# From a text, build an `address` object (name and address).
# Add a isValid field if the given email is well formed.
parseAddress: (text) ->
text = text.trim()
if match = text.match /"{0,1}(.*)"{0,1} <(.*)>/
address =
name: match[1]
address: match[2]
else
address =
address: text.replace(/^\s*/, '')
# Test email validity
emailRe = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
address.isValid = address.address.match emailRe
address
# Extract a reply address from a `message` object.
getReplyToAddress: (message) ->
reply = message.get 'replyTo'
from = message.get 'from'
if (reply? and reply.length isnt 0)
return reply
else
return from
# Add signature at the end of the message
addSignature: (message, signature) ->
message.text += "\n\n-- \n#{signature}"
signatureHtml = signature.replace /\n/g, '<br>'
message.html += """
<p><br></p><p id="signature">-- \n<br>#{signatureHtml}</p>
<p><br></p>
"""
# Build message to put in the email composer depending on the context
# (reply, reply to all, forward or simple message).
# It add appropriate headers to the message. It adds style tags when
# required too.
# It adds signature at the end of the zone where the user will type.
makeReplyMessage: (myAddress, inReplyTo, action, inHTML, signature) ->
message =
composeInHTML: inHTML
attachments: Immutable.Vector.empty()
if inReplyTo
message.accountID = inReplyTo.get 'accountID'
message.conversationID = inReplyTo.get 'conversationID'
dateHuman = @formatReplyDate inReplyTo.get 'createdAt'
sender = @displayAddresses inReplyTo.get 'from'
text = inReplyTo.get 'text'
html = inReplyTo.get 'html'
text = '' unless text? # Some message have no content, only attachements
if text? and not html? and inHTML
try
html = markdown.toHTML text
catch e
console.error "Error converting message to Markdown: #{e}"
html = "<div class='text'>#{text}</div>"
if html? and not text? and not inHTML
text = toMarkdown html
message.inReplyTo = [inReplyTo.get 'id']
message.references = inReplyTo.get('references') or []
message.references = message.references.concat message.inReplyTo
if signature? and signature.length > 0
isSignature = true
else
isSignature = false
options = {
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
}
switch action
when ComposeActions.REPLY
@setMessageAsReply options
when ComposeActions.REPLY_ALL
@setMessageAsReplyAll options
when ComposeActions.FORWARD
@setMessageAsForward options
when null
@setMessageAsDefault options
# remove my address from dests
notMe = (dest) -> return dest.address isnt myAddress
message.to = message.to.filter notMe
message.cc = message.cc.filter notMe
return message
# Build message to display in composer in case of a reply to a message:
# * set subject automatically (Re: previous subject)
# * Set recipient based on sender
# * add a style header for proper display
# * Add quote of the previous message at the beginning of the message
# * adds a signature at the message end.
setMessageAsReply: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
params = date: dateHuman, sender: sender
separator = t 'compose reply separator', params
message.to = @getReplyToAddress inReplyTo
message.cc = []
message.bcc = []
message.subject = @getReplySubject inReplyTo
message.text = separator + @generateReplyText(text) + "\n"
message.html = """
#{COMPOSE_STYLE}
<p><br></p>
"""
if isSignature
@addSignature message, signature
message.html += """
<p>#{separator}<span class="originalToggle"> … </span></p>
<blockquote style="#{QUOTE_STYLE}">#{html}</blockquote>
"""
# Build message to display in composer in case of a reply to all message:
# * set subject automatically (Re: previous subject)
# * Set recipients based on all people set in the conversation.
# * add a style header for proper display
# * Add quote of the previous message at the beginning of the message
# * adds a signature at the message end.
setMessageAsReplyAll: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
params = date: dateHuman, sender: sender
separator = t 'compose reply separator', params
message.to = @getReplyToAddress inReplyTo
# filter to don't have same address twice
toAddresses = message.to.map (dest) -> return dest.address
message.cc = [].concat(
inReplyTo.get('from'),
inReplyTo.get('to'),
inReplyTo.get('cc')
).filter (dest) ->
return dest? and toAddresses.indexOf(dest.address) is -1
message.bcc = []
message.subject = @getReplySubject inReplyTo
message.text = separator + @generateReplyText(text) + "\n"
message.html = """
#{COMPOSE_STYLE}
<p><br></p>
"""
if isSignature
@addSignature message, signature
message.html += """
<p>#{separator}<span class="originalToggle"> … </span></p>
<blockquote style="#{QUOTE_STYLE}">#{html}</blockquote>
<p><br></p>
"""
# Build message to display in composer in case of a message forwarding:
# * set subject automatically (fwd: previous subject)
# * add a style header for proper display
# * Add forward information at the beginning of the message
# We don't add signature here (see Thunderbird behavior)
setMessageAsForward: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
addresses = inReplyTo.get('to')
.map (address) -> address.address
.join ', '
senderInfos = @getReplyToAddress inReplyTo
senderName = ""
senderAddress =
if senderInfos.length > 0
senderName = senderInfos[0].name
senderAddress = senderInfos[0].address
if senderName.length > 0
fromField = "#{senderName} <#{senderAddress}>"
else
fromField = senderAddress
separator = """
----- #{t 'compose forward header'} ------
#{t 'compose forward subject'} #{inReplyTo.get 'subject'}
#{t 'compose forward date'} #{dateHuman}
#{t 'compose forward from'} #{fromField}
#{t 'compose forward to'} #{addresses}
"""
textSeparator = separator.replace('<', '<').replace('>', '>')
textSeparator = textSeparator.replace('<pre>', '').replace('</pre>', '')
htmlSeparator = separator.replace /(\n)+/g, '<br>'
@setMessageAsDefault options
message.subject = """
#{t 'compose forward prefix'}#{inReplyTo.get 'subject'}
"""
message.text = textSeparator + text
message.html = "#{COMPOSE_STYLE}"
if isSignature
@addSignature message, signature
message.html += """
<p>#{htmlSeparator}</p><p><br></p>#{html}
"""
message.attachments = inReplyTo.get 'attachments'
return message
# Clear all fields of the message object.
# Add signature if given.
setMessageAsDefault: (options) ->
{
message
inReplyTo
dateHuman
sender
text
html
signature
isSignature
} = options
message.to = []
message.cc = []
message.bcc = []
message.subject = ''
message.text = ''
message.html = "#{COMPOSE_STYLE}\n<p><br></p>"
if isSignature
@addSignature message, signature
return message
# Generate reply text by adding `>` before each line of the given text.
generateReplyText: (text) ->
text = text.split '\n'
res = []
text.forEach (line) ->
res.push "> #{line}"
return res.join "\n"
# Guess simple attachment type from mime type.
getAttachmentType: (type) ->
return null unless type
sub = type.split '/'
switch sub[0]
when 'audio', 'image', 'text', 'video'
return sub[0]
when "application"
switch sub[1]
when "vnd.ms-excel",\
"vnd.oasis.opendocument.spreadsheet",\
"vnd.openxmlformats-officedocument.spreadsheetml.sheet"
return "spreadsheet"
when "msword",\
"vnd.ms-word",\
"vnd.oasis.opendocument.text",\
"vnd.openxmlformats-officedocument.wordprocessingm" + \
"l.document"
return "word"
when "vns.ms-powerpoint",\
"vnd.oasis.opendocument.presentation",\
"vnd.openxmlformats-officedocument.presentationml." + \
"presentation"
return "presentation"
when "pdf" then return sub[1]
when "gzip", "zip" then return 'archive'
# Format date to a conventional format for reply headers.
formatReplyDate: (date) ->
date = moment() unless date?
date = moment date
date.format 'lll'
# Display date as a readable string.
# Make it shorter if compact is set to true.
formatDate: (date, compact) ->
unless date?
return null
else
today = moment()
date = moment date
if date.isBefore today, 'year'
formatter = 'DD/MM/YYYY'
else if date.isBefore today, 'day'
if compact? and compact
formatter = 'L'
else
formatter = 'MMM DD'
else
formatter = 'HH:mm'
return date.format formatter
# Return avatar corresponding to sender by matching his email address with
# addresses from existing contacts.
getAvatar: (message) ->
if message.get('from')[0]?
return ContactStore.getAvatar message.get('from')[0].address
else
return null
# Remove from given string:
# * html tags
# * extra spaces between reply markers and text
# * empty reply lines
cleanReplyText: (html) ->
# Convert HTML to markdown
try
result = html.replace /<(style>)[^\1]*\1/gim, ''
result = toMarkdown result
catch
if html?
result = html.replace /<(style>)[^\1]*\1/gim, ''
result = html.replace /<[^>]*>/gi, ''
# convert HTML entities
tmp = document.createElement 'div'
tmp.innerHTML = result
result = tmp.textContent
# Make citation more human readable.
result = result.replace />[ \t]+/ig, '> '
result = result.replace /(> \n)+/g, '> \n'
result
# Add additional html tags to HTML replies:
# * add style block to change the blockquotes styles.
# * make "pre" without background
# * remove margins to "p"
wrapReplyHtml: (html) ->
html = html.replace /<p>/g, '<p style="margin: 0">'
return """
<style type="text/css">
blockquote {
margin: 0.8ex;
padding-left: 1ex;
border-left: 3px solid #34A6FF;
}
p {margin: 0;}
pre {background: transparent; border: 0}
</style>
#{html}
"""
# Add a reply prefix to the current subject. Do not add it again if it's
# already there.
getReplySubject: (inReplyTo) ->
subject = inReplyTo.get('subject') or ''
replyPrefix = t 'compose reply prefix'
if subject.indexOf(replyPrefix) isnt 0
subject = "#{replyPrefix}#{subject}"
subject
# To keep HTML markup light, create the contact tooltip dynamicaly
# on mouse over
# options:
# - container : tooltip container
# - delay : nb of miliseconds to wait before displaying tooltip
# - showOnClick: set to true to display tooltip when clicking on element
tooltip: (node, address, onAdd, options) ->
options ?= {}
timeout = null
doAdd = (e) ->
e.preventDefault()
e.stopPropagation()
onAdd address
addTooltip = (e) ->
if node.dataset.tooltip
return
node.dataset.tooltip = true
contact = ContactStore.getByAddress address.address
avatar = contact?.get 'avatar'
add = ''
image = ''
if contact?
if avatar?
image = "<img class='avatar' src=#{avatar}>"
else
image = "<div class='no-avatar'>?</div>"
image = """
<div class="tooltip-avatar">
<a href="/#apps/contacts/contact/#{contact.get 'id'}" target="blank">
#{image}
</a>
</div>
"""
else
if onAdd?
add = """
<p class="tooltip-toolbar">
<button class="btn btn-cozy btn-add" type="button">
#{t 'contact button label'}
</button>
</p>
"""
template = """
<div class="tooltip" role="tooltip">
<div class="tooltip-arrow"></div>
<div class="tooltip-content">
#{image}
<div>
#{address.name}
#{if address.name then '<br>' else ''}
<#{address.address}>
</div>
#{add}
</div>
</div>'
"""
options =
title: address.address
template: template
trigger: 'manual'
placement: 'auto top'
container: options.container or node.parentNode
jQuery(node).tooltip(options).tooltip('show')
tooltipNode = jQuery(node).data('bs.tooltip').tip()[0]
if parseInt(tooltipNode.style.left, 10) < 0
tooltipNode.style.left = 0
rect = tooltipNode.getBoundingClientRect()
mask = document.createElement 'div'
mask.classList.add 'tooltip-mask'
mask.style.top = (rect.top - 8) + 'px'
mask.style.left = (rect.left - 8) + 'px'
mask.style.height = (rect.height + 32) + 'px'
mask.style.width = (rect.width + 16) + 'px'
document.body.appendChild mask
mask.addEventListener 'mouseout', (e) ->
if not ( rect.left < e.pageX < rect.right) or
not ( rect.top < e.pageY < rect.bottom)
mask.parentNode.removeChild mask
removeTooltip()
if onAdd?
addNode = tooltipNode.querySelector('.btn-add')
if addNode?
addNode.addEventListener 'click', doAdd
removeTooltip = ->
addNode = node.querySelector('.btn-add')
if addNode?
addNode.removeEventListener 'click', doAdd
delete node.dataset.tooltip
jQuery(node).tooltip('destroy')
node.addEventListener 'mouseover', ->
timeout = setTimeout ->
addTooltip()
, options.delay or 1000
node.addEventListener 'mouseout', ->
clearTimeout timeout
if options.showOnClick
node.addEventListener 'click', (event) ->
event.stopPropagation()
addTooltip()
|
[
{
"context": "uide: true\n \"exception-reporting\":\n userId: \"3a901ed7-702f-439b-a3e8-aa196721c2be\"\n \"package-sync\":\n createOnChange: true\n f",
"end": 286,
"score": 0.6650506854057312,
"start": 251,
"tag": "PASSWORD",
"value": "a901ed7-702f-439b-a3e8-aa196721c2be"
}
] | .atom/config.cson | mrlesmithjr/dotfiles | 17 | "*":
core:
telemetryConsent: "no"
themes: [
"dracula-ui"
"dracula-syntax"
]
editor:
autoIndentOnPaste: false
fontFamily: "Fira Code"
fontSize: 18
showIndentGuide: true
"exception-reporting":
userId: "3a901ed7-702f-439b-a3e8-aa196721c2be"
"package-sync":
createOnChange: true
forceOverwrite: true
welcome:
showOnStartup: false
| 143225 | "*":
core:
telemetryConsent: "no"
themes: [
"dracula-ui"
"dracula-syntax"
]
editor:
autoIndentOnPaste: false
fontFamily: "Fira Code"
fontSize: 18
showIndentGuide: true
"exception-reporting":
userId: "3<PASSWORD>"
"package-sync":
createOnChange: true
forceOverwrite: true
welcome:
showOnStartup: false
| true | "*":
core:
telemetryConsent: "no"
themes: [
"dracula-ui"
"dracula-syntax"
]
editor:
autoIndentOnPaste: false
fontFamily: "Fira Code"
fontSize: 18
showIndentGuide: true
"exception-reporting":
userId: "3PI:PASSWORD:<PASSWORD>END_PI"
"package-sync":
createOnChange: true
forceOverwrite: true
welcome:
showOnStartup: false
|
[
{
"context": " ->\n setting =\n key: 'loginWithFacebook'\n value: true\n app.mo",
"end": 9523,
"score": 0.9974769949913025,
"start": 9506,
"tag": "KEY",
"value": "loginWithFacebook"
},
{
"context": "->\n setting1 =\... | test/unit/server/mocha/authentication/index.coffee | valueflowquality/gi-security-update | 0 | expect = require('chai').expect
sinon = require 'sinon'
proxyquire = require 'proxyquire'
path = require 'path'
permissionFilter = require './permissionFilter'
module.exports = () ->
describe 'Authentication', ->
describe 'Public', ->
dir = path.normalize __dirname + '../../../../../../server'
permissionsMiddlewareSpy = sinon.spy()
basic =
routes: sinon.spy()
facebook =
routes: sinon.spy()
passport =
initialize: () ->
return 'passport-initialize'
session: () ->
return 'passport-session'
stubs =
'./permissionFilter': sinon.stub().returns permissionsMiddlewareSpy
'./hmac': sinon.spy()
'./play': sinon.spy()
'./basic': sinon.stub().returns basic
'./facebook': sinon.stub().returns facebook
'passport': passport
authenticationModule = proxyquire dir + '/authentication', stubs
app =
use: sinon.spy()
get: sinon.spy()
post: ->
router: 'app-router'
models:
users: 'users'
environments:
forHost: ->
settings:
get: ->
afterEach (done) ->
permissionsMiddlewareSpy.reset()
done()
it 'Exports a factory function', (done) ->
expect(authenticationModule).to.be.a('function')
done()
describe 'Factory Function: (app, options) -> { middleware }', ->
authentication = authenticationModule app, {}
describe 'Initialisation', (done) ->
it 'Uses permissionFilter', (done) ->
expect(stubs['./permissionFilter'].calledWithExactly(app))
.to.be.true
done()
it 'requires basic authenticaion', (done) ->
expect(stubs['./basic'].callCount).to.equal 1
expect(stubs['./basic'].calledWithExactly app.models.users)
.to.be.true
done()
it 'requires facebook authenticaion', (done) ->
expect(stubs['./facebook'].callCount).to.equal 1
expect(stubs['./facebook'].calledWithExactly app.models.users)
.to.be.true
done()
it 'requires hmac authenticaion', (done) ->
expect(stubs['./hmac'].callCount).to.equal 1
expect(stubs['./hmac'].calledWithExactly app.models.users)
.to.be.true
done()
it 'requires play authenticaion', (done) ->
expect(stubs['./play'].callCount).to.equal 1
expect(stubs['./play'].calledWithExactly app.models.users)
.to.be.true
done()
it 'makes the app use passport intialize', (done) ->
expect(app.use.getCall(0).args[0]).to.equal 'passport-initialize'
done()
it 'makes the app use passport session', (done) ->
expect(app.use.getCall(1).args[0]).to.equal 'passport-session'
done()
it 'makes the app use the apps router', (done) ->
expect(app.use.calledWith app.router).to.be.true
done()
it 'creates an api route for logout', (done) ->
expect(app.get.calledWith '/api/logout', sinon.match.func)
.to.be.true
done()
it 'configures the routes defined in basic strategy', (done) ->
expect(basic.routes.calledWith app, sinon.match.func)
.to.be.true
done()
it 'configures the routes defined in facebook stratgegy', (done) ->
expect(facebook.routes.calledWith app, sinon.match.func)
.to.be.true
done()
describe 'Public Exports (Connect Middleware)', ->
it 'userAction', (done) ->
expect(authentication).to.have.ownProperty 'userAction'
expect(authentication.userAction).to.be.a 'function'
done()
it 'publicAction', (done) ->
expect(authentication).to.have.ownProperty 'publicAction'
expect(authentication.publicAction).to.be.a 'function'
done()
it 'adminAction', (done) ->
expect(authentication).to.have.ownProperty 'adminAction'
expect(authentication.adminAction).to.be.a 'function'
done()
it 'sysAdminAction', (done) ->
expect(authentication).to.have.ownProperty 'sysAdminAction'
expect(authentication.sysAdminAction).to.be.a 'function'
done()
describe 'publicAction: Function(req, res, next) -> void', ->
beforeEach (done) ->
sinon.stub authentication, '_systemCheck'
done()
afterEach (done) ->
authentication._systemCheck.restore()
done()
it 'passes args through systemCheck', (done) ->
authentication.publicAction {a: 'b'}, {c : 'd'}, {e: 'f'}
expect(authentication._systemCheck.calledWithExactly(
{a: 'b'}, {c : 'd'}, {e: 'f'}
)).to.be.true
done()
describe 'userAction: Function(req, res, next) -> void', ->
req = {}
res =
json: ->
beforeEach (done) ->
sinon.stub authentication, 'publicAction'
done()
afterEach (done) ->
authentication.publicAction.restore()
done()
it 'passes args through publicAction', (done) ->
req.user = {}
res =
json: sinon.spy()
authentication.publicAction.callsArg 2
authentication.userAction req, {a: 'b'}, {c : 'd'}
expect(authentication.publicAction.calledWith(
req, {a: 'b'}
)).to.be.true
done()
it 'passes to permissionsMiddleware if req has a user'
, (done) ->
req.user = {}
authentication.publicAction.callsArg 2
authentication.userAction req, {a: 'b'}, {c: 'd'}
expect(permissionsMiddlewareSpy.calledWithExactly(
req, {a: 'b'}, {c: 'd'})).to.be.true
done()
it 'calls res.json if req has no user' +
' an error', (done) ->
req.user = null
res =
json: sinon.spy()
authentication.publicAction.callsArg 2
, {user: 'object'}
authentication.userAction req, res, {c: 'd'}
expect(permissionsMiddlewareSpy.called).to.be.false
expect(res.json.calledWith 401, {}).to.be.true
done()
describe 'Private Functions', ->
it '_getSystemStrategies', (done) ->
expect(authentication).to.have.ownProperty '_getSystemStrategies'
expect(authentication._getSystemStrategies).to.be.a 'function'
done()
it '_systemCheck', (done) ->
expect(authentication).to.have.ownProperty '_systemCheck'
expect(authentication._systemCheck).to.be.a 'function'
done()
it '_hmacAuth', (done) ->
expect(authentication).to.have.ownProperty '_hmacAuth'
expect(authentication._hmacAuth).to.be.a 'function'
done()
it '_playAuth', (done) ->
expect(authentication).to.have.ownProperty '_playAuth'
expect(authentication._playAuth).to.be.a 'function'
done()
describe '_getSystemStrategies: Function(req, done) -> void', ->
req =
systemId: "a sys id"
environmentId: "an env id"
beforeEach (done) ->
sinon.stub app.models.settings, 'get'
done()
afterEach (done) ->
app.models.settings.get.restore()
done()
it 'gets login with Facebook setting', (done) ->
authentication._getSystemStrategies req, "done"
expect(
app.models.settings.get.calledWith 'loginWithFacebook'
, req.systemId
, req.environmentId
, sinon.match.func
).to.be.true
done()
it 'gets login with Hmac setting', (done) ->
authentication._getSystemStrategies req, "done"
expect(
app.models.settings.get.calledWith 'loginWithHmac'
, req.systemId
, req.environmentId
, sinon.match.func
).to.be.true
done()
it 'gets login with Play setting', (done) ->
authentication._getSystemStrategies req, "done"
expect(
app.models.settings.get.calledWith 'loginWithPlay'
, req.systemId
, req.environmentId
, sinon.match.func
).to.be.true
done()
it 'supresses any errors', (done) ->
app.models.settings.get.callsArgWith 3, "an error", null
authentication._getSystemStrategies req, (err, result) ->
expect(err).to.not.exist
expect(result).to.exist
expect(result.length).to.equal 0
done()
it 'calls back with the result', (done) ->
setting =
key: 'loginWithFacebook'
value: true
app.models.settings.get.callsArgWith 3, null, setting
authentication._getSystemStrategies req, (err, result) ->
expect(result[0]).to.equal 'facebook'
expect(result[1]).to.equal 'Hmac'
expect(result[2]).to.equal 'Play'
expect(err).to.not.exist
done()
it 'omits false settings from result', (done) ->
setting1 =
key: 'loginWithFacebook'
value: false
setting2 =
key: 'loginWithHmac'
value: true
setting3 =
key: 'loginWithPlay'
value: true
app.models.settings.get.callsArgWith 3, null, setting1
app.models.settings.get.callsArgWith 3, null, setting2
app.models.settings.get.callsArgWith 3, null, setting3
authentication._getSystemStrategies req, (err, result) ->
expect(result.length).to.equal 2
expect(result[0]).to.equal 'Hmac'
expect(result[1]).to.equal 'Play'
expect(err).to.not.exist
done()
it 'omits missing settings from result', (done) ->
setting1 =
key: 'loginWithFacebook'
value: true
setting3 =
key: 'loginWithPlay'
value: false
app.models.settings.get.callsArgWith 3, null, setting1
app.models.settings.get.callsArgWith 3, "setting not found", null
app.models.settings.get.callsArgWith 3, null, setting3
authentication._getSystemStrategies req, (err, result) ->
expect(result.length).to.equal 1
expect(result[0]).to.equal 'facebook'
expect(err).to.not.exist
done()
describe '_systemCheck: Function(req, res, next) -> void', ->
req = null
res = null
environment = null
beforeEach (done) ->
req =
host: 'test.gi-security.com'
isAuthenticated: () ->
true
res =
json: sinon.spy()
environment =
_id: "an environment Id"
systemId: "a systemId"
sinon.stub app.models.environments, 'forHost'
sinon.stub authentication, '_getSystemStrategies'
sinon.stub authentication, '_findUser'
done()
afterEach ->
app.models.environments.forHost.restore()
authentication._getSystemStrategies.restore()
authentication._findUser.restore()
it 'returns 500 error if no request', (done) ->
authentication._systemCheck null, res, null
expect(res.json.calledWith 500
, {message: 'host not found on request object'}
).to.be.true
done()
it 'returns 500 error if no request.host', (done) ->
req = {}
authentication._systemCheck req, res, null
expect(res.json.calledWith 500
, {message: 'host not found on request object'}
).to.be.true
done()
it 'tries to find an environment matching the host', (done) ->
authentication._systemCheck req, res, null
expect(app.models.environments.forHost.calledWith req.host
, sinon.match.func
).to.be.true
done()
it 'returns a 500 error and a message if this fails', (done) ->
app.models.environments.forHost.callsArgWith 1, "an error", null
authentication._systemCheck req, res, null
expect(res.json.calledWith 500
, {message: "an error"}
).to.be.true
done()
it 'returns not found if no environment', (done) ->
app.models.environments.forHost.callsArgWith 1, null, null
authentication._systemCheck req, res, null
expect(res.json.calledWith 404
, {message: "environment not found"}
).to.be.true
done()
it 'sets systemId on request if env found', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._systemCheck req, res, null
expect(req.systemId).to.equal environment.systemId
done()
it 'sets environmentId on request if env found', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._systemCheck req, res, null
expect(req.environmentId).to.equal environment._id
done()
it 'gets systemStrategies', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._systemCheck req, res, null
expect(authentication._getSystemStrategies.called).to.be.true
reqArg = authentication._getSystemStrategies.getCall(0).args[0]
expect(reqArg.systemId).to.equal environment.systemId
expect(reqArg.environmentId).to.equal environment._id
expect(reqArg).to.deep.equal req
done()
it 'does not set req.strategies if _getSystemStrategies errors'
, (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._findUser.callsArg 2
authentication._getSystemStrategies.callsArgWith 1
, "an error", {some: 'thing'}
authentication._systemCheck req, res, ->
expect(req.strategies).to.not.exist
done()
it 'does not set req.strategies if _getSystemStrategies is null'
, (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._getSystemStrategies.callsArgWith 1
authentication._findUser.callsArg 2
authentication._systemCheck req, res, ->
expect(req.strategies).to.not.exist
done()
it 'sets req.strategies otherwise', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._getSystemStrategies.callsArgWith 1
, null, 'something'
authentication._findUser.callsArg 2
authentication._systemCheck req, res, ->
expect(req.strategies).to.equal 'something'
done()
describe '_hmacAuth: Function(req, res, next) -> void', ->
req =
strategies: ['some other strategy']
it 'Checks if Hmac is a supported strategy', (done) ->
authentication._hmacAuth req, null, (err, result) ->
expect(err).to.equal 'Hmac strategy not supported'
expect(result).to.not.exist
done()
describe '_playAuth: Function(req, res, next) -> void', ->
req =
strategies: ['some other strategy']
it 'Checks if Play is a supported strategy', (done) ->
authentication._playAuth req, null, (err, result) ->
expect(err).to.equal 'Play strategy not supported'
expect(result).to.not.exist
done()
describe 'Private', ->
permissionFilter() | 124186 | expect = require('chai').expect
sinon = require 'sinon'
proxyquire = require 'proxyquire'
path = require 'path'
permissionFilter = require './permissionFilter'
module.exports = () ->
describe 'Authentication', ->
describe 'Public', ->
dir = path.normalize __dirname + '../../../../../../server'
permissionsMiddlewareSpy = sinon.spy()
basic =
routes: sinon.spy()
facebook =
routes: sinon.spy()
passport =
initialize: () ->
return 'passport-initialize'
session: () ->
return 'passport-session'
stubs =
'./permissionFilter': sinon.stub().returns permissionsMiddlewareSpy
'./hmac': sinon.spy()
'./play': sinon.spy()
'./basic': sinon.stub().returns basic
'./facebook': sinon.stub().returns facebook
'passport': passport
authenticationModule = proxyquire dir + '/authentication', stubs
app =
use: sinon.spy()
get: sinon.spy()
post: ->
router: 'app-router'
models:
users: 'users'
environments:
forHost: ->
settings:
get: ->
afterEach (done) ->
permissionsMiddlewareSpy.reset()
done()
it 'Exports a factory function', (done) ->
expect(authenticationModule).to.be.a('function')
done()
describe 'Factory Function: (app, options) -> { middleware }', ->
authentication = authenticationModule app, {}
describe 'Initialisation', (done) ->
it 'Uses permissionFilter', (done) ->
expect(stubs['./permissionFilter'].calledWithExactly(app))
.to.be.true
done()
it 'requires basic authenticaion', (done) ->
expect(stubs['./basic'].callCount).to.equal 1
expect(stubs['./basic'].calledWithExactly app.models.users)
.to.be.true
done()
it 'requires facebook authenticaion', (done) ->
expect(stubs['./facebook'].callCount).to.equal 1
expect(stubs['./facebook'].calledWithExactly app.models.users)
.to.be.true
done()
it 'requires hmac authenticaion', (done) ->
expect(stubs['./hmac'].callCount).to.equal 1
expect(stubs['./hmac'].calledWithExactly app.models.users)
.to.be.true
done()
it 'requires play authenticaion', (done) ->
expect(stubs['./play'].callCount).to.equal 1
expect(stubs['./play'].calledWithExactly app.models.users)
.to.be.true
done()
it 'makes the app use passport intialize', (done) ->
expect(app.use.getCall(0).args[0]).to.equal 'passport-initialize'
done()
it 'makes the app use passport session', (done) ->
expect(app.use.getCall(1).args[0]).to.equal 'passport-session'
done()
it 'makes the app use the apps router', (done) ->
expect(app.use.calledWith app.router).to.be.true
done()
it 'creates an api route for logout', (done) ->
expect(app.get.calledWith '/api/logout', sinon.match.func)
.to.be.true
done()
it 'configures the routes defined in basic strategy', (done) ->
expect(basic.routes.calledWith app, sinon.match.func)
.to.be.true
done()
it 'configures the routes defined in facebook stratgegy', (done) ->
expect(facebook.routes.calledWith app, sinon.match.func)
.to.be.true
done()
describe 'Public Exports (Connect Middleware)', ->
it 'userAction', (done) ->
expect(authentication).to.have.ownProperty 'userAction'
expect(authentication.userAction).to.be.a 'function'
done()
it 'publicAction', (done) ->
expect(authentication).to.have.ownProperty 'publicAction'
expect(authentication.publicAction).to.be.a 'function'
done()
it 'adminAction', (done) ->
expect(authentication).to.have.ownProperty 'adminAction'
expect(authentication.adminAction).to.be.a 'function'
done()
it 'sysAdminAction', (done) ->
expect(authentication).to.have.ownProperty 'sysAdminAction'
expect(authentication.sysAdminAction).to.be.a 'function'
done()
describe 'publicAction: Function(req, res, next) -> void', ->
beforeEach (done) ->
sinon.stub authentication, '_systemCheck'
done()
afterEach (done) ->
authentication._systemCheck.restore()
done()
it 'passes args through systemCheck', (done) ->
authentication.publicAction {a: 'b'}, {c : 'd'}, {e: 'f'}
expect(authentication._systemCheck.calledWithExactly(
{a: 'b'}, {c : 'd'}, {e: 'f'}
)).to.be.true
done()
describe 'userAction: Function(req, res, next) -> void', ->
req = {}
res =
json: ->
beforeEach (done) ->
sinon.stub authentication, 'publicAction'
done()
afterEach (done) ->
authentication.publicAction.restore()
done()
it 'passes args through publicAction', (done) ->
req.user = {}
res =
json: sinon.spy()
authentication.publicAction.callsArg 2
authentication.userAction req, {a: 'b'}, {c : 'd'}
expect(authentication.publicAction.calledWith(
req, {a: 'b'}
)).to.be.true
done()
it 'passes to permissionsMiddleware if req has a user'
, (done) ->
req.user = {}
authentication.publicAction.callsArg 2
authentication.userAction req, {a: 'b'}, {c: 'd'}
expect(permissionsMiddlewareSpy.calledWithExactly(
req, {a: 'b'}, {c: 'd'})).to.be.true
done()
it 'calls res.json if req has no user' +
' an error', (done) ->
req.user = null
res =
json: sinon.spy()
authentication.publicAction.callsArg 2
, {user: 'object'}
authentication.userAction req, res, {c: 'd'}
expect(permissionsMiddlewareSpy.called).to.be.false
expect(res.json.calledWith 401, {}).to.be.true
done()
describe 'Private Functions', ->
it '_getSystemStrategies', (done) ->
expect(authentication).to.have.ownProperty '_getSystemStrategies'
expect(authentication._getSystemStrategies).to.be.a 'function'
done()
it '_systemCheck', (done) ->
expect(authentication).to.have.ownProperty '_systemCheck'
expect(authentication._systemCheck).to.be.a 'function'
done()
it '_hmacAuth', (done) ->
expect(authentication).to.have.ownProperty '_hmacAuth'
expect(authentication._hmacAuth).to.be.a 'function'
done()
it '_playAuth', (done) ->
expect(authentication).to.have.ownProperty '_playAuth'
expect(authentication._playAuth).to.be.a 'function'
done()
describe '_getSystemStrategies: Function(req, done) -> void', ->
req =
systemId: "a sys id"
environmentId: "an env id"
beforeEach (done) ->
sinon.stub app.models.settings, 'get'
done()
afterEach (done) ->
app.models.settings.get.restore()
done()
it 'gets login with Facebook setting', (done) ->
authentication._getSystemStrategies req, "done"
expect(
app.models.settings.get.calledWith 'loginWithFacebook'
, req.systemId
, req.environmentId
, sinon.match.func
).to.be.true
done()
it 'gets login with Hmac setting', (done) ->
authentication._getSystemStrategies req, "done"
expect(
app.models.settings.get.calledWith 'loginWithHmac'
, req.systemId
, req.environmentId
, sinon.match.func
).to.be.true
done()
it 'gets login with Play setting', (done) ->
authentication._getSystemStrategies req, "done"
expect(
app.models.settings.get.calledWith 'loginWithPlay'
, req.systemId
, req.environmentId
, sinon.match.func
).to.be.true
done()
it 'supresses any errors', (done) ->
app.models.settings.get.callsArgWith 3, "an error", null
authentication._getSystemStrategies req, (err, result) ->
expect(err).to.not.exist
expect(result).to.exist
expect(result.length).to.equal 0
done()
it 'calls back with the result', (done) ->
setting =
key: '<KEY>'
value: true
app.models.settings.get.callsArgWith 3, null, setting
authentication._getSystemStrategies req, (err, result) ->
expect(result[0]).to.equal 'facebook'
expect(result[1]).to.equal 'Hmac'
expect(result[2]).to.equal 'Play'
expect(err).to.not.exist
done()
it 'omits false settings from result', (done) ->
setting1 =
key: '<KEY>'
value: false
setting2 =
key: '<KEY>'
value: true
setting3 =
key: '<KEY>'
value: true
app.models.settings.get.callsArgWith 3, null, setting1
app.models.settings.get.callsArgWith 3, null, setting2
app.models.settings.get.callsArgWith 3, null, setting3
authentication._getSystemStrategies req, (err, result) ->
expect(result.length).to.equal 2
expect(result[0]).to.equal 'Hmac'
expect(result[1]).to.equal 'Play'
expect(err).to.not.exist
done()
it 'omits missing settings from result', (done) ->
setting1 =
key: '<KEY>'
value: true
setting3 =
key: '<KEY>'
value: false
app.models.settings.get.callsArgWith 3, null, setting1
app.models.settings.get.callsArgWith 3, "setting not found", null
app.models.settings.get.callsArgWith 3, null, setting3
authentication._getSystemStrategies req, (err, result) ->
expect(result.length).to.equal 1
expect(result[0]).to.equal 'facebook'
expect(err).to.not.exist
done()
describe '_systemCheck: Function(req, res, next) -> void', ->
req = null
res = null
environment = null
beforeEach (done) ->
req =
host: 'test.gi-security.com'
isAuthenticated: () ->
true
res =
json: sinon.spy()
environment =
_id: "an environment Id"
systemId: "a systemId"
sinon.stub app.models.environments, 'forHost'
sinon.stub authentication, '_getSystemStrategies'
sinon.stub authentication, '_findUser'
done()
afterEach ->
app.models.environments.forHost.restore()
authentication._getSystemStrategies.restore()
authentication._findUser.restore()
it 'returns 500 error if no request', (done) ->
authentication._systemCheck null, res, null
expect(res.json.calledWith 500
, {message: 'host not found on request object'}
).to.be.true
done()
it 'returns 500 error if no request.host', (done) ->
req = {}
authentication._systemCheck req, res, null
expect(res.json.calledWith 500
, {message: 'host not found on request object'}
).to.be.true
done()
it 'tries to find an environment matching the host', (done) ->
authentication._systemCheck req, res, null
expect(app.models.environments.forHost.calledWith req.host
, sinon.match.func
).to.be.true
done()
it 'returns a 500 error and a message if this fails', (done) ->
app.models.environments.forHost.callsArgWith 1, "an error", null
authentication._systemCheck req, res, null
expect(res.json.calledWith 500
, {message: "an error"}
).to.be.true
done()
it 'returns not found if no environment', (done) ->
app.models.environments.forHost.callsArgWith 1, null, null
authentication._systemCheck req, res, null
expect(res.json.calledWith 404
, {message: "environment not found"}
).to.be.true
done()
it 'sets systemId on request if env found', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._systemCheck req, res, null
expect(req.systemId).to.equal environment.systemId
done()
it 'sets environmentId on request if env found', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._systemCheck req, res, null
expect(req.environmentId).to.equal environment._id
done()
it 'gets systemStrategies', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._systemCheck req, res, null
expect(authentication._getSystemStrategies.called).to.be.true
reqArg = authentication._getSystemStrategies.getCall(0).args[0]
expect(reqArg.systemId).to.equal environment.systemId
expect(reqArg.environmentId).to.equal environment._id
expect(reqArg).to.deep.equal req
done()
it 'does not set req.strategies if _getSystemStrategies errors'
, (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._findUser.callsArg 2
authentication._getSystemStrategies.callsArgWith 1
, "an error", {some: 'thing'}
authentication._systemCheck req, res, ->
expect(req.strategies).to.not.exist
done()
it 'does not set req.strategies if _getSystemStrategies is null'
, (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._getSystemStrategies.callsArgWith 1
authentication._findUser.callsArg 2
authentication._systemCheck req, res, ->
expect(req.strategies).to.not.exist
done()
it 'sets req.strategies otherwise', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._getSystemStrategies.callsArgWith 1
, null, 'something'
authentication._findUser.callsArg 2
authentication._systemCheck req, res, ->
expect(req.strategies).to.equal 'something'
done()
describe '_hmacAuth: Function(req, res, next) -> void', ->
req =
strategies: ['some other strategy']
it 'Checks if Hmac is a supported strategy', (done) ->
authentication._hmacAuth req, null, (err, result) ->
expect(err).to.equal 'Hmac strategy not supported'
expect(result).to.not.exist
done()
describe '_playAuth: Function(req, res, next) -> void', ->
req =
strategies: ['some other strategy']
it 'Checks if Play is a supported strategy', (done) ->
authentication._playAuth req, null, (err, result) ->
expect(err).to.equal 'Play strategy not supported'
expect(result).to.not.exist
done()
describe 'Private', ->
permissionFilter() | true | expect = require('chai').expect
sinon = require 'sinon'
proxyquire = require 'proxyquire'
path = require 'path'
permissionFilter = require './permissionFilter'
module.exports = () ->
describe 'Authentication', ->
describe 'Public', ->
dir = path.normalize __dirname + '../../../../../../server'
permissionsMiddlewareSpy = sinon.spy()
basic =
routes: sinon.spy()
facebook =
routes: sinon.spy()
passport =
initialize: () ->
return 'passport-initialize'
session: () ->
return 'passport-session'
stubs =
'./permissionFilter': sinon.stub().returns permissionsMiddlewareSpy
'./hmac': sinon.spy()
'./play': sinon.spy()
'./basic': sinon.stub().returns basic
'./facebook': sinon.stub().returns facebook
'passport': passport
authenticationModule = proxyquire dir + '/authentication', stubs
app =
use: sinon.spy()
get: sinon.spy()
post: ->
router: 'app-router'
models:
users: 'users'
environments:
forHost: ->
settings:
get: ->
afterEach (done) ->
permissionsMiddlewareSpy.reset()
done()
it 'Exports a factory function', (done) ->
expect(authenticationModule).to.be.a('function')
done()
describe 'Factory Function: (app, options) -> { middleware }', ->
authentication = authenticationModule app, {}
describe 'Initialisation', (done) ->
it 'Uses permissionFilter', (done) ->
expect(stubs['./permissionFilter'].calledWithExactly(app))
.to.be.true
done()
it 'requires basic authenticaion', (done) ->
expect(stubs['./basic'].callCount).to.equal 1
expect(stubs['./basic'].calledWithExactly app.models.users)
.to.be.true
done()
it 'requires facebook authenticaion', (done) ->
expect(stubs['./facebook'].callCount).to.equal 1
expect(stubs['./facebook'].calledWithExactly app.models.users)
.to.be.true
done()
it 'requires hmac authenticaion', (done) ->
expect(stubs['./hmac'].callCount).to.equal 1
expect(stubs['./hmac'].calledWithExactly app.models.users)
.to.be.true
done()
it 'requires play authenticaion', (done) ->
expect(stubs['./play'].callCount).to.equal 1
expect(stubs['./play'].calledWithExactly app.models.users)
.to.be.true
done()
it 'makes the app use passport intialize', (done) ->
expect(app.use.getCall(0).args[0]).to.equal 'passport-initialize'
done()
it 'makes the app use passport session', (done) ->
expect(app.use.getCall(1).args[0]).to.equal 'passport-session'
done()
it 'makes the app use the apps router', (done) ->
expect(app.use.calledWith app.router).to.be.true
done()
it 'creates an api route for logout', (done) ->
expect(app.get.calledWith '/api/logout', sinon.match.func)
.to.be.true
done()
it 'configures the routes defined in basic strategy', (done) ->
expect(basic.routes.calledWith app, sinon.match.func)
.to.be.true
done()
it 'configures the routes defined in facebook stratgegy', (done) ->
expect(facebook.routes.calledWith app, sinon.match.func)
.to.be.true
done()
describe 'Public Exports (Connect Middleware)', ->
it 'userAction', (done) ->
expect(authentication).to.have.ownProperty 'userAction'
expect(authentication.userAction).to.be.a 'function'
done()
it 'publicAction', (done) ->
expect(authentication).to.have.ownProperty 'publicAction'
expect(authentication.publicAction).to.be.a 'function'
done()
it 'adminAction', (done) ->
expect(authentication).to.have.ownProperty 'adminAction'
expect(authentication.adminAction).to.be.a 'function'
done()
it 'sysAdminAction', (done) ->
expect(authentication).to.have.ownProperty 'sysAdminAction'
expect(authentication.sysAdminAction).to.be.a 'function'
done()
describe 'publicAction: Function(req, res, next) -> void', ->
beforeEach (done) ->
sinon.stub authentication, '_systemCheck'
done()
afterEach (done) ->
authentication._systemCheck.restore()
done()
it 'passes args through systemCheck', (done) ->
authentication.publicAction {a: 'b'}, {c : 'd'}, {e: 'f'}
expect(authentication._systemCheck.calledWithExactly(
{a: 'b'}, {c : 'd'}, {e: 'f'}
)).to.be.true
done()
describe 'userAction: Function(req, res, next) -> void', ->
req = {}
res =
json: ->
beforeEach (done) ->
sinon.stub authentication, 'publicAction'
done()
afterEach (done) ->
authentication.publicAction.restore()
done()
it 'passes args through publicAction', (done) ->
req.user = {}
res =
json: sinon.spy()
authentication.publicAction.callsArg 2
authentication.userAction req, {a: 'b'}, {c : 'd'}
expect(authentication.publicAction.calledWith(
req, {a: 'b'}
)).to.be.true
done()
it 'passes to permissionsMiddleware if req has a user'
, (done) ->
req.user = {}
authentication.publicAction.callsArg 2
authentication.userAction req, {a: 'b'}, {c: 'd'}
expect(permissionsMiddlewareSpy.calledWithExactly(
req, {a: 'b'}, {c: 'd'})).to.be.true
done()
it 'calls res.json if req has no user' +
' an error', (done) ->
req.user = null
res =
json: sinon.spy()
authentication.publicAction.callsArg 2
, {user: 'object'}
authentication.userAction req, res, {c: 'd'}
expect(permissionsMiddlewareSpy.called).to.be.false
expect(res.json.calledWith 401, {}).to.be.true
done()
describe 'Private Functions', ->
it '_getSystemStrategies', (done) ->
expect(authentication).to.have.ownProperty '_getSystemStrategies'
expect(authentication._getSystemStrategies).to.be.a 'function'
done()
it '_systemCheck', (done) ->
expect(authentication).to.have.ownProperty '_systemCheck'
expect(authentication._systemCheck).to.be.a 'function'
done()
it '_hmacAuth', (done) ->
expect(authentication).to.have.ownProperty '_hmacAuth'
expect(authentication._hmacAuth).to.be.a 'function'
done()
it '_playAuth', (done) ->
expect(authentication).to.have.ownProperty '_playAuth'
expect(authentication._playAuth).to.be.a 'function'
done()
describe '_getSystemStrategies: Function(req, done) -> void', ->
req =
systemId: "a sys id"
environmentId: "an env id"
beforeEach (done) ->
sinon.stub app.models.settings, 'get'
done()
afterEach (done) ->
app.models.settings.get.restore()
done()
it 'gets login with Facebook setting', (done) ->
authentication._getSystemStrategies req, "done"
expect(
app.models.settings.get.calledWith 'loginWithFacebook'
, req.systemId
, req.environmentId
, sinon.match.func
).to.be.true
done()
it 'gets login with Hmac setting', (done) ->
authentication._getSystemStrategies req, "done"
expect(
app.models.settings.get.calledWith 'loginWithHmac'
, req.systemId
, req.environmentId
, sinon.match.func
).to.be.true
done()
it 'gets login with Play setting', (done) ->
authentication._getSystemStrategies req, "done"
expect(
app.models.settings.get.calledWith 'loginWithPlay'
, req.systemId
, req.environmentId
, sinon.match.func
).to.be.true
done()
it 'supresses any errors', (done) ->
app.models.settings.get.callsArgWith 3, "an error", null
authentication._getSystemStrategies req, (err, result) ->
expect(err).to.not.exist
expect(result).to.exist
expect(result.length).to.equal 0
done()
it 'calls back with the result', (done) ->
setting =
key: 'PI:KEY:<KEY>END_PI'
value: true
app.models.settings.get.callsArgWith 3, null, setting
authentication._getSystemStrategies req, (err, result) ->
expect(result[0]).to.equal 'facebook'
expect(result[1]).to.equal 'Hmac'
expect(result[2]).to.equal 'Play'
expect(err).to.not.exist
done()
it 'omits false settings from result', (done) ->
setting1 =
key: 'PI:KEY:<KEY>END_PI'
value: false
setting2 =
key: 'PI:KEY:<KEY>END_PI'
value: true
setting3 =
key: 'PI:KEY:<KEY>END_PI'
value: true
app.models.settings.get.callsArgWith 3, null, setting1
app.models.settings.get.callsArgWith 3, null, setting2
app.models.settings.get.callsArgWith 3, null, setting3
authentication._getSystemStrategies req, (err, result) ->
expect(result.length).to.equal 2
expect(result[0]).to.equal 'Hmac'
expect(result[1]).to.equal 'Play'
expect(err).to.not.exist
done()
it 'omits missing settings from result', (done) ->
setting1 =
key: 'PI:KEY:<KEY>END_PI'
value: true
setting3 =
key: 'PI:KEY:<KEY>END_PI'
value: false
app.models.settings.get.callsArgWith 3, null, setting1
app.models.settings.get.callsArgWith 3, "setting not found", null
app.models.settings.get.callsArgWith 3, null, setting3
authentication._getSystemStrategies req, (err, result) ->
expect(result.length).to.equal 1
expect(result[0]).to.equal 'facebook'
expect(err).to.not.exist
done()
describe '_systemCheck: Function(req, res, next) -> void', ->
req = null
res = null
environment = null
beforeEach (done) ->
req =
host: 'test.gi-security.com'
isAuthenticated: () ->
true
res =
json: sinon.spy()
environment =
_id: "an environment Id"
systemId: "a systemId"
sinon.stub app.models.environments, 'forHost'
sinon.stub authentication, '_getSystemStrategies'
sinon.stub authentication, '_findUser'
done()
afterEach ->
app.models.environments.forHost.restore()
authentication._getSystemStrategies.restore()
authentication._findUser.restore()
it 'returns 500 error if no request', (done) ->
authentication._systemCheck null, res, null
expect(res.json.calledWith 500
, {message: 'host not found on request object'}
).to.be.true
done()
it 'returns 500 error if no request.host', (done) ->
req = {}
authentication._systemCheck req, res, null
expect(res.json.calledWith 500
, {message: 'host not found on request object'}
).to.be.true
done()
it 'tries to find an environment matching the host', (done) ->
authentication._systemCheck req, res, null
expect(app.models.environments.forHost.calledWith req.host
, sinon.match.func
).to.be.true
done()
it 'returns a 500 error and a message if this fails', (done) ->
app.models.environments.forHost.callsArgWith 1, "an error", null
authentication._systemCheck req, res, null
expect(res.json.calledWith 500
, {message: "an error"}
).to.be.true
done()
it 'returns not found if no environment', (done) ->
app.models.environments.forHost.callsArgWith 1, null, null
authentication._systemCheck req, res, null
expect(res.json.calledWith 404
, {message: "environment not found"}
).to.be.true
done()
it 'sets systemId on request if env found', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._systemCheck req, res, null
expect(req.systemId).to.equal environment.systemId
done()
it 'sets environmentId on request if env found', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._systemCheck req, res, null
expect(req.environmentId).to.equal environment._id
done()
it 'gets systemStrategies', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._systemCheck req, res, null
expect(authentication._getSystemStrategies.called).to.be.true
reqArg = authentication._getSystemStrategies.getCall(0).args[0]
expect(reqArg.systemId).to.equal environment.systemId
expect(reqArg.environmentId).to.equal environment._id
expect(reqArg).to.deep.equal req
done()
it 'does not set req.strategies if _getSystemStrategies errors'
, (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._findUser.callsArg 2
authentication._getSystemStrategies.callsArgWith 1
, "an error", {some: 'thing'}
authentication._systemCheck req, res, ->
expect(req.strategies).to.not.exist
done()
it 'does not set req.strategies if _getSystemStrategies is null'
, (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._getSystemStrategies.callsArgWith 1
authentication._findUser.callsArg 2
authentication._systemCheck req, res, ->
expect(req.strategies).to.not.exist
done()
it 'sets req.strategies otherwise', (done) ->
app.models.environments.forHost.callsArgWith 1, null, environment
authentication._getSystemStrategies.callsArgWith 1
, null, 'something'
authentication._findUser.callsArg 2
authentication._systemCheck req, res, ->
expect(req.strategies).to.equal 'something'
done()
describe '_hmacAuth: Function(req, res, next) -> void', ->
req =
strategies: ['some other strategy']
it 'Checks if Hmac is a supported strategy', (done) ->
authentication._hmacAuth req, null, (err, result) ->
expect(err).to.equal 'Hmac strategy not supported'
expect(result).to.not.exist
done()
describe '_playAuth: Function(req, res, next) -> void', ->
req =
strategies: ['some other strategy']
it 'Checks if Play is a supported strategy', (done) ->
authentication._playAuth req, null, (err, result) ->
expect(err).to.equal 'Play strategy not supported'
expect(result).to.not.exist
done()
describe 'Private', ->
permissionFilter() |
[
{
"context": " 'nl': 'slak'\n name:\n 'nl-BE': 'alee'\n 'de': 'hallo'\n expect(json).toEqu",
"end": 2027,
"score": 0.9780330657958984,
"start": 2023,
"tag": "NAME",
"value": "alee"
},
{
"context": " name:\n 'nl-BE': 'alee'\n 'de': 'ha... | src/spec/csv/exportmapping.spec.coffee | sphereio/sphere-category-sync | 1 | fs = require 'fs'
path = require 'path'
_ = require 'underscore'
ExportMapping = require '../../lib/csv/exportmapping'
describe 'ExportMapping', ->
describe '#constructor', ->
it 'should initialize', ->
expect(-> new ExportMapping()).toBeDefined()
describe '#validate', ->
it 'should map a simple entry', ->
ex = new ExportMapping [ 'id' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 'foo'
expect(json).toEqual [ 'foo' ]
it 'should map parentId entry', ->
ex = new ExportMapping [ 'parentId' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
parent:
type: 'category'
id: 'root'
expect(json).toEqual [ 'root' ]
it 'should not map empty parentId entry', ->
ex = new ExportMapping [ 'parentId' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 123
expect(json).toEqual [ '' ]
it 'should map a localized entry', ->
ex = new ExportMapping [ 'slug.it', 'name.de' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV
slug:
it: 'ciao'
en: 'hi'
name:
en: 'hello'
de: 'Hallo'
expect(json).toEqual [ 'ciao', 'Hallo' ]
it 'should support region subtags', ->
ex = new ExportMapping [ 'slug.nl', 'name.nl-BE' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV
slug:
'en-US': 'ciao'
'nl': 'slak'
name:
'nl-BE': 'alee'
'de': 'hallo'
expect(json).toEqual [ 'slak', 'alee' ]
it 'should not map an empty localized entry', ->
ex = new ExportMapping [ 'slug.de', 'name.it' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV
slug:
it: 'ciao'
en: 'hi'
name:
en: 'hello'
de: 'Hallo'
expect(json).toEqual [ '', '' ]
it 'should map to undefined for any unknown header', ->
ex = new ExportMapping [ 'foo.en', 'bar' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV {}
expect(json).toEqual [ undefined, undefined ]
it 'should map externalId into parentId if requested', ->
ex = new ExportMapping [ 'parentId' ], parentBy: 'externalId'
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 'i1'
externalId: 'e1'
parent:
type: 'category'
id: 'i2'
obj:
id: 'i2'
externalId: 'e2'
expect(json).toEqual [ 'e2' ]
it 'should map slug into parentId if requested', ->
ex = new ExportMapping [ 'parentId' ], { language: 'en', parentBy: 'slug' }
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 'i3'
externalId: 'e3'
parent:
type: 'category'
id: 'i4'
obj:
id: 'i4'
externalId: 'e4'
slug:
en: 'slug-4'
expect(json).toEqual [ 'slug-4' ]
describe '#customFields', ->
it 'should map and export all customFields', ->
template = fs.readFileSync(path.join(__dirname, '../../data/customFieldsTemplate.csv'))
.toString()
categoryWithCustomFields = require(path.join(__dirname, '../../data/categoryWithCustomFields'))
ex = new ExportMapping template.split(',')
ex.validate()
json = ex.toCSV(categoryWithCustomFields)
expected = [
# key externalId slug.en custom key number money
'tstcstfields', 'tstcstfields', 'cat-cust-fields', 'custom-type-key', 123, 'EUR 1234',
# lenum set string set of lenum keys set of lenum En labels
'lenumKey1', 'aaaa;bbbb', 'setOflenumKey1;setOflenumKey2', 'Lenum1En;Lenum2En',
# set of lenum de labels string set of enum keys true false
'SetLenum1De;SetLenum2De', 'string value', 'setOfEnumKey1;setOfEnumKey2', 'true', undefined,
# number enum key lenum EN lenum DE
'1;2;3', 'enumKey1', 'En value', 'De value'
]
expect(json).toEqual expected
| 66900 | fs = require 'fs'
path = require 'path'
_ = require 'underscore'
ExportMapping = require '../../lib/csv/exportmapping'
describe 'ExportMapping', ->
describe '#constructor', ->
it 'should initialize', ->
expect(-> new ExportMapping()).toBeDefined()
describe '#validate', ->
it 'should map a simple entry', ->
ex = new ExportMapping [ 'id' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 'foo'
expect(json).toEqual [ 'foo' ]
it 'should map parentId entry', ->
ex = new ExportMapping [ 'parentId' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
parent:
type: 'category'
id: 'root'
expect(json).toEqual [ 'root' ]
it 'should not map empty parentId entry', ->
ex = new ExportMapping [ 'parentId' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 123
expect(json).toEqual [ '' ]
it 'should map a localized entry', ->
ex = new ExportMapping [ 'slug.it', 'name.de' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV
slug:
it: 'ciao'
en: 'hi'
name:
en: 'hello'
de: 'Hallo'
expect(json).toEqual [ 'ciao', 'Hallo' ]
it 'should support region subtags', ->
ex = new ExportMapping [ 'slug.nl', 'name.nl-BE' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV
slug:
'en-US': 'ciao'
'nl': 'slak'
name:
'nl-BE': '<NAME>'
'de': '<NAME>'
expect(json).toEqual [ 'slak', 'alee' ]
it 'should not map an empty localized entry', ->
ex = new ExportMapping [ 'slug.de', 'name.it' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV
slug:
it: 'ciao'
en: 'hi'
name:
en: 'hello'
de: '<NAME>'
expect(json).toEqual [ '', '' ]
it 'should map to undefined for any unknown header', ->
ex = new ExportMapping [ 'foo.en', 'bar' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV {}
expect(json).toEqual [ undefined, undefined ]
it 'should map externalId into parentId if requested', ->
ex = new ExportMapping [ 'parentId' ], parentBy: 'externalId'
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 'i1'
externalId: 'e1'
parent:
type: 'category'
id: 'i2'
obj:
id: 'i2'
externalId: 'e2'
expect(json).toEqual [ 'e2' ]
it 'should map slug into parentId if requested', ->
ex = new ExportMapping [ 'parentId' ], { language: 'en', parentBy: 'slug' }
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 'i3'
externalId: 'e3'
parent:
type: 'category'
id: 'i4'
obj:
id: 'i4'
externalId: 'e4'
slug:
en: 'slug-4'
expect(json).toEqual [ 'slug-4' ]
describe '#customFields', ->
it 'should map and export all customFields', ->
template = fs.readFileSync(path.join(__dirname, '../../data/customFieldsTemplate.csv'))
.toString()
categoryWithCustomFields = require(path.join(__dirname, '../../data/categoryWithCustomFields'))
ex = new ExportMapping template.split(',')
ex.validate()
json = ex.toCSV(categoryWithCustomFields)
expected = [
# key externalId slug.en custom key number money
'tstcstfields', 'tstcstfields', 'cat-cust-fields', 'custom-type-key', 123, 'EUR 1234',
# lenum set string set of lenum keys set of lenum En labels
'lenumKey1', '<KEY>', 'setOflenumKey1;setOflenumKey2', 'Lenum1En;Lenum2En',
# set of lenum de labels string set of enum keys true false
'SetLenum1De;SetLenum2De', 'string value', 'setOfEnumKey1;setOfEnumKey2', 'true', undefined,
# number enum key lenum EN lenum DE
'1;2;3', 'enumKey1', 'En value', 'De value'
]
expect(json).toEqual expected
| true | fs = require 'fs'
path = require 'path'
_ = require 'underscore'
ExportMapping = require '../../lib/csv/exportmapping'
describe 'ExportMapping', ->
describe '#constructor', ->
it 'should initialize', ->
expect(-> new ExportMapping()).toBeDefined()
describe '#validate', ->
it 'should map a simple entry', ->
ex = new ExportMapping [ 'id' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 'foo'
expect(json).toEqual [ 'foo' ]
it 'should map parentId entry', ->
ex = new ExportMapping [ 'parentId' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
parent:
type: 'category'
id: 'root'
expect(json).toEqual [ 'root' ]
it 'should not map empty parentId entry', ->
ex = new ExportMapping [ 'parentId' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 123
expect(json).toEqual [ '' ]
it 'should map a localized entry', ->
ex = new ExportMapping [ 'slug.it', 'name.de' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV
slug:
it: 'ciao'
en: 'hi'
name:
en: 'hello'
de: 'Hallo'
expect(json).toEqual [ 'ciao', 'Hallo' ]
it 'should support region subtags', ->
ex = new ExportMapping [ 'slug.nl', 'name.nl-BE' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV
slug:
'en-US': 'ciao'
'nl': 'slak'
name:
'nl-BE': 'PI:NAME:<NAME>END_PI'
'de': 'PI:NAME:<NAME>END_PI'
expect(json).toEqual [ 'slak', 'alee' ]
it 'should not map an empty localized entry', ->
ex = new ExportMapping [ 'slug.de', 'name.it' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV
slug:
it: 'ciao'
en: 'hi'
name:
en: 'hello'
de: 'PI:NAME:<NAME>END_PI'
expect(json).toEqual [ '', '' ]
it 'should map to undefined for any unknown header', ->
ex = new ExportMapping [ 'foo.en', 'bar' ]
ex.validate()
expect(_.size ex.index2CsvFn).toBe 2
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
expect(_.isFunction(ex.index2CsvFn[1])).toBe true
json = ex.toCSV {}
expect(json).toEqual [ undefined, undefined ]
it 'should map externalId into parentId if requested', ->
ex = new ExportMapping [ 'parentId' ], parentBy: 'externalId'
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 'i1'
externalId: 'e1'
parent:
type: 'category'
id: 'i2'
obj:
id: 'i2'
externalId: 'e2'
expect(json).toEqual [ 'e2' ]
it 'should map slug into parentId if requested', ->
ex = new ExportMapping [ 'parentId' ], { language: 'en', parentBy: 'slug' }
ex.validate()
expect(_.size ex.index2CsvFn).toBe 1
expect(_.isFunction(ex.index2CsvFn[0])).toBe true
json = ex.toCSV
id: 'i3'
externalId: 'e3'
parent:
type: 'category'
id: 'i4'
obj:
id: 'i4'
externalId: 'e4'
slug:
en: 'slug-4'
expect(json).toEqual [ 'slug-4' ]
describe '#customFields', ->
it 'should map and export all customFields', ->
template = fs.readFileSync(path.join(__dirname, '../../data/customFieldsTemplate.csv'))
.toString()
categoryWithCustomFields = require(path.join(__dirname, '../../data/categoryWithCustomFields'))
ex = new ExportMapping template.split(',')
ex.validate()
json = ex.toCSV(categoryWithCustomFields)
expected = [
# key externalId slug.en custom key number money
'tstcstfields', 'tstcstfields', 'cat-cust-fields', 'custom-type-key', 123, 'EUR 1234',
# lenum set string set of lenum keys set of lenum En labels
'lenumKey1', 'PI:KEY:<KEY>END_PI', 'setOflenumKey1;setOflenumKey2', 'Lenum1En;Lenum2En',
# set of lenum de labels string set of enum keys true false
'SetLenum1De;SetLenum2De', 'string value', 'setOfEnumKey1;setOfEnumKey2', 'true', undefined,
# number enum key lenum EN lenum DE
'1;2;3', 'enumKey1', 'En value', 'De value'
]
expect(json).toEqual expected
|
[
{
"context": "###\npostCtrl.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.com>\n\nDistributed under terms of t",
"end": 47,
"score": 0.9995703101158142,
"start": 39,
"tag": "NAME",
"value": "ender xu"
},
{
"context": "###\npostCtrl.coffee\nCopyright (C) 2014 ender xu <xuender@gm... | src/web/cs/postsCtrl.coffee | xuender/mindfulness | 0 | ###
postCtrl.coffee
Copyright (C) 2014 ender xu <xuender@gmail.com>
Distributed under terms of the MIT license.
###
PostsCtrl = ($scope, $http, $log, $modal, ngTableParams, $filter, $q)->
### 帖子 ###
$log.debug '帖子'
$scope.$parent.name = 'post'
$scope.type = (id)->
for k of POST_TYPE
if k == id
return POST_TYPE[k]
'未知'
$scope.status = (id)->
for p in POST_STATUS
if p.id == id
return p.title
'未知'
$scope.selectType = ->
# 布尔列表
def = $q.defer()
ret = []
for k of POST_TYPE
ret.push(
id: k
title: POST_TYPE[k]
)
def.resolve(ret)
def
$scope.selectStatus = ->
# 布尔列表
def = $q.defer()
ret = []
for i in POST_STATUS
ret.push i
def.resolve(ret)
def
$scope.tableParams = new ngTableParams(
page: 1
count: 10
sorting:
ca: 'desc'
,
getData: ($defer, params)->
# 过滤
$http.post('/cs/post',
Page: params.page()
Count: params.count()
Sorting: params.orderBy()
Filter: params.filter()
).success((data)->
$log.debug data
if data.ok
params.total(data.count)
$defer.resolve(data.data)
else
alert(data.err)
)
)
$scope.ret = (s, d, rt=null)->
# 回复
if rt
d.rt = rt
d.status = s
$http.put('/cs/post',d).success((data)->
$log.debug data
if data.ok
d.$edit = false
#alert('修改成功')
else
alert(data.err)
)
$scope.remove = (d)->
# 删除
$scope.confirm("是否删除 [ #{ d.title } ] ?", ->
$http.delete("/cs/post/#{d.id}").success((data)->
$log.debug data
if data.ok
$scope.tableParams.reload()
alert('删除成功')
else
alert(data.err)
)
)
$scope.log = (d)->
$modal.open(
templateUrl: 'partials/log.html?3.html'
controller: LogCtrl
backdrop: 'static'
size: 'lg'
resolve:
oid: ->
d.id
)
PostsCtrl.$inject = [
'$scope'
'$http'
'$log'
'$modal'
'ngTableParams'
'$filter'
'$q'
]
| 43006 | ###
postCtrl.coffee
Copyright (C) 2014 <NAME> <<EMAIL>>
Distributed under terms of the MIT license.
###
PostsCtrl = ($scope, $http, $log, $modal, ngTableParams, $filter, $q)->
### 帖子 ###
$log.debug '帖子'
$scope.$parent.name = 'post'
$scope.type = (id)->
for k of POST_TYPE
if k == id
return POST_TYPE[k]
'未知'
$scope.status = (id)->
for p in POST_STATUS
if p.id == id
return p.title
'未知'
$scope.selectType = ->
# 布尔列表
def = $q.defer()
ret = []
for k of POST_TYPE
ret.push(
id: k
title: POST_TYPE[k]
)
def.resolve(ret)
def
$scope.selectStatus = ->
# 布尔列表
def = $q.defer()
ret = []
for i in POST_STATUS
ret.push i
def.resolve(ret)
def
$scope.tableParams = new ngTableParams(
page: 1
count: 10
sorting:
ca: 'desc'
,
getData: ($defer, params)->
# 过滤
$http.post('/cs/post',
Page: params.page()
Count: params.count()
Sorting: params.orderBy()
Filter: params.filter()
).success((data)->
$log.debug data
if data.ok
params.total(data.count)
$defer.resolve(data.data)
else
alert(data.err)
)
)
$scope.ret = (s, d, rt=null)->
# 回复
if rt
d.rt = rt
d.status = s
$http.put('/cs/post',d).success((data)->
$log.debug data
if data.ok
d.$edit = false
#alert('修改成功')
else
alert(data.err)
)
$scope.remove = (d)->
# 删除
$scope.confirm("是否删除 [ #{ d.title } ] ?", ->
$http.delete("/cs/post/#{d.id}").success((data)->
$log.debug data
if data.ok
$scope.tableParams.reload()
alert('删除成功')
else
alert(data.err)
)
)
$scope.log = (d)->
$modal.open(
templateUrl: 'partials/log.html?3.html'
controller: LogCtrl
backdrop: 'static'
size: 'lg'
resolve:
oid: ->
d.id
)
PostsCtrl.$inject = [
'$scope'
'$http'
'$log'
'$modal'
'ngTableParams'
'$filter'
'$q'
]
| true | ###
postCtrl.coffee
Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Distributed under terms of the MIT license.
###
PostsCtrl = ($scope, $http, $log, $modal, ngTableParams, $filter, $q)->
### 帖子 ###
$log.debug '帖子'
$scope.$parent.name = 'post'
$scope.type = (id)->
for k of POST_TYPE
if k == id
return POST_TYPE[k]
'未知'
$scope.status = (id)->
for p in POST_STATUS
if p.id == id
return p.title
'未知'
$scope.selectType = ->
# 布尔列表
def = $q.defer()
ret = []
for k of POST_TYPE
ret.push(
id: k
title: POST_TYPE[k]
)
def.resolve(ret)
def
$scope.selectStatus = ->
# 布尔列表
def = $q.defer()
ret = []
for i in POST_STATUS
ret.push i
def.resolve(ret)
def
$scope.tableParams = new ngTableParams(
page: 1
count: 10
sorting:
ca: 'desc'
,
getData: ($defer, params)->
# 过滤
$http.post('/cs/post',
Page: params.page()
Count: params.count()
Sorting: params.orderBy()
Filter: params.filter()
).success((data)->
$log.debug data
if data.ok
params.total(data.count)
$defer.resolve(data.data)
else
alert(data.err)
)
)
$scope.ret = (s, d, rt=null)->
# 回复
if rt
d.rt = rt
d.status = s
$http.put('/cs/post',d).success((data)->
$log.debug data
if data.ok
d.$edit = false
#alert('修改成功')
else
alert(data.err)
)
$scope.remove = (d)->
# 删除
$scope.confirm("是否删除 [ #{ d.title } ] ?", ->
$http.delete("/cs/post/#{d.id}").success((data)->
$log.debug data
if data.ok
$scope.tableParams.reload()
alert('删除成功')
else
alert(data.err)
)
)
$scope.log = (d)->
$modal.open(
templateUrl: 'partials/log.html?3.html'
controller: LogCtrl
backdrop: 'static'
size: 'lg'
resolve:
oid: ->
d.id
)
PostsCtrl.$inject = [
'$scope'
'$http'
'$log'
'$modal'
'ngTableParams'
'$filter'
'$q'
]
|
[
{
"context": "ss TimeBars extends _Base\n\tdefaults: \n\t\ttimeKey: \"ts\"\n\t\tcountKey: \"count\"\n\n\t\twidth: 700\n\t\theight: 300\n",
"end": 180,
"score": 0.8231475949287415,
"start": 178,
"tag": "KEY",
"value": "ts"
},
{
"context": "ds _Base\n\tdefaults: \n\t\ttimeKey: \"ts\"\n... | _src/js/timebars.coffee | mpneuried/tcs-charts | 1 | if module?.exports?
_Base = require( "./base.js" )
@d3 = require( "d3" )
else
_Base = window.tcscharts.Base
_TimeBars = class TimeBars extends _Base
defaults:
timeKey: "ts"
countKey: "count"
width: 700
height: 300
margin:
top: 20
right: 20
bottom: 10
left: 40
spacing: 3
barsColor: null
showCount: false
countColorIn: "#fff"
countColorOut: "#666"
ticks: "minutes"
timeFormat: null
timeDomain: null
smallBarWidth: 20
animationDuration: 600
constructor: ( @target, @data = [], options )->
_ret = super( @target )
@_initOptions( options, true )
@_calcMetrics()
@create()
return _ret
_calcMetrics: =>
if @domainX?
@_oldDomainX = @domainX
if @opt.timeDomain?
@domainX = @opt.timeDomain
@data = for _dt in @data when _dt[ @opt.timeKey ] > @domainX[ 0 ] and _dt[ @opt.timeKey ] < @domainX[ 1 ]
_dt
else
times = for _d in @data
_d[ @opt.timeKey ]
@domainX = [ d3.min(times), d3.max(times) ]
@domainY = [ d3.max( @data, ( ( d )=>d[ @opt.countKey ] ) ), 0]
@interpolateX = d3.time.scale()
.domain( @domainX )
@interpolateY = d3.scale.linear()
.range([ 0, @opt.height - 25 ])
.domain( @domainY )
@_barWidth = @_calcBarWidth()
@interpolateX
.range([0, @opt.width - @_barWidth ])
@xAxis = d3.svg.axis()
.scale(@interpolateX)
.orient("bottom")
@yAxis = d3.svg.axis()
.scale(@interpolateY)
.tickSize(@opt.width)
.orient("left")
if @opt.tickCount?
@xAxis.ticks( @opt.tickCount )
if @opt.timeFormat?
if typeof @opt.timeFormat is "function"
@xAxis.tickFormat( @opt.timeFormat )
else
@xAxis.tickFormat ( date )=>
d3.time.format( @opt.timeFormat )( date )
return
_initOptions: ( options, def = false )=>
@_extend( @opt = {}, @defaults, options ) if def
@opt._width = @opt.width + @opt.margin.left + @opt.margin.right
@opt._height = @opt.height + @opt.margin.top + @opt.margin.bottom
if def
for _k of @opt
@_initOption( _k )
return
_initOption: ( key )=>
odef =
get: =>
return @opt[ key ]
set: ( _v )=>
@opt[ key ] = _v
switch key
when "width", "height"
@create()
else
@create()
return
@define( key, odef, @ )
fnRect: ( update = false, remove = false )=>
return ( _el )=>
_el.attr "class", (d)=>
_classes = [ "bar" ]
if @_barWidth > @opt.smallBarWidth
_classes.push "normal"
else
_classes.push "small"
if d[ @opt.countKey ] < @domainY[0] * .2
_classes.push "low"
else
_classes.push "high"
return _classes.join( " " )
if update
_el
.transition()
.duration( @opt.animationDuration )
.attrTween "transform", ( d, i, current )=>
[ _tx, _ty ] = current[10..-2].split(",")
if remove
_h = 0
else
_h = @interpolateY( d[ @opt.countKey ] )
_x = @interpolateX( new Date( d.ts ) )
_y = _h
interX = d3.interpolate( d._x or parseFloat( _tx ), _x )
interY = d3.interpolate( d._y or parseFloat( _ty ), _y )
d._x = _x
d._y = _y
d._h = _h
return ( _t )->"translate(#{ interX( _t ) },#{ interY( _t ) })"
else
_this = @
_el.on "mouseenter", ( datum )-> _this._enterRect( @, datum )
_el.on "mouseleave", ( datum )-> _this._leaveRect( @, datum )
_el
.datum ( d )=>
_h = @interpolateY( d[ @opt.countKey ] )
d._x = @interpolateX( new Date( d.ts ) )
d._y = _h
d._h = _h
return d
.attr "transform", (d, i)=>
return "translate(#{ d._x },#{d._y})"
if update
_rect = _el.select( "rect" )
else
_rect = _el.append("rect")
if @opt.barsColor?
_rect
.attr( "fill", @opt.barsColor )
if update
_rect
.transition()
.duration( @opt.animationDuration )
.attr( "width", => @_barWidth )
.attr "height", (d, i)=>
if remove
return 1e-6
else
return @opt.height - 25 - @interpolateY( d[ @opt.countKey ] )
else
_rect
.attr( "width", => @_barWidth )
.attr "height", (d, i)=>
if remove
return 1e-6
else
return @opt.height - 25 - @interpolateY( d[ @opt.countKey ] )
if @opt.showCount
if update
_el.select( ".count" )
.attr "class", (d)=>
_classes = [ "count" ]
if @_barWidth > @opt.smallBarWidth
_classes.push "normal"
else
_classes.push "small"
if d[ @opt.countKey ] < @domainY[0] * .2
_classes.push "low"
else
_classes.push "high"
return _classes.join( " " )
_txt = _el.select( "text" )
else
_el
.append( "rect" )
.attr( "class", "count" )
.attr( "height", 20 )
.attr( "width", => @_barWidth - 8 )
_txtg = _el
.append( "g" )
.attr "transform", =>return "translate(#{@_barWidth/2},19)"
_txt = _txtg.append( "text" )
_txt.text ( d )=>
return d[ @opt.countKey ]
#
#.attr "fill", ( d )=>
# if d[ @opt.countKey ] < @domainY[0] * .2
# @opt.countColorOut
# else
# @opt.countColorIn
return _el
_enterRect: ( el, datum )=>
return
_leaveRect: ( el, datum )=>
return
create: =>
_tgrt = d3.select(@target)
_tgrt.select( "svg" ).remove()
@svg = _tgrt.append("svg")
.attr( "height", @opt._height )
.attr( "width", @opt._width )
.append("g")
.attr("transform", "translate(" + @opt.margin.left + "," + @opt.margin.top + ")")
@gxAxis = @svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(#{ @_barWidth / 2 }," + ( @opt.height - 20 ) + ")")
.call( @xAxis )
@gyAxis = @svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + ( @opt.width - 12 ) + ", 0)")
.call( @yAxis )
@_update()
return
_calcBarWidth: =>
_l = @interpolateX.ticks( d3.time[ @opt.ticks ] ).length
( @opt.width - ( _l * @opt.spacing ) ) / _l
getData: =>
@data
add: ( _data )=>
@data.push( _data )
@_calcMetrics()
@_update( true )
return
rem: ( id )=>
_removed = false
for _data, idx in @data when _data[ @opt.timeKey ] is id
@data.splice( idx, 1 )
_removed = true
break
if _removed
@_calcMetrics()
@_update( true )
return
reset: ( @data )=>
@_calcMetrics()
@_update( true )
return
_update: ( update = false )=>
@bars = @svg.selectAll(".bar")
.data @data, ( _d )=>
return _d[ @opt.timeKey ]
if update
@gxAxis
.transition()
.duration( @opt.animationDuration )
.attr("transform", "translate(#{ @_barWidth / 2 }," + ( @opt.height - 20 ) + ")")
.call( @xAxis )
@gyAxis
.transition()
.duration( @opt.animationDuration )
#.attr("transform", "translate(#{ @_barWidth / 2 }," + ( @opt.height - 20 ) + ")")
.call( @yAxis )
@bars
.transition()
.duration( @opt.animationDuration )
@bars
.enter()
.append("g")
.call( @fnRect( false ) )
@bars
.call( @fnRect( true ) )
_rems = @bars
.exit()
.call( @fnRect( true, true ) )
.remove()
return
if module?.exports?
module.exports = _TimeBars
else
window.tcscharts or= {}
window.tcscharts.TimeBars = _TimeBars | 181464 | if module?.exports?
_Base = require( "./base.js" )
@d3 = require( "d3" )
else
_Base = window.tcscharts.Base
_TimeBars = class TimeBars extends _Base
defaults:
timeKey: "<KEY>"
countKey: "<KEY>"
width: 700
height: 300
margin:
top: 20
right: 20
bottom: 10
left: 40
spacing: 3
barsColor: null
showCount: false
countColorIn: "#fff"
countColorOut: "#666"
ticks: "minutes"
timeFormat: null
timeDomain: null
smallBarWidth: 20
animationDuration: 600
constructor: ( @target, @data = [], options )->
_ret = super( @target )
@_initOptions( options, true )
@_calcMetrics()
@create()
return _ret
_calcMetrics: =>
if @domainX?
@_oldDomainX = @domainX
if @opt.timeDomain?
@domainX = @opt.timeDomain
@data = for _dt in @data when _dt[ @opt.timeKey ] > @domainX[ 0 ] and _dt[ @opt.timeKey ] < @domainX[ 1 ]
_dt
else
times = for _d in @data
_d[ @opt.timeKey ]
@domainX = [ d3.min(times), d3.max(times) ]
@domainY = [ d3.max( @data, ( ( d )=>d[ @opt.countKey ] ) ), 0]
@interpolateX = d3.time.scale()
.domain( @domainX )
@interpolateY = d3.scale.linear()
.range([ 0, @opt.height - 25 ])
.domain( @domainY )
@_barWidth = @_calcBarWidth()
@interpolateX
.range([0, @opt.width - @_barWidth ])
@xAxis = d3.svg.axis()
.scale(@interpolateX)
.orient("bottom")
@yAxis = d3.svg.axis()
.scale(@interpolateY)
.tickSize(@opt.width)
.orient("left")
if @opt.tickCount?
@xAxis.ticks( @opt.tickCount )
if @opt.timeFormat?
if typeof @opt.timeFormat is "function"
@xAxis.tickFormat( @opt.timeFormat )
else
@xAxis.tickFormat ( date )=>
d3.time.format( @opt.timeFormat )( date )
return
_initOptions: ( options, def = false )=>
@_extend( @opt = {}, @defaults, options ) if def
@opt._width = @opt.width + @opt.margin.left + @opt.margin.right
@opt._height = @opt.height + @opt.margin.top + @opt.margin.bottom
if def
for _k of @opt
@_initOption( _k )
return
_initOption: ( key )=>
odef =
get: =>
return @opt[ key ]
set: ( _v )=>
@opt[ key ] = _v
switch key
when "width", "height"
@create()
else
@create()
return
@define( key, odef, @ )
fnRect: ( update = false, remove = false )=>
return ( _el )=>
_el.attr "class", (d)=>
_classes = [ "bar" ]
if @_barWidth > @opt.smallBarWidth
_classes.push "normal"
else
_classes.push "small"
if d[ @opt.countKey ] < @domainY[0] * .2
_classes.push "low"
else
_classes.push "high"
return _classes.join( " " )
if update
_el
.transition()
.duration( @opt.animationDuration )
.attrTween "transform", ( d, i, current )=>
[ _tx, _ty ] = current[10..-2].split(",")
if remove
_h = 0
else
_h = @interpolateY( d[ @opt.countKey ] )
_x = @interpolateX( new Date( d.ts ) )
_y = _h
interX = d3.interpolate( d._x or parseFloat( _tx ), _x )
interY = d3.interpolate( d._y or parseFloat( _ty ), _y )
d._x = _x
d._y = _y
d._h = _h
return ( _t )->"translate(#{ interX( _t ) },#{ interY( _t ) })"
else
_this = @
_el.on "mouseenter", ( datum )-> _this._enterRect( @, datum )
_el.on "mouseleave", ( datum )-> _this._leaveRect( @, datum )
_el
.datum ( d )=>
_h = @interpolateY( d[ @opt.countKey ] )
d._x = @interpolateX( new Date( d.ts ) )
d._y = _h
d._h = _h
return d
.attr "transform", (d, i)=>
return "translate(#{ d._x },#{d._y})"
if update
_rect = _el.select( "rect" )
else
_rect = _el.append("rect")
if @opt.barsColor?
_rect
.attr( "fill", @opt.barsColor )
if update
_rect
.transition()
.duration( @opt.animationDuration )
.attr( "width", => @_barWidth )
.attr "height", (d, i)=>
if remove
return 1e-6
else
return @opt.height - 25 - @interpolateY( d[ @opt.countKey ] )
else
_rect
.attr( "width", => @_barWidth )
.attr "height", (d, i)=>
if remove
return 1e-6
else
return @opt.height - 25 - @interpolateY( d[ @opt.countKey ] )
if @opt.showCount
if update
_el.select( ".count" )
.attr "class", (d)=>
_classes = [ "count" ]
if @_barWidth > @opt.smallBarWidth
_classes.push "normal"
else
_classes.push "small"
if d[ @opt.countKey ] < @domainY[0] * .2
_classes.push "low"
else
_classes.push "high"
return _classes.join( " " )
_txt = _el.select( "text" )
else
_el
.append( "rect" )
.attr( "class", "count" )
.attr( "height", 20 )
.attr( "width", => @_barWidth - 8 )
_txtg = _el
.append( "g" )
.attr "transform", =>return "translate(#{@_barWidth/2},19)"
_txt = _txtg.append( "text" )
_txt.text ( d )=>
return d[ @opt.countKey ]
#
#.attr "fill", ( d )=>
# if d[ @opt.countKey ] < @domainY[0] * .2
# @opt.countColorOut
# else
# @opt.countColorIn
return _el
_enterRect: ( el, datum )=>
return
_leaveRect: ( el, datum )=>
return
create: =>
_tgrt = d3.select(@target)
_tgrt.select( "svg" ).remove()
@svg = _tgrt.append("svg")
.attr( "height", @opt._height )
.attr( "width", @opt._width )
.append("g")
.attr("transform", "translate(" + @opt.margin.left + "," + @opt.margin.top + ")")
@gxAxis = @svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(#{ @_barWidth / 2 }," + ( @opt.height - 20 ) + ")")
.call( @xAxis )
@gyAxis = @svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + ( @opt.width - 12 ) + ", 0)")
.call( @yAxis )
@_update()
return
_calcBarWidth: =>
_l = @interpolateX.ticks( d3.time[ @opt.ticks ] ).length
( @opt.width - ( _l * @opt.spacing ) ) / _l
getData: =>
@data
add: ( _data )=>
@data.push( _data )
@_calcMetrics()
@_update( true )
return
rem: ( id )=>
_removed = false
for _data, idx in @data when _data[ @opt.timeKey ] is id
@data.splice( idx, 1 )
_removed = true
break
if _removed
@_calcMetrics()
@_update( true )
return
reset: ( @data )=>
@_calcMetrics()
@_update( true )
return
_update: ( update = false )=>
@bars = @svg.selectAll(".bar")
.data @data, ( _d )=>
return _d[ @opt.timeKey ]
if update
@gxAxis
.transition()
.duration( @opt.animationDuration )
.attr("transform", "translate(#{ @_barWidth / 2 }," + ( @opt.height - 20 ) + ")")
.call( @xAxis )
@gyAxis
.transition()
.duration( @opt.animationDuration )
#.attr("transform", "translate(#{ @_barWidth / 2 }," + ( @opt.height - 20 ) + ")")
.call( @yAxis )
@bars
.transition()
.duration( @opt.animationDuration )
@bars
.enter()
.append("g")
.call( @fnRect( false ) )
@bars
.call( @fnRect( true ) )
_rems = @bars
.exit()
.call( @fnRect( true, true ) )
.remove()
return
if module?.exports?
module.exports = _TimeBars
else
window.tcscharts or= {}
window.tcscharts.TimeBars = _TimeBars | true | if module?.exports?
_Base = require( "./base.js" )
@d3 = require( "d3" )
else
_Base = window.tcscharts.Base
_TimeBars = class TimeBars extends _Base
defaults:
timeKey: "PI:KEY:<KEY>END_PI"
countKey: "PI:KEY:<KEY>END_PI"
width: 700
height: 300
margin:
top: 20
right: 20
bottom: 10
left: 40
spacing: 3
barsColor: null
showCount: false
countColorIn: "#fff"
countColorOut: "#666"
ticks: "minutes"
timeFormat: null
timeDomain: null
smallBarWidth: 20
animationDuration: 600
constructor: ( @target, @data = [], options )->
_ret = super( @target )
@_initOptions( options, true )
@_calcMetrics()
@create()
return _ret
_calcMetrics: =>
if @domainX?
@_oldDomainX = @domainX
if @opt.timeDomain?
@domainX = @opt.timeDomain
@data = for _dt in @data when _dt[ @opt.timeKey ] > @domainX[ 0 ] and _dt[ @opt.timeKey ] < @domainX[ 1 ]
_dt
else
times = for _d in @data
_d[ @opt.timeKey ]
@domainX = [ d3.min(times), d3.max(times) ]
@domainY = [ d3.max( @data, ( ( d )=>d[ @opt.countKey ] ) ), 0]
@interpolateX = d3.time.scale()
.domain( @domainX )
@interpolateY = d3.scale.linear()
.range([ 0, @opt.height - 25 ])
.domain( @domainY )
@_barWidth = @_calcBarWidth()
@interpolateX
.range([0, @opt.width - @_barWidth ])
@xAxis = d3.svg.axis()
.scale(@interpolateX)
.orient("bottom")
@yAxis = d3.svg.axis()
.scale(@interpolateY)
.tickSize(@opt.width)
.orient("left")
if @opt.tickCount?
@xAxis.ticks( @opt.tickCount )
if @opt.timeFormat?
if typeof @opt.timeFormat is "function"
@xAxis.tickFormat( @opt.timeFormat )
else
@xAxis.tickFormat ( date )=>
d3.time.format( @opt.timeFormat )( date )
return
_initOptions: ( options, def = false )=>
@_extend( @opt = {}, @defaults, options ) if def
@opt._width = @opt.width + @opt.margin.left + @opt.margin.right
@opt._height = @opt.height + @opt.margin.top + @opt.margin.bottom
if def
for _k of @opt
@_initOption( _k )
return
_initOption: ( key )=>
odef =
get: =>
return @opt[ key ]
set: ( _v )=>
@opt[ key ] = _v
switch key
when "width", "height"
@create()
else
@create()
return
@define( key, odef, @ )
fnRect: ( update = false, remove = false )=>
return ( _el )=>
_el.attr "class", (d)=>
_classes = [ "bar" ]
if @_barWidth > @opt.smallBarWidth
_classes.push "normal"
else
_classes.push "small"
if d[ @opt.countKey ] < @domainY[0] * .2
_classes.push "low"
else
_classes.push "high"
return _classes.join( " " )
if update
_el
.transition()
.duration( @opt.animationDuration )
.attrTween "transform", ( d, i, current )=>
[ _tx, _ty ] = current[10..-2].split(",")
if remove
_h = 0
else
_h = @interpolateY( d[ @opt.countKey ] )
_x = @interpolateX( new Date( d.ts ) )
_y = _h
interX = d3.interpolate( d._x or parseFloat( _tx ), _x )
interY = d3.interpolate( d._y or parseFloat( _ty ), _y )
d._x = _x
d._y = _y
d._h = _h
return ( _t )->"translate(#{ interX( _t ) },#{ interY( _t ) })"
else
_this = @
_el.on "mouseenter", ( datum )-> _this._enterRect( @, datum )
_el.on "mouseleave", ( datum )-> _this._leaveRect( @, datum )
_el
.datum ( d )=>
_h = @interpolateY( d[ @opt.countKey ] )
d._x = @interpolateX( new Date( d.ts ) )
d._y = _h
d._h = _h
return d
.attr "transform", (d, i)=>
return "translate(#{ d._x },#{d._y})"
if update
_rect = _el.select( "rect" )
else
_rect = _el.append("rect")
if @opt.barsColor?
_rect
.attr( "fill", @opt.barsColor )
if update
_rect
.transition()
.duration( @opt.animationDuration )
.attr( "width", => @_barWidth )
.attr "height", (d, i)=>
if remove
return 1e-6
else
return @opt.height - 25 - @interpolateY( d[ @opt.countKey ] )
else
_rect
.attr( "width", => @_barWidth )
.attr "height", (d, i)=>
if remove
return 1e-6
else
return @opt.height - 25 - @interpolateY( d[ @opt.countKey ] )
if @opt.showCount
if update
_el.select( ".count" )
.attr "class", (d)=>
_classes = [ "count" ]
if @_barWidth > @opt.smallBarWidth
_classes.push "normal"
else
_classes.push "small"
if d[ @opt.countKey ] < @domainY[0] * .2
_classes.push "low"
else
_classes.push "high"
return _classes.join( " " )
_txt = _el.select( "text" )
else
_el
.append( "rect" )
.attr( "class", "count" )
.attr( "height", 20 )
.attr( "width", => @_barWidth - 8 )
_txtg = _el
.append( "g" )
.attr "transform", =>return "translate(#{@_barWidth/2},19)"
_txt = _txtg.append( "text" )
_txt.text ( d )=>
return d[ @opt.countKey ]
#
#.attr "fill", ( d )=>
# if d[ @opt.countKey ] < @domainY[0] * .2
# @opt.countColorOut
# else
# @opt.countColorIn
return _el
_enterRect: ( el, datum )=>
return
_leaveRect: ( el, datum )=>
return
create: =>
_tgrt = d3.select(@target)
_tgrt.select( "svg" ).remove()
@svg = _tgrt.append("svg")
.attr( "height", @opt._height )
.attr( "width", @opt._width )
.append("g")
.attr("transform", "translate(" + @opt.margin.left + "," + @opt.margin.top + ")")
@gxAxis = @svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(#{ @_barWidth / 2 }," + ( @opt.height - 20 ) + ")")
.call( @xAxis )
@gyAxis = @svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + ( @opt.width - 12 ) + ", 0)")
.call( @yAxis )
@_update()
return
_calcBarWidth: =>
_l = @interpolateX.ticks( d3.time[ @opt.ticks ] ).length
( @opt.width - ( _l * @opt.spacing ) ) / _l
getData: =>
@data
add: ( _data )=>
@data.push( _data )
@_calcMetrics()
@_update( true )
return
rem: ( id )=>
_removed = false
for _data, idx in @data when _data[ @opt.timeKey ] is id
@data.splice( idx, 1 )
_removed = true
break
if _removed
@_calcMetrics()
@_update( true )
return
reset: ( @data )=>
@_calcMetrics()
@_update( true )
return
_update: ( update = false )=>
@bars = @svg.selectAll(".bar")
.data @data, ( _d )=>
return _d[ @opt.timeKey ]
if update
@gxAxis
.transition()
.duration( @opt.animationDuration )
.attr("transform", "translate(#{ @_barWidth / 2 }," + ( @opt.height - 20 ) + ")")
.call( @xAxis )
@gyAxis
.transition()
.duration( @opt.animationDuration )
#.attr("transform", "translate(#{ @_barWidth / 2 }," + ( @opt.height - 20 ) + ")")
.call( @yAxis )
@bars
.transition()
.duration( @opt.animationDuration )
@bars
.enter()
.append("g")
.call( @fnRect( false ) )
@bars
.call( @fnRect( true ) )
_rems = @bars
.exit()
.call( @fnRect( true, true ) )
.remove()
return
if module?.exports?
module.exports = _TimeBars
else
window.tcscharts or= {}
window.tcscharts.TimeBars = _TimeBars |
[
{
"context": "ast')\n\n# We use the [bluebird](https://github.com/petkaantonov/bluebird)\n# third-party module to provide a promi",
"end": 3338,
"score": 0.9995909929275513,
"start": 3326,
"tag": "USERNAME",
"value": "petkaantonov"
},
{
"context": "nce method\n # [nodeify](htt... | drivers/javascript/net.coffee | NicoHood/rethinkdb | 0 | # # Network (net.coffee)
#
# This module handles network and protocol related functionality for
# the driver. The classes defined here are:
#
# - `Connection`, which is an EventEmitter and the base class for
# - `TcpConnection`, the standard driver connection
# - `HttpConnection`, the connection type used by the webui
#
# ### Imports
#
# The [net module](http://nodejs.org/api/net.html) is the low-level
# networking library Node.js provides. We need it for `TcpConnection`
# objects
net = require('net')
# The [tls module](http://nodejs.org/api/tls.html) is the TLS/SSL
# networking library Node.js provides. We need it to establish an
# encrypted connection for `TcpConnection` objects
tls = require('tls')
# The [events module](http://nodejs.org/api/events.html) is a core
# Node.js module that provides the ability for objects to emit events,
# and for callbacks to be attached to those events.
events = require('events')
# The [util module](util.html) contains utility methods used several
# places in the driver
util = require('./util')
# The [errors module](errors.html) contains exceptions thrown by the driver
err = require('./errors')
# The [cursors module](cursors.html) contains data structures used to
# iterate over large result sets or infinite streams of data from the
# database (changefeeds).
cursors = require('./cursor')
# The `proto-def` module is an autogenerated file full of protocol
# definitions used to communicate to the RethinkDB server (basically a
# ton of human readable names for magic numbers).
#
# It is created by the python script `convert_protofile` in the
# `drivers` directory (one level up from this file) by converting a
# protocol buffers definition file into a JavaScript file. To generate
# the `proto-def.js` file, see the instructions in the
# [README](./index.html#creating-the-proto-defjs)
#
# Note that it's a plain JavaScript file, not a CoffeeScript file.
protodef = require('./proto-def')
crypto = require("crypto")
# Each version of the protocol has a magic number specified in
# `./proto-def.coffee`. The most recent version is 4. Generally the
# official driver will always be updated to the newest version of the
# protocol, though RethinkDB supports older versions for some time.
protoVersion = protodef.VersionDummy.Version.V1_0
protoVersionNumber = 0
# We are using the JSON protocol for RethinkDB, which is the most
# recent version. The older protocol is based on Protocol Buffers, and
# is deprecated.
protoProtocol = protodef.VersionDummy.Protocol.JSON
# The `QueryType` definitions are used to control at a high level how
# we interact with the server. So we can `START` a new query, `STOP`
# an executing query, `CONTINUE` receiving results from an existing
# cursor, or wait for all outstanding `noreply` queries to finish with
# `NOREPLY_WAIT`.
protoQueryType = protodef.Query.QueryType
# The server can respond to queries in several ways. These are the
# definitions for the response types.
protoResponseType = protodef.Response.ResponseType
# The [ast module](ast.html) contains the bulk of the api exposed by
# the driver. It defines how you can create ReQL queries, and handles
# serializing those queries into JSON to be transmitted over the wire
# to the database server.
r = require('./ast')
# We use the [bluebird](https://github.com/petkaantonov/bluebird)
# third-party module to provide a promise implementation for the
# driver.
Promise = require('bluebird')
# These are some functions we import directly from the `util` module
# for convenience.
ar = util.ar
varar = util.varar
aropt = util.aropt
mkAtom = util.mkAtom
mkErr = util.mkErr
# These are the default hostname and port used by RethinkDB
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 28015
module.exports.DEFAULT_HOST = DEFAULT_HOST
module.exports.DEFAULT_PORT = DEFAULT_PORT
# These are strings returned by the server after a handshake
# request. Since they must match exactly they're defined in
# "constants" here at the top
HANDSHAKE_SUCCESS = "SUCCESS"
HANDSHAKE_AUTHFAIL = "ERROR: Incorrect authorization key.\n"
# ### Connection
#
# Connection is the base class for both `TcpConnection` and
# `HttpConnection`. Applications using this driver will need to get a
# connection object to be able to query the server.
#
# Connection is a subclass of
# [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter),
# and it will emit the following events:
#
# - `"connect"` is emitted by the subclasses `TcpConnection` and
# `HttpConnection` when they connect to the server successfully.
# - `"error"` is emitted when protocol level errors occur (notably
# not query errors! Those are returned as arguments to the
# callback the user provides.) `"error"` will also be accompanied
# by a message indicating what went wrong.
# - `"close"` is emitted when the connection is closed either through
# an error or by the user calling `connection.close()` explicitly
# - `"timeout"` will be emitted by the `TcpConnection` subclass if the
# underlying socket times out for any reason.
class Connection extends events.EventEmitter
# By default, RethinkDB doesn't use an authorization key.
DEFAULT_AUTH_KEY: ''
# Each connection has a timeout (in seconds) for the initial handshake with the
# server. Note that this is not a timeout for queries to return
# results.
DEFAULT_TIMEOUT: 20 # In seconds
# #### Connection constructor
constructor: (host, callback) ->
# We need to set the defaults if the user hasn't supplied anything.
if typeof host is 'undefined'
host = {}
# It's really convenient to be able to pass just a hostname to
# connect, since that's the thing that is most likely to vary
# (default ports, no auth key, default connection timeout are
# all common). We just detect that case and wrap it.
else if typeof host is 'string'
host = {host: host}
# Here we set all of the connection parameters to their defaults.
@host = host.host || DEFAULT_HOST
@port = host.port || DEFAULT_PORT
# One notable exception to defaulting is the db name. If the
# user doesn't specify it, we leave it undefined. On the
# server side, if no database is specified for a table, the
# database will default to `"test"`.
@db = host.db # left undefined if this is not set
@authKey = host.authKey || @DEFAULT_AUTH_KEY
@timeout = host.timeout || @DEFAULT_TIMEOUT
# Configuration options for enabling an SSL connection
# Allows the ability to pass in all the options as specified in
# [tls.connect](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback)
# or just true in case the client wants ssl but the server
# is using a certificate with a valid verified chain and there
# is no need to specify certificates on the client
if typeof host.ssl is 'boolean' && host.ssl
@ssl = {}
else if typeof host.ssl is 'object'
@ssl = host.ssl
else
@ssl = false
# The protocol allows for responses to queries on the same
# connection to be returned interleaved. When a query is run
# with this connection, an entry is added to
# `@outstandingCallbacks`. The key is the query token, and the
# value is an object with the following fields:
#
# - **cb**: The callback to invoke when a query returns another
# batch of results
# - **root**: a subclass of `TermBase` (defined in the
# [ast module](ast.html)) representing the query being run.
# - **opts**: global options passed to `.run`.
#
# Once the server returns a response, one of two fields may be
# added to the entry for that query depending on what comes
# back (this is done in `_processResponse`):
#
# - **cursor**: is set to a `Cursor` object (defined in the
# [cursor module](cursor.html)) if the server
# replies with `SUCCESS_PARTIAL`. This happens when a
# result is too large to send back all in one batch. The
# `Cursor` allows fetching results lazily as they're needed.
# - **feed**: is set to a `Feed` object (defined in the
# [cursor module](cursor.html)). This is very similar to a `Cursor`,
# except that it is potentially infinite. Changefeeds are a way
# for the server to notify the client when a change occurs to
# the results of a query the user wants to watch.
#
# Any other responses are considered "done" and don't have any
# further results to fetch from the server. At that time the
# query token is deleted from `@outstandingCallbacks` since we
# don't expect any more results using that token.
@outstandingCallbacks = {}
# Each query to the server requires a unique token (per
# connection). `nextToken` is incremented every time we issue
# a new query
@nextToken = 1
# `@open` and `@closing` are used to record changes in the
# connection state. A connection is open after the handshake
# is successfully completed, and it becomes closed after the
# server confirms the connection is closed.
@open = false
# `@closing` is true when the `conn.close()` method is called,
# and becomes false again just before the callback provided to
# `close` is called. This allows `noreplyWait` to be called
# from within `.close`, but prevents any other queries from
# being run on a closing connection. (`noreplyWait` checks
# `@open` only to see if the connection is closed, but the
# `.isOpen()` method checks both flags)
@closing = false
# We create a [Buffer](http://nodejs.org/api/buffer.html)
# object to receive all bytes coming in on this
# connection. The buffer is modified in the `_data` method
# (which is called whenever data comes in over the network on
# this connection), and it is also modified by the handshake
# callback that's defined in the `TcpConnection` constructor.
@buffer = new Buffer(0)
@_events = @_events || {}
# Now we set up two callbacks, one to run on successful
# connection, and the other to run if we fail to connect to
# the server. They listen to the `"connect"` and `"error"`
# events respectively. If successful, we set `@open` to
# `true`, otherwise we pass an error to the connection
# callback that was passed to the constructor (`callback`)
errCallback = (e) =>
@removeListener 'connect', conCallback
if e instanceof err.ReqlError
callback e
else
callback new err.ReqlDriverError "Could not connect to #{@host}:#{@port}.\n#{e.message}"
@once 'error', errCallback
conCallback = =>
@removeListener 'error', errCallback
@open = true
callback null, @
@once 'connect', conCallback
# closePromise holds the promise created when `.close()` is
# first called. Subsequent calls to close will simply add to
# this promise, rather than attempt closing again.
@_closePromise = null
# #### Connection _data method
#
# This method is responsible for parsing responses from the server
# after the initial handshake is over. It reads the token number
# of the response (so we know which query is being responded to),
# and the response length, then parses the rest of the response as
# JSON.
_data: (buf) ->
# We extend the current buffer with the contents of `buf` that
# we got from the server.
@buffer = Buffer.concat([@buffer, buf])
# The first 8 bytes in a response are the token number of the
# query the server is responding to. The next 4 bytes indicate
# how long the response will be. So if the response isn't at
# least 12 bytes long, there's nothing else to do.
while @buffer.length >= 12
# When a query is sent to the server, we write out the
# token in a way that can be read back later as a native
# integer. Since Node buffers don't have a method like
# `readUInt64LE`, we're forced to emulate it ourselves.
token = @buffer.readUInt32LE(0) + 0x100000000 * @buffer.readUInt32LE(4)
# Next up is the response length. The protocol dictates
# this must be a 32 bit unsigned integer in little endian
# byte order.
responseLength = @buffer.readUInt32LE(8)
# This ensures that the responseLength is less than or
# equal to the amount of data we have in the buffer
# (including the token and response length itself). If the
# buffer doesn't have enough data in it, we just break
# out. More data will be coming later, and it will be
# added to the end of the buffer, so we'll wait until the
# full response is available.
unless @buffer.length >= (12 + responseLength)
break
# Since we have enough data, we slice it out of the
# buffer, and parse it as JSON.
responseBuffer = @buffer.slice(12, responseLength + 12)
response = JSON.parse(responseBuffer)
# Now it's off to `_processResponse` where the data is
# converted to a format the user will be able to work
# with, error responses are detected etc.
@_processResponse response, token
# Finally, we truncate the buffer to the end of the
# current response. The buffer may already be queuing up a
# new response, so it's never safe to clear it or create a
# new one.
@buffer = @buffer.slice(12 + responseLength)
# #### Connection _delQuery method
#
# This method just removes the entry in `@outstandingCallbacks`
# for a given token. It's called whenever a response doesn't
# return a cursor, a cursor is completely consumed, or the query
# encounters an error.
_delQuery: (token) ->
delete @outstandingCallbacks[token]
# #### Connection _processResponse method
#
# This method is contains the main logic for taking different
# actions based on the response type. It receives the response as
# an object (parsed from the JSON coming over the wire), and the
# token for the query the response corresponds to.
_processResponse: (response, token) ->
# For brevity the wire format specifies that the profile key
# is "p". We give it a more readable variable name here.
profile = response.p
# First we need to check if we're even expecting a response
# for this token. If not it's an error.
if @outstandingCallbacks[token]?
{cb:cb, root:root, cursor: cursor, opts: opts, feed: feed} = @outstandingCallbacks[token]
# Some results for queries are not returned all at once,
# but in chunks. The driver takes care of making sure the
# user doesn't see this, and uses `Cursor`s to take
# multiple responses and make them into one long stream of
# query results.
#
# Depending on the type of result, and whether this is the
# first response for this token, we may or may not have a
# cursor defined for this token. If we do have a cursor
# defined already, we add this response to the cursor.
if cursor?
cursor._addResponse(response)
# `cursor._addResponse` will check if this response is
# the last one for this token, and if so will set its
# `cursor._endFlag` to true. If this is the last
# response for this query and we aren't waiting on any
# other responses for this cursor (if, for example, we
# get the responses out of order), then we remove this
# token's entry in `@outstandingCallbacks`.
if cursor._endFlag && cursor._outstandingRequests is 0
@_delQuery(token)
# Next we check if we have a callback registered for this
# token. In [ast](ast.html) we always provide `_start`
# with a wrapped callback function, so this may as well be
# an else branch.
else if cb?
# The protocol (again for brevity) puts the response
# type into a key called "t". What we do next depends
# on that value. We'll be comparing it to the values
# in the `proto-def` module, in `protoResponseType`.
switch response.t
# ##### Error responses
when protoResponseType.COMPILE_ERROR
# Compile errors happen during parsing and
# type checking the query on the server
# side. An example is passing too many
# arguments to a function. We pass an error
# object that includes the backtrace from the
# response and the original query
# (`root`). Then we delete the token from
# `@outstandingCallbacks`.
cb mkErr(err.ReqlServerCompileError, response, root)
@_delQuery(token)
when protoResponseType.CLIENT_ERROR
# Client errors are returned when the client
# is buggy. This can happen if a query isn't
# serialized right, or the handshake is done
# incorrectly etc. Hopefully end users of the
# driver should never see these.
cb mkErr(err.ReqlDriverError, response, root)
@_delQuery(token)
when protoResponseType.RUNTIME_ERROR
# Runtime errors are the most common type of
# error. They happen when something goes wrong
# that can only be determined by running the
# query. For example, if you try to get the
# value of a field in an object that doesn't
# exist.
errType = util.errorClass(response.e)
cb mkErr(errType, response, root)
@_delQuery(token)
# ##### Success responses
when protoResponseType.SUCCESS_ATOM
# `SUCCESS_ATOM` is returned when the query
# was successful and returned a single ReQL
# data type. The `mkAtom` function from the
# [util module](util.html) converts all
# pseudotypes in this response to their
# corresponding native types
response = mkAtom response, opts
# If the response is an array, we patch it a
# bit so it can be used as a stream.
if Array.isArray response
response = cursors.makeIterable response
# If there's a profile available, we nest the
# response slightly differently before passing
# it to the callback for this token.
if profile?
response = {profile: profile, value: response}
cb null, response
# The `SUCCESS_ATOM` response means there will
# be no further results for this query, so we
# remove it from `@outstandingCallbacks`
@_delQuery(token)
when protoResponseType.SUCCESS_PARTIAL
# `SUCCESS_PARTIAL` indicates the client
# should create a cursor and request more data
# from the server when it's ready by sending a
# `CONTINUE` query with the same token. So, we
# create a new Cursor for this token, and add
# it to the object stored in
# `@outstandingCallbacks`.
# We create a new cursor, which is sometimes a
# `Feed`, `AtomFeed`, or `OrderByLimitFeed`
# depending on the `ResponseNotes`. (This
# usually doesn't matter, but third-party ORMs
# might want to treat these differently.)
cursor = null
for note in response.n
switch note
when protodef.Response.ResponseNote.SEQUENCE_FEED
cursor ?= new cursors.Feed @, token, opts, root
when protodef.Response.ResponseNote.UNIONED_FEED
cursor ?= new cursors.UnionedFeed @, token, opts, root
when protodef.Response.ResponseNote.ATOM_FEED
cursor ?= new cursors.AtomFeed @, token, opts, root
when protodef.Response.ResponseNote.ORDER_BY_LIMIT_FEED
cursor ?= new cursors.OrderByLimitFeed @, token, opts, root
cursor ?= new cursors.Cursor @, token, opts, root
# When we've created the cursor, we add it to
# the object stored in
# `@outstandingCallbacks`.
@outstandingCallbacks[token].cursor = cursor
# Again, if we have profile information, we
# wrap the result given to the callback. In
# either case, we need to add the response to
# the new Cursor.
if profile?
cb null, {profile: profile, value: cursor._addResponse(response)}
else
cb null, cursor._addResponse(response)
when protoResponseType.SUCCESS_SEQUENCE
# The `SUCCESS_SEQUENCE` response is sent when
# a cursor or feed is complete, and this is
# the last response that will be received for
# this token. Often, however, the entire
# result for a query fits within the initial
# batch. In this case, we never see a
# `SUCCESS_PARTIAL` response, so there is no
# existing Cursor to add the response to. So,
# that's what we do here, create a new Cursor,
# and delete the token from the
# `@outstandingCallbacks`.
#
# Note that qeries that have already received
# a `SUCCESS_PARTIAL` will not be handled
# here. They will be handled when we check for
# `cursor?` in the conditional up above. In
# that branch, we call cursor._addResponse,
# which takes care of checking if we received
# a `SUCCESS_SEQUENCE`. So this code only gets
# executed when the first batch on a cursor is
# also our last.
cursor = new cursors.Cursor @, token, opts, root
@_delQuery(token)
if profile?
cb null, {profile: profile, value: cursor._addResponse(response)}
else
cb null, cursor._addResponse(response)
when protoResponseType.WAIT_COMPLETE
# The `WAIT_COMPLETE` response is sent by the
# server after all queries executed with the
# optarg `noReply: true` have completed. No
# data is returned, so the callback is just provided `null`
@_delQuery(token)
cb null, null
when protoResponseType.SERVER_INFO
@_delQuery(token)
response = mkAtom response, opts
cb null, response
else
cb new err.ReqlDriverError "Unknown response type"
else
# We just ignore tokens we don't have a record of. This is
# what the other drivers do as well.
# #### Connection close method
#
# A public method that closes the connection. See [API docs for
# close](http://rethinkdb.com/api/javascript/close/).
close: (varar 0, 2, (optsOrCallback, callback) ->
# First determine which argument combination this method was
# called with, and set the callback and options appropriately.
if callback?
# When calling like `.close({...}, function(...){ ... })`
opts = optsOrCallback
unless Object::toString.call(opts) is '[object Object]'
throw new err.ReqlDriverError "First argument to two-argument `close` must be an object."
cb = callback
else if Object::toString.call(optsOrCallback) is '[object Object]'
# When calling like `.close({...})`
opts = optsOrCallback
cb = null
else if typeof optsOrCallback is 'function'
# When calling like `.close(function(...){ ... })`
opts = {}
cb = optsOrCallback
else
# When calling like `.close({...})`
opts = optsOrCallback
cb = null
for own key of opts
# Currently, only one optional argument is accepted by
# `.close`: whether or not to wait for completion of all
# outstanding `noreply` queries. So we throw an error if
# anything else is passed.
unless key in ['noreplyWait']
throw new err.ReqlDriverError "First argument to two-argument `close` must be { noreplyWait: <bool> }."
# If we're currently in the process of closing, just add the
# callback to the current promise
if @_closePromise?
return @_closePromise.nodeify(cb)
# Next we set `@closing` to true. It will be set false once
# the promise that `.close` returns resolves (see below). The
# `isOpen` method takes this variable into account.
@closing = true
# Should we wait for all outstanding `noreply` writes before
# considering the connection closed?
#
# - if the options object doesn't have a `noreplyWait` key, we
# default to `true`.
# - if we do have a `noreplyWait` key, then use that value
# - if this connection isn't `@open`, then this is all moot
noreplyWait = ((not opts.noreplyWait?) or opts.noreplyWait) and @open
# Finally, close returns a promise. This promise must do two
# things:
#
# 1. Set the flags for this connection to false (`@open` &
# `@closing`)
#
# 2. Close all cursors and feeds for outstanding callbacks. We
# won't be receiving any more responses for them, so they are
# no longer outstanding. (this is what `@cancel()` does)
#
# In addition to these two finalization steps, we may need to
# wait for all `noreply` queries to finish.
#
# You'll notice we don't close sockets or anything like that
# here. Those steps are done in the subclasses because they
# have knowledge about what kind of underlying connection is
# being used.
#
# We save the promise here in case others attempt to call
# `close` before we've gotten a response from the server (when
# the @closing flag is true).
@_closePromise = new Promise( (resolve, reject) =>
# Now we create the Promise that `.close` returns. If we
# aren't waiting for `noreply` queries, then we set the flags
# and cancel feeds/cursors immediately. If we are waiting,
# then we run a `noreplyWait` query and set the flags and
# cancel cursors when that query receives a response.
#
# In addition, we chain the callback passed to `.close` on the
# end, using bluebird's convenience method
# [nodeify](https://github.com/petkaantonov/bluebird/blob/master/API.md#nodeifyfunction-callback--object-options---promise)
#
wrappedCb = (err, result) =>
@open = false
@closing = false
@cancel()
if err?
reject err
else
resolve result
if noreplyWait
@noreplyWait(wrappedCb)
else
wrappedCb()
).nodeify cb
)
# #### Connection noreplyWait method
#
# A public method that sends a query to the server that completes
# when all previous outstanding queries are completed. See [API
# docs for
# noreplyWait](http://rethinkdb.com/api/javascript/noreplyWait/).
noreplyWait: varar 0, 1, (callback) ->
# If the connection is not open, all of the outstanding
# `noreply` queries have already been cancelled by the server,
# so it's an error to call this now. However, `noreplyWait` is
# called by the `.close` method just before setting the
# `@open` flag to false. This is why we need the `@closing`
# flag, so we can allow one last `noreplyWait` call before the
# connection is closed completely.
unless @open
return new Promise( (resolve, reject) ->
reject(new err.ReqlDriverError "Connection is closed.")
).nodeify callback
# Since `noreplyWait` is invoked just like any other query, we
# need a token.
token = @nextToken++
# Here we construct the query itself. There's no body needed,
# we just have to set the type to the appropriate value from
# `proto-def` and set the token.
query = {}
query.type = protoQueryType.NOREPLY_WAIT
query.token = token
new Promise( (resolve, reject) =>
# The method passed to Promise is invoked immediately
wrappedCb = (err, result) ->
# This callback will be invoked when the
# `NOREPLY_WAIT` query finally returns.
if (err)
reject(err)
else
resolve(result)
# Here we add an entry for this query to
# `@outstandingCallbacks`. This promise will be resolved
# or rejected at that time.
@outstandingCallbacks[token] = {cb:wrappedCb, root:null, opts:null}
# Finally, serialize the query and send it to the server
@_sendQuery(query)
# After the promise is resolved, the callback passed to
# `noreplyWait` can be invoked.
).nodeify callback
# #### Connection server method
#
# Public, retrieves the remote server id and name. See [API docs
# for server](http://rethinkdb.com/api/javascript/server/).
server: varar 0, 1, (callback) ->
unless @open
return new Promise( (resolve, reject) ->
reject(new err.ReqlDriverError "Connection is closed.")
).nodeify callback
token = @nextToken++
query = {}
query.type = protoQueryType.SERVER_INFO
query.token = token
new Promise( (resolve, reject) =>
wrappedCb = (err, result) ->
if (err)
reject(err)
else
resolve(result)
@outstandingCallbacks[token] = {cb:wrappedCb, root:null, opts:null}
@_sendQuery(query)
).nodeify callback
# #### Connection cancel method
#
# This method inserts a dummy error response into all outstanding
# cursors and feeds, effectively closing them. It also calls all
# registered callbacks with an error response. Then it clears the
# `@outstandingCallbacks` registry.
cancel: ar () ->
# The type of the dummy response is a runtime error, the
# reason for the error is "Connection is closed" and the
# backtrace provided is empty
response = {t:protoResponseType.RUNTIME_ERROR,r:["Connection is closed."],b:[]}
for own key, value of @outstandingCallbacks
if value.cursor?
value.cursor._addResponse(response)
else if value.cb?
value.cb mkErr(util.errorClass(response.e), response, value.root)
@outstandingCallbacks = {}
# #### Connection reconnect method
#
# Closes and re-opens a connection. See the [API
# docs](http://rethinkdb.com/api/javascript/reconnect/)
reconnect: (varar 0, 2, (optsOrCallback, callback) ->
# Similar to `.close`, there are a few different ways of
# calling `.reconnect`, so we need to determine which way it
# was called, and set the options and callback appropriately.
if callback?
# When calling like `reconnect({}, function(..){ ... })`
opts = optsOrCallback
cb = callback
else if typeof optsOrCallback is "function"
# When calling like `reconnect(function(..){ ... })`
opts = {}
cb = optsOrCallback
else
# In either of these cases, the callback will be undefined
if optsOrCallback?
# Was called like `reconnect({})`
opts = optsOrCallback
else
# Was called like `reconnect()`
opts = {}
cb = callback
# Here we call `close` with a callback that will reconnect
# with the same parameters
new Promise( (resolve, reject) =>
closeCb = (err) =>
@constructor.call @,
host:@host,
port:@port
timeout:@timeout,
authKey:@authKey
, (err, conn) ->
if err?
reject err
else
resolve conn
@close(opts, closeCb)
).nodeify cb
)
# #### Connection use method
#
# This is a public method, [see the API
# docs](http://rethinkdb.com/api/javascript/use/). It sets the
# default db to use when `r.table` is called without specifying a
# db explicitly. The db variable is sent as a global optarg when
# querying.
use: ar (db) ->
@db = db
# #### Connection isOpen method
#
# This is a non-public method that's used by subclasses to
# determine if it's safe to call `noreplyWait` when closing. It
# respects both the `@open` flag and the `@closing` flag, whose
# behavior is described in the docs for `.close`
isOpen: () ->
@open and not @closing
# #### Connection _start method
#
# `_start` combines the raw query term with global optargs,
# creates a new token for the query and invokes `_sendQuery` with
# it. `_start` is called by the `.run` method from the [ast
# module](ast.html)
_start: (term, cb, opts) ->
# Obviously, you can't query with a closed connection.
unless @open then throw new err.ReqlDriverError "Connection is closed."
# Here is where the token for the query is
# generated. @nextToken is only ever incremented here and in
# the `.noreplyWait` method
token = @nextToken++
# Here we construct the wrapper object for queries
query = {}
# The global optargs are the optional arguments passed to
# `.run`, plus some variables that are set on the connection
# itself, like `db`.
query.global_optargs = {}
# Normal queries begin with `START`. The other options are
# `CONTINUE` (for feeds and cursors), `STOP` (for closing an
# open cursor/feed), and `NOREPLY_WAIT` which is a special
# type of query (see the `.noreplyWait` method).
query.type = protoQueryType.START
query.query = term.build()
query.token = token
# Now we loop through the options passed to `.run`, convert
# them to the right format, and put them into the global
# optargs object for this query
for own key, value of opts
# In the protocol, only "snake_case" is accepted for
# optargs. Because the JS convention is to use
# "camelCase", we convert it before serializing.
#
# In addition, we take the values passed, and convert them
# into a ReQL term, and dump them in the protocol format,
# instead of including them directly as they are. This
# gives resistance to injection attacks.
query.global_optargs[util.fromCamelCase(key)] = r.expr(value).build()
# If the user has specified the `db` on the connection (either
# in the constructor, as an optarg to .run(), or with the `.use` method)
# we add that db to the optargs for the query.
if opts.db? or @db?
query.global_optargs.db = r.db(opts.db or @db).build()
# Next, ensure that the `noreply` and `profile` options
# (if present) are actual booleans using the `!!` trick.
# Note that `r.expr(false).build() == false` and
# `r.expr(null).build() == null`, so the conversion in the
# loop above won't affect the boolean value the user intended
# to pass.
if opts.noreply?
query.global_optargs['noreply'] = r.expr(!!opts.noreply).build()
if opts.profile?
query.global_optargs['profile'] = r.expr(!!opts.profile).build()
# Here we stash away the callback the user provided in
# `@outstandingCallbacks`, with the query term and the options
# passed to `.run`. Note that we don't consider the callback
# as outstanding if the user has specified `noreply`. Since
# the server will never respond, it would sit in
# `@outstandingCallbacks` forever.
if (not opts.noreply?) or !opts.noreply
@outstandingCallbacks[token] = {cb:cb, root:term, opts:opts}
# Now we send the user's query. `_sendQuery` writes the
# necessary headers and will serialize it for sending over the
# underlying connection type (either tcp or http).
@_sendQuery(query)
# Finally, if the user called `.run` with both a callback and
# the `noreply` flag set, we just invoke it immediately, since
# there won't be a response from the server. Since we have no
# idea if there's an error and no response, we just pass it
# null (with error undefined).
if opts.noreply? and opts.noreply and typeof(cb) is 'function'
cb null # There is no error and result is `undefined`
# #### Connection _continueQuery method
#
# This method sends a notification to the server that we'd like to
# receive the next batch from a feed or a cursor
# (`CONTINUE`). Feeds may block indefinitely, but cursors should
# return quickly.
_continueQuery: (token) ->
unless @open then throw new err.ReqlDriverError "Connection is closed."
query =
type: protoQueryType.CONTINUE
token: token
@_sendQuery(query)
# #### Connection _endQuery method
#
# This method sends a notification to the server that we don't
# care about the rest of the results on a cursor or feed (`STOP`).
_endQuery: (token) ->
unless @open then throw new err.ReqlDriverError "Connection is closed."
query =
type: protoQueryType.STOP
token: token
@_sendQuery(query)
# #### Connection _sendQuery method
#
# This method serializes a javascript object in the rethinkdb json
# protocol format into a string, and sends it over the underlying
# connection by calling `_writeQuery`
_sendQuery: (query) ->
# The wire protocol doesn't use JSON objects except for things
# like optargs. Instead it's a bunch of nested arrays, where
# the first element of the array indicates what the type of
# that object is. This is a lot like lisp. Here the entire
# query is wrapped in an array, with the first element the
# type of the query (`START`, `STOP`, `CONTINUE`, or
# `NOREPLY_WAIT`).
data = [query.type]
# If the query has a body, (which it only does in the `START`
# case), then we push it into the outer array.
if !(query.query is undefined)
data.push(query.query)
if query.global_optargs? and Object.keys(query.global_optargs).length > 0
data.push(query.global_optargs)
# This is the last bit the Connection superclass can
# do. `_writeQuery` is implemented by the subclasses since
# they know what underlying connection type is being used.
# This is also where the query is finally converted into a
# string.
@_writeQuery(query.token, JSON.stringify(data))
# Global cache variable for storing the results of pbkdf2_hmac
pbkdf2_cache = {}
# ### TcpConnection
#
# This class implements all of the TCP specific behavior for normal
# driver connections. External users of the driver should only use
# `TcpConnection`s since `HttpConnection` are just for the webui.
#
# Fundamentally, this class uses the `net` module to wrap a raw socket
# connection to the server.
class TcpConnection extends Connection
# #### TcpConnection isAvailable method
#
# The TcpConnection should never be used by the webui, so we have
# an extra method here that decides whether it's available. This
# is called by the constructor, but also by the `.connect`
# function which uses it to decide what kind of connection to
# create.
@isAvailable: () -> !(process.browser)
# #### TcpConnection constructor method
#
# This sets up all aspects of the connection that relate to
# TCP. Everything else is done in the Connection superclass
# constructor.
constructor: (host, callback) ->
# Bail out early if we happen to be in the browser
unless TcpConnection.isAvailable()
throw new err.ReqlDriverError "TCP sockets are not available in this environment"
# Invoke the superclass's constructor. This initializes the
# attributes `@host`, `@port`, `@db`, `@authKey` and
# `@timeout`, `@outstandingCallbacks`, `@nextToken`, `@open`,
# `@closing`, and `@buffer`. It also registers the callback to
# be invoked once the `"connect"` event is emitted.
super(host, callback)
# Next we create the underlying tcp connection to the server
# using the net module and store it in the `@rawSocket`
# attribute.
if @ssl
@ssl.host = @host
@ssl.port = @port
@rawSocket = tls.connect @ssl
else
@rawSocket = net.connect @port, @host
# We disable [Nagle's
# algorithm](http://en.wikipedia.org/wiki/Nagle%27s_algorithm)
# on the socket because it can impose unnecessary
# latency.
@rawSocket.setNoDelay()
# Enable TCP keepalive so we can detect dead connections.
@rawSocket.setKeepAlive(true)
# Here we use the `@timeout` value passed to `.connect` to
# destroy the socket and emit a timeout error. The timer will
# be cancelled upon successful connection.
timeout = setTimeout( (()=>
@rawSocket.destroy()
@emit 'error', new err.ReqlTimeoutError(
"Could not connect to #{@host}:#{@port}, operation timed out.")
), @timeout*1000)
# If any other kind of error occurs, we also want to cancel
# the timeout error callback. Otherwise a connection error
# would be followed shortly by a spurious timeout error.
@rawSocket.once 'error', => clearTimeout(timeout)
# Once the TCP socket successfully connects, we can begin the
# handshake with the server to establish the connection on the
# server.
@rawSocket.once 'connect', =>
# The protocol specifies that the magic number for the
# version should be given as a little endian 32 bit
# unsigned integer. The value is given in the `proto-def`
# module, but it is just a random number that's unlikely
# to be accidentally the first few bytes of an erroneous
# connection on the socket.
version = new Buffer(4)
version.writeUInt32LE(protoVersion, 0)
# Send the protocol type that we will be using to
# communicate with the server. Json is the only currently
# supported protocol.
protocol = new Buffer(4)
protocol.writeUInt32LE(protoProtocol, 0)
r_string = new Buffer(crypto.randomBytes(18)).toString('base64')
@rawSocket.user = host["user"]
@rawSocket.password = host["password"]
# Default to admin user with no password if none is given.
if @rawSocket.user is undefined
@rawSocket.user = "admin"
if @rawSocket.password is undefined
@rawSocket.password = ""
client_first_message_bare = "n=" + @rawSocket.user + ",r=" + r_string
message = JSON.stringify({
protocol_version: protoVersionNumber,
authentication_method: "SCRAM-SHA-256",
authentication: "n,," + client_first_message_bare})
nullbyte = new Buffer('\0', "binary")
@rawSocket.write Buffer.concat([version, Buffer(message.toString()), nullbyte])
# Now we have to wait for a response from the server
# acknowledging the new connection. The following callback
# will be invoked when the server sends the first few
# bytes over the socket.
state = 1
min = 0
max = 0
server_first_message = ""
server_signature = ""
auth_r = ""
auth_salt = ""
auth_i = 0
xor_bytes = (a, b) ->
res = []
len = Math.min(a.length, b.length)
for i in [0...len]
res.push(a[i] ^ b[i])
return new Buffer(res)
# We implement this ourselves because early versions of node will ignore the "sha256" option
# and just return the hash for sha1.
pbkdf2_hmac = (password, salt, iterations) =>
cache_string = password.toString("base64") + "," + salt.toString("base64") + "," + iterations.toString()
if pbkdf2_cache[cache_string]
return pbkdf2_cache[cache_string]
mac = crypto.createHmac("sha256", password)
mac.update(salt)
mac.update("\x00\x00\x00\x01")
u = mac.digest()
t = u
for c in [0...iterations-1]
mac = crypto.createHmac("sha256", password)
mac.update(t)
t = mac.digest()
u = xor_bytes(u, t)
pbkdf2_cache[cache_string] = u
return u
# a, b should be strings
compare_digest = (a, b) ->
left = undefined
right = b
result = undefined
if a.length is b.length
left = a
result = 0
if a.length != b.length
left = b
result = 1
len = Math.min(left.length, right.length)
for i in [0...len]
result |= left[i] ^ right[i]
return result is 0
handshake_error = (code, message) =>
if 10 <= code <= 20
@emit 'error', new err.ReqlAuthError(message)
else
@emit 'error', new err.ReqlDriverError(message)
handshake_callback = (buf) =>
# Once we receive a response, extend the current
# buffer with the data from the server. The reason we
# extend it, vs. just setting it to the value of `buf`
# is that this callback may be invoked several times
# before the server response is received in full. Each
# time through we check if we've received the entire
# response, and only disable this event listener at
# that time.
@buffer = Buffer.concat([@buffer, buf])
# Next we read bytes until we get a null byte. Then we follow
# the new handshake logic to authenticate the user with the
# server.
j = 0
for b,i in @buffer
if b is 0
# Here we pull the status string out of the
# buffer and convert it into a string.
status_buf = @buffer.slice(j, i)
j = i+1
status_str = status_buf.toString()
# Get the reply from the server, and parse it as JSON
try
server_reply = JSON.parse(status_str)
catch json_error
throw new err.ReqlDriverError(status_str)
if state is 1
if not server_reply.success
handshake_error(server_reply.error_code, server_reply.error)
return
min = server_reply.min_protocol_version
max = server_reply.max_protocol_version
if min > protoVersionNumber or max < protoVersionNumber
# We don't actually support changing the protocol yet, so just error.
throw new err.ReqlDriverError(
"""Unsupported protocol version #{protoVersionNumber}, \
expected between #{min} and #{max}.""")
state = 2
else if state is 2
if not server_reply.success
handshake_error(server_reply.error_code, server_reply.error)
return
authentication = {}
server_first_message = server_reply.authentication
for item in server_first_message.split(",")
i = item.indexOf("=")
authentication[item.slice(0, i)] = item.slice(i+1)
auth_r = authentication.r
auth_salt = new Buffer(authentication.s, 'base64')
auth_i = parseInt(authentication.i)
if not (auth_r.substr(0, r_string.length) == r_string)
throw new err.ReqlAuthError("Invalid nonce from server")
client_final_message_without_proof = "c=biws,r=" + auth_r
salted_password = pbkdf2_hmac(@rawSocket.password, auth_salt, auth_i)
client_key = crypto.createHmac("sha256", salted_password).update("Client Key").digest()
stored_key = crypto.createHash("sha256").update(client_key).digest()
auth_message =
client_first_message_bare + "," +
server_first_message + "," +
client_final_message_without_proof
client_signature = crypto.createHmac("sha256", stored_key).update(auth_message).digest()
client_proof = xor_bytes(client_key, client_signature)
server_key = crypto.createHmac("sha256", salted_password).update("Server Key").digest()
server_signature = crypto.createHmac("sha256", server_key).update(auth_message).digest()
state = 3
message = JSON.stringify({authentication: client_final_message_without_proof + ",p=" + client_proof.toString("base64")})
nullbyte = new Buffer('\0', "binary")
@rawSocket.write Buffer.concat([Buffer(message.toString()), nullbyte])
else if state is 3
if not server_reply.success
handshake_error(server_reply.error_code, server_reply.error)
return
first_equals = server_reply.authentication.indexOf('=')
v = server_reply.authentication.slice(first_equals+1)
if not compare_digest(v, server_signature.toString("base64"))
throw new err.ReqlAuthError("Invalid server signature")
state = 4
@rawSocket.removeListener('data', handshake_callback)
@rawSocket.on 'data', (buf) => @_data(buf)
# We also want to cancel the timeout error
# callback that we set earlier. Even though we
# haven't checked `status_str` yet, we've
# gotten a response so it isn't a timeout.
clearTimeout(timeout)
# Notify listeners we've connected
# successfully. Notably, the Connection
# constructor registers a listener for the
# `"connect"` event that sets the `@open`
# flag on the connection and invokes the
# callback passed to the `r.connect`
# function.
@emit 'connect'
else
throw new err.ReqlDriverError("Unexpected handshake state")
# We may have more messages if we're in the middle of the handshake,
# so we have to update the buffer.
@buffer = @buffer.slice(j + 1)
# This is the end of the handshake callback.
# Register the handshake callback on the socket. Once the
# handshake completes, it will unregister itself and
# register `_data` on the socket for `"data"` events.
@rawSocket.on 'data', handshake_callback
# In case the socket encounters an error, we re-emit the error
# ourselves. The Connection superclass constructor will invoke
# the user's `r.connect` callback with the appropriate error
# object.
@rawSocket.on 'error', (err) => @emit 'error', err
# Upon closing the `@rawSocket` for any reason, we close this
# connection. Passing `noreplyWait: false` ensures that we
# won't try to emit anything else on the socket.
@rawSocket.on 'close', =>
if @isOpen()
@close({noreplyWait: false})
@emit 'close'
# We re-raise the `timeout` event. Node says the socket must
# be closed by the user though. We should do that rather than
# just set the `@open` flag to `false`
@rawSocket.on 'timeout', => @open = false; @emit 'timeout'
clientPort: -> @rawSocket.localPort
clientAddress: -> @rawSocket.localAddress
# #### TcpConnection close method
#
# This is a public method for closing the current connection. It
# performs the raw socket related cleanup, and delegates the work
# of setting `@open` etc to the Connection superclass's
# implementation of `.close`
close: (varar 0, 2, (optsOrCallback, callback) ->
# Here we handle different ways of calling `.close`
if callback?
# This is when calling close like `.close({..}, function(..) {})`
opts = optsOrCallback
cb = callback
else if Object::toString.call(optsOrCallback) is '[object Object]'
# This is when calling close like `.close({..})`
opts = optsOrCallback
cb = null
else if typeof optsOrCallback is "function"
# This is when calling close like `.close(function(..){..})`
opts = {}
cb = optsOrCallback
else
# And the default is when calling like `.close()`
opts = {}
# Finally, we create the promise for this function. It closes
# the socket and invokes the superclass to clean up everything
# else, then invokes the user's callback to this function.
#
# In order:
#
# 1. The promise is initialized, with `resolve` and `reject` passed
# to the anonymous promise callback immediately.
# 2. The anonymous promise callback calls the superclass's
# `close` method on this connection, with the `opts` that
# were passed to this function. The only option `close`
# accepts is `noreplyWait`
# 3. The superclass's close method sets `@open` to false, and
# also closes all cursors, feeds, and callbacks that are
# currently outstanding.
# 4. Depending on whether `opts.noreplyWait` is true, the
# superclass's `close` may immediately invoke `wrappedCb`,
# or it may defer it until all outstanding `noreply`
# queries are completed.
# 5. When `wrappedCb` is invoked, it calls `.end()` on the raw
# socket for this connection, telling Node we'd like the
# tcp connection to be closed.
# 6. The socket will raise the `"close"` event when it's done
# closing, and at that time the promise here will be
# resolved or rejected.
# 7. If the promise was resolved, the callback provided to
# this function (`cb`) will be run (it's chained to the
# promise).
new Promise( (resolve, reject) =>
wrappedCb = (error, result) =>
closeCb = =>
if error?
reject error
else
resolve result
cleanupSocket = =>
# Resolve the promise, invoke all callbacks, then
# destroy remaining listeners and remove our
# reference to the socket.
closeCb()
@rawSocket?.removeAllListeners()
@rawSocket = null
@emit("close")
if @rawSocket?
if @rawSocket.readyState == 'closed'
# Socket is already closed for some reason,
# just clean up
cleanupSocket()
else
# Otherwise, wait until we get the close event
@rawSocket?.once("close", cleanupSocket)
@rawSocket.end()
else
# If the rawSocket is already closed, there's no
# reason to wait for a 'close' event that will
# never come. However we still need to fulfill the
# promise interface, so we do the next best thing
# and resolve it on the next event loop tick.
process.nextTick(closeCb)
TcpConnection.__super__.close.call(@, opts, wrappedCb)
).nodeify cb
)
# #### TcpConnection close method
#
# This method is called by the superclass in the `.close`
# method. It simply closes the socket completely and calls the
# superclass's `cancel`. The superclass's cancel closes all
# outstanding cursors and feeds, and invokes all outstanding query
# callbacks with an error.
#
# Despite not starting with an underscore, this is not a public
# method.
cancel: () ->
@rawSocket.destroy()
super()
# #### TcpConnection _writeQuery method
#
# This method emits a query's token on the socket, then invokes
# `.write` which emits the body of the query.
_writeQuery: (token, data) ->
tokenBuf = new Buffer(8)
# We write the token in two 4-byte chunks: least significant
# bytes first, then most significant bytes. (This is the same
# order as little endian 8 bytes would be). The `_data` method
# in the `Connection` class extracts the token from server
# responses by reversing this process.
#
# The key here is to write the token in a consistent way (so
# responses can be paired with outstanding requests), and to
# ensure the number isn't interpreted as a negative number by
# the server. The server doesn't actually care if the numbers
# are sequential.
tokenBuf.writeUInt32LE(token & 0xFFFFFFFF, 0)
tokenBuf.writeUInt32LE(Math.floor(token / 0xFFFFFFFF), 4)
# Write out the token to the socket, then invoke `.write` to
# write the data to the socket.
@rawSocket.write tokenBuf
@write new Buffer(data)
# #### TcpConnection write method
#
# This method is called by `_writeQuery` and just writes the body
# of a query to the socket.
#
# Despite not starting with an underscore, it is not a public
# method.
write: (chunk) ->
# Before writing the data, we need to write the length of the
# data as an unsigned little-endian 4 byte integer.
lengthBuffer = new Buffer(4)
lengthBuffer.writeUInt32LE(chunk.length, 0)
@rawSocket.write lengthBuffer
# Finally we write the data to the socket. It is serialized
# from json to a string in the `Connection` class's
# `_sendQuery` method.
@rawSocket.write chunk
# ### HttpConnection class
#
# This class is used to run queries from the webui to the RethinkDB
# internal http server using XHR. It's not intended for general usage
# in applications.
class HttpConnection extends Connection
# We defined the default protocol in case the user doesn't specify
# one.
DEFAULT_PROTOCOL: 'http'
# A static method used by `r.connect` to decide which kind of
# connection to create in a given environment. Here we check if
# XHRs are defined. If not, we aren't in the browser and shouldn't
# be using `HttpConnection`
@isAvailable: -> typeof XMLHttpRequest isnt "undefined"
# #### HttpConnection constructor method
#
# This method sets up the XMLHttpRequest object that all
# requests/responses will be sent and received on. Unlike the
# TcpConnection, the HTTP server only allows one outstanding query
# at a time per connection. Because of this, currently the web ui
# creates many different connections.
#
# The state of an HTTP connection is actually stored on the
# server, and they automatically time out after 5 minutes. The way
# it works is we send a POST request to:
# `/ajax/reql/open-new-connection`, which gets us a connection
# id. The browser can also explicitly destroy server connections
# with the `/ajax/reql/close-connection?conn_id=` url.
#
# Ultimately, the server keeps track of the connections because
# it needs to give the client a way to fetch more results from
# cursors and feeds.
constructor: (host, callback) ->
# A quick check to ensure we can create an `HttpConnection`
unless HttpConnection.isAvailable()
throw new err.ReqlDriverError "XMLHttpRequest is not available in this environment"
# Call the superclass constructor. This initializes the
# attributes `@host`, `@port`, `@db`, `@authKey`, `@timeout`,
# `@outstandingCallbacks`, `@nextToken`, `@open`, `@closing`,
# and `@buffer`. It also registers the callback to be invoked
# once the `"connect"` event is emitted.
super(host, callback)
# A protocol may be supplied in the host object. If the host
# doesn't have a protocol key, (or is a string, which it's
# also allowed to be), then use the default protocol, which is
# 'http'
protocol = if host.protocol is 'https' then 'https' else @DEFAULT_PROTOCOL
# Next we construct an XHR with the path to the reql query
# endpoint on the http server.
url = "#{protocol}://#{@host}:#{@port}#{host.pathname}ajax/reql/"
xhr = new XMLHttpRequest
#The request is a `POST` to ensure the response isn't cached
# by the browser (which has caused bugs in the past). The
# `true` argument is setting the request to be asynchronous.
# Some browsers cache this request no matter what cache
# control headers are set on the request or the server's
# response. So the `cacheBuster` argument ensures every time
# we create a connection it's a unique url, and we really do
# create a new connection on the server.
xhr.open("POST", url+"open-new-connection?cacheBuster=#{Math.random()}", true)
# We response will be a connection ID, which we receive as text.
xhr.responseType = "text"
# Next, set up the callback to process the response from the
# server when the new connection is established.
xhr.onreadystatechange = (e) =>
# readyState 4 is "DONE", the data has been completely received.
if xhr.readyState is 4
# The status is 200 if we get a successful response
if xhr.status is 200
# Now we finally store the `@_url` variable. No
# particular reason for not doing this sooner
# since the url doesn't change.
@_url = url
# Keep the connection ID we received.
@_connId = xhr.response
# Emit the `"connect"` event. The `Connection`
# superclass's constructor listens for this event
# to set the `@open` flag to `true` and invoke its
# callback (which is callback passed to this
# method)
@emit 'connect'
else
# In case we get anything other than a 200, raise an error.
@emit 'error', new err.ReqlDriverError "XHR error, http status #{xhr.status}."
# Send the xhr, and store it in the instance for later.
xhr.send()
@xhr = xhr
# #### HttpConnection cancel method
#
# This sends a POST to the `close-connection` endpoint, so the
# server can deallocate resources related to the connection. This
# throws out any data for unconsumed cursors etc and invalidates
# this connection id.
cancel: ->
# Check if the connection id is still open. `@connId` is null
# if the connection was previously closed or cancelled
if @_connId?
# Since only one request can happen at a time, we need to
# abort any in-progress xhr request before sending a new
# request to close the connection.
@xhr.abort()
xhr = new XMLHttpRequest
# This sends the close connection request asynchronously.
xhr.open("POST", "#{@_url}close-connection?conn_id=#{@_connId}", true)
# We ignore the result, but Firefox doesn't. Without this line it complains
# about "No element found" when trying to parse the response as xml.
xhr.responseType = "arraybuffer"
xhr.send()
# Null out @conn_Id so we know not to send another
# close request to the server later.
@_url = null
@_connId = null
# This will end any outstanding cursors and feeds, though
# there should be at most one since we don't support
# multiple queries at once on http connections.
super()
# #### HttpConnection close method
#
# Closes the http connection. Does nothing new or special beyond
# what the superclass already does. The server connection is
# closed in `cancel` above, which the superclass calls for us.
close: (varar 0, 2, (optsOrCallback, callback) ->
if callback?
opts = optsOrCallback
cb = callback
else if Object::toString.call(optsOrCallback) is '[object Object]'
opts = optsOrCallback
cb = null
else
opts = {}
cb = optsOrCallback
unless not cb? or typeof cb is 'function'
throw new err.ReqlDriverError "Final argument to `close` must be a callback function or object."
# This would simply be `super(opts, wrappedCb)`, if we were
# not in the varar anonymous function
HttpConnection.__super__.close.call(this, opts, cb)
)
# #### HttpConnection _writeQuery method
#
# This creates the buffer to send to the server, writes the token
# and data to it, then passes the data and buffer down to `write`
# to write the data itself to the xhr request.
#
# This differs from `TcpConnection`'s version of `_writeQuery`
# which only writes the token.
_writeQuery: (token, data) ->
# We use encodeURI to get the length of the unicode
# representation of the data.
buf = new Buffer(encodeURI(data).split(/%..|./).length - 1 + 8)
# Again, the token is encoded as a little-endian 8 byte
# unsigned integer.
buf.writeUInt32LE(token & 0xFFFFFFFF, 0)
buf.writeUInt32LE(Math.floor(token / 0xFFFFFFFF), 4)
# Write the data out to the bufferm then invoke `write` with
# the buffer and token
buf.write(data, 8)
@write buf, token
# #### HttpConnection write method
#
# This method takes a Node Buffer (or more accurately, the Buffer
# class that Browserify polyfills for us) and turns it into an
# ArrayBufferView, then sends it over the XHR with the current
# connection id.
#
# Despite not starting with an underscore, this is not a public
# method.
write: (chunk, token) ->
# Create a new XHR with to run the query over.
xhr = new XMLHttpRequest
xhr.open("POST", "#{@_url}?conn_id=#{@_connId}", true)
xhr.responseType = "arraybuffer"
xhr.onreadystatechange = (e) =>
# When the server responds, the state must be 4 ("DONE"),
# and the HTTP status code should be success. Otherwise we
# just do nothing. There's a separate callback if the XHR
# encounters an error.
if xhr.readyState is 4 and xhr.status is 200
# Convert the response from a browser ArrayBuffer into
# a Node buffer
buf = new Buffer(b for b in (new Uint8Array(xhr.response)))
# The data method is defined in the `Connection` class
# and reads and parses the response from the server.
@_data(buf)
# On error we want to invoke the callback for this query with
# an error.
xhr.onerror = (e) =>
@outstandingCallbacks[token].cb(new Error("This HTTP connection is not open"))
# To serialize the query (held in chunk) for the XHR, we need
# to convert it from a node buffer into an `ArrayBufferView`
# (specifically `Uint8Array`), since passing an `ArrayBuffer`
# in xhr.send is deprecated
view = new Uint8Array(chunk.length)
i = 0
while i < chunk.length
view[i] = chunk[i]
i++
# And send it on its way to the server
xhr.send view
@xhr = xhr
# ## isConnection
#
# This is an exported function that determines whether something is a
# Connection. It's used by the [ast module](ast.html) to validate the
# first argument passed to `.run` (which must always be a connection).
module.exports.isConnection = (connection) ->
return connection instanceof Connection
# ## connect
#
# The main function of this module, which is exposed to end users as
# `r.connect`. See the [API
# docs](http://rethinkdb.com/api/javascript/connect/).
module.exports.connect = varar 0, 2, (hostOrCallback, callback) ->
if typeof hostOrCallback is 'function'
# This occurs when called like `r.connect(function(..){..})`
# Override the callback variable (which should be undefined)
# and set host to an empty object
host = {}
callback = hostOrCallback
else
# Otherwise, the `callback` variable is already correctly
# holding the callback, and the host variable is the first
# argument
host = hostOrCallback || {}
# `r.connect` returns a Promise which does the following:
#
# 1. Determines whether to create a `TcpConnection` or an
# `HttpConnection` depending on whether we're running on Node
# or in the browser.
# 2. Initializes the connection, and when it's complete invokes
# the user's callback
new Promise( (resolve, reject) ->
if host.authKey? && (host.password? || host.user? || host.username?)
throw new err.ReqlDriverError "Cannot use both authKey and password"
if host.user && host.username
throw new err.ReqlDriverError "Cannot use both user and username"
else if host.authKey
host.user = "admin"
host.password = host.authKey
else
# Fixing mismatch between drivers
if host.username?
host.user = host.username
create_connection = (host, callback) =>
if TcpConnection.isAvailable()
new TcpConnection host, callback
else if HttpConnection.isAvailable()
new HttpConnection host, callback
else
throw new err.ReqlDriverError "Neither TCP nor HTTP avaiable in this environment"
wrappedCb = (err, result) ->
if (err)
reject(err)
else
resolve(result)
create_connection(host, wrappedCb)
).nodeify callback
# Exposing the connection classes
module.exports.Connection = Connection
module.exports.HttpConnection = HttpConnection
module.exports.TcpConnection = TcpConnection
| 206222 | # # Network (net.coffee)
#
# This module handles network and protocol related functionality for
# the driver. The classes defined here are:
#
# - `Connection`, which is an EventEmitter and the base class for
# - `TcpConnection`, the standard driver connection
# - `HttpConnection`, the connection type used by the webui
#
# ### Imports
#
# The [net module](http://nodejs.org/api/net.html) is the low-level
# networking library Node.js provides. We need it for `TcpConnection`
# objects
net = require('net')
# The [tls module](http://nodejs.org/api/tls.html) is the TLS/SSL
# networking library Node.js provides. We need it to establish an
# encrypted connection for `TcpConnection` objects
tls = require('tls')
# The [events module](http://nodejs.org/api/events.html) is a core
# Node.js module that provides the ability for objects to emit events,
# and for callbacks to be attached to those events.
events = require('events')
# The [util module](util.html) contains utility methods used several
# places in the driver
util = require('./util')
# The [errors module](errors.html) contains exceptions thrown by the driver
err = require('./errors')
# The [cursors module](cursors.html) contains data structures used to
# iterate over large result sets or infinite streams of data from the
# database (changefeeds).
cursors = require('./cursor')
# The `proto-def` module is an autogenerated file full of protocol
# definitions used to communicate to the RethinkDB server (basically a
# ton of human readable names for magic numbers).
#
# It is created by the python script `convert_protofile` in the
# `drivers` directory (one level up from this file) by converting a
# protocol buffers definition file into a JavaScript file. To generate
# the `proto-def.js` file, see the instructions in the
# [README](./index.html#creating-the-proto-defjs)
#
# Note that it's a plain JavaScript file, not a CoffeeScript file.
protodef = require('./proto-def')
crypto = require("crypto")
# Each version of the protocol has a magic number specified in
# `./proto-def.coffee`. The most recent version is 4. Generally the
# official driver will always be updated to the newest version of the
# protocol, though RethinkDB supports older versions for some time.
protoVersion = protodef.VersionDummy.Version.V1_0
protoVersionNumber = 0
# We are using the JSON protocol for RethinkDB, which is the most
# recent version. The older protocol is based on Protocol Buffers, and
# is deprecated.
protoProtocol = protodef.VersionDummy.Protocol.JSON
# The `QueryType` definitions are used to control at a high level how
# we interact with the server. So we can `START` a new query, `STOP`
# an executing query, `CONTINUE` receiving results from an existing
# cursor, or wait for all outstanding `noreply` queries to finish with
# `NOREPLY_WAIT`.
protoQueryType = protodef.Query.QueryType
# The server can respond to queries in several ways. These are the
# definitions for the response types.
protoResponseType = protodef.Response.ResponseType
# The [ast module](ast.html) contains the bulk of the api exposed by
# the driver. It defines how you can create ReQL queries, and handles
# serializing those queries into JSON to be transmitted over the wire
# to the database server.
r = require('./ast')
# We use the [bluebird](https://github.com/petkaantonov/bluebird)
# third-party module to provide a promise implementation for the
# driver.
Promise = require('bluebird')
# These are some functions we import directly from the `util` module
# for convenience.
ar = util.ar
varar = util.varar
aropt = util.aropt
mkAtom = util.mkAtom
mkErr = util.mkErr
# These are the default hostname and port used by RethinkDB
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 28015
module.exports.DEFAULT_HOST = DEFAULT_HOST
module.exports.DEFAULT_PORT = DEFAULT_PORT
# These are strings returned by the server after a handshake
# request. Since they must match exactly they're defined in
# "constants" here at the top
HANDSHAKE_SUCCESS = "SUCCESS"
HANDSHAKE_AUTHFAIL = "ERROR: Incorrect authorization key.\n"
# ### Connection
#
# Connection is the base class for both `TcpConnection` and
# `HttpConnection`. Applications using this driver will need to get a
# connection object to be able to query the server.
#
# Connection is a subclass of
# [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter),
# and it will emit the following events:
#
# - `"connect"` is emitted by the subclasses `TcpConnection` and
# `HttpConnection` when they connect to the server successfully.
# - `"error"` is emitted when protocol level errors occur (notably
# not query errors! Those are returned as arguments to the
# callback the user provides.) `"error"` will also be accompanied
# by a message indicating what went wrong.
# - `"close"` is emitted when the connection is closed either through
# an error or by the user calling `connection.close()` explicitly
# - `"timeout"` will be emitted by the `TcpConnection` subclass if the
# underlying socket times out for any reason.
class Connection extends events.EventEmitter
# By default, RethinkDB doesn't use an authorization key.
DEFAULT_AUTH_KEY: ''
# Each connection has a timeout (in seconds) for the initial handshake with the
# server. Note that this is not a timeout for queries to return
# results.
DEFAULT_TIMEOUT: 20 # In seconds
# #### Connection constructor
constructor: (host, callback) ->
# We need to set the defaults if the user hasn't supplied anything.
if typeof host is 'undefined'
host = {}
# It's really convenient to be able to pass just a hostname to
# connect, since that's the thing that is most likely to vary
# (default ports, no auth key, default connection timeout are
# all common). We just detect that case and wrap it.
else if typeof host is 'string'
host = {host: host}
# Here we set all of the connection parameters to their defaults.
@host = host.host || DEFAULT_HOST
@port = host.port || DEFAULT_PORT
# One notable exception to defaulting is the db name. If the
# user doesn't specify it, we leave it undefined. On the
# server side, if no database is specified for a table, the
# database will default to `"test"`.
@db = host.db # left undefined if this is not set
@authKey = host.authKey || @DEFAULT_AUTH_KEY
@timeout = host.timeout || @DEFAULT_TIMEOUT
# Configuration options for enabling an SSL connection
# Allows the ability to pass in all the options as specified in
# [tls.connect](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback)
# or just true in case the client wants ssl but the server
# is using a certificate with a valid verified chain and there
# is no need to specify certificates on the client
if typeof host.ssl is 'boolean' && host.ssl
@ssl = {}
else if typeof host.ssl is 'object'
@ssl = host.ssl
else
@ssl = false
# The protocol allows for responses to queries on the same
# connection to be returned interleaved. When a query is run
# with this connection, an entry is added to
# `@outstandingCallbacks`. The key is the query token, and the
# value is an object with the following fields:
#
# - **cb**: The callback to invoke when a query returns another
# batch of results
# - **root**: a subclass of `TermBase` (defined in the
# [ast module](ast.html)) representing the query being run.
# - **opts**: global options passed to `.run`.
#
# Once the server returns a response, one of two fields may be
# added to the entry for that query depending on what comes
# back (this is done in `_processResponse`):
#
# - **cursor**: is set to a `Cursor` object (defined in the
# [cursor module](cursor.html)) if the server
# replies with `SUCCESS_PARTIAL`. This happens when a
# result is too large to send back all in one batch. The
# `Cursor` allows fetching results lazily as they're needed.
# - **feed**: is set to a `Feed` object (defined in the
# [cursor module](cursor.html)). This is very similar to a `Cursor`,
# except that it is potentially infinite. Changefeeds are a way
# for the server to notify the client when a change occurs to
# the results of a query the user wants to watch.
#
# Any other responses are considered "done" and don't have any
# further results to fetch from the server. At that time the
# query token is deleted from `@outstandingCallbacks` since we
# don't expect any more results using that token.
@outstandingCallbacks = {}
# Each query to the server requires a unique token (per
# connection). `nextToken` is incremented every time we issue
# a new query
@nextToken = 1
# `@open` and `@closing` are used to record changes in the
# connection state. A connection is open after the handshake
# is successfully completed, and it becomes closed after the
# server confirms the connection is closed.
@open = false
# `@closing` is true when the `conn.close()` method is called,
# and becomes false again just before the callback provided to
# `close` is called. This allows `noreplyWait` to be called
# from within `.close`, but prevents any other queries from
# being run on a closing connection. (`noreplyWait` checks
# `@open` only to see if the connection is closed, but the
# `.isOpen()` method checks both flags)
@closing = false
# We create a [Buffer](http://nodejs.org/api/buffer.html)
# object to receive all bytes coming in on this
# connection. The buffer is modified in the `_data` method
# (which is called whenever data comes in over the network on
# this connection), and it is also modified by the handshake
# callback that's defined in the `TcpConnection` constructor.
@buffer = new Buffer(0)
@_events = @_events || {}
# Now we set up two callbacks, one to run on successful
# connection, and the other to run if we fail to connect to
# the server. They listen to the `"connect"` and `"error"`
# events respectively. If successful, we set `@open` to
# `true`, otherwise we pass an error to the connection
# callback that was passed to the constructor (`callback`)
errCallback = (e) =>
@removeListener 'connect', conCallback
if e instanceof err.ReqlError
callback e
else
callback new err.ReqlDriverError "Could not connect to #{@host}:#{@port}.\n#{e.message}"
@once 'error', errCallback
conCallback = =>
@removeListener 'error', errCallback
@open = true
callback null, @
@once 'connect', conCallback
# closePromise holds the promise created when `.close()` is
# first called. Subsequent calls to close will simply add to
# this promise, rather than attempt closing again.
@_closePromise = null
# #### Connection _data method
#
# This method is responsible for parsing responses from the server
# after the initial handshake is over. It reads the token number
# of the response (so we know which query is being responded to),
# and the response length, then parses the rest of the response as
# JSON.
_data: (buf) ->
# We extend the current buffer with the contents of `buf` that
# we got from the server.
@buffer = Buffer.concat([@buffer, buf])
# The first 8 bytes in a response are the token number of the
# query the server is responding to. The next 4 bytes indicate
# how long the response will be. So if the response isn't at
# least 12 bytes long, there's nothing else to do.
while @buffer.length >= 12
# When a query is sent to the server, we write out the
# token in a way that can be read back later as a native
# integer. Since Node buffers don't have a method like
# `readUInt64LE`, we're forced to emulate it ourselves.
token = @buffer.readUInt32LE(0) + 0x100000000 * @buffer.readUInt32LE(4)
# Next up is the response length. The protocol dictates
# this must be a 32 bit unsigned integer in little endian
# byte order.
responseLength = @buffer.readUInt32LE(8)
# This ensures that the responseLength is less than or
# equal to the amount of data we have in the buffer
# (including the token and response length itself). If the
# buffer doesn't have enough data in it, we just break
# out. More data will be coming later, and it will be
# added to the end of the buffer, so we'll wait until the
# full response is available.
unless @buffer.length >= (12 + responseLength)
break
# Since we have enough data, we slice it out of the
# buffer, and parse it as JSON.
responseBuffer = @buffer.slice(12, responseLength + 12)
response = JSON.parse(responseBuffer)
# Now it's off to `_processResponse` where the data is
# converted to a format the user will be able to work
# with, error responses are detected etc.
@_processResponse response, token
# Finally, we truncate the buffer to the end of the
# current response. The buffer may already be queuing up a
# new response, so it's never safe to clear it or create a
# new one.
@buffer = @buffer.slice(12 + responseLength)
# #### Connection _delQuery method
#
# This method just removes the entry in `@outstandingCallbacks`
# for a given token. It's called whenever a response doesn't
# return a cursor, a cursor is completely consumed, or the query
# encounters an error.
_delQuery: (token) ->
delete @outstandingCallbacks[token]
# #### Connection _processResponse method
#
# This method is contains the main logic for taking different
# actions based on the response type. It receives the response as
# an object (parsed from the JSON coming over the wire), and the
# token for the query the response corresponds to.
_processResponse: (response, token) ->
# For brevity the wire format specifies that the profile key
# is "p". We give it a more readable variable name here.
profile = response.p
# First we need to check if we're even expecting a response
# for this token. If not it's an error.
if @outstandingCallbacks[token]?
{cb:cb, root:root, cursor: cursor, opts: opts, feed: feed} = @outstandingCallbacks[token]
# Some results for queries are not returned all at once,
# but in chunks. The driver takes care of making sure the
# user doesn't see this, and uses `Cursor`s to take
# multiple responses and make them into one long stream of
# query results.
#
# Depending on the type of result, and whether this is the
# first response for this token, we may or may not have a
# cursor defined for this token. If we do have a cursor
# defined already, we add this response to the cursor.
if cursor?
cursor._addResponse(response)
# `cursor._addResponse` will check if this response is
# the last one for this token, and if so will set its
# `cursor._endFlag` to true. If this is the last
# response for this query and we aren't waiting on any
# other responses for this cursor (if, for example, we
# get the responses out of order), then we remove this
# token's entry in `@outstandingCallbacks`.
if cursor._endFlag && cursor._outstandingRequests is 0
@_delQuery(token)
# Next we check if we have a callback registered for this
# token. In [ast](ast.html) we always provide `_start`
# with a wrapped callback function, so this may as well be
# an else branch.
else if cb?
# The protocol (again for brevity) puts the response
# type into a key called "t". What we do next depends
# on that value. We'll be comparing it to the values
# in the `proto-def` module, in `protoResponseType`.
switch response.t
# ##### Error responses
when protoResponseType.COMPILE_ERROR
# Compile errors happen during parsing and
# type checking the query on the server
# side. An example is passing too many
# arguments to a function. We pass an error
# object that includes the backtrace from the
# response and the original query
# (`root`). Then we delete the token from
# `@outstandingCallbacks`.
cb mkErr(err.ReqlServerCompileError, response, root)
@_delQuery(token)
when protoResponseType.CLIENT_ERROR
# Client errors are returned when the client
# is buggy. This can happen if a query isn't
# serialized right, or the handshake is done
# incorrectly etc. Hopefully end users of the
# driver should never see these.
cb mkErr(err.ReqlDriverError, response, root)
@_delQuery(token)
when protoResponseType.RUNTIME_ERROR
# Runtime errors are the most common type of
# error. They happen when something goes wrong
# that can only be determined by running the
# query. For example, if you try to get the
# value of a field in an object that doesn't
# exist.
errType = util.errorClass(response.e)
cb mkErr(errType, response, root)
@_delQuery(token)
# ##### Success responses
when protoResponseType.SUCCESS_ATOM
# `SUCCESS_ATOM` is returned when the query
# was successful and returned a single ReQL
# data type. The `mkAtom` function from the
# [util module](util.html) converts all
# pseudotypes in this response to their
# corresponding native types
response = mkAtom response, opts
# If the response is an array, we patch it a
# bit so it can be used as a stream.
if Array.isArray response
response = cursors.makeIterable response
# If there's a profile available, we nest the
# response slightly differently before passing
# it to the callback for this token.
if profile?
response = {profile: profile, value: response}
cb null, response
# The `SUCCESS_ATOM` response means there will
# be no further results for this query, so we
# remove it from `@outstandingCallbacks`
@_delQuery(token)
when protoResponseType.SUCCESS_PARTIAL
# `SUCCESS_PARTIAL` indicates the client
# should create a cursor and request more data
# from the server when it's ready by sending a
# `CONTINUE` query with the same token. So, we
# create a new Cursor for this token, and add
# it to the object stored in
# `@outstandingCallbacks`.
# We create a new cursor, which is sometimes a
# `Feed`, `AtomFeed`, or `OrderByLimitFeed`
# depending on the `ResponseNotes`. (This
# usually doesn't matter, but third-party ORMs
# might want to treat these differently.)
cursor = null
for note in response.n
switch note
when protodef.Response.ResponseNote.SEQUENCE_FEED
cursor ?= new cursors.Feed @, token, opts, root
when protodef.Response.ResponseNote.UNIONED_FEED
cursor ?= new cursors.UnionedFeed @, token, opts, root
when protodef.Response.ResponseNote.ATOM_FEED
cursor ?= new cursors.AtomFeed @, token, opts, root
when protodef.Response.ResponseNote.ORDER_BY_LIMIT_FEED
cursor ?= new cursors.OrderByLimitFeed @, token, opts, root
cursor ?= new cursors.Cursor @, token, opts, root
# When we've created the cursor, we add it to
# the object stored in
# `@outstandingCallbacks`.
@outstandingCallbacks[token].cursor = cursor
# Again, if we have profile information, we
# wrap the result given to the callback. In
# either case, we need to add the response to
# the new Cursor.
if profile?
cb null, {profile: profile, value: cursor._addResponse(response)}
else
cb null, cursor._addResponse(response)
when protoResponseType.SUCCESS_SEQUENCE
# The `SUCCESS_SEQUENCE` response is sent when
# a cursor or feed is complete, and this is
# the last response that will be received for
# this token. Often, however, the entire
# result for a query fits within the initial
# batch. In this case, we never see a
# `SUCCESS_PARTIAL` response, so there is no
# existing Cursor to add the response to. So,
# that's what we do here, create a new Cursor,
# and delete the token from the
# `@outstandingCallbacks`.
#
# Note that qeries that have already received
# a `SUCCESS_PARTIAL` will not be handled
# here. They will be handled when we check for
# `cursor?` in the conditional up above. In
# that branch, we call cursor._addResponse,
# which takes care of checking if we received
# a `SUCCESS_SEQUENCE`. So this code only gets
# executed when the first batch on a cursor is
# also our last.
cursor = new cursors.Cursor @, token, opts, root
@_delQuery(token)
if profile?
cb null, {profile: profile, value: cursor._addResponse(response)}
else
cb null, cursor._addResponse(response)
when protoResponseType.WAIT_COMPLETE
# The `WAIT_COMPLETE` response is sent by the
# server after all queries executed with the
# optarg `noReply: true` have completed. No
# data is returned, so the callback is just provided `null`
@_delQuery(token)
cb null, null
when protoResponseType.SERVER_INFO
@_delQuery(token)
response = mkAtom response, opts
cb null, response
else
cb new err.ReqlDriverError "Unknown response type"
else
# We just ignore tokens we don't have a record of. This is
# what the other drivers do as well.
# #### Connection close method
#
# A public method that closes the connection. See [API docs for
# close](http://rethinkdb.com/api/javascript/close/).
close: (varar 0, 2, (optsOrCallback, callback) ->
# First determine which argument combination this method was
# called with, and set the callback and options appropriately.
if callback?
# When calling like `.close({...}, function(...){ ... })`
opts = optsOrCallback
unless Object::toString.call(opts) is '[object Object]'
throw new err.ReqlDriverError "First argument to two-argument `close` must be an object."
cb = callback
else if Object::toString.call(optsOrCallback) is '[object Object]'
# When calling like `.close({...})`
opts = optsOrCallback
cb = null
else if typeof optsOrCallback is 'function'
# When calling like `.close(function(...){ ... })`
opts = {}
cb = optsOrCallback
else
# When calling like `.close({...})`
opts = optsOrCallback
cb = null
for own key of opts
# Currently, only one optional argument is accepted by
# `.close`: whether or not to wait for completion of all
# outstanding `noreply` queries. So we throw an error if
# anything else is passed.
unless key in ['noreplyWait']
throw new err.ReqlDriverError "First argument to two-argument `close` must be { noreplyWait: <bool> }."
# If we're currently in the process of closing, just add the
# callback to the current promise
if @_closePromise?
return @_closePromise.nodeify(cb)
# Next we set `@closing` to true. It will be set false once
# the promise that `.close` returns resolves (see below). The
# `isOpen` method takes this variable into account.
@closing = true
# Should we wait for all outstanding `noreply` writes before
# considering the connection closed?
#
# - if the options object doesn't have a `noreplyWait` key, we
# default to `true`.
# - if we do have a `noreplyWait` key, then use that value
# - if this connection isn't `@open`, then this is all moot
noreplyWait = ((not opts.noreplyWait?) or opts.noreplyWait) and @open
# Finally, close returns a promise. This promise must do two
# things:
#
# 1. Set the flags for this connection to false (`@open` &
# `@closing`)
#
# 2. Close all cursors and feeds for outstanding callbacks. We
# won't be receiving any more responses for them, so they are
# no longer outstanding. (this is what `@cancel()` does)
#
# In addition to these two finalization steps, we may need to
# wait for all `noreply` queries to finish.
#
# You'll notice we don't close sockets or anything like that
# here. Those steps are done in the subclasses because they
# have knowledge about what kind of underlying connection is
# being used.
#
# We save the promise here in case others attempt to call
# `close` before we've gotten a response from the server (when
# the @closing flag is true).
@_closePromise = new Promise( (resolve, reject) =>
# Now we create the Promise that `.close` returns. If we
# aren't waiting for `noreply` queries, then we set the flags
# and cancel feeds/cursors immediately. If we are waiting,
# then we run a `noreplyWait` query and set the flags and
# cancel cursors when that query receives a response.
#
# In addition, we chain the callback passed to `.close` on the
# end, using bluebird's convenience method
# [nodeify](https://github.com/petkaantonov/bluebird/blob/master/API.md#nodeifyfunction-callback--object-options---promise)
#
wrappedCb = (err, result) =>
@open = false
@closing = false
@cancel()
if err?
reject err
else
resolve result
if noreplyWait
@noreplyWait(wrappedCb)
else
wrappedCb()
).nodeify cb
)
# #### Connection noreplyWait method
#
# A public method that sends a query to the server that completes
# when all previous outstanding queries are completed. See [API
# docs for
# noreplyWait](http://rethinkdb.com/api/javascript/noreplyWait/).
noreplyWait: varar 0, 1, (callback) ->
# If the connection is not open, all of the outstanding
# `noreply` queries have already been cancelled by the server,
# so it's an error to call this now. However, `noreplyWait` is
# called by the `.close` method just before setting the
# `@open` flag to false. This is why we need the `@closing`
# flag, so we can allow one last `noreplyWait` call before the
# connection is closed completely.
unless @open
return new Promise( (resolve, reject) ->
reject(new err.ReqlDriverError "Connection is closed.")
).nodeify callback
# Since `noreplyWait` is invoked just like any other query, we
# need a token.
token = @nextToken++
# Here we construct the query itself. There's no body needed,
# we just have to set the type to the appropriate value from
# `proto-def` and set the token.
query = {}
query.type = protoQueryType.NOREPLY_WAIT
query.token = token
new Promise( (resolve, reject) =>
# The method passed to Promise is invoked immediately
wrappedCb = (err, result) ->
# This callback will be invoked when the
# `NOREPLY_WAIT` query finally returns.
if (err)
reject(err)
else
resolve(result)
# Here we add an entry for this query to
# `@outstandingCallbacks`. This promise will be resolved
# or rejected at that time.
@outstandingCallbacks[token] = {cb:wrappedCb, root:null, opts:null}
# Finally, serialize the query and send it to the server
@_sendQuery(query)
# After the promise is resolved, the callback passed to
# `noreplyWait` can be invoked.
).nodeify callback
# #### Connection server method
#
# Public, retrieves the remote server id and name. See [API docs
# for server](http://rethinkdb.com/api/javascript/server/).
server: varar 0, 1, (callback) ->
unless @open
return new Promise( (resolve, reject) ->
reject(new err.ReqlDriverError "Connection is closed.")
).nodeify callback
token = <KEY>nextToken++
query = {}
query.type = protoQueryType.SERVER_INFO
query.token = token
new Promise( (resolve, reject) =>
wrappedCb = (err, result) ->
if (err)
reject(err)
else
resolve(result)
@outstandingCallbacks[token] = {cb:wrappedCb, root:null, opts:null}
@_sendQuery(query)
).nodeify callback
# #### Connection cancel method
#
# This method inserts a dummy error response into all outstanding
# cursors and feeds, effectively closing them. It also calls all
# registered callbacks with an error response. Then it clears the
# `@outstandingCallbacks` registry.
cancel: ar () ->
# The type of the dummy response is a runtime error, the
# reason for the error is "Connection is closed" and the
# backtrace provided is empty
response = {t:protoResponseType.RUNTIME_ERROR,r:["Connection is closed."],b:[]}
for own key, value of @outstandingCallbacks
if value.cursor?
value.cursor._addResponse(response)
else if value.cb?
value.cb mkErr(util.errorClass(response.e), response, value.root)
@outstandingCallbacks = {}
# #### Connection reconnect method
#
# Closes and re-opens a connection. See the [API
# docs](http://rethinkdb.com/api/javascript/reconnect/)
reconnect: (varar 0, 2, (optsOrCallback, callback) ->
# Similar to `.close`, there are a few different ways of
# calling `.reconnect`, so we need to determine which way it
# was called, and set the options and callback appropriately.
if callback?
# When calling like `reconnect({}, function(..){ ... })`
opts = optsOrCallback
cb = callback
else if typeof optsOrCallback is "function"
# When calling like `reconnect(function(..){ ... })`
opts = {}
cb = optsOrCallback
else
# In either of these cases, the callback will be undefined
if optsOrCallback?
# Was called like `reconnect({})`
opts = optsOrCallback
else
# Was called like `reconnect()`
opts = {}
cb = callback
# Here we call `close` with a callback that will reconnect
# with the same parameters
new Promise( (resolve, reject) =>
closeCb = (err) =>
@constructor.call @,
host:@host,
port:@port
timeout:@timeout,
authKey:@authKey
, (err, conn) ->
if err?
reject err
else
resolve conn
@close(opts, closeCb)
).nodeify cb
)
# #### Connection use method
#
# This is a public method, [see the API
# docs](http://rethinkdb.com/api/javascript/use/). It sets the
# default db to use when `r.table` is called without specifying a
# db explicitly. The db variable is sent as a global optarg when
# querying.
use: ar (db) ->
@db = db
# #### Connection isOpen method
#
# This is a non-public method that's used by subclasses to
# determine if it's safe to call `noreplyWait` when closing. It
# respects both the `@open` flag and the `@closing` flag, whose
# behavior is described in the docs for `.close`
isOpen: () ->
@open and not @closing
# #### Connection _start method
#
# `_start` combines the raw query term with global optargs,
# creates a new token for the query and invokes `_sendQuery` with
# it. `_start` is called by the `.run` method from the [ast
# module](ast.html)
_start: (term, cb, opts) ->
# Obviously, you can't query with a closed connection.
unless @open then throw new err.ReqlDriverError "Connection is closed."
# Here is where the token for the query is
# generated. @nextToken is only ever incremented here and in
# the `.noreplyWait` method
token = @nextToken++
# Here we construct the wrapper object for queries
query = {}
# The global optargs are the optional arguments passed to
# `.run`, plus some variables that are set on the connection
# itself, like `db`.
query.global_optargs = {}
# Normal queries begin with `START`. The other options are
# `CONTINUE` (for feeds and cursors), `STOP` (for closing an
# open cursor/feed), and `NOREPLY_WAIT` which is a special
# type of query (see the `.noreplyWait` method).
query.type = protoQueryType.START
query.query = term.build()
query.token = token
# Now we loop through the options passed to `.run`, convert
# them to the right format, and put them into the global
# optargs object for this query
for own key, value of opts
# In the protocol, only "snake_case" is accepted for
# optargs. Because the JS convention is to use
# "camelCase", we convert it before serializing.
#
# In addition, we take the values passed, and convert them
# into a ReQL term, and dump them in the protocol format,
# instead of including them directly as they are. This
# gives resistance to injection attacks.
query.global_optargs[util.fromCamelCase(key)] = r.expr(value).build()
# If the user has specified the `db` on the connection (either
# in the constructor, as an optarg to .run(), or with the `.use` method)
# we add that db to the optargs for the query.
if opts.db? or @db?
query.global_optargs.db = r.db(opts.db or @db).build()
# Next, ensure that the `noreply` and `profile` options
# (if present) are actual booleans using the `!!` trick.
# Note that `r.expr(false).build() == false` and
# `r.expr(null).build() == null`, so the conversion in the
# loop above won't affect the boolean value the user intended
# to pass.
if opts.noreply?
query.global_optargs['noreply'] = r.expr(!!opts.noreply).build()
if opts.profile?
query.global_optargs['profile'] = r.expr(!!opts.profile).build()
# Here we stash away the callback the user provided in
# `@outstandingCallbacks`, with the query term and the options
# passed to `.run`. Note that we don't consider the callback
# as outstanding if the user has specified `noreply`. Since
# the server will never respond, it would sit in
# `@outstandingCallbacks` forever.
if (not opts.noreply?) or !opts.noreply
@outstandingCallbacks[token] = {cb:cb, root:term, opts:opts}
# Now we send the user's query. `_sendQuery` writes the
# necessary headers and will serialize it for sending over the
# underlying connection type (either tcp or http).
@_sendQuery(query)
# Finally, if the user called `.run` with both a callback and
# the `noreply` flag set, we just invoke it immediately, since
# there won't be a response from the server. Since we have no
# idea if there's an error and no response, we just pass it
# null (with error undefined).
if opts.noreply? and opts.noreply and typeof(cb) is 'function'
cb null # There is no error and result is `undefined`
# #### Connection _continueQuery method
#
# This method sends a notification to the server that we'd like to
# receive the next batch from a feed or a cursor
# (`CONTINUE`). Feeds may block indefinitely, but cursors should
# return quickly.
_continueQuery: (token) ->
unless @open then throw new err.ReqlDriverError "Connection is closed."
query =
type: protoQueryType.CONTINUE
token: token
@_sendQuery(query)
# #### Connection _endQuery method
#
# This method sends a notification to the server that we don't
# care about the rest of the results on a cursor or feed (`STOP`).
_endQuery: (token) ->
unless @open then throw new err.ReqlDriverError "Connection is closed."
query =
type: protoQueryType.STOP
token: token
@_sendQuery(query)
# #### Connection _sendQuery method
#
# This method serializes a javascript object in the rethinkdb json
# protocol format into a string, and sends it over the underlying
# connection by calling `_writeQuery`
_sendQuery: (query) ->
# The wire protocol doesn't use JSON objects except for things
# like optargs. Instead it's a bunch of nested arrays, where
# the first element of the array indicates what the type of
# that object is. This is a lot like lisp. Here the entire
# query is wrapped in an array, with the first element the
# type of the query (`START`, `STOP`, `CONTINUE`, or
# `NOREPLY_WAIT`).
data = [query.type]
# If the query has a body, (which it only does in the `START`
# case), then we push it into the outer array.
if !(query.query is undefined)
data.push(query.query)
if query.global_optargs? and Object.keys(query.global_optargs).length > 0
data.push(query.global_optargs)
# This is the last bit the Connection superclass can
# do. `_writeQuery` is implemented by the subclasses since
# they know what underlying connection type is being used.
# This is also where the query is finally converted into a
# string.
@_writeQuery(query.token, JSON.stringify(data))
# Global cache variable for storing the results of pbkdf2_hmac
pbkdf2_cache = {}
# ### TcpConnection
#
# This class implements all of the TCP specific behavior for normal
# driver connections. External users of the driver should only use
# `TcpConnection`s since `HttpConnection` are just for the webui.
#
# Fundamentally, this class uses the `net` module to wrap a raw socket
# connection to the server.
class TcpConnection extends Connection
# #### TcpConnection isAvailable method
#
# The TcpConnection should never be used by the webui, so we have
# an extra method here that decides whether it's available. This
# is called by the constructor, but also by the `.connect`
# function which uses it to decide what kind of connection to
# create.
@isAvailable: () -> !(process.browser)
# #### TcpConnection constructor method
#
# This sets up all aspects of the connection that relate to
# TCP. Everything else is done in the Connection superclass
# constructor.
constructor: (host, callback) ->
# Bail out early if we happen to be in the browser
unless TcpConnection.isAvailable()
throw new err.ReqlDriverError "TCP sockets are not available in this environment"
# Invoke the superclass's constructor. This initializes the
# attributes `@host`, `@port`, `@db`, `@authKey` and
# `@timeout`, `@outstandingCallbacks`, `@nextToken`, `@open`,
# `@closing`, and `@buffer`. It also registers the callback to
# be invoked once the `"connect"` event is emitted.
super(host, callback)
# Next we create the underlying tcp connection to the server
# using the net module and store it in the `@rawSocket`
# attribute.
if @ssl
@ssl.host = @host
@ssl.port = @port
@rawSocket = tls.connect @ssl
else
@rawSocket = net.connect @port, @host
# We disable [Nagle's
# algorithm](http://en.wikipedia.org/wiki/Nagle%27s_algorithm)
# on the socket because it can impose unnecessary
# latency.
@rawSocket.setNoDelay()
# Enable TCP keepalive so we can detect dead connections.
@rawSocket.setKeepAlive(true)
# Here we use the `@timeout` value passed to `.connect` to
# destroy the socket and emit a timeout error. The timer will
# be cancelled upon successful connection.
timeout = setTimeout( (()=>
@rawSocket.destroy()
@emit 'error', new err.ReqlTimeoutError(
"Could not connect to #{@host}:#{@port}, operation timed out.")
), @timeout*1000)
# If any other kind of error occurs, we also want to cancel
# the timeout error callback. Otherwise a connection error
# would be followed shortly by a spurious timeout error.
@rawSocket.once 'error', => clearTimeout(timeout)
# Once the TCP socket successfully connects, we can begin the
# handshake with the server to establish the connection on the
# server.
@rawSocket.once 'connect', =>
# The protocol specifies that the magic number for the
# version should be given as a little endian 32 bit
# unsigned integer. The value is given in the `proto-def`
# module, but it is just a random number that's unlikely
# to be accidentally the first few bytes of an erroneous
# connection on the socket.
version = new Buffer(4)
version.writeUInt32LE(protoVersion, 0)
# Send the protocol type that we will be using to
# communicate with the server. Json is the only currently
# supported protocol.
protocol = new Buffer(4)
protocol.writeUInt32LE(protoProtocol, 0)
r_string = new Buffer(crypto.randomBytes(18)).toString('base64')
@rawSocket.user = host["user"]
@rawSocket.password = host["<PASSWORD>"]
# Default to admin user with no password if none is given.
if @rawSocket.user is undefined
@rawSocket.user = "admin"
if @rawSocket.password is undefined
@rawSocket.password = ""
client_first_message_bare = "n=" + @rawSocket.user + ",r=" + r_string
message = JSON.stringify({
protocol_version: protoVersionNumber,
authentication_method: "SCRAM-SHA-256",
authentication: "n,," + client_first_message_bare})
nullbyte = new Buffer('\0', "binary")
@rawSocket.write Buffer.concat([version, Buffer(message.toString()), nullbyte])
# Now we have to wait for a response from the server
# acknowledging the new connection. The following callback
# will be invoked when the server sends the first few
# bytes over the socket.
state = 1
min = 0
max = 0
server_first_message = ""
server_signature = ""
auth_r = ""
auth_salt = ""
auth_i = 0
xor_bytes = (a, b) ->
res = []
len = Math.min(a.length, b.length)
for i in [0...len]
res.push(a[i] ^ b[i])
return new Buffer(res)
# We implement this ourselves because early versions of node will ignore the "sha256" option
# and just return the hash for sha1.
pbkdf2_hmac = (password, salt, iterations) =>
cache_string = password.toString("base64") + "," + salt.toString("base64") + "," + iterations.toString()
if pbkdf2_cache[cache_string]
return pbkdf2_cache[cache_string]
mac = crypto.createHmac("sha256", password)
mac.update(salt)
mac.update("\x00\x00\x00\x01")
u = mac.digest()
t = u
for c in [0...iterations-1]
mac = crypto.createHmac("sha256", password)
mac.update(t)
t = mac.digest()
u = xor_bytes(u, t)
pbkdf2_cache[cache_string] = u
return u
# a, b should be strings
compare_digest = (a, b) ->
left = undefined
right = b
result = undefined
if a.length is b.length
left = a
result = 0
if a.length != b.length
left = b
result = 1
len = Math.min(left.length, right.length)
for i in [0...len]
result |= left[i] ^ right[i]
return result is 0
handshake_error = (code, message) =>
if 10 <= code <= 20
@emit 'error', new err.ReqlAuthError(message)
else
@emit 'error', new err.ReqlDriverError(message)
handshake_callback = (buf) =>
# Once we receive a response, extend the current
# buffer with the data from the server. The reason we
# extend it, vs. just setting it to the value of `buf`
# is that this callback may be invoked several times
# before the server response is received in full. Each
# time through we check if we've received the entire
# response, and only disable this event listener at
# that time.
@buffer = Buffer.concat([@buffer, buf])
# Next we read bytes until we get a null byte. Then we follow
# the new handshake logic to authenticate the user with the
# server.
j = 0
for b,i in @buffer
if b is 0
# Here we pull the status string out of the
# buffer and convert it into a string.
status_buf = @buffer.slice(j, i)
j = i+1
status_str = status_buf.toString()
# Get the reply from the server, and parse it as JSON
try
server_reply = JSON.parse(status_str)
catch json_error
throw new err.ReqlDriverError(status_str)
if state is 1
if not server_reply.success
handshake_error(server_reply.error_code, server_reply.error)
return
min = server_reply.min_protocol_version
max = server_reply.max_protocol_version
if min > protoVersionNumber or max < protoVersionNumber
# We don't actually support changing the protocol yet, so just error.
throw new err.ReqlDriverError(
"""Unsupported protocol version #{protoVersionNumber}, \
expected between #{min} and #{max}.""")
state = 2
else if state is 2
if not server_reply.success
handshake_error(server_reply.error_code, server_reply.error)
return
authentication = {}
server_first_message = server_reply.authentication
for item in server_first_message.split(",")
i = item.indexOf("=")
authentication[item.slice(0, i)] = item.slice(i+1)
auth_r = authentication.r
auth_salt = new Buffer(authentication.s, 'base64')
auth_i = parseInt(authentication.i)
if not (auth_r.substr(0, r_string.length) == r_string)
throw new err.ReqlAuthError("Invalid nonce from server")
client_final_message_without_proof = "c=biws,r=" + auth_r
salted_password = pb<PASSWORD>2_hmac(@rawSocket.password, auth_salt, auth_i)
client_key = crypto.createHmac("sha256", salted_password).update("Client Key").digest()
stored_key = crypto.createHash("sha256").update(client_key).digest()
auth_message =
client_first_message_bare + "," +
server_first_message + "," +
client_final_message_without_proof
client_signature = crypto.createHmac("sha256", stored_key).update(auth_message).digest()
client_proof = xor_bytes(client_key, client_signature)
server_key = crypto.createHmac("sha<KEY>", salted_password).update("Server Key").digest()
server_signature = crypto.createHmac("sha256", server_key).update(auth_message).digest()
state = 3
message = JSON.stringify({authentication: client_final_message_without_proof + ",p=" + client_proof.toString("base64")})
nullbyte = new Buffer('\0', "binary")
@rawSocket.write Buffer.concat([Buffer(message.toString()), nullbyte])
else if state is 3
if not server_reply.success
handshake_error(server_reply.error_code, server_reply.error)
return
first_equals = server_reply.authentication.indexOf('=')
v = server_reply.authentication.slice(first_equals+1)
if not compare_digest(v, server_signature.toString("base64"))
throw new err.ReqlAuthError("Invalid server signature")
state = 4
@rawSocket.removeListener('data', handshake_callback)
@rawSocket.on 'data', (buf) => @_data(buf)
# We also want to cancel the timeout error
# callback that we set earlier. Even though we
# haven't checked `status_str` yet, we've
# gotten a response so it isn't a timeout.
clearTimeout(timeout)
# Notify listeners we've connected
# successfully. Notably, the Connection
# constructor registers a listener for the
# `"connect"` event that sets the `@open`
# flag on the connection and invokes the
# callback passed to the `r.connect`
# function.
@emit 'connect'
else
throw new err.ReqlDriverError("Unexpected handshake state")
# We may have more messages if we're in the middle of the handshake,
# so we have to update the buffer.
@buffer = @buffer.slice(j + 1)
# This is the end of the handshake callback.
# Register the handshake callback on the socket. Once the
# handshake completes, it will unregister itself and
# register `_data` on the socket for `"data"` events.
@rawSocket.on 'data', handshake_callback
# In case the socket encounters an error, we re-emit the error
# ourselves. The Connection superclass constructor will invoke
# the user's `r.connect` callback with the appropriate error
# object.
@rawSocket.on 'error', (err) => @emit 'error', err
# Upon closing the `@rawSocket` for any reason, we close this
# connection. Passing `noreplyWait: false` ensures that we
# won't try to emit anything else on the socket.
@rawSocket.on 'close', =>
if @isOpen()
@close({noreplyWait: false})
@emit 'close'
# We re-raise the `timeout` event. Node says the socket must
# be closed by the user though. We should do that rather than
# just set the `@open` flag to `false`
@rawSocket.on 'timeout', => @open = false; @emit 'timeout'
clientPort: -> @rawSocket.localPort
clientAddress: -> @rawSocket.localAddress
# #### TcpConnection close method
#
# This is a public method for closing the current connection. It
# performs the raw socket related cleanup, and delegates the work
# of setting `@open` etc to the Connection superclass's
# implementation of `.close`
close: (varar 0, 2, (optsOrCallback, callback) ->
# Here we handle different ways of calling `.close`
if callback?
# This is when calling close like `.close({..}, function(..) {})`
opts = optsOrCallback
cb = callback
else if Object::toString.call(optsOrCallback) is '[object Object]'
# This is when calling close like `.close({..})`
opts = optsOrCallback
cb = null
else if typeof optsOrCallback is "function"
# This is when calling close like `.close(function(..){..})`
opts = {}
cb = optsOrCallback
else
# And the default is when calling like `.close()`
opts = {}
# Finally, we create the promise for this function. It closes
# the socket and invokes the superclass to clean up everything
# else, then invokes the user's callback to this function.
#
# In order:
#
# 1. The promise is initialized, with `resolve` and `reject` passed
# to the anonymous promise callback immediately.
# 2. The anonymous promise callback calls the superclass's
# `close` method on this connection, with the `opts` that
# were passed to this function. The only option `close`
# accepts is `noreplyWait`
# 3. The superclass's close method sets `@open` to false, and
# also closes all cursors, feeds, and callbacks that are
# currently outstanding.
# 4. Depending on whether `opts.noreplyWait` is true, the
# superclass's `close` may immediately invoke `wrappedCb`,
# or it may defer it until all outstanding `noreply`
# queries are completed.
# 5. When `wrappedCb` is invoked, it calls `.end()` on the raw
# socket for this connection, telling Node we'd like the
# tcp connection to be closed.
# 6. The socket will raise the `"close"` event when it's done
# closing, and at that time the promise here will be
# resolved or rejected.
# 7. If the promise was resolved, the callback provided to
# this function (`cb`) will be run (it's chained to the
# promise).
new Promise( (resolve, reject) =>
wrappedCb = (error, result) =>
closeCb = =>
if error?
reject error
else
resolve result
cleanupSocket = =>
# Resolve the promise, invoke all callbacks, then
# destroy remaining listeners and remove our
# reference to the socket.
closeCb()
@rawSocket?.removeAllListeners()
@rawSocket = null
@emit("close")
if @rawSocket?
if @rawSocket.readyState == 'closed'
# Socket is already closed for some reason,
# just clean up
cleanupSocket()
else
# Otherwise, wait until we get the close event
@rawSocket?.once("close", cleanupSocket)
@rawSocket.end()
else
# If the rawSocket is already closed, there's no
# reason to wait for a 'close' event that will
# never come. However we still need to fulfill the
# promise interface, so we do the next best thing
# and resolve it on the next event loop tick.
process.nextTick(closeCb)
TcpConnection.__super__.close.call(@, opts, wrappedCb)
).nodeify cb
)
# #### TcpConnection close method
#
# This method is called by the superclass in the `.close`
# method. It simply closes the socket completely and calls the
# superclass's `cancel`. The superclass's cancel closes all
# outstanding cursors and feeds, and invokes all outstanding query
# callbacks with an error.
#
# Despite not starting with an underscore, this is not a public
# method.
cancel: () ->
@rawSocket.destroy()
super()
# #### TcpConnection _writeQuery method
#
# This method emits a query's token on the socket, then invokes
# `.write` which emits the body of the query.
_writeQuery: (token, data) ->
tokenBuf = new Buffer(8)
# We write the token in two 4-byte chunks: least significant
# bytes first, then most significant bytes. (This is the same
# order as little endian 8 bytes would be). The `_data` method
# in the `Connection` class extracts the token from server
# responses by reversing this process.
#
# The key here is to write the token in a consistent way (so
# responses can be paired with outstanding requests), and to
# ensure the number isn't interpreted as a negative number by
# the server. The server doesn't actually care if the numbers
# are sequential.
tokenBuf.writeUInt32LE(token & 0xFFFFFFFF, 0)
tokenBuf.writeUInt32LE(Math.floor(token / 0xFFFFFFFF), 4)
# Write out the token to the socket, then invoke `.write` to
# write the data to the socket.
@rawSocket.write tokenBuf
@write new Buffer(data)
# #### TcpConnection write method
#
# This method is called by `_writeQuery` and just writes the body
# of a query to the socket.
#
# Despite not starting with an underscore, it is not a public
# method.
write: (chunk) ->
# Before writing the data, we need to write the length of the
# data as an unsigned little-endian 4 byte integer.
lengthBuffer = new Buffer(4)
lengthBuffer.writeUInt32LE(chunk.length, 0)
@rawSocket.write lengthBuffer
# Finally we write the data to the socket. It is serialized
# from json to a string in the `Connection` class's
# `_sendQuery` method.
@rawSocket.write chunk
# ### HttpConnection class
#
# This class is used to run queries from the webui to the RethinkDB
# internal http server using XHR. It's not intended for general usage
# in applications.
class HttpConnection extends Connection
# We defined the default protocol in case the user doesn't specify
# one.
DEFAULT_PROTOCOL: 'http'
# A static method used by `r.connect` to decide which kind of
# connection to create in a given environment. Here we check if
# XHRs are defined. If not, we aren't in the browser and shouldn't
# be using `HttpConnection`
@isAvailable: -> typeof XMLHttpRequest isnt "undefined"
# #### HttpConnection constructor method
#
# This method sets up the XMLHttpRequest object that all
# requests/responses will be sent and received on. Unlike the
# TcpConnection, the HTTP server only allows one outstanding query
# at a time per connection. Because of this, currently the web ui
# creates many different connections.
#
# The state of an HTTP connection is actually stored on the
# server, and they automatically time out after 5 minutes. The way
# it works is we send a POST request to:
# `/ajax/reql/open-new-connection`, which gets us a connection
# id. The browser can also explicitly destroy server connections
# with the `/ajax/reql/close-connection?conn_id=` url.
#
# Ultimately, the server keeps track of the connections because
# it needs to give the client a way to fetch more results from
# cursors and feeds.
constructor: (host, callback) ->
# A quick check to ensure we can create an `HttpConnection`
unless HttpConnection.isAvailable()
throw new err.ReqlDriverError "XMLHttpRequest is not available in this environment"
# Call the superclass constructor. This initializes the
# attributes `@host`, `@port`, `@db`, `@authKey`, `@timeout`,
# `@outstandingCallbacks`, `@nextToken`, `@open`, `@closing`,
# and `@buffer`. It also registers the callback to be invoked
# once the `"connect"` event is emitted.
super(host, callback)
# A protocol may be supplied in the host object. If the host
# doesn't have a protocol key, (or is a string, which it's
# also allowed to be), then use the default protocol, which is
# 'http'
protocol = if host.protocol is 'https' then 'https' else @DEFAULT_PROTOCOL
# Next we construct an XHR with the path to the reql query
# endpoint on the http server.
url = "#{protocol}://#{@host}:#{@port}#{host.pathname}ajax/reql/"
xhr = new XMLHttpRequest
#The request is a `POST` to ensure the response isn't cached
# by the browser (which has caused bugs in the past). The
# `true` argument is setting the request to be asynchronous.
# Some browsers cache this request no matter what cache
# control headers are set on the request or the server's
# response. So the `cacheBuster` argument ensures every time
# we create a connection it's a unique url, and we really do
# create a new connection on the server.
xhr.open("POST", url+"open-new-connection?cacheBuster=#{Math.random()}", true)
# We response will be a connection ID, which we receive as text.
xhr.responseType = "text"
# Next, set up the callback to process the response from the
# server when the new connection is established.
xhr.onreadystatechange = (e) =>
# readyState 4 is "DONE", the data has been completely received.
if xhr.readyState is 4
# The status is 200 if we get a successful response
if xhr.status is 200
# Now we finally store the `@_url` variable. No
# particular reason for not doing this sooner
# since the url doesn't change.
@_url = url
# Keep the connection ID we received.
@_connId = xhr.response
# Emit the `"connect"` event. The `Connection`
# superclass's constructor listens for this event
# to set the `@open` flag to `true` and invoke its
# callback (which is callback passed to this
# method)
@emit 'connect'
else
# In case we get anything other than a 200, raise an error.
@emit 'error', new err.ReqlDriverError "XHR error, http status #{xhr.status}."
# Send the xhr, and store it in the instance for later.
xhr.send()
@xhr = xhr
# #### HttpConnection cancel method
#
# This sends a POST to the `close-connection` endpoint, so the
# server can deallocate resources related to the connection. This
# throws out any data for unconsumed cursors etc and invalidates
# this connection id.
cancel: ->
# Check if the connection id is still open. `@connId` is null
# if the connection was previously closed or cancelled
if @_connId?
# Since only one request can happen at a time, we need to
# abort any in-progress xhr request before sending a new
# request to close the connection.
@xhr.abort()
xhr = new XMLHttpRequest
# This sends the close connection request asynchronously.
xhr.open("POST", "#{@_url}close-connection?conn_id=#{@_connId}", true)
# We ignore the result, but Firefox doesn't. Without this line it complains
# about "No element found" when trying to parse the response as xml.
xhr.responseType = "arraybuffer"
xhr.send()
# Null out @conn_Id so we know not to send another
# close request to the server later.
@_url = null
@_connId = null
# This will end any outstanding cursors and feeds, though
# there should be at most one since we don't support
# multiple queries at once on http connections.
super()
# #### HttpConnection close method
#
# Closes the http connection. Does nothing new or special beyond
# what the superclass already does. The server connection is
# closed in `cancel` above, which the superclass calls for us.
close: (varar 0, 2, (optsOrCallback, callback) ->
if callback?
opts = optsOrCallback
cb = callback
else if Object::toString.call(optsOrCallback) is '[object Object]'
opts = optsOrCallback
cb = null
else
opts = {}
cb = optsOrCallback
unless not cb? or typeof cb is 'function'
throw new err.ReqlDriverError "Final argument to `close` must be a callback function or object."
# This would simply be `super(opts, wrappedCb)`, if we were
# not in the varar anonymous function
HttpConnection.__super__.close.call(this, opts, cb)
)
# #### HttpConnection _writeQuery method
#
# This creates the buffer to send to the server, writes the token
# and data to it, then passes the data and buffer down to `write`
# to write the data itself to the xhr request.
#
# This differs from `TcpConnection`'s version of `_writeQuery`
# which only writes the token.
_writeQuery: (token, data) ->
# We use encodeURI to get the length of the unicode
# representation of the data.
buf = new Buffer(encodeURI(data).split(/%..|./).length - 1 + 8)
# Again, the token is encoded as a little-endian 8 byte
# unsigned integer.
buf.writeUInt32LE(token & 0xFFFFFFFF, 0)
buf.writeUInt32LE(Math.floor(token / 0xFFFFFFFF), 4)
# Write the data out to the bufferm then invoke `write` with
# the buffer and token
buf.write(data, 8)
@write buf, token
# #### HttpConnection write method
#
# This method takes a Node Buffer (or more accurately, the Buffer
# class that Browserify polyfills for us) and turns it into an
# ArrayBufferView, then sends it over the XHR with the current
# connection id.
#
# Despite not starting with an underscore, this is not a public
# method.
write: (chunk, token) ->
# Create a new XHR with to run the query over.
xhr = new XMLHttpRequest
xhr.open("POST", "#{@_url}?conn_id=#{@_connId}", true)
xhr.responseType = "arraybuffer"
xhr.onreadystatechange = (e) =>
# When the server responds, the state must be 4 ("DONE"),
# and the HTTP status code should be success. Otherwise we
# just do nothing. There's a separate callback if the XHR
# encounters an error.
if xhr.readyState is 4 and xhr.status is 200
# Convert the response from a browser ArrayBuffer into
# a Node buffer
buf = new Buffer(b for b in (new Uint8Array(xhr.response)))
# The data method is defined in the `Connection` class
# and reads and parses the response from the server.
@_data(buf)
# On error we want to invoke the callback for this query with
# an error.
xhr.onerror = (e) =>
@outstandingCallbacks[token].cb(new Error("This HTTP connection is not open"))
# To serialize the query (held in chunk) for the XHR, we need
# to convert it from a node buffer into an `ArrayBufferView`
# (specifically `Uint8Array`), since passing an `ArrayBuffer`
# in xhr.send is deprecated
view = new Uint8Array(chunk.length)
i = 0
while i < chunk.length
view[i] = chunk[i]
i++
# And send it on its way to the server
xhr.send view
@xhr = xhr
# ## isConnection
#
# This is an exported function that determines whether something is a
# Connection. It's used by the [ast module](ast.html) to validate the
# first argument passed to `.run` (which must always be a connection).
module.exports.isConnection = (connection) ->
return connection instanceof Connection
# ## connect
#
# The main function of this module, which is exposed to end users as
# `r.connect`. See the [API
# docs](http://rethinkdb.com/api/javascript/connect/).
module.exports.connect = varar 0, 2, (hostOrCallback, callback) ->
if typeof hostOrCallback is 'function'
# This occurs when called like `r.connect(function(..){..})`
# Override the callback variable (which should be undefined)
# and set host to an empty object
host = {}
callback = hostOrCallback
else
# Otherwise, the `callback` variable is already correctly
# holding the callback, and the host variable is the first
# argument
host = hostOrCallback || {}
# `r.connect` returns a Promise which does the following:
#
# 1. Determines whether to create a `TcpConnection` or an
# `HttpConnection` depending on whether we're running on Node
# or in the browser.
# 2. Initializes the connection, and when it's complete invokes
# the user's callback
new Promise( (resolve, reject) ->
if host.authKey? && (host.password? || host.user? || host.username?)
throw new err.ReqlDriverError "Cannot use both authKey and password"
if host.user && host.username
throw new err.ReqlDriverError "Cannot use both user and username"
else if host.authKey
host.user = "admin"
host.password = host.authKey
else
# Fixing mismatch between drivers
if host.username?
host.user = host.username
create_connection = (host, callback) =>
if TcpConnection.isAvailable()
new TcpConnection host, callback
else if HttpConnection.isAvailable()
new HttpConnection host, callback
else
throw new err.ReqlDriverError "Neither TCP nor HTTP avaiable in this environment"
wrappedCb = (err, result) ->
if (err)
reject(err)
else
resolve(result)
create_connection(host, wrappedCb)
).nodeify callback
# Exposing the connection classes
module.exports.Connection = Connection
module.exports.HttpConnection = HttpConnection
module.exports.TcpConnection = TcpConnection
| true | # # Network (net.coffee)
#
# This module handles network and protocol related functionality for
# the driver. The classes defined here are:
#
# - `Connection`, which is an EventEmitter and the base class for
# - `TcpConnection`, the standard driver connection
# - `HttpConnection`, the connection type used by the webui
#
# ### Imports
#
# The [net module](http://nodejs.org/api/net.html) is the low-level
# networking library Node.js provides. We need it for `TcpConnection`
# objects
net = require('net')
# The [tls module](http://nodejs.org/api/tls.html) is the TLS/SSL
# networking library Node.js provides. We need it to establish an
# encrypted connection for `TcpConnection` objects
tls = require('tls')
# The [events module](http://nodejs.org/api/events.html) is a core
# Node.js module that provides the ability for objects to emit events,
# and for callbacks to be attached to those events.
events = require('events')
# The [util module](util.html) contains utility methods used several
# places in the driver
util = require('./util')
# The [errors module](errors.html) contains exceptions thrown by the driver
err = require('./errors')
# The [cursors module](cursors.html) contains data structures used to
# iterate over large result sets or infinite streams of data from the
# database (changefeeds).
cursors = require('./cursor')
# The `proto-def` module is an autogenerated file full of protocol
# definitions used to communicate to the RethinkDB server (basically a
# ton of human readable names for magic numbers).
#
# It is created by the python script `convert_protofile` in the
# `drivers` directory (one level up from this file) by converting a
# protocol buffers definition file into a JavaScript file. To generate
# the `proto-def.js` file, see the instructions in the
# [README](./index.html#creating-the-proto-defjs)
#
# Note that it's a plain JavaScript file, not a CoffeeScript file.
protodef = require('./proto-def')
crypto = require("crypto")
# Each version of the protocol has a magic number specified in
# `./proto-def.coffee`. The most recent version is 4. Generally the
# official driver will always be updated to the newest version of the
# protocol, though RethinkDB supports older versions for some time.
protoVersion = protodef.VersionDummy.Version.V1_0
protoVersionNumber = 0
# We are using the JSON protocol for RethinkDB, which is the most
# recent version. The older protocol is based on Protocol Buffers, and
# is deprecated.
protoProtocol = protodef.VersionDummy.Protocol.JSON
# The `QueryType` definitions are used to control at a high level how
# we interact with the server. So we can `START` a new query, `STOP`
# an executing query, `CONTINUE` receiving results from an existing
# cursor, or wait for all outstanding `noreply` queries to finish with
# `NOREPLY_WAIT`.
protoQueryType = protodef.Query.QueryType
# The server can respond to queries in several ways. These are the
# definitions for the response types.
protoResponseType = protodef.Response.ResponseType
# The [ast module](ast.html) contains the bulk of the api exposed by
# the driver. It defines how you can create ReQL queries, and handles
# serializing those queries into JSON to be transmitted over the wire
# to the database server.
r = require('./ast')
# We use the [bluebird](https://github.com/petkaantonov/bluebird)
# third-party module to provide a promise implementation for the
# driver.
Promise = require('bluebird')
# These are some functions we import directly from the `util` module
# for convenience.
ar = util.ar
varar = util.varar
aropt = util.aropt
mkAtom = util.mkAtom
mkErr = util.mkErr
# These are the default hostname and port used by RethinkDB
DEFAULT_HOST = 'localhost'
DEFAULT_PORT = 28015
module.exports.DEFAULT_HOST = DEFAULT_HOST
module.exports.DEFAULT_PORT = DEFAULT_PORT
# These are strings returned by the server after a handshake
# request. Since they must match exactly they're defined in
# "constants" here at the top
HANDSHAKE_SUCCESS = "SUCCESS"
HANDSHAKE_AUTHFAIL = "ERROR: Incorrect authorization key.\n"
# ### Connection
#
# Connection is the base class for both `TcpConnection` and
# `HttpConnection`. Applications using this driver will need to get a
# connection object to be able to query the server.
#
# Connection is a subclass of
# [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter),
# and it will emit the following events:
#
# - `"connect"` is emitted by the subclasses `TcpConnection` and
# `HttpConnection` when they connect to the server successfully.
# - `"error"` is emitted when protocol level errors occur (notably
# not query errors! Those are returned as arguments to the
# callback the user provides.) `"error"` will also be accompanied
# by a message indicating what went wrong.
# - `"close"` is emitted when the connection is closed either through
# an error or by the user calling `connection.close()` explicitly
# - `"timeout"` will be emitted by the `TcpConnection` subclass if the
# underlying socket times out for any reason.
class Connection extends events.EventEmitter
# By default, RethinkDB doesn't use an authorization key.
DEFAULT_AUTH_KEY: ''
# Each connection has a timeout (in seconds) for the initial handshake with the
# server. Note that this is not a timeout for queries to return
# results.
DEFAULT_TIMEOUT: 20 # In seconds
# #### Connection constructor
constructor: (host, callback) ->
# We need to set the defaults if the user hasn't supplied anything.
if typeof host is 'undefined'
host = {}
# It's really convenient to be able to pass just a hostname to
# connect, since that's the thing that is most likely to vary
# (default ports, no auth key, default connection timeout are
# all common). We just detect that case and wrap it.
else if typeof host is 'string'
host = {host: host}
# Here we set all of the connection parameters to their defaults.
@host = host.host || DEFAULT_HOST
@port = host.port || DEFAULT_PORT
# One notable exception to defaulting is the db name. If the
# user doesn't specify it, we leave it undefined. On the
# server side, if no database is specified for a table, the
# database will default to `"test"`.
@db = host.db # left undefined if this is not set
@authKey = host.authKey || @DEFAULT_AUTH_KEY
@timeout = host.timeout || @DEFAULT_TIMEOUT
# Configuration options for enabling an SSL connection
# Allows the ability to pass in all the options as specified in
# [tls.connect](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback)
# or just true in case the client wants ssl but the server
# is using a certificate with a valid verified chain and there
# is no need to specify certificates on the client
if typeof host.ssl is 'boolean' && host.ssl
@ssl = {}
else if typeof host.ssl is 'object'
@ssl = host.ssl
else
@ssl = false
# The protocol allows for responses to queries on the same
# connection to be returned interleaved. When a query is run
# with this connection, an entry is added to
# `@outstandingCallbacks`. The key is the query token, and the
# value is an object with the following fields:
#
# - **cb**: The callback to invoke when a query returns another
# batch of results
# - **root**: a subclass of `TermBase` (defined in the
# [ast module](ast.html)) representing the query being run.
# - **opts**: global options passed to `.run`.
#
# Once the server returns a response, one of two fields may be
# added to the entry for that query depending on what comes
# back (this is done in `_processResponse`):
#
# - **cursor**: is set to a `Cursor` object (defined in the
# [cursor module](cursor.html)) if the server
# replies with `SUCCESS_PARTIAL`. This happens when a
# result is too large to send back all in one batch. The
# `Cursor` allows fetching results lazily as they're needed.
# - **feed**: is set to a `Feed` object (defined in the
# [cursor module](cursor.html)). This is very similar to a `Cursor`,
# except that it is potentially infinite. Changefeeds are a way
# for the server to notify the client when a change occurs to
# the results of a query the user wants to watch.
#
# Any other responses are considered "done" and don't have any
# further results to fetch from the server. At that time the
# query token is deleted from `@outstandingCallbacks` since we
# don't expect any more results using that token.
@outstandingCallbacks = {}
# Each query to the server requires a unique token (per
# connection). `nextToken` is incremented every time we issue
# a new query
@nextToken = 1
# `@open` and `@closing` are used to record changes in the
# connection state. A connection is open after the handshake
# is successfully completed, and it becomes closed after the
# server confirms the connection is closed.
@open = false
# `@closing` is true when the `conn.close()` method is called,
# and becomes false again just before the callback provided to
# `close` is called. This allows `noreplyWait` to be called
# from within `.close`, but prevents any other queries from
# being run on a closing connection. (`noreplyWait` checks
# `@open` only to see if the connection is closed, but the
# `.isOpen()` method checks both flags)
@closing = false
# We create a [Buffer](http://nodejs.org/api/buffer.html)
# object to receive all bytes coming in on this
# connection. The buffer is modified in the `_data` method
# (which is called whenever data comes in over the network on
# this connection), and it is also modified by the handshake
# callback that's defined in the `TcpConnection` constructor.
@buffer = new Buffer(0)
@_events = @_events || {}
# Now we set up two callbacks, one to run on successful
# connection, and the other to run if we fail to connect to
# the server. They listen to the `"connect"` and `"error"`
# events respectively. If successful, we set `@open` to
# `true`, otherwise we pass an error to the connection
# callback that was passed to the constructor (`callback`)
errCallback = (e) =>
@removeListener 'connect', conCallback
if e instanceof err.ReqlError
callback e
else
callback new err.ReqlDriverError "Could not connect to #{@host}:#{@port}.\n#{e.message}"
@once 'error', errCallback
conCallback = =>
@removeListener 'error', errCallback
@open = true
callback null, @
@once 'connect', conCallback
# closePromise holds the promise created when `.close()` is
# first called. Subsequent calls to close will simply add to
# this promise, rather than attempt closing again.
@_closePromise = null
# #### Connection _data method
#
# This method is responsible for parsing responses from the server
# after the initial handshake is over. It reads the token number
# of the response (so we know which query is being responded to),
# and the response length, then parses the rest of the response as
# JSON.
_data: (buf) ->
# We extend the current buffer with the contents of `buf` that
# we got from the server.
@buffer = Buffer.concat([@buffer, buf])
# The first 8 bytes in a response are the token number of the
# query the server is responding to. The next 4 bytes indicate
# how long the response will be. So if the response isn't at
# least 12 bytes long, there's nothing else to do.
while @buffer.length >= 12
# When a query is sent to the server, we write out the
# token in a way that can be read back later as a native
# integer. Since Node buffers don't have a method like
# `readUInt64LE`, we're forced to emulate it ourselves.
token = @buffer.readUInt32LE(0) + 0x100000000 * @buffer.readUInt32LE(4)
# Next up is the response length. The protocol dictates
# this must be a 32 bit unsigned integer in little endian
# byte order.
responseLength = @buffer.readUInt32LE(8)
# This ensures that the responseLength is less than or
# equal to the amount of data we have in the buffer
# (including the token and response length itself). If the
# buffer doesn't have enough data in it, we just break
# out. More data will be coming later, and it will be
# added to the end of the buffer, so we'll wait until the
# full response is available.
unless @buffer.length >= (12 + responseLength)
break
# Since we have enough data, we slice it out of the
# buffer, and parse it as JSON.
responseBuffer = @buffer.slice(12, responseLength + 12)
response = JSON.parse(responseBuffer)
# Now it's off to `_processResponse` where the data is
# converted to a format the user will be able to work
# with, error responses are detected etc.
@_processResponse response, token
# Finally, we truncate the buffer to the end of the
# current response. The buffer may already be queuing up a
# new response, so it's never safe to clear it or create a
# new one.
@buffer = @buffer.slice(12 + responseLength)
# #### Connection _delQuery method
#
# This method just removes the entry in `@outstandingCallbacks`
# for a given token. It's called whenever a response doesn't
# return a cursor, a cursor is completely consumed, or the query
# encounters an error.
_delQuery: (token) ->
delete @outstandingCallbacks[token]
# #### Connection _processResponse method
#
# This method is contains the main logic for taking different
# actions based on the response type. It receives the response as
# an object (parsed from the JSON coming over the wire), and the
# token for the query the response corresponds to.
_processResponse: (response, token) ->
# For brevity the wire format specifies that the profile key
# is "p". We give it a more readable variable name here.
profile = response.p
# First we need to check if we're even expecting a response
# for this token. If not it's an error.
if @outstandingCallbacks[token]?
{cb:cb, root:root, cursor: cursor, opts: opts, feed: feed} = @outstandingCallbacks[token]
# Some results for queries are not returned all at once,
# but in chunks. The driver takes care of making sure the
# user doesn't see this, and uses `Cursor`s to take
# multiple responses and make them into one long stream of
# query results.
#
# Depending on the type of result, and whether this is the
# first response for this token, we may or may not have a
# cursor defined for this token. If we do have a cursor
# defined already, we add this response to the cursor.
if cursor?
cursor._addResponse(response)
# `cursor._addResponse` will check if this response is
# the last one for this token, and if so will set its
# `cursor._endFlag` to true. If this is the last
# response for this query and we aren't waiting on any
# other responses for this cursor (if, for example, we
# get the responses out of order), then we remove this
# token's entry in `@outstandingCallbacks`.
if cursor._endFlag && cursor._outstandingRequests is 0
@_delQuery(token)
# Next we check if we have a callback registered for this
# token. In [ast](ast.html) we always provide `_start`
# with a wrapped callback function, so this may as well be
# an else branch.
else if cb?
# The protocol (again for brevity) puts the response
# type into a key called "t". What we do next depends
# on that value. We'll be comparing it to the values
# in the `proto-def` module, in `protoResponseType`.
switch response.t
# ##### Error responses
when protoResponseType.COMPILE_ERROR
# Compile errors happen during parsing and
# type checking the query on the server
# side. An example is passing too many
# arguments to a function. We pass an error
# object that includes the backtrace from the
# response and the original query
# (`root`). Then we delete the token from
# `@outstandingCallbacks`.
cb mkErr(err.ReqlServerCompileError, response, root)
@_delQuery(token)
when protoResponseType.CLIENT_ERROR
# Client errors are returned when the client
# is buggy. This can happen if a query isn't
# serialized right, or the handshake is done
# incorrectly etc. Hopefully end users of the
# driver should never see these.
cb mkErr(err.ReqlDriverError, response, root)
@_delQuery(token)
when protoResponseType.RUNTIME_ERROR
# Runtime errors are the most common type of
# error. They happen when something goes wrong
# that can only be determined by running the
# query. For example, if you try to get the
# value of a field in an object that doesn't
# exist.
errType = util.errorClass(response.e)
cb mkErr(errType, response, root)
@_delQuery(token)
# ##### Success responses
when protoResponseType.SUCCESS_ATOM
# `SUCCESS_ATOM` is returned when the query
# was successful and returned a single ReQL
# data type. The `mkAtom` function from the
# [util module](util.html) converts all
# pseudotypes in this response to their
# corresponding native types
response = mkAtom response, opts
# If the response is an array, we patch it a
# bit so it can be used as a stream.
if Array.isArray response
response = cursors.makeIterable response
# If there's a profile available, we nest the
# response slightly differently before passing
# it to the callback for this token.
if profile?
response = {profile: profile, value: response}
cb null, response
# The `SUCCESS_ATOM` response means there will
# be no further results for this query, so we
# remove it from `@outstandingCallbacks`
@_delQuery(token)
when protoResponseType.SUCCESS_PARTIAL
# `SUCCESS_PARTIAL` indicates the client
# should create a cursor and request more data
# from the server when it's ready by sending a
# `CONTINUE` query with the same token. So, we
# create a new Cursor for this token, and add
# it to the object stored in
# `@outstandingCallbacks`.
# We create a new cursor, which is sometimes a
# `Feed`, `AtomFeed`, or `OrderByLimitFeed`
# depending on the `ResponseNotes`. (This
# usually doesn't matter, but third-party ORMs
# might want to treat these differently.)
cursor = null
for note in response.n
switch note
when protodef.Response.ResponseNote.SEQUENCE_FEED
cursor ?= new cursors.Feed @, token, opts, root
when protodef.Response.ResponseNote.UNIONED_FEED
cursor ?= new cursors.UnionedFeed @, token, opts, root
when protodef.Response.ResponseNote.ATOM_FEED
cursor ?= new cursors.AtomFeed @, token, opts, root
when protodef.Response.ResponseNote.ORDER_BY_LIMIT_FEED
cursor ?= new cursors.OrderByLimitFeed @, token, opts, root
cursor ?= new cursors.Cursor @, token, opts, root
# When we've created the cursor, we add it to
# the object stored in
# `@outstandingCallbacks`.
@outstandingCallbacks[token].cursor = cursor
# Again, if we have profile information, we
# wrap the result given to the callback. In
# either case, we need to add the response to
# the new Cursor.
if profile?
cb null, {profile: profile, value: cursor._addResponse(response)}
else
cb null, cursor._addResponse(response)
when protoResponseType.SUCCESS_SEQUENCE
# The `SUCCESS_SEQUENCE` response is sent when
# a cursor or feed is complete, and this is
# the last response that will be received for
# this token. Often, however, the entire
# result for a query fits within the initial
# batch. In this case, we never see a
# `SUCCESS_PARTIAL` response, so there is no
# existing Cursor to add the response to. So,
# that's what we do here, create a new Cursor,
# and delete the token from the
# `@outstandingCallbacks`.
#
# Note that qeries that have already received
# a `SUCCESS_PARTIAL` will not be handled
# here. They will be handled when we check for
# `cursor?` in the conditional up above. In
# that branch, we call cursor._addResponse,
# which takes care of checking if we received
# a `SUCCESS_SEQUENCE`. So this code only gets
# executed when the first batch on a cursor is
# also our last.
cursor = new cursors.Cursor @, token, opts, root
@_delQuery(token)
if profile?
cb null, {profile: profile, value: cursor._addResponse(response)}
else
cb null, cursor._addResponse(response)
when protoResponseType.WAIT_COMPLETE
# The `WAIT_COMPLETE` response is sent by the
# server after all queries executed with the
# optarg `noReply: true` have completed. No
# data is returned, so the callback is just provided `null`
@_delQuery(token)
cb null, null
when protoResponseType.SERVER_INFO
@_delQuery(token)
response = mkAtom response, opts
cb null, response
else
cb new err.ReqlDriverError "Unknown response type"
else
# We just ignore tokens we don't have a record of. This is
# what the other drivers do as well.
# #### Connection close method
#
# A public method that closes the connection. See [API docs for
# close](http://rethinkdb.com/api/javascript/close/).
close: (varar 0, 2, (optsOrCallback, callback) ->
# First determine which argument combination this method was
# called with, and set the callback and options appropriately.
if callback?
# When calling like `.close({...}, function(...){ ... })`
opts = optsOrCallback
unless Object::toString.call(opts) is '[object Object]'
throw new err.ReqlDriverError "First argument to two-argument `close` must be an object."
cb = callback
else if Object::toString.call(optsOrCallback) is '[object Object]'
# When calling like `.close({...})`
opts = optsOrCallback
cb = null
else if typeof optsOrCallback is 'function'
# When calling like `.close(function(...){ ... })`
opts = {}
cb = optsOrCallback
else
# When calling like `.close({...})`
opts = optsOrCallback
cb = null
for own key of opts
# Currently, only one optional argument is accepted by
# `.close`: whether or not to wait for completion of all
# outstanding `noreply` queries. So we throw an error if
# anything else is passed.
unless key in ['noreplyWait']
throw new err.ReqlDriverError "First argument to two-argument `close` must be { noreplyWait: <bool> }."
# If we're currently in the process of closing, just add the
# callback to the current promise
if @_closePromise?
return @_closePromise.nodeify(cb)
# Next we set `@closing` to true. It will be set false once
# the promise that `.close` returns resolves (see below). The
# `isOpen` method takes this variable into account.
@closing = true
# Should we wait for all outstanding `noreply` writes before
# considering the connection closed?
#
# - if the options object doesn't have a `noreplyWait` key, we
# default to `true`.
# - if we do have a `noreplyWait` key, then use that value
# - if this connection isn't `@open`, then this is all moot
noreplyWait = ((not opts.noreplyWait?) or opts.noreplyWait) and @open
# Finally, close returns a promise. This promise must do two
# things:
#
# 1. Set the flags for this connection to false (`@open` &
# `@closing`)
#
# 2. Close all cursors and feeds for outstanding callbacks. We
# won't be receiving any more responses for them, so they are
# no longer outstanding. (this is what `@cancel()` does)
#
# In addition to these two finalization steps, we may need to
# wait for all `noreply` queries to finish.
#
# You'll notice we don't close sockets or anything like that
# here. Those steps are done in the subclasses because they
# have knowledge about what kind of underlying connection is
# being used.
#
# We save the promise here in case others attempt to call
# `close` before we've gotten a response from the server (when
# the @closing flag is true).
@_closePromise = new Promise( (resolve, reject) =>
# Now we create the Promise that `.close` returns. If we
# aren't waiting for `noreply` queries, then we set the flags
# and cancel feeds/cursors immediately. If we are waiting,
# then we run a `noreplyWait` query and set the flags and
# cancel cursors when that query receives a response.
#
# In addition, we chain the callback passed to `.close` on the
# end, using bluebird's convenience method
# [nodeify](https://github.com/petkaantonov/bluebird/blob/master/API.md#nodeifyfunction-callback--object-options---promise)
#
wrappedCb = (err, result) =>
@open = false
@closing = false
@cancel()
if err?
reject err
else
resolve result
if noreplyWait
@noreplyWait(wrappedCb)
else
wrappedCb()
).nodeify cb
)
# #### Connection noreplyWait method
#
# A public method that sends a query to the server that completes
# when all previous outstanding queries are completed. See [API
# docs for
# noreplyWait](http://rethinkdb.com/api/javascript/noreplyWait/).
noreplyWait: varar 0, 1, (callback) ->
# If the connection is not open, all of the outstanding
# `noreply` queries have already been cancelled by the server,
# so it's an error to call this now. However, `noreplyWait` is
# called by the `.close` method just before setting the
# `@open` flag to false. This is why we need the `@closing`
# flag, so we can allow one last `noreplyWait` call before the
# connection is closed completely.
unless @open
return new Promise( (resolve, reject) ->
reject(new err.ReqlDriverError "Connection is closed.")
).nodeify callback
# Since `noreplyWait` is invoked just like any other query, we
# need a token.
token = @nextToken++
# Here we construct the query itself. There's no body needed,
# we just have to set the type to the appropriate value from
# `proto-def` and set the token.
query = {}
query.type = protoQueryType.NOREPLY_WAIT
query.token = token
new Promise( (resolve, reject) =>
# The method passed to Promise is invoked immediately
wrappedCb = (err, result) ->
# This callback will be invoked when the
# `NOREPLY_WAIT` query finally returns.
if (err)
reject(err)
else
resolve(result)
# Here we add an entry for this query to
# `@outstandingCallbacks`. This promise will be resolved
# or rejected at that time.
@outstandingCallbacks[token] = {cb:wrappedCb, root:null, opts:null}
# Finally, serialize the query and send it to the server
@_sendQuery(query)
# After the promise is resolved, the callback passed to
# `noreplyWait` can be invoked.
).nodeify callback
# #### Connection server method
#
# Public, retrieves the remote server id and name. See [API docs
# for server](http://rethinkdb.com/api/javascript/server/).
server: varar 0, 1, (callback) ->
unless @open
return new Promise( (resolve, reject) ->
reject(new err.ReqlDriverError "Connection is closed.")
).nodeify callback
token = PI:KEY:<KEY>END_PInextToken++
query = {}
query.type = protoQueryType.SERVER_INFO
query.token = token
new Promise( (resolve, reject) =>
wrappedCb = (err, result) ->
if (err)
reject(err)
else
resolve(result)
@outstandingCallbacks[token] = {cb:wrappedCb, root:null, opts:null}
@_sendQuery(query)
).nodeify callback
# #### Connection cancel method
#
# This method inserts a dummy error response into all outstanding
# cursors and feeds, effectively closing them. It also calls all
# registered callbacks with an error response. Then it clears the
# `@outstandingCallbacks` registry.
cancel: ar () ->
# The type of the dummy response is a runtime error, the
# reason for the error is "Connection is closed" and the
# backtrace provided is empty
response = {t:protoResponseType.RUNTIME_ERROR,r:["Connection is closed."],b:[]}
for own key, value of @outstandingCallbacks
if value.cursor?
value.cursor._addResponse(response)
else if value.cb?
value.cb mkErr(util.errorClass(response.e), response, value.root)
@outstandingCallbacks = {}
# #### Connection reconnect method
#
# Closes and re-opens a connection. See the [API
# docs](http://rethinkdb.com/api/javascript/reconnect/)
reconnect: (varar 0, 2, (optsOrCallback, callback) ->
# Similar to `.close`, there are a few different ways of
# calling `.reconnect`, so we need to determine which way it
# was called, and set the options and callback appropriately.
if callback?
# When calling like `reconnect({}, function(..){ ... })`
opts = optsOrCallback
cb = callback
else if typeof optsOrCallback is "function"
# When calling like `reconnect(function(..){ ... })`
opts = {}
cb = optsOrCallback
else
# In either of these cases, the callback will be undefined
if optsOrCallback?
# Was called like `reconnect({})`
opts = optsOrCallback
else
# Was called like `reconnect()`
opts = {}
cb = callback
# Here we call `close` with a callback that will reconnect
# with the same parameters
new Promise( (resolve, reject) =>
closeCb = (err) =>
@constructor.call @,
host:@host,
port:@port
timeout:@timeout,
authKey:@authKey
, (err, conn) ->
if err?
reject err
else
resolve conn
@close(opts, closeCb)
).nodeify cb
)
# #### Connection use method
#
# This is a public method, [see the API
# docs](http://rethinkdb.com/api/javascript/use/). It sets the
# default db to use when `r.table` is called without specifying a
# db explicitly. The db variable is sent as a global optarg when
# querying.
use: ar (db) ->
@db = db
# #### Connection isOpen method
#
# This is a non-public method that's used by subclasses to
# determine if it's safe to call `noreplyWait` when closing. It
# respects both the `@open` flag and the `@closing` flag, whose
# behavior is described in the docs for `.close`
isOpen: () ->
@open and not @closing
# #### Connection _start method
#
# `_start` combines the raw query term with global optargs,
# creates a new token for the query and invokes `_sendQuery` with
# it. `_start` is called by the `.run` method from the [ast
# module](ast.html)
_start: (term, cb, opts) ->
# Obviously, you can't query with a closed connection.
unless @open then throw new err.ReqlDriverError "Connection is closed."
# Here is where the token for the query is
# generated. @nextToken is only ever incremented here and in
# the `.noreplyWait` method
token = @nextToken++
# Here we construct the wrapper object for queries
query = {}
# The global optargs are the optional arguments passed to
# `.run`, plus some variables that are set on the connection
# itself, like `db`.
query.global_optargs = {}
# Normal queries begin with `START`. The other options are
# `CONTINUE` (for feeds and cursors), `STOP` (for closing an
# open cursor/feed), and `NOREPLY_WAIT` which is a special
# type of query (see the `.noreplyWait` method).
query.type = protoQueryType.START
query.query = term.build()
query.token = token
# Now we loop through the options passed to `.run`, convert
# them to the right format, and put them into the global
# optargs object for this query
for own key, value of opts
# In the protocol, only "snake_case" is accepted for
# optargs. Because the JS convention is to use
# "camelCase", we convert it before serializing.
#
# In addition, we take the values passed, and convert them
# into a ReQL term, and dump them in the protocol format,
# instead of including them directly as they are. This
# gives resistance to injection attacks.
query.global_optargs[util.fromCamelCase(key)] = r.expr(value).build()
# If the user has specified the `db` on the connection (either
# in the constructor, as an optarg to .run(), or with the `.use` method)
# we add that db to the optargs for the query.
if opts.db? or @db?
query.global_optargs.db = r.db(opts.db or @db).build()
# Next, ensure that the `noreply` and `profile` options
# (if present) are actual booleans using the `!!` trick.
# Note that `r.expr(false).build() == false` and
# `r.expr(null).build() == null`, so the conversion in the
# loop above won't affect the boolean value the user intended
# to pass.
if opts.noreply?
query.global_optargs['noreply'] = r.expr(!!opts.noreply).build()
if opts.profile?
query.global_optargs['profile'] = r.expr(!!opts.profile).build()
# Here we stash away the callback the user provided in
# `@outstandingCallbacks`, with the query term and the options
# passed to `.run`. Note that we don't consider the callback
# as outstanding if the user has specified `noreply`. Since
# the server will never respond, it would sit in
# `@outstandingCallbacks` forever.
if (not opts.noreply?) or !opts.noreply
@outstandingCallbacks[token] = {cb:cb, root:term, opts:opts}
# Now we send the user's query. `_sendQuery` writes the
# necessary headers and will serialize it for sending over the
# underlying connection type (either tcp or http).
@_sendQuery(query)
# Finally, if the user called `.run` with both a callback and
# the `noreply` flag set, we just invoke it immediately, since
# there won't be a response from the server. Since we have no
# idea if there's an error and no response, we just pass it
# null (with error undefined).
if opts.noreply? and opts.noreply and typeof(cb) is 'function'
cb null # There is no error and result is `undefined`
# #### Connection _continueQuery method
#
# This method sends a notification to the server that we'd like to
# receive the next batch from a feed or a cursor
# (`CONTINUE`). Feeds may block indefinitely, but cursors should
# return quickly.
_continueQuery: (token) ->
unless @open then throw new err.ReqlDriverError "Connection is closed."
query =
type: protoQueryType.CONTINUE
token: token
@_sendQuery(query)
# #### Connection _endQuery method
#
# This method sends a notification to the server that we don't
# care about the rest of the results on a cursor or feed (`STOP`).
_endQuery: (token) ->
unless @open then throw new err.ReqlDriverError "Connection is closed."
query =
type: protoQueryType.STOP
token: token
@_sendQuery(query)
# #### Connection _sendQuery method
#
# This method serializes a javascript object in the rethinkdb json
# protocol format into a string, and sends it over the underlying
# connection by calling `_writeQuery`
_sendQuery: (query) ->
# The wire protocol doesn't use JSON objects except for things
# like optargs. Instead it's a bunch of nested arrays, where
# the first element of the array indicates what the type of
# that object is. This is a lot like lisp. Here the entire
# query is wrapped in an array, with the first element the
# type of the query (`START`, `STOP`, `CONTINUE`, or
# `NOREPLY_WAIT`).
data = [query.type]
# If the query has a body, (which it only does in the `START`
# case), then we push it into the outer array.
if !(query.query is undefined)
data.push(query.query)
if query.global_optargs? and Object.keys(query.global_optargs).length > 0
data.push(query.global_optargs)
# This is the last bit the Connection superclass can
# do. `_writeQuery` is implemented by the subclasses since
# they know what underlying connection type is being used.
# This is also where the query is finally converted into a
# string.
@_writeQuery(query.token, JSON.stringify(data))
# Global cache variable for storing the results of pbkdf2_hmac
pbkdf2_cache = {}
# ### TcpConnection
#
# This class implements all of the TCP specific behavior for normal
# driver connections. External users of the driver should only use
# `TcpConnection`s since `HttpConnection` are just for the webui.
#
# Fundamentally, this class uses the `net` module to wrap a raw socket
# connection to the server.
class TcpConnection extends Connection
# #### TcpConnection isAvailable method
#
# The TcpConnection should never be used by the webui, so we have
# an extra method here that decides whether it's available. This
# is called by the constructor, but also by the `.connect`
# function which uses it to decide what kind of connection to
# create.
@isAvailable: () -> !(process.browser)
# #### TcpConnection constructor method
#
# This sets up all aspects of the connection that relate to
# TCP. Everything else is done in the Connection superclass
# constructor.
constructor: (host, callback) ->
# Bail out early if we happen to be in the browser
unless TcpConnection.isAvailable()
throw new err.ReqlDriverError "TCP sockets are not available in this environment"
# Invoke the superclass's constructor. This initializes the
# attributes `@host`, `@port`, `@db`, `@authKey` and
# `@timeout`, `@outstandingCallbacks`, `@nextToken`, `@open`,
# `@closing`, and `@buffer`. It also registers the callback to
# be invoked once the `"connect"` event is emitted.
super(host, callback)
# Next we create the underlying tcp connection to the server
# using the net module and store it in the `@rawSocket`
# attribute.
if @ssl
@ssl.host = @host
@ssl.port = @port
@rawSocket = tls.connect @ssl
else
@rawSocket = net.connect @port, @host
# We disable [Nagle's
# algorithm](http://en.wikipedia.org/wiki/Nagle%27s_algorithm)
# on the socket because it can impose unnecessary
# latency.
@rawSocket.setNoDelay()
# Enable TCP keepalive so we can detect dead connections.
@rawSocket.setKeepAlive(true)
# Here we use the `@timeout` value passed to `.connect` to
# destroy the socket and emit a timeout error. The timer will
# be cancelled upon successful connection.
timeout = setTimeout( (()=>
@rawSocket.destroy()
@emit 'error', new err.ReqlTimeoutError(
"Could not connect to #{@host}:#{@port}, operation timed out.")
), @timeout*1000)
# If any other kind of error occurs, we also want to cancel
# the timeout error callback. Otherwise a connection error
# would be followed shortly by a spurious timeout error.
@rawSocket.once 'error', => clearTimeout(timeout)
# Once the TCP socket successfully connects, we can begin the
# handshake with the server to establish the connection on the
# server.
@rawSocket.once 'connect', =>
# The protocol specifies that the magic number for the
# version should be given as a little endian 32 bit
# unsigned integer. The value is given in the `proto-def`
# module, but it is just a random number that's unlikely
# to be accidentally the first few bytes of an erroneous
# connection on the socket.
version = new Buffer(4)
version.writeUInt32LE(protoVersion, 0)
# Send the protocol type that we will be using to
# communicate with the server. Json is the only currently
# supported protocol.
protocol = new Buffer(4)
protocol.writeUInt32LE(protoProtocol, 0)
r_string = new Buffer(crypto.randomBytes(18)).toString('base64')
@rawSocket.user = host["user"]
@rawSocket.password = host["PI:PASSWORD:<PASSWORD>END_PI"]
# Default to admin user with no password if none is given.
if @rawSocket.user is undefined
@rawSocket.user = "admin"
if @rawSocket.password is undefined
@rawSocket.password = ""
client_first_message_bare = "n=" + @rawSocket.user + ",r=" + r_string
message = JSON.stringify({
protocol_version: protoVersionNumber,
authentication_method: "SCRAM-SHA-256",
authentication: "n,," + client_first_message_bare})
nullbyte = new Buffer('\0', "binary")
@rawSocket.write Buffer.concat([version, Buffer(message.toString()), nullbyte])
# Now we have to wait for a response from the server
# acknowledging the new connection. The following callback
# will be invoked when the server sends the first few
# bytes over the socket.
state = 1
min = 0
max = 0
server_first_message = ""
server_signature = ""
auth_r = ""
auth_salt = ""
auth_i = 0
xor_bytes = (a, b) ->
res = []
len = Math.min(a.length, b.length)
for i in [0...len]
res.push(a[i] ^ b[i])
return new Buffer(res)
# We implement this ourselves because early versions of node will ignore the "sha256" option
# and just return the hash for sha1.
pbkdf2_hmac = (password, salt, iterations) =>
cache_string = password.toString("base64") + "," + salt.toString("base64") + "," + iterations.toString()
if pbkdf2_cache[cache_string]
return pbkdf2_cache[cache_string]
mac = crypto.createHmac("sha256", password)
mac.update(salt)
mac.update("\x00\x00\x00\x01")
u = mac.digest()
t = u
for c in [0...iterations-1]
mac = crypto.createHmac("sha256", password)
mac.update(t)
t = mac.digest()
u = xor_bytes(u, t)
pbkdf2_cache[cache_string] = u
return u
# a, b should be strings
compare_digest = (a, b) ->
left = undefined
right = b
result = undefined
if a.length is b.length
left = a
result = 0
if a.length != b.length
left = b
result = 1
len = Math.min(left.length, right.length)
for i in [0...len]
result |= left[i] ^ right[i]
return result is 0
handshake_error = (code, message) =>
if 10 <= code <= 20
@emit 'error', new err.ReqlAuthError(message)
else
@emit 'error', new err.ReqlDriverError(message)
handshake_callback = (buf) =>
# Once we receive a response, extend the current
# buffer with the data from the server. The reason we
# extend it, vs. just setting it to the value of `buf`
# is that this callback may be invoked several times
# before the server response is received in full. Each
# time through we check if we've received the entire
# response, and only disable this event listener at
# that time.
@buffer = Buffer.concat([@buffer, buf])
# Next we read bytes until we get a null byte. Then we follow
# the new handshake logic to authenticate the user with the
# server.
j = 0
for b,i in @buffer
if b is 0
# Here we pull the status string out of the
# buffer and convert it into a string.
status_buf = @buffer.slice(j, i)
j = i+1
status_str = status_buf.toString()
# Get the reply from the server, and parse it as JSON
try
server_reply = JSON.parse(status_str)
catch json_error
throw new err.ReqlDriverError(status_str)
if state is 1
if not server_reply.success
handshake_error(server_reply.error_code, server_reply.error)
return
min = server_reply.min_protocol_version
max = server_reply.max_protocol_version
if min > protoVersionNumber or max < protoVersionNumber
# We don't actually support changing the protocol yet, so just error.
throw new err.ReqlDriverError(
"""Unsupported protocol version #{protoVersionNumber}, \
expected between #{min} and #{max}.""")
state = 2
else if state is 2
if not server_reply.success
handshake_error(server_reply.error_code, server_reply.error)
return
authentication = {}
server_first_message = server_reply.authentication
for item in server_first_message.split(",")
i = item.indexOf("=")
authentication[item.slice(0, i)] = item.slice(i+1)
auth_r = authentication.r
auth_salt = new Buffer(authentication.s, 'base64')
auth_i = parseInt(authentication.i)
if not (auth_r.substr(0, r_string.length) == r_string)
throw new err.ReqlAuthError("Invalid nonce from server")
client_final_message_without_proof = "c=biws,r=" + auth_r
salted_password = pbPI:PASSWORD:<PASSWORD>END_PI2_hmac(@rawSocket.password, auth_salt, auth_i)
client_key = crypto.createHmac("sha256", salted_password).update("Client Key").digest()
stored_key = crypto.createHash("sha256").update(client_key).digest()
auth_message =
client_first_message_bare + "," +
server_first_message + "," +
client_final_message_without_proof
client_signature = crypto.createHmac("sha256", stored_key).update(auth_message).digest()
client_proof = xor_bytes(client_key, client_signature)
server_key = crypto.createHmac("shaPI:KEY:<KEY>END_PI", salted_password).update("Server Key").digest()
server_signature = crypto.createHmac("sha256", server_key).update(auth_message).digest()
state = 3
message = JSON.stringify({authentication: client_final_message_without_proof + ",p=" + client_proof.toString("base64")})
nullbyte = new Buffer('\0', "binary")
@rawSocket.write Buffer.concat([Buffer(message.toString()), nullbyte])
else if state is 3
if not server_reply.success
handshake_error(server_reply.error_code, server_reply.error)
return
first_equals = server_reply.authentication.indexOf('=')
v = server_reply.authentication.slice(first_equals+1)
if not compare_digest(v, server_signature.toString("base64"))
throw new err.ReqlAuthError("Invalid server signature")
state = 4
@rawSocket.removeListener('data', handshake_callback)
@rawSocket.on 'data', (buf) => @_data(buf)
# We also want to cancel the timeout error
# callback that we set earlier. Even though we
# haven't checked `status_str` yet, we've
# gotten a response so it isn't a timeout.
clearTimeout(timeout)
# Notify listeners we've connected
# successfully. Notably, the Connection
# constructor registers a listener for the
# `"connect"` event that sets the `@open`
# flag on the connection and invokes the
# callback passed to the `r.connect`
# function.
@emit 'connect'
else
throw new err.ReqlDriverError("Unexpected handshake state")
# We may have more messages if we're in the middle of the handshake,
# so we have to update the buffer.
@buffer = @buffer.slice(j + 1)
# This is the end of the handshake callback.
# Register the handshake callback on the socket. Once the
# handshake completes, it will unregister itself and
# register `_data` on the socket for `"data"` events.
@rawSocket.on 'data', handshake_callback
# In case the socket encounters an error, we re-emit the error
# ourselves. The Connection superclass constructor will invoke
# the user's `r.connect` callback with the appropriate error
# object.
@rawSocket.on 'error', (err) => @emit 'error', err
# Upon closing the `@rawSocket` for any reason, we close this
# connection. Passing `noreplyWait: false` ensures that we
# won't try to emit anything else on the socket.
@rawSocket.on 'close', =>
if @isOpen()
@close({noreplyWait: false})
@emit 'close'
# We re-raise the `timeout` event. Node says the socket must
# be closed by the user though. We should do that rather than
# just set the `@open` flag to `false`
@rawSocket.on 'timeout', => @open = false; @emit 'timeout'
clientPort: -> @rawSocket.localPort
clientAddress: -> @rawSocket.localAddress
# #### TcpConnection close method
#
# This is a public method for closing the current connection. It
# performs the raw socket related cleanup, and delegates the work
# of setting `@open` etc to the Connection superclass's
# implementation of `.close`
close: (varar 0, 2, (optsOrCallback, callback) ->
# Here we handle different ways of calling `.close`
if callback?
# This is when calling close like `.close({..}, function(..) {})`
opts = optsOrCallback
cb = callback
else if Object::toString.call(optsOrCallback) is '[object Object]'
# This is when calling close like `.close({..})`
opts = optsOrCallback
cb = null
else if typeof optsOrCallback is "function"
# This is when calling close like `.close(function(..){..})`
opts = {}
cb = optsOrCallback
else
# And the default is when calling like `.close()`
opts = {}
# Finally, we create the promise for this function. It closes
# the socket and invokes the superclass to clean up everything
# else, then invokes the user's callback to this function.
#
# In order:
#
# 1. The promise is initialized, with `resolve` and `reject` passed
# to the anonymous promise callback immediately.
# 2. The anonymous promise callback calls the superclass's
# `close` method on this connection, with the `opts` that
# were passed to this function. The only option `close`
# accepts is `noreplyWait`
# 3. The superclass's close method sets `@open` to false, and
# also closes all cursors, feeds, and callbacks that are
# currently outstanding.
# 4. Depending on whether `opts.noreplyWait` is true, the
# superclass's `close` may immediately invoke `wrappedCb`,
# or it may defer it until all outstanding `noreply`
# queries are completed.
# 5. When `wrappedCb` is invoked, it calls `.end()` on the raw
# socket for this connection, telling Node we'd like the
# tcp connection to be closed.
# 6. The socket will raise the `"close"` event when it's done
# closing, and at that time the promise here will be
# resolved or rejected.
# 7. If the promise was resolved, the callback provided to
# this function (`cb`) will be run (it's chained to the
# promise).
new Promise( (resolve, reject) =>
wrappedCb = (error, result) =>
closeCb = =>
if error?
reject error
else
resolve result
cleanupSocket = =>
# Resolve the promise, invoke all callbacks, then
# destroy remaining listeners and remove our
# reference to the socket.
closeCb()
@rawSocket?.removeAllListeners()
@rawSocket = null
@emit("close")
if @rawSocket?
if @rawSocket.readyState == 'closed'
# Socket is already closed for some reason,
# just clean up
cleanupSocket()
else
# Otherwise, wait until we get the close event
@rawSocket?.once("close", cleanupSocket)
@rawSocket.end()
else
# If the rawSocket is already closed, there's no
# reason to wait for a 'close' event that will
# never come. However we still need to fulfill the
# promise interface, so we do the next best thing
# and resolve it on the next event loop tick.
process.nextTick(closeCb)
TcpConnection.__super__.close.call(@, opts, wrappedCb)
).nodeify cb
)
# #### TcpConnection close method
#
# This method is called by the superclass in the `.close`
# method. It simply closes the socket completely and calls the
# superclass's `cancel`. The superclass's cancel closes all
# outstanding cursors and feeds, and invokes all outstanding query
# callbacks with an error.
#
# Despite not starting with an underscore, this is not a public
# method.
cancel: () ->
@rawSocket.destroy()
super()
# #### TcpConnection _writeQuery method
#
# This method emits a query's token on the socket, then invokes
# `.write` which emits the body of the query.
_writeQuery: (token, data) ->
tokenBuf = new Buffer(8)
# We write the token in two 4-byte chunks: least significant
# bytes first, then most significant bytes. (This is the same
# order as little endian 8 bytes would be). The `_data` method
# in the `Connection` class extracts the token from server
# responses by reversing this process.
#
# The key here is to write the token in a consistent way (so
# responses can be paired with outstanding requests), and to
# ensure the number isn't interpreted as a negative number by
# the server. The server doesn't actually care if the numbers
# are sequential.
tokenBuf.writeUInt32LE(token & 0xFFFFFFFF, 0)
tokenBuf.writeUInt32LE(Math.floor(token / 0xFFFFFFFF), 4)
# Write out the token to the socket, then invoke `.write` to
# write the data to the socket.
@rawSocket.write tokenBuf
@write new Buffer(data)
# #### TcpConnection write method
#
# This method is called by `_writeQuery` and just writes the body
# of a query to the socket.
#
# Despite not starting with an underscore, it is not a public
# method.
write: (chunk) ->
# Before writing the data, we need to write the length of the
# data as an unsigned little-endian 4 byte integer.
lengthBuffer = new Buffer(4)
lengthBuffer.writeUInt32LE(chunk.length, 0)
@rawSocket.write lengthBuffer
# Finally we write the data to the socket. It is serialized
# from json to a string in the `Connection` class's
# `_sendQuery` method.
@rawSocket.write chunk
# ### HttpConnection class
#
# This class is used to run queries from the webui to the RethinkDB
# internal http server using XHR. It's not intended for general usage
# in applications.
class HttpConnection extends Connection
# We defined the default protocol in case the user doesn't specify
# one.
DEFAULT_PROTOCOL: 'http'
# A static method used by `r.connect` to decide which kind of
# connection to create in a given environment. Here we check if
# XHRs are defined. If not, we aren't in the browser and shouldn't
# be using `HttpConnection`
@isAvailable: -> typeof XMLHttpRequest isnt "undefined"
# #### HttpConnection constructor method
#
# This method sets up the XMLHttpRequest object that all
# requests/responses will be sent and received on. Unlike the
# TcpConnection, the HTTP server only allows one outstanding query
# at a time per connection. Because of this, currently the web ui
# creates many different connections.
#
# The state of an HTTP connection is actually stored on the
# server, and they automatically time out after 5 minutes. The way
# it works is we send a POST request to:
# `/ajax/reql/open-new-connection`, which gets us a connection
# id. The browser can also explicitly destroy server connections
# with the `/ajax/reql/close-connection?conn_id=` url.
#
# Ultimately, the server keeps track of the connections because
# it needs to give the client a way to fetch more results from
# cursors and feeds.
constructor: (host, callback) ->
# A quick check to ensure we can create an `HttpConnection`
unless HttpConnection.isAvailable()
throw new err.ReqlDriverError "XMLHttpRequest is not available in this environment"
# Call the superclass constructor. This initializes the
# attributes `@host`, `@port`, `@db`, `@authKey`, `@timeout`,
# `@outstandingCallbacks`, `@nextToken`, `@open`, `@closing`,
# and `@buffer`. It also registers the callback to be invoked
# once the `"connect"` event is emitted.
super(host, callback)
# A protocol may be supplied in the host object. If the host
# doesn't have a protocol key, (or is a string, which it's
# also allowed to be), then use the default protocol, which is
# 'http'
protocol = if host.protocol is 'https' then 'https' else @DEFAULT_PROTOCOL
# Next we construct an XHR with the path to the reql query
# endpoint on the http server.
url = "#{protocol}://#{@host}:#{@port}#{host.pathname}ajax/reql/"
xhr = new XMLHttpRequest
#The request is a `POST` to ensure the response isn't cached
# by the browser (which has caused bugs in the past). The
# `true` argument is setting the request to be asynchronous.
# Some browsers cache this request no matter what cache
# control headers are set on the request or the server's
# response. So the `cacheBuster` argument ensures every time
# we create a connection it's a unique url, and we really do
# create a new connection on the server.
xhr.open("POST", url+"open-new-connection?cacheBuster=#{Math.random()}", true)
# We response will be a connection ID, which we receive as text.
xhr.responseType = "text"
# Next, set up the callback to process the response from the
# server when the new connection is established.
xhr.onreadystatechange = (e) =>
# readyState 4 is "DONE", the data has been completely received.
if xhr.readyState is 4
# The status is 200 if we get a successful response
if xhr.status is 200
# Now we finally store the `@_url` variable. No
# particular reason for not doing this sooner
# since the url doesn't change.
@_url = url
# Keep the connection ID we received.
@_connId = xhr.response
# Emit the `"connect"` event. The `Connection`
# superclass's constructor listens for this event
# to set the `@open` flag to `true` and invoke its
# callback (which is callback passed to this
# method)
@emit 'connect'
else
# In case we get anything other than a 200, raise an error.
@emit 'error', new err.ReqlDriverError "XHR error, http status #{xhr.status}."
# Send the xhr, and store it in the instance for later.
xhr.send()
@xhr = xhr
# #### HttpConnection cancel method
#
# This sends a POST to the `close-connection` endpoint, so the
# server can deallocate resources related to the connection. This
# throws out any data for unconsumed cursors etc and invalidates
# this connection id.
cancel: ->
# Check if the connection id is still open. `@connId` is null
# if the connection was previously closed or cancelled
if @_connId?
# Since only one request can happen at a time, we need to
# abort any in-progress xhr request before sending a new
# request to close the connection.
@xhr.abort()
xhr = new XMLHttpRequest
# This sends the close connection request asynchronously.
xhr.open("POST", "#{@_url}close-connection?conn_id=#{@_connId}", true)
# We ignore the result, but Firefox doesn't. Without this line it complains
# about "No element found" when trying to parse the response as xml.
xhr.responseType = "arraybuffer"
xhr.send()
# Null out @conn_Id so we know not to send another
# close request to the server later.
@_url = null
@_connId = null
# This will end any outstanding cursors and feeds, though
# there should be at most one since we don't support
# multiple queries at once on http connections.
super()
# #### HttpConnection close method
#
# Closes the http connection. Does nothing new or special beyond
# what the superclass already does. The server connection is
# closed in `cancel` above, which the superclass calls for us.
close: (varar 0, 2, (optsOrCallback, callback) ->
if callback?
opts = optsOrCallback
cb = callback
else if Object::toString.call(optsOrCallback) is '[object Object]'
opts = optsOrCallback
cb = null
else
opts = {}
cb = optsOrCallback
unless not cb? or typeof cb is 'function'
throw new err.ReqlDriverError "Final argument to `close` must be a callback function or object."
# This would simply be `super(opts, wrappedCb)`, if we were
# not in the varar anonymous function
HttpConnection.__super__.close.call(this, opts, cb)
)
# #### HttpConnection _writeQuery method
#
# This creates the buffer to send to the server, writes the token
# and data to it, then passes the data and buffer down to `write`
# to write the data itself to the xhr request.
#
# This differs from `TcpConnection`'s version of `_writeQuery`
# which only writes the token.
_writeQuery: (token, data) ->
# We use encodeURI to get the length of the unicode
# representation of the data.
buf = new Buffer(encodeURI(data).split(/%..|./).length - 1 + 8)
# Again, the token is encoded as a little-endian 8 byte
# unsigned integer.
buf.writeUInt32LE(token & 0xFFFFFFFF, 0)
buf.writeUInt32LE(Math.floor(token / 0xFFFFFFFF), 4)
# Write the data out to the bufferm then invoke `write` with
# the buffer and token
buf.write(data, 8)
@write buf, token
# #### HttpConnection write method
#
# This method takes a Node Buffer (or more accurately, the Buffer
# class that Browserify polyfills for us) and turns it into an
# ArrayBufferView, then sends it over the XHR with the current
# connection id.
#
# Despite not starting with an underscore, this is not a public
# method.
write: (chunk, token) ->
# Create a new XHR with to run the query over.
xhr = new XMLHttpRequest
xhr.open("POST", "#{@_url}?conn_id=#{@_connId}", true)
xhr.responseType = "arraybuffer"
xhr.onreadystatechange = (e) =>
# When the server responds, the state must be 4 ("DONE"),
# and the HTTP status code should be success. Otherwise we
# just do nothing. There's a separate callback if the XHR
# encounters an error.
if xhr.readyState is 4 and xhr.status is 200
# Convert the response from a browser ArrayBuffer into
# a Node buffer
buf = new Buffer(b for b in (new Uint8Array(xhr.response)))
# The data method is defined in the `Connection` class
# and reads and parses the response from the server.
@_data(buf)
# On error we want to invoke the callback for this query with
# an error.
xhr.onerror = (e) =>
@outstandingCallbacks[token].cb(new Error("This HTTP connection is not open"))
# To serialize the query (held in chunk) for the XHR, we need
# to convert it from a node buffer into an `ArrayBufferView`
# (specifically `Uint8Array`), since passing an `ArrayBuffer`
# in xhr.send is deprecated
view = new Uint8Array(chunk.length)
i = 0
while i < chunk.length
view[i] = chunk[i]
i++
# And send it on its way to the server
xhr.send view
@xhr = xhr
# ## isConnection
#
# This is an exported function that determines whether something is a
# Connection. It's used by the [ast module](ast.html) to validate the
# first argument passed to `.run` (which must always be a connection).
module.exports.isConnection = (connection) ->
return connection instanceof Connection
# ## connect
#
# The main function of this module, which is exposed to end users as
# `r.connect`. See the [API
# docs](http://rethinkdb.com/api/javascript/connect/).
module.exports.connect = varar 0, 2, (hostOrCallback, callback) ->
if typeof hostOrCallback is 'function'
# This occurs when called like `r.connect(function(..){..})`
# Override the callback variable (which should be undefined)
# and set host to an empty object
host = {}
callback = hostOrCallback
else
# Otherwise, the `callback` variable is already correctly
# holding the callback, and the host variable is the first
# argument
host = hostOrCallback || {}
# `r.connect` returns a Promise which does the following:
#
# 1. Determines whether to create a `TcpConnection` or an
# `HttpConnection` depending on whether we're running on Node
# or in the browser.
# 2. Initializes the connection, and when it's complete invokes
# the user's callback
new Promise( (resolve, reject) ->
if host.authKey? && (host.password? || host.user? || host.username?)
throw new err.ReqlDriverError "Cannot use both authKey and password"
if host.user && host.username
throw new err.ReqlDriverError "Cannot use both user and username"
else if host.authKey
host.user = "admin"
host.password = host.authKey
else
# Fixing mismatch between drivers
if host.username?
host.user = host.username
create_connection = (host, callback) =>
if TcpConnection.isAvailable()
new TcpConnection host, callback
else if HttpConnection.isAvailable()
new HttpConnection host, callback
else
throw new err.ReqlDriverError "Neither TCP nor HTTP avaiable in this environment"
wrappedCb = (err, result) ->
if (err)
reject(err)
else
resolve(result)
create_connection(host, wrappedCb)
).nodeify callback
# Exposing the connection classes
module.exports.Connection = Connection
module.exports.HttpConnection = HttpConnection
module.exports.TcpConnection = TcpConnection
|
[
{
"context": "scriptions: null\n flows: []\n flow: null\n key: \"activate-power-mode.flow\"\n\n enable: ->\n @subscriptions = new Composite",
"end": 136,
"score": 0.9697783589363098,
"start": 112,
"tag": "KEY",
"value": "activate-power-mode.flow"
}
] | lib/flow-registry.coffee | kyl3r92/activate-power-mode | 4,172 | {CompositeDisposable} = require "atom"
module.exports =
subscriptions: null
flows: []
flow: null
key: "activate-power-mode.flow"
enable: ->
@subscriptions = new CompositeDisposable
@observeFlow()
@initList()
disable: ->
@subscriptions?.dispose()
@flowList?.dispose()
@flowList = null
setDefaultFlow: (flow) ->
@flow = flow
@flows['default'] = flow
addFlow: (code, flow) ->
@flows[code] = flow
if atom.config.get(@key) is code
@flow = flow
removeFlow: (code) ->
if atom.config.get(@key) is code
@flow = @flows['default']
delete @flows[code]
observeFlow: ->
@subscriptions.add atom.config.observe(
@key, (code) =>
if @flows[code]?
@flow = @flows[code]
else
@flow = @flows['default']
)
selectFlow: (code) ->
atom.config.set(@key, code)
initList: ->
return if @flowList?
@flowList = require "./flow-list"
@flowList.init this
@subscriptions.add atom.commands.add "atom-workspace",
"activate-power-mode:select-flow": =>
@flowList.toggle()
| 67579 | {CompositeDisposable} = require "atom"
module.exports =
subscriptions: null
flows: []
flow: null
key: "<KEY>"
enable: ->
@subscriptions = new CompositeDisposable
@observeFlow()
@initList()
disable: ->
@subscriptions?.dispose()
@flowList?.dispose()
@flowList = null
setDefaultFlow: (flow) ->
@flow = flow
@flows['default'] = flow
addFlow: (code, flow) ->
@flows[code] = flow
if atom.config.get(@key) is code
@flow = flow
removeFlow: (code) ->
if atom.config.get(@key) is code
@flow = @flows['default']
delete @flows[code]
observeFlow: ->
@subscriptions.add atom.config.observe(
@key, (code) =>
if @flows[code]?
@flow = @flows[code]
else
@flow = @flows['default']
)
selectFlow: (code) ->
atom.config.set(@key, code)
initList: ->
return if @flowList?
@flowList = require "./flow-list"
@flowList.init this
@subscriptions.add atom.commands.add "atom-workspace",
"activate-power-mode:select-flow": =>
@flowList.toggle()
| true | {CompositeDisposable} = require "atom"
module.exports =
subscriptions: null
flows: []
flow: null
key: "PI:KEY:<KEY>END_PI"
enable: ->
@subscriptions = new CompositeDisposable
@observeFlow()
@initList()
disable: ->
@subscriptions?.dispose()
@flowList?.dispose()
@flowList = null
setDefaultFlow: (flow) ->
@flow = flow
@flows['default'] = flow
addFlow: (code, flow) ->
@flows[code] = flow
if atom.config.get(@key) is code
@flow = flow
removeFlow: (code) ->
if atom.config.get(@key) is code
@flow = @flows['default']
delete @flows[code]
observeFlow: ->
@subscriptions.add atom.config.observe(
@key, (code) =>
if @flows[code]?
@flow = @flows[code]
else
@flow = @flows['default']
)
selectFlow: (code) ->
atom.config.set(@key, code)
initList: ->
return if @flowList?
@flowList = require "./flow-list"
@flowList.init this
@subscriptions.add atom.commands.add "atom-workspace",
"activate-power-mode:select-flow": =>
@flowList.toggle()
|
[
{
"context": "e17f6f?imageView2/2/w/200\"\n initialRoomName = \"夏力维和他的朋友们\"\n isLoadingMore = false\n base_rooms =",
"end": 5671,
"score": 0.6867448091506958,
"start": 5668,
"tag": "NAME",
"value": "夏力维"
},
{
"context": " if user_id == USER_ID\n msg_owner = \"wx... | index.coffee | hotpoor-for-Liwei/bangfer-web-chatroom | 0 | $ ->
$("#hotpoor_shares_qrcode_weixin_area").remove()
$("#hotpoor_shares").css
"position":"relative"
"paddingBottom":"0px"
"height":"100%"
$("#hotpoor_shares").append """
<style>
.comments_area{
width:100%;
height:calc(100% - 44px);
overflow-y: auto;
}
.comments_area_tools{
width:100%;
height:44px;
background-color:#f2f2f2;
border-top:1px solid #d4d4d4;
position:relative;
}
.comment_content{
width: calc(100% - 82px);
border-radius: 4px;
border: 1px solid #c3c3c3;
resize: none;
position: absolute;
left: 4px;
top: 3px;
font-size: 14px;
padding: 4px;
height: 26px;
}
.comment_submit{
width: 60px;
height: 32px;
font-size: 15px;
color: #999999;
border-radius: 7px;
border: 1px solid #c3c3c3;
background-color: #f2f2f2;
position: absolute;
right: 4px;
top: 5px;
padding-left: 2px;
padding-right: 2px;
}
.wxmsg{
width:100%;
padding:5px 0px 10px 0px;
}
.wxmsg_time{
margin: 2px;
}
.wxmsg_time>div{
background-color:rgba(0,0,0,0.2);
border-radius:4px;
color:white;
font-size:12px;
padding:1px 5px;
width: fit-content;
width: -moz-fit-content;
width: -webkit-fit-content;
}
.wxmsg_head_area{
width:100%;
position:relative;
}
.wxmsg_headimg{
position:absolute;
}
.wxmsg_headimg.wxmsg_self{
right:5px;
}
.wxmsg_headimg.wxmsg_other{
left:5px;
}
.wxmsg_headimg>img{
width: 36px;
height: 36px;
background-color: rgba(255,255,255,0.8);
box-shadow: 0px 0px 2px rgba(0,0,0,0.05);
}
.wxmsg_nickname{
font-size:14px;
color:#999;
font-weight:500;
}
.wxmsg_nickname.wxmsg_self{
text-align:right;
padding-right:50px;
}
.wxmsg_nickname.wxmsg_other{
text-align:left;
padding-left:50px;
}
.wxmsg_content{
text-align:left;
word-break: break-word;
background-color: white;
padding: 9px;
font-size: 14px;
line-height: 18px;
border-radius: 5px;
box-shadow: 0px 0px 2px rgba(0,0,0,0.2);
position: relative;
width: fit-content;
width: -moz-fit-content;
width: -webkit-fit-content;
min-width:15px;
max-width:500px;
}
.wxmsg_content.wxmsg_self{
margin-right: 50px;
margin-left: 60px;
}
.wxmsg_content.wxmsg_self:before {
content: " ";
width: 9px;
height: 9px;
background-color: white;
position: absolute;
right: -4px;
top: 13px;
box-shadow: 1px 1px 1px rgba(0,0,0,0.1);
transform: rotate(-45deg);
}
.wxmsg_content.wxmsg_other{
margin-left: 50px;
margin-right: 60px;
}
.wxmsg_content.wxmsg_other:before {
content: " ";
width: 9px;
height: 9px;
background-color: white;
position: absolute;
left: -4px;
top: 13px;
box-shadow: -1px 1px 1px rgba(0,0,0,0.1);
transform: rotate(45deg);
}
.wxmsg_content_hqwebimg,.wxmsg_content_hwebimg{
max-width:100%;
min-width:10px;
max-height:200px;
}
.wxmsg_load_tip{
text-align:center;
color:#999;
font-size:14px;
padding:5px;
}
.wxmsg_face_img{
width:60px;
height:auto;
}
.wxmsg_content.wxmsg_other.wxmsg_face{
box-shadow:none;
background-color:unset;
margin-left: 50px;
margin-right: 60px;
}
.wxmsg_content.wxmsg_self.wxmsg_face{
box-shadow:none;
background-color:unset;
margin-right: 50px;
margin-left: 60px;
}
.wxmsg_content.wxmsg_self.wxmsg_face:before,.wxmsg_content.wxmsg_other.wxmsg_face:before{
display:none;
}
</style>
"""
$("#hotpoor_shares").append """
<div class="comments_area">
</div>
<div class="comments_area_tools">
<textarea class="comment_content"></textarea><button class="comment_submit">发送</button>
</div>
"""
$("#hotpoor_shares").on "touchstart",".comments_area",(e)->
el_now = this
scrollTop = el_now.scrollTop
if scrollTop==0
el_now.scrollTop = 1
if el_now.scrollTop+el_now.offsetHeight==el_now.scrollHeight
el_now.scrollTop = (parseInt(el_now.scrollHeight)-parseInt(el_now.offsetHeight)-1)
targetRoomId = null
initialRoomId = "0cd8429c1da249b6935d7eef72d7fc0b"
initialRoomImg = "http://image.hotpoor.org/2dd2c53e7c654c66b398e574848d4c34_08aed20957caca43b0df23442de17f6f?imageView2/2/w/200"
initialRoomName = "夏力维和他的朋友们"
isLoadingMore = false
base_rooms = [
[
initialRoomId
initialRoomImg
initialRoomName
]
]
rooms_info = {}
for base_room in base_rooms
roomId = base_room[0]
imgUrl = base_room[1]
roomName = base_room[2]
time_now = (new Date()).getTime() / 1000
rooms_info[roomId] =
"imgUrl": imgUrl
"roomName": roomName
"createtime": time_now
"finishtime": null
"room_time_flag": time_now
"createuser":null
"finishuser":null
"createcommentsequence":null
"finishcommentsequence":null
"latestComment": null
"last_comment_id": null
"roomNewMsgCount": 0
"roomImages":[]
members_json = {}
load_start = ()->
$(".comments_area").empty()
$(".comments_area").attr("data-room-id",roomId)
$(".comments_area").on "scroll",(e)->
onRoomScroll(e)
$.ajax
url: 'http://www.hotpoor.org/api/comment/load'
type: 'POST'
dataType: 'json'
data:
app: 'bangfer'
aim_id: roomId
comment_id: rooms_info[roomId].last_comment_id
success: (data)->
console.log data
if data.info == "ok"
rooms_info[roomId].last_comment_id = data.last_comment_id
members_json_now = members_json
members_json_new = data.members
members_json = $.extend({}, members_json_now,members_json_new)
comments = data.comments
for comment in comments by -1
_msg = [comment[3],{
"content": comment[4],
"nickname": members_json[comment[1]].nickname,
"headimgurl": members_json[comment[1]].headimgurl,
"time": comment[2],
"user_id": comment[1],
"tel": members_json[comment[1]].tel,
"plus": comment[5],
"sequence": comment[0],
"comment_id": data.comment_id,
},roomId]
console.log _msg
loadMessage(_msg)
if not rooms_info[roomId]["latestComment"]?
rooms_info[roomId]["latestComment"] = _msg
item_text = ""
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].finishcommentsequence}]")[0].scrollIntoView(false)
error: (error)->
console.log(error)
$("body").on "click","#bangfer_shares",(evt)->
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].finishcommentsequence}]")[0].scrollIntoView(false)
$("body").on "click",".wxmsg_content_hqwebimg,.wxmsg_content_hwebimg",(evt)->
wx.previewImage
current: $(this).attr("data-uri"), #当前显示图片的http链接
urls: rooms_info[roomId].roomImages #需要预览的图片http链接列表
loadMessage = (msg)->
msgType = msg[0]
roomId = msg[2]
content = msg[1].content
content = escapeHTML(content)
content = content.replace(/\n/g, '<br>')
headimg = msg[1].headimgurl
nickname = msg[1].nickname
timer = msg[1].time
time = formatDate(timer)
user_id = msg[1].user_id
tel = msg[1].tel
plus = msg[1].plus
plus_content = escapeHTML(plus.content)
plus_type = escapeHTML(plus.type)
if not plus.destination?
plus_content_destination = ""
else
plus_content_destination = escapeHTML(plus.destination)
if plus_type == "百度语音转文字"
plus_content = plus_content.split("百度语音转文字: ")[1]
if plus_content_destination.split("百度语音翻译: ").length==2
plus_content_destination = plus_content_destination.split("百度语音翻译: ")[1]
comment_id = msg[1].comment_id
comment_sequence = msg[1].sequence
content_type = content.split("//")[0]
content_values = content.split("//")[1]
if user_id == USER_ID
msg_owner = "wxmsg_self"
msg_html_align = "right"
else
msg_owner = "wxmsg_other"
msg_html_align = "left"
console.log "#{rooms_info[roomId].createtime} - #{timer} = "+(rooms_info[roomId].createtime - timer)
msg_time_hide = ""
if rooms_info[roomId].createtime - timer < 300
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].createcommentsequence}]>.wxmsg_time").hide()
rooms_info[roomId].createtime = timer
rooms_info[roomId].createuser = user_id
rooms_info[roomId].createcommentsequence = comment_id+"_"+comment_sequence
if not rooms_info[roomId].finishtime?
rooms_info[roomId].finishtime = timer
if not rooms_info[roomId].finishcommentsequence?
rooms_info[roomId].finishcommentsequence = comment_id+"_"+comment_sequence
msg_headimg_hide = ""
msg_nickname_hide = ""
error_img = "http://www.hotpoor.org/static/img/tools/error_img_"+parseInt(Math.random()*10%2)+".png"
content_html = "#{content}"
if msgType == "COMMENT"
content_values = content.split(content_type+"//")[1]
if content_type == "HQWEBIMG"
img_uri = "http://image.hotpoor.org/#{roomId}_#{content_values}?imageView2"
rooms_info[roomId].roomImages.unshift(img_uri)
content_html = """
<img crossorigin="Anonymous" class="wxmsg_content_hqwebimg" data-uri="#{img_uri}" src="http://image.hotpoor.org/#{roomId}_#{content_values}?imageView2/2/w/320" onerror="this.src='#{error_img}'">
"""
else if content_type == "HWEBIMG"
img_uri = decodeURIComponent(content_values)
rooms_info[roomId].roomImages.unshift(img_uri)
content_html = """
<img crossorigin="Anonymous" class="wxmsg_content_hwebimg" data-uri="#{img_uri}" src="#{content_values}" onerror="this.src='#{error_img}'" >
"""
else if content_type == "HWEBFACEIMG"
face_url = decodeURIComponent(content_values)
msg_owner = "#{msg_owner} wxmsg_face"
content_html = """
<img crossorigin="Anonymous" class="wxmsg_face_img" src="#{face_url}" onerror="this.src='#{error_img}'" >
"""
msg_html = """
<div class="wxmsg #{msg_owner}" data-comment-flag="#{comment_id}_#{comment_sequence}" align="#{msg_html_align}">
<div class="wxmsg_time" style="#{msg_time_hide}" align="center"><div>#{time}</div></div>
<div class="wxmsg_head_area">
<div class="wxmsg_headimg #{msg_owner}"><img src="#{headimg}"></div>
</div>
<div class="wxmsg_nickname #{msg_owner}"><span>#{nickname}</span></div>
<div class="wxmsg_content #{msg_owner}">#{content_html}</div>
</div>
"""
$('.comments_area').prepend msg_html
loadHistory = (currentRoomId)->
isLoadingMore = true
$('.comments_area').prepend """
<div class="wxmsg_load_tip">加载中...</div>
"""
$.ajax
url: 'http://www.hotpoor.org/api/comment/load'
type: 'POST'
dataType: 'json'
data:
app: 'bangfer'
aim_id: currentRoomId
comment_id: rooms_info[currentRoomId].last_comment_id
success: (data)->
console.log data
if data.info == "ok"
rooms_info[currentRoomId].last_comment_id = data.last_comment_id
members_json_now = members_json
members_json_new = data.members
members_json = $.extend({}, members_json_now,members_json_new)
comments = data.comments
commentsequence_flag = null
for comment in comments by -1
_msg = [comment[3],{
"content": comment[4],
"nickname": members_json[comment[1]].nickname,
"headimgurl": members_json[comment[1]].headimgurl,
"time": comment[2],
"user_id": comment[1],
"tel": members_json[comment[1]].tel,
"plus": comment[5],
"sequence": comment[0],
"comment_id": data.comment_id,
},roomId]
console.log _msg
loadMessage(_msg)
if not rooms_info[currentRoomId]["latestComment"]?
rooms_info[currentRoomId]["latestComment"] = _msg
item_text = ""
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].finishcommentsequence}]")[0].scrollIntoView(false)
if not commentsequence_flag?
commentsequence_flag = "#{data.comment_id}_#{comment[0]}"
console.log $(".wxmsg[data-comment-flag=#{commentsequence_flag}]")[0]
scrollIntoElement(roomId,$(".wxmsg[data-comment-flag=#{commentsequence_flag}]")[0])
$(".wxmsg_load_tip").text("加载成功!")
setTimeout ()->
$(".wxmsg_load_tip").remove()
isLoadingMore = false
, 1000
error: (error)->
console.log(error)
scrollIntoElement = (currentRoomId,el) ->
roomEl = $(".comments_area")
if not typeof(el)?
roomEl.stop().animate ()->
"scrollTop":el.offseTop
onRoomScroll = (evt)->
cu_el = $(evt.currentTarget)
cu_roomId = cu_el.data("room-id")
cu_scrollTop = cu_el.scrollTop()
if cu_scrollTop <5 and !isLoadingMore
if rooms_info[cu_roomId].last_comment_id?
loadHistory(cu_roomId)
formatDate = (now)->
now_date = new Date(now * 1000)
comment_time_now = new Date
year = now_date.getFullYear()
month = now_date.getMonth() + 1
date = now_date.getDate()
hour = now_date.getHours()
minute = now_date.getMinutes()
if hour < 10
hour = "0" + hour
if minute < 10
minute = "0" + minute
if comment_time_now.getFullYear() == year and comment_time_now.getMonth() + 1 == month and comment_time_now.getDate() == date
return hour + ":" + minute
if comment_time_now.getFullYear() == year
return month + "月" + date + "日 " + hour + ":" + minute
return year + "年" + month + "月" + date + "日 " + hour + ":" + minute
escapeHTML = (str)->
return $('<div></div>').text(str).html()
load_start()
| 8950 | $ ->
$("#hotpoor_shares_qrcode_weixin_area").remove()
$("#hotpoor_shares").css
"position":"relative"
"paddingBottom":"0px"
"height":"100%"
$("#hotpoor_shares").append """
<style>
.comments_area{
width:100%;
height:calc(100% - 44px);
overflow-y: auto;
}
.comments_area_tools{
width:100%;
height:44px;
background-color:#f2f2f2;
border-top:1px solid #d4d4d4;
position:relative;
}
.comment_content{
width: calc(100% - 82px);
border-radius: 4px;
border: 1px solid #c3c3c3;
resize: none;
position: absolute;
left: 4px;
top: 3px;
font-size: 14px;
padding: 4px;
height: 26px;
}
.comment_submit{
width: 60px;
height: 32px;
font-size: 15px;
color: #999999;
border-radius: 7px;
border: 1px solid #c3c3c3;
background-color: #f2f2f2;
position: absolute;
right: 4px;
top: 5px;
padding-left: 2px;
padding-right: 2px;
}
.wxmsg{
width:100%;
padding:5px 0px 10px 0px;
}
.wxmsg_time{
margin: 2px;
}
.wxmsg_time>div{
background-color:rgba(0,0,0,0.2);
border-radius:4px;
color:white;
font-size:12px;
padding:1px 5px;
width: fit-content;
width: -moz-fit-content;
width: -webkit-fit-content;
}
.wxmsg_head_area{
width:100%;
position:relative;
}
.wxmsg_headimg{
position:absolute;
}
.wxmsg_headimg.wxmsg_self{
right:5px;
}
.wxmsg_headimg.wxmsg_other{
left:5px;
}
.wxmsg_headimg>img{
width: 36px;
height: 36px;
background-color: rgba(255,255,255,0.8);
box-shadow: 0px 0px 2px rgba(0,0,0,0.05);
}
.wxmsg_nickname{
font-size:14px;
color:#999;
font-weight:500;
}
.wxmsg_nickname.wxmsg_self{
text-align:right;
padding-right:50px;
}
.wxmsg_nickname.wxmsg_other{
text-align:left;
padding-left:50px;
}
.wxmsg_content{
text-align:left;
word-break: break-word;
background-color: white;
padding: 9px;
font-size: 14px;
line-height: 18px;
border-radius: 5px;
box-shadow: 0px 0px 2px rgba(0,0,0,0.2);
position: relative;
width: fit-content;
width: -moz-fit-content;
width: -webkit-fit-content;
min-width:15px;
max-width:500px;
}
.wxmsg_content.wxmsg_self{
margin-right: 50px;
margin-left: 60px;
}
.wxmsg_content.wxmsg_self:before {
content: " ";
width: 9px;
height: 9px;
background-color: white;
position: absolute;
right: -4px;
top: 13px;
box-shadow: 1px 1px 1px rgba(0,0,0,0.1);
transform: rotate(-45deg);
}
.wxmsg_content.wxmsg_other{
margin-left: 50px;
margin-right: 60px;
}
.wxmsg_content.wxmsg_other:before {
content: " ";
width: 9px;
height: 9px;
background-color: white;
position: absolute;
left: -4px;
top: 13px;
box-shadow: -1px 1px 1px rgba(0,0,0,0.1);
transform: rotate(45deg);
}
.wxmsg_content_hqwebimg,.wxmsg_content_hwebimg{
max-width:100%;
min-width:10px;
max-height:200px;
}
.wxmsg_load_tip{
text-align:center;
color:#999;
font-size:14px;
padding:5px;
}
.wxmsg_face_img{
width:60px;
height:auto;
}
.wxmsg_content.wxmsg_other.wxmsg_face{
box-shadow:none;
background-color:unset;
margin-left: 50px;
margin-right: 60px;
}
.wxmsg_content.wxmsg_self.wxmsg_face{
box-shadow:none;
background-color:unset;
margin-right: 50px;
margin-left: 60px;
}
.wxmsg_content.wxmsg_self.wxmsg_face:before,.wxmsg_content.wxmsg_other.wxmsg_face:before{
display:none;
}
</style>
"""
$("#hotpoor_shares").append """
<div class="comments_area">
</div>
<div class="comments_area_tools">
<textarea class="comment_content"></textarea><button class="comment_submit">发送</button>
</div>
"""
$("#hotpoor_shares").on "touchstart",".comments_area",(e)->
el_now = this
scrollTop = el_now.scrollTop
if scrollTop==0
el_now.scrollTop = 1
if el_now.scrollTop+el_now.offsetHeight==el_now.scrollHeight
el_now.scrollTop = (parseInt(el_now.scrollHeight)-parseInt(el_now.offsetHeight)-1)
targetRoomId = null
initialRoomId = "0cd8429c1da249b6935d7eef72d7fc0b"
initialRoomImg = "http://image.hotpoor.org/2dd2c53e7c654c66b398e574848d4c34_08aed20957caca43b0df23442de17f6f?imageView2/2/w/200"
initialRoomName = "<NAME>和他的朋友们"
isLoadingMore = false
base_rooms = [
[
initialRoomId
initialRoomImg
initialRoomName
]
]
rooms_info = {}
for base_room in base_rooms
roomId = base_room[0]
imgUrl = base_room[1]
roomName = base_room[2]
time_now = (new Date()).getTime() / 1000
rooms_info[roomId] =
"imgUrl": imgUrl
"roomName": roomName
"createtime": time_now
"finishtime": null
"room_time_flag": time_now
"createuser":null
"finishuser":null
"createcommentsequence":null
"finishcommentsequence":null
"latestComment": null
"last_comment_id": null
"roomNewMsgCount": 0
"roomImages":[]
members_json = {}
load_start = ()->
$(".comments_area").empty()
$(".comments_area").attr("data-room-id",roomId)
$(".comments_area").on "scroll",(e)->
onRoomScroll(e)
$.ajax
url: 'http://www.hotpoor.org/api/comment/load'
type: 'POST'
dataType: 'json'
data:
app: 'bangfer'
aim_id: roomId
comment_id: rooms_info[roomId].last_comment_id
success: (data)->
console.log data
if data.info == "ok"
rooms_info[roomId].last_comment_id = data.last_comment_id
members_json_now = members_json
members_json_new = data.members
members_json = $.extend({}, members_json_now,members_json_new)
comments = data.comments
for comment in comments by -1
_msg = [comment[3],{
"content": comment[4],
"nickname": members_json[comment[1]].nickname,
"headimgurl": members_json[comment[1]].headimgurl,
"time": comment[2],
"user_id": comment[1],
"tel": members_json[comment[1]].tel,
"plus": comment[5],
"sequence": comment[0],
"comment_id": data.comment_id,
},roomId]
console.log _msg
loadMessage(_msg)
if not rooms_info[roomId]["latestComment"]?
rooms_info[roomId]["latestComment"] = _msg
item_text = ""
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].finishcommentsequence}]")[0].scrollIntoView(false)
error: (error)->
console.log(error)
$("body").on "click","#bangfer_shares",(evt)->
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].finishcommentsequence}]")[0].scrollIntoView(false)
$("body").on "click",".wxmsg_content_hqwebimg,.wxmsg_content_hwebimg",(evt)->
wx.previewImage
current: $(this).attr("data-uri"), #当前显示图片的http链接
urls: rooms_info[roomId].roomImages #需要预览的图片http链接列表
loadMessage = (msg)->
msgType = msg[0]
roomId = msg[2]
content = msg[1].content
content = escapeHTML(content)
content = content.replace(/\n/g, '<br>')
headimg = msg[1].headimgurl
nickname = msg[1].nickname
timer = msg[1].time
time = formatDate(timer)
user_id = msg[1].user_id
tel = msg[1].tel
plus = msg[1].plus
plus_content = escapeHTML(plus.content)
plus_type = escapeHTML(plus.type)
if not plus.destination?
plus_content_destination = ""
else
plus_content_destination = escapeHTML(plus.destination)
if plus_type == "百度语音转文字"
plus_content = plus_content.split("百度语音转文字: ")[1]
if plus_content_destination.split("百度语音翻译: ").length==2
plus_content_destination = plus_content_destination.split("百度语音翻译: ")[1]
comment_id = msg[1].comment_id
comment_sequence = msg[1].sequence
content_type = content.split("//")[0]
content_values = content.split("//")[1]
if user_id == USER_ID
msg_owner = "wxmsg_self"
msg_html_align = "right"
else
msg_owner = "wxmsg_other"
msg_html_align = "left"
console.log "#{rooms_info[roomId].createtime} - #{timer} = "+(rooms_info[roomId].createtime - timer)
msg_time_hide = ""
if rooms_info[roomId].createtime - timer < 300
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].createcommentsequence}]>.wxmsg_time").hide()
rooms_info[roomId].createtime = timer
rooms_info[roomId].createuser = user_id
rooms_info[roomId].createcommentsequence = comment_id+"_"+comment_sequence
if not rooms_info[roomId].finishtime?
rooms_info[roomId].finishtime = timer
if not rooms_info[roomId].finishcommentsequence?
rooms_info[roomId].finishcommentsequence = comment_id+"_"+comment_sequence
msg_headimg_hide = ""
msg_nickname_hide = ""
error_img = "http://www.hotpoor.org/static/img/tools/error_img_"+parseInt(Math.random()*10%2)+".png"
content_html = "#{content}"
if msgType == "COMMENT"
content_values = content.split(content_type+"//")[1]
if content_type == "HQWEBIMG"
img_uri = "http://image.hotpoor.org/#{roomId}_#{content_values}?imageView2"
rooms_info[roomId].roomImages.unshift(img_uri)
content_html = """
<img crossorigin="Anonymous" class="wxmsg_content_hqwebimg" data-uri="#{img_uri}" src="http://image.hotpoor.org/#{roomId}_#{content_values}?imageView2/2/w/320" onerror="this.src='#{error_img}'">
"""
else if content_type == "HWEBIMG"
img_uri = decodeURIComponent(content_values)
rooms_info[roomId].roomImages.unshift(img_uri)
content_html = """
<img crossorigin="Anonymous" class="wxmsg_content_hwebimg" data-uri="#{img_uri}" src="#{content_values}" onerror="this.src='#{error_img}'" >
"""
else if content_type == "HWEBFACEIMG"
face_url = decodeURIComponent(content_values)
msg_owner = "#{msg_owner} wxmsg_face"
content_html = """
<img crossorigin="Anonymous" class="wxmsg_face_img" src="#{face_url}" onerror="this.src='#{error_img}'" >
"""
msg_html = """
<div class="wxmsg #{msg_owner}" data-comment-flag="#{comment_id}_#{comment_sequence}" align="#{msg_html_align}">
<div class="wxmsg_time" style="#{msg_time_hide}" align="center"><div>#{time}</div></div>
<div class="wxmsg_head_area">
<div class="wxmsg_headimg #{msg_owner}"><img src="#{headimg}"></div>
</div>
<div class="wxmsg_nickname #{msg_owner}"><span>#{nickname}</span></div>
<div class="wxmsg_content #{msg_owner}">#{content_html}</div>
</div>
"""
$('.comments_area').prepend msg_html
loadHistory = (currentRoomId)->
isLoadingMore = true
$('.comments_area').prepend """
<div class="wxmsg_load_tip">加载中...</div>
"""
$.ajax
url: 'http://www.hotpoor.org/api/comment/load'
type: 'POST'
dataType: 'json'
data:
app: 'bangfer'
aim_id: currentRoomId
comment_id: rooms_info[currentRoomId].last_comment_id
success: (data)->
console.log data
if data.info == "ok"
rooms_info[currentRoomId].last_comment_id = data.last_comment_id
members_json_now = members_json
members_json_new = data.members
members_json = $.extend({}, members_json_now,members_json_new)
comments = data.comments
commentsequence_flag = null
for comment in comments by -1
_msg = [comment[3],{
"content": comment[4],
"nickname": members_json[comment[1]].nickname,
"headimgurl": members_json[comment[1]].headimgurl,
"time": comment[2],
"user_id": comment[1],
"tel": members_json[comment[1]].tel,
"plus": comment[5],
"sequence": comment[0],
"comment_id": data.comment_id,
},roomId]
console.log _msg
loadMessage(_msg)
if not rooms_info[currentRoomId]["latestComment"]?
rooms_info[currentRoomId]["latestComment"] = _msg
item_text = ""
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].finishcommentsequence}]")[0].scrollIntoView(false)
if not commentsequence_flag?
commentsequence_flag = "#{data.comment_id}_#{comment[0]}"
console.log $(".wxmsg[data-comment-flag=#{commentsequence_flag}]")[0]
scrollIntoElement(roomId,$(".wxmsg[data-comment-flag=#{commentsequence_flag}]")[0])
$(".wxmsg_load_tip").text("加载成功!")
setTimeout ()->
$(".wxmsg_load_tip").remove()
isLoadingMore = false
, 1000
error: (error)->
console.log(error)
scrollIntoElement = (currentRoomId,el) ->
roomEl = $(".comments_area")
if not typeof(el)?
roomEl.stop().animate ()->
"scrollTop":el.offseTop
onRoomScroll = (evt)->
cu_el = $(evt.currentTarget)
cu_roomId = cu_el.data("room-id")
cu_scrollTop = cu_el.scrollTop()
if cu_scrollTop <5 and !isLoadingMore
if rooms_info[cu_roomId].last_comment_id?
loadHistory(cu_roomId)
formatDate = (now)->
now_date = new Date(now * 1000)
comment_time_now = new Date
year = now_date.getFullYear()
month = now_date.getMonth() + 1
date = now_date.getDate()
hour = now_date.getHours()
minute = now_date.getMinutes()
if hour < 10
hour = "0" + hour
if minute < 10
minute = "0" + minute
if comment_time_now.getFullYear() == year and comment_time_now.getMonth() + 1 == month and comment_time_now.getDate() == date
return hour + ":" + minute
if comment_time_now.getFullYear() == year
return month + "月" + date + "日 " + hour + ":" + minute
return year + "年" + month + "月" + date + "日 " + hour + ":" + minute
escapeHTML = (str)->
return $('<div></div>').text(str).html()
load_start()
| true | $ ->
$("#hotpoor_shares_qrcode_weixin_area").remove()
$("#hotpoor_shares").css
"position":"relative"
"paddingBottom":"0px"
"height":"100%"
$("#hotpoor_shares").append """
<style>
.comments_area{
width:100%;
height:calc(100% - 44px);
overflow-y: auto;
}
.comments_area_tools{
width:100%;
height:44px;
background-color:#f2f2f2;
border-top:1px solid #d4d4d4;
position:relative;
}
.comment_content{
width: calc(100% - 82px);
border-radius: 4px;
border: 1px solid #c3c3c3;
resize: none;
position: absolute;
left: 4px;
top: 3px;
font-size: 14px;
padding: 4px;
height: 26px;
}
.comment_submit{
width: 60px;
height: 32px;
font-size: 15px;
color: #999999;
border-radius: 7px;
border: 1px solid #c3c3c3;
background-color: #f2f2f2;
position: absolute;
right: 4px;
top: 5px;
padding-left: 2px;
padding-right: 2px;
}
.wxmsg{
width:100%;
padding:5px 0px 10px 0px;
}
.wxmsg_time{
margin: 2px;
}
.wxmsg_time>div{
background-color:rgba(0,0,0,0.2);
border-radius:4px;
color:white;
font-size:12px;
padding:1px 5px;
width: fit-content;
width: -moz-fit-content;
width: -webkit-fit-content;
}
.wxmsg_head_area{
width:100%;
position:relative;
}
.wxmsg_headimg{
position:absolute;
}
.wxmsg_headimg.wxmsg_self{
right:5px;
}
.wxmsg_headimg.wxmsg_other{
left:5px;
}
.wxmsg_headimg>img{
width: 36px;
height: 36px;
background-color: rgba(255,255,255,0.8);
box-shadow: 0px 0px 2px rgba(0,0,0,0.05);
}
.wxmsg_nickname{
font-size:14px;
color:#999;
font-weight:500;
}
.wxmsg_nickname.wxmsg_self{
text-align:right;
padding-right:50px;
}
.wxmsg_nickname.wxmsg_other{
text-align:left;
padding-left:50px;
}
.wxmsg_content{
text-align:left;
word-break: break-word;
background-color: white;
padding: 9px;
font-size: 14px;
line-height: 18px;
border-radius: 5px;
box-shadow: 0px 0px 2px rgba(0,0,0,0.2);
position: relative;
width: fit-content;
width: -moz-fit-content;
width: -webkit-fit-content;
min-width:15px;
max-width:500px;
}
.wxmsg_content.wxmsg_self{
margin-right: 50px;
margin-left: 60px;
}
.wxmsg_content.wxmsg_self:before {
content: " ";
width: 9px;
height: 9px;
background-color: white;
position: absolute;
right: -4px;
top: 13px;
box-shadow: 1px 1px 1px rgba(0,0,0,0.1);
transform: rotate(-45deg);
}
.wxmsg_content.wxmsg_other{
margin-left: 50px;
margin-right: 60px;
}
.wxmsg_content.wxmsg_other:before {
content: " ";
width: 9px;
height: 9px;
background-color: white;
position: absolute;
left: -4px;
top: 13px;
box-shadow: -1px 1px 1px rgba(0,0,0,0.1);
transform: rotate(45deg);
}
.wxmsg_content_hqwebimg,.wxmsg_content_hwebimg{
max-width:100%;
min-width:10px;
max-height:200px;
}
.wxmsg_load_tip{
text-align:center;
color:#999;
font-size:14px;
padding:5px;
}
.wxmsg_face_img{
width:60px;
height:auto;
}
.wxmsg_content.wxmsg_other.wxmsg_face{
box-shadow:none;
background-color:unset;
margin-left: 50px;
margin-right: 60px;
}
.wxmsg_content.wxmsg_self.wxmsg_face{
box-shadow:none;
background-color:unset;
margin-right: 50px;
margin-left: 60px;
}
.wxmsg_content.wxmsg_self.wxmsg_face:before,.wxmsg_content.wxmsg_other.wxmsg_face:before{
display:none;
}
</style>
"""
$("#hotpoor_shares").append """
<div class="comments_area">
</div>
<div class="comments_area_tools">
<textarea class="comment_content"></textarea><button class="comment_submit">发送</button>
</div>
"""
$("#hotpoor_shares").on "touchstart",".comments_area",(e)->
el_now = this
scrollTop = el_now.scrollTop
if scrollTop==0
el_now.scrollTop = 1
if el_now.scrollTop+el_now.offsetHeight==el_now.scrollHeight
el_now.scrollTop = (parseInt(el_now.scrollHeight)-parseInt(el_now.offsetHeight)-1)
targetRoomId = null
initialRoomId = "0cd8429c1da249b6935d7eef72d7fc0b"
initialRoomImg = "http://image.hotpoor.org/2dd2c53e7c654c66b398e574848d4c34_08aed20957caca43b0df23442de17f6f?imageView2/2/w/200"
initialRoomName = "PI:NAME:<NAME>END_PI和他的朋友们"
isLoadingMore = false
base_rooms = [
[
initialRoomId
initialRoomImg
initialRoomName
]
]
rooms_info = {}
for base_room in base_rooms
roomId = base_room[0]
imgUrl = base_room[1]
roomName = base_room[2]
time_now = (new Date()).getTime() / 1000
rooms_info[roomId] =
"imgUrl": imgUrl
"roomName": roomName
"createtime": time_now
"finishtime": null
"room_time_flag": time_now
"createuser":null
"finishuser":null
"createcommentsequence":null
"finishcommentsequence":null
"latestComment": null
"last_comment_id": null
"roomNewMsgCount": 0
"roomImages":[]
members_json = {}
load_start = ()->
$(".comments_area").empty()
$(".comments_area").attr("data-room-id",roomId)
$(".comments_area").on "scroll",(e)->
onRoomScroll(e)
$.ajax
url: 'http://www.hotpoor.org/api/comment/load'
type: 'POST'
dataType: 'json'
data:
app: 'bangfer'
aim_id: roomId
comment_id: rooms_info[roomId].last_comment_id
success: (data)->
console.log data
if data.info == "ok"
rooms_info[roomId].last_comment_id = data.last_comment_id
members_json_now = members_json
members_json_new = data.members
members_json = $.extend({}, members_json_now,members_json_new)
comments = data.comments
for comment in comments by -1
_msg = [comment[3],{
"content": comment[4],
"nickname": members_json[comment[1]].nickname,
"headimgurl": members_json[comment[1]].headimgurl,
"time": comment[2],
"user_id": comment[1],
"tel": members_json[comment[1]].tel,
"plus": comment[5],
"sequence": comment[0],
"comment_id": data.comment_id,
},roomId]
console.log _msg
loadMessage(_msg)
if not rooms_info[roomId]["latestComment"]?
rooms_info[roomId]["latestComment"] = _msg
item_text = ""
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].finishcommentsequence}]")[0].scrollIntoView(false)
error: (error)->
console.log(error)
$("body").on "click","#bangfer_shares",(evt)->
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].finishcommentsequence}]")[0].scrollIntoView(false)
$("body").on "click",".wxmsg_content_hqwebimg,.wxmsg_content_hwebimg",(evt)->
wx.previewImage
current: $(this).attr("data-uri"), #当前显示图片的http链接
urls: rooms_info[roomId].roomImages #需要预览的图片http链接列表
loadMessage = (msg)->
msgType = msg[0]
roomId = msg[2]
content = msg[1].content
content = escapeHTML(content)
content = content.replace(/\n/g, '<br>')
headimg = msg[1].headimgurl
nickname = msg[1].nickname
timer = msg[1].time
time = formatDate(timer)
user_id = msg[1].user_id
tel = msg[1].tel
plus = msg[1].plus
plus_content = escapeHTML(plus.content)
plus_type = escapeHTML(plus.type)
if not plus.destination?
plus_content_destination = ""
else
plus_content_destination = escapeHTML(plus.destination)
if plus_type == "百度语音转文字"
plus_content = plus_content.split("百度语音转文字: ")[1]
if plus_content_destination.split("百度语音翻译: ").length==2
plus_content_destination = plus_content_destination.split("百度语音翻译: ")[1]
comment_id = msg[1].comment_id
comment_sequence = msg[1].sequence
content_type = content.split("//")[0]
content_values = content.split("//")[1]
if user_id == USER_ID
msg_owner = "wxmsg_self"
msg_html_align = "right"
else
msg_owner = "wxmsg_other"
msg_html_align = "left"
console.log "#{rooms_info[roomId].createtime} - #{timer} = "+(rooms_info[roomId].createtime - timer)
msg_time_hide = ""
if rooms_info[roomId].createtime - timer < 300
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].createcommentsequence}]>.wxmsg_time").hide()
rooms_info[roomId].createtime = timer
rooms_info[roomId].createuser = user_id
rooms_info[roomId].createcommentsequence = comment_id+"_"+comment_sequence
if not rooms_info[roomId].finishtime?
rooms_info[roomId].finishtime = timer
if not rooms_info[roomId].finishcommentsequence?
rooms_info[roomId].finishcommentsequence = comment_id+"_"+comment_sequence
msg_headimg_hide = ""
msg_nickname_hide = ""
error_img = "http://www.hotpoor.org/static/img/tools/error_img_"+parseInt(Math.random()*10%2)+".png"
content_html = "#{content}"
if msgType == "COMMENT"
content_values = content.split(content_type+"//")[1]
if content_type == "HQWEBIMG"
img_uri = "http://image.hotpoor.org/#{roomId}_#{content_values}?imageView2"
rooms_info[roomId].roomImages.unshift(img_uri)
content_html = """
<img crossorigin="Anonymous" class="wxmsg_content_hqwebimg" data-uri="#{img_uri}" src="http://image.hotpoor.org/#{roomId}_#{content_values}?imageView2/2/w/320" onerror="this.src='#{error_img}'">
"""
else if content_type == "HWEBIMG"
img_uri = decodeURIComponent(content_values)
rooms_info[roomId].roomImages.unshift(img_uri)
content_html = """
<img crossorigin="Anonymous" class="wxmsg_content_hwebimg" data-uri="#{img_uri}" src="#{content_values}" onerror="this.src='#{error_img}'" >
"""
else if content_type == "HWEBFACEIMG"
face_url = decodeURIComponent(content_values)
msg_owner = "#{msg_owner} wxmsg_face"
content_html = """
<img crossorigin="Anonymous" class="wxmsg_face_img" src="#{face_url}" onerror="this.src='#{error_img}'" >
"""
msg_html = """
<div class="wxmsg #{msg_owner}" data-comment-flag="#{comment_id}_#{comment_sequence}" align="#{msg_html_align}">
<div class="wxmsg_time" style="#{msg_time_hide}" align="center"><div>#{time}</div></div>
<div class="wxmsg_head_area">
<div class="wxmsg_headimg #{msg_owner}"><img src="#{headimg}"></div>
</div>
<div class="wxmsg_nickname #{msg_owner}"><span>#{nickname}</span></div>
<div class="wxmsg_content #{msg_owner}">#{content_html}</div>
</div>
"""
$('.comments_area').prepend msg_html
loadHistory = (currentRoomId)->
isLoadingMore = true
$('.comments_area').prepend """
<div class="wxmsg_load_tip">加载中...</div>
"""
$.ajax
url: 'http://www.hotpoor.org/api/comment/load'
type: 'POST'
dataType: 'json'
data:
app: 'bangfer'
aim_id: currentRoomId
comment_id: rooms_info[currentRoomId].last_comment_id
success: (data)->
console.log data
if data.info == "ok"
rooms_info[currentRoomId].last_comment_id = data.last_comment_id
members_json_now = members_json
members_json_new = data.members
members_json = $.extend({}, members_json_now,members_json_new)
comments = data.comments
commentsequence_flag = null
for comment in comments by -1
_msg = [comment[3],{
"content": comment[4],
"nickname": members_json[comment[1]].nickname,
"headimgurl": members_json[comment[1]].headimgurl,
"time": comment[2],
"user_id": comment[1],
"tel": members_json[comment[1]].tel,
"plus": comment[5],
"sequence": comment[0],
"comment_id": data.comment_id,
},roomId]
console.log _msg
loadMessage(_msg)
if not rooms_info[currentRoomId]["latestComment"]?
rooms_info[currentRoomId]["latestComment"] = _msg
item_text = ""
$(".wxmsg[data-comment-flag=#{rooms_info[roomId].finishcommentsequence}]")[0].scrollIntoView(false)
if not commentsequence_flag?
commentsequence_flag = "#{data.comment_id}_#{comment[0]}"
console.log $(".wxmsg[data-comment-flag=#{commentsequence_flag}]")[0]
scrollIntoElement(roomId,$(".wxmsg[data-comment-flag=#{commentsequence_flag}]")[0])
$(".wxmsg_load_tip").text("加载成功!")
setTimeout ()->
$(".wxmsg_load_tip").remove()
isLoadingMore = false
, 1000
error: (error)->
console.log(error)
scrollIntoElement = (currentRoomId,el) ->
roomEl = $(".comments_area")
if not typeof(el)?
roomEl.stop().animate ()->
"scrollTop":el.offseTop
onRoomScroll = (evt)->
cu_el = $(evt.currentTarget)
cu_roomId = cu_el.data("room-id")
cu_scrollTop = cu_el.scrollTop()
if cu_scrollTop <5 and !isLoadingMore
if rooms_info[cu_roomId].last_comment_id?
loadHistory(cu_roomId)
formatDate = (now)->
now_date = new Date(now * 1000)
comment_time_now = new Date
year = now_date.getFullYear()
month = now_date.getMonth() + 1
date = now_date.getDate()
hour = now_date.getHours()
minute = now_date.getMinutes()
if hour < 10
hour = "0" + hour
if minute < 10
minute = "0" + minute
if comment_time_now.getFullYear() == year and comment_time_now.getMonth() + 1 == month and comment_time_now.getDate() == date
return hour + ":" + minute
if comment_time_now.getFullYear() == year
return month + "月" + date + "日 " + hour + ":" + minute
return year + "年" + month + "月" + date + "日 " + hour + ":" + minute
escapeHTML = (str)->
return $('<div></div>').text(str).html()
load_start()
|
[
{
"context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 43,
"score": 0.6368123292922974,
"start": 33,
"tag": "NAME",
"value": "Technology"
}
] | community/server/src/main/coffeescript/neo4j/webadmin/modules/databrowser/visualization/models/Filters.coffee | rebaze/neo4j | 1 | ###
Copyright (c) 2002-2013 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['./filters/PropertyFilter',
'./filters/GroupSizeFilter',
'ribcage/LocalCollection'],
(PropertyFilter, GroupSizeFilter, LocalCollection) ->
filters = [
PropertyFilter
GroupSizeFilter
]
filterMap = {}
for f in filters
filterMap[f.type] = f
class Filters extends LocalCollection
filters : filterMap
# Override the normal deserialization method,
# to allow us to deserialize to multiple different
# filter types.
deserializeItem : (raw) ->
# Fix for a corruption bug where type was set to "d", rather than "propertyFilter"
raw.type = PropertyFilter.type if raw.type is 'd'
if @filters[raw.type]?
return new @filters[raw.type](raw)
throw new Error("Unknown filter type '#{raw.type}' for visualization profile")
)
| 74374 | ###
Copyright (c) 2002-2013 "Neo <NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['./filters/PropertyFilter',
'./filters/GroupSizeFilter',
'ribcage/LocalCollection'],
(PropertyFilter, GroupSizeFilter, LocalCollection) ->
filters = [
PropertyFilter
GroupSizeFilter
]
filterMap = {}
for f in filters
filterMap[f.type] = f
class Filters extends LocalCollection
filters : filterMap
# Override the normal deserialization method,
# to allow us to deserialize to multiple different
# filter types.
deserializeItem : (raw) ->
# Fix for a corruption bug where type was set to "d", rather than "propertyFilter"
raw.type = PropertyFilter.type if raw.type is 'd'
if @filters[raw.type]?
return new @filters[raw.type](raw)
throw new Error("Unknown filter type '#{raw.type}' for visualization profile")
)
| true | ###
Copyright (c) 2002-2013 "Neo PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['./filters/PropertyFilter',
'./filters/GroupSizeFilter',
'ribcage/LocalCollection'],
(PropertyFilter, GroupSizeFilter, LocalCollection) ->
filters = [
PropertyFilter
GroupSizeFilter
]
filterMap = {}
for f in filters
filterMap[f.type] = f
class Filters extends LocalCollection
filters : filterMap
# Override the normal deserialization method,
# to allow us to deserialize to multiple different
# filter types.
deserializeItem : (raw) ->
# Fix for a corruption bug where type was set to "d", rather than "propertyFilter"
raw.type = PropertyFilter.type if raw.type is 'd'
if @filters[raw.type]?
return new @filters[raw.type](raw)
throw new Error("Unknown filter type '#{raw.type}' for visualization profile")
)
|
[
{
"context": " uuid: 'green-blue'\n token: 'blue-purple'\n toUuid: 'orange'\n fromUui",
"end": 580,
"score": 0.966088593006134,
"start": 569,
"tag": "PASSWORD",
"value": "blue-purple"
},
{
"context": " uuid: 'green-blue'\n ... | test/check-broadcast-sent-whitelist-spec.coffee | octoblu/meshblu-core-task-check-broadcast-sent-whitelist | 0 | http = require 'http'
CheckBroadcastSentWhitelist = require '../'
describe 'CheckBroadcastSentWhitelist', ->
beforeEach ->
@whitelistManager =
checkBroadcastSent: sinon.stub()
@sut = new CheckBroadcastSentWhitelist
whitelistManager: @whitelistManager
describe '->do', ->
describe 'when called with a toUuid that does not match the auth', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'blue-purple'
toUuid: 'orange'
fromUuid: 'dim-green'
responseId: 'yellow-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 403', ->
expect(@result.metadata.code).to.equal 403
it 'should get have the status of Forbidden', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[403]
describe 'when called with a valid job', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'blue-purple'
toUuid: 'green-blue'
fromUuid: 'dim-green'
responseId: 'yellow-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 204', ->
expect(@result.metadata.code).to.equal 204
it 'should get have the status of No Content', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a valid job without a from', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'blue-purple'
toUuid: 'bright-green'
responseId: 'yellow-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 422', ->
expect(@result.metadata.code).to.equal 422
it 'should get have the status of Unprocessable Entity', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[422]
describe 'when called with a different valid job', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'dim-green'
token: 'blue-lime-green'
toUuid: 'dim-green'
fromUuid: 'ugly-yellow'
responseId: 'purple-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 204', ->
expect(@result.metadata.code).to.equal 204
it 'should get have the status of OK', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a job that with a device that has an invalid whitelist', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, false
job =
metadata:
auth:
uuid: 'puke-green'
token: 'blue-lime-green'
toUuid: 'puke-green'
fromUuid: 'not-so-super-purple'
responseId: 'purple-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 403', ->
expect(@result.metadata.code).to.equal 403
it 'should get have the status of Forbidden', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[403]
describe 'when called and the checkBroadcastSent yields an error', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields new Error "black-n-black"
job =
metadata:
auth:
uuid: 'puke-green'
token: 'blue-lime-green'
toUuid: 'puke-green'
fromUuid: 'green-safe'
responseId: 'purple-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 500', ->
expect(@result.metadata.code).to.equal 500
it 'should get have the status of Internal Server Error', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[500]
| 117697 | http = require 'http'
CheckBroadcastSentWhitelist = require '../'
describe 'CheckBroadcastSentWhitelist', ->
beforeEach ->
@whitelistManager =
checkBroadcastSent: sinon.stub()
@sut = new CheckBroadcastSentWhitelist
whitelistManager: @whitelistManager
describe '->do', ->
describe 'when called with a toUuid that does not match the auth', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: '<PASSWORD>'
toUuid: 'orange'
fromUuid: 'dim-green'
responseId: 'yellow-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 403', ->
expect(@result.metadata.code).to.equal 403
it 'should get have the status of Forbidden', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[403]
describe 'when called with a valid job', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: '<PASSWORD>'
toUuid: 'green-blue'
fromUuid: 'dim-green'
responseId: 'yellow-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 204', ->
expect(@result.metadata.code).to.equal 204
it 'should get have the status of No Content', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a valid job without a from', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'blue-purple'
toUuid: 'bright-green'
responseId: 'yellow-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 422', ->
expect(@result.metadata.code).to.equal 422
it 'should get have the status of Unprocessable Entity', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[422]
describe 'when called with a different valid job', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'dim-green'
token: '<PASSWORD>'
toUuid: 'dim-green'
fromUuid: 'ugly-yellow'
responseId: 'purple-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 204', ->
expect(@result.metadata.code).to.equal 204
it 'should get have the status of OK', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a job that with a device that has an invalid whitelist', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, false
job =
metadata:
auth:
uuid: 'puke-green'
token: '<PASSWORD>'
toUuid: 'puke-green'
fromUuid: 'not-so-super-purple'
responseId: 'purple-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 403', ->
expect(@result.metadata.code).to.equal 403
it 'should get have the status of Forbidden', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[403]
describe 'when called and the checkBroadcastSent yields an error', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields new Error "black-n-black"
job =
metadata:
auth:
uuid: 'puke-green'
token: '<PASSWORD>'
toUuid: 'puke-green'
fromUuid: 'green-safe'
responseId: 'purple-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 500', ->
expect(@result.metadata.code).to.equal 500
it 'should get have the status of Internal Server Error', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[500]
| true | http = require 'http'
CheckBroadcastSentWhitelist = require '../'
describe 'CheckBroadcastSentWhitelist', ->
beforeEach ->
@whitelistManager =
checkBroadcastSent: sinon.stub()
@sut = new CheckBroadcastSentWhitelist
whitelistManager: @whitelistManager
describe '->do', ->
describe 'when called with a toUuid that does not match the auth', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: 'orange'
fromUuid: 'dim-green'
responseId: 'yellow-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 403', ->
expect(@result.metadata.code).to.equal 403
it 'should get have the status of Forbidden', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[403]
describe 'when called with a valid job', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: 'green-blue'
fromUuid: 'dim-green'
responseId: 'yellow-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 204', ->
expect(@result.metadata.code).to.equal 204
it 'should get have the status of No Content', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a valid job without a from', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'green-blue'
token: 'blue-purple'
toUuid: 'bright-green'
responseId: 'yellow-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'yellow-green'
it 'should get have the status code of 422', ->
expect(@result.metadata.code).to.equal 422
it 'should get have the status of Unprocessable Entity', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[422]
describe 'when called with a different valid job', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, true
job =
metadata:
auth:
uuid: 'dim-green'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: 'dim-green'
fromUuid: 'ugly-yellow'
responseId: 'purple-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 204', ->
expect(@result.metadata.code).to.equal 204
it 'should get have the status of OK', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[204]
describe 'when called with a job that with a device that has an invalid whitelist', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields null, false
job =
metadata:
auth:
uuid: 'puke-green'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: 'puke-green'
fromUuid: 'not-so-super-purple'
responseId: 'purple-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 403', ->
expect(@result.metadata.code).to.equal 403
it 'should get have the status of Forbidden', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[403]
describe 'when called and the checkBroadcastSent yields an error', ->
beforeEach (done) ->
@whitelistManager.checkBroadcastSent.yields new Error "black-n-black"
job =
metadata:
auth:
uuid: 'puke-green'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
toUuid: 'puke-green'
fromUuid: 'green-safe'
responseId: 'purple-green'
@sut.do job, (error, @result) => done error
it 'should get have the responseId', ->
expect(@result.metadata.responseId).to.equal 'purple-green'
it 'should get have the status code of 500', ->
expect(@result.metadata.code).to.equal 500
it 'should get have the status of Internal Server Error', ->
expect(@result.metadata.status).to.equal http.STATUS_CODES[500]
|
[
{
"context": "# iplotScanone_noeff: LOD curves (nothing else)\n# Karl W Broman\n\niplotScanone_noeff = (widgetdiv, data, chartOpts",
"end": 63,
"score": 0.9997490048408508,
"start": 50,
"tag": "NAME",
"value": "Karl W Broman"
}
] | inst/htmlwidgets/lib/qtlcharts/iplotScanone_noeff.coffee | Alanocallaghan/qtlcharts | 0 | # iplotScanone_noeff: LOD curves (nothing else)
# Karl W Broman
iplotScanone_noeff = (widgetdiv, data, chartOpts) ->
# chartOpts start
height = chartOpts?.height ? 450 # height of image in pixels
width = chartOpts?.width ? 900 # width of image in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
ylim = chartOpts?.ylim ? chartOpts?.lod_ylim ? null # y-axis limits
nyticks = chartOpts?.nyticks ? chartOpts?.lod_nyticks ? 5 # number of ticks in y-axis
yticks = chartOpts?.yticks ? chartOpts?.lod_yticks ? null # vector of tick positions for y-axis
chrGap = chartOpts?.chrGap ? 6 # gap between chromosomes in pixels
rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of background rectangle
altrectcolor = chartOpts?.altrectcolor ? "#C8C8C8" # color of alternate background rectangle
linecolor = chartOpts?.linecolor ? chartOpts?.lod_linecolor ? "darkslateblue" # line color for LOD curves
linewidth = chartOpts?.linewidth ? chartOpts?.lod_linewidth ? 2 # line width for LOD curves
pointcolor = chartOpts?.pointcolor ? chartOpts?.lod_pointcolor ? "#E9CFEC" # color for points at markers
pointsize = chartOpts?.pointsize ? chartOpts?.lod_pointsize ? 0 # size of points at markers (default = 0 corresponding to no visible points at markers)
pointstroke = chartOpts?.pointstroke ? chartOpts?.lod_pointstroke ? "black" # color of outer circle for points at markers
title = chartOpts?.title ? chartOpts?.lod_title ? "" # title of chart
xlab = chartOpts?.xlab ? chartOpts?.lod_xlab ? null # x-axis label
ylab = chartOpts?.ylab ? chartOpts?.lod_ylab ? "LOD score" # y-axis label
rotate_ylab = chartOpts?.rotate_ylab ? chartOpts?.lod_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
widgetdivid = d3.select(widgetdiv).attr('id')
# make sure list args have all necessary bits
margin = d3panels.check_listarg_v_default(margin, {left:60, top:40, right:40, bottom: 40, inner:5})
axispos = d3panels.check_listarg_v_default(axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5})
mylodchart = d3panels.lodchart({
height:height
width:width
margin:margin
axispos:axispos
titlepos:titlepos
ylim:ylim
nyticks:nyticks
yticks:yticks
chrGap:chrGap
rectcolor:rectcolor
altrectcolor:altrectcolor
linecolor:linecolor
linewidth:linewidth
pointcolor:pointcolor
pointsize:pointsize
pointstroke:pointstroke
title:title
xlab:xlab
ylab:ylab
rotate_ylab:rotate_ylab
tipclass:widgetdivid})
mylodchart(d3.select(widgetdiv).select("svg"), data)
# animate points at markers on click
mylodchart.markerSelect()
.on "click", (d) ->
r = d3.select(this).attr("r")
d3.select(this)
.transition().duration(500).attr("r", r*3)
.transition().duration(500).attr("r", r)
if chartOpts.heading?
d3.select("div#htmlwidget_container")
.insert("h2", ":first-child")
.html(chartOpts.heading)
.style("font-family", "sans-serif")
if chartOpts.caption?
d3.select("body")
.append("p")
.attr("class", "caption")
.html(chartOpts.caption)
if chartOpts.footer?
d3.select("body")
.append("div")
.html(chartOpts.footer)
.style("font-family", "sans-serif")
| 24178 | # iplotScanone_noeff: LOD curves (nothing else)
# <NAME>
iplotScanone_noeff = (widgetdiv, data, chartOpts) ->
# chartOpts start
height = chartOpts?.height ? 450 # height of image in pixels
width = chartOpts?.width ? 900 # width of image in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
ylim = chartOpts?.ylim ? chartOpts?.lod_ylim ? null # y-axis limits
nyticks = chartOpts?.nyticks ? chartOpts?.lod_nyticks ? 5 # number of ticks in y-axis
yticks = chartOpts?.yticks ? chartOpts?.lod_yticks ? null # vector of tick positions for y-axis
chrGap = chartOpts?.chrGap ? 6 # gap between chromosomes in pixels
rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of background rectangle
altrectcolor = chartOpts?.altrectcolor ? "#C8C8C8" # color of alternate background rectangle
linecolor = chartOpts?.linecolor ? chartOpts?.lod_linecolor ? "darkslateblue" # line color for LOD curves
linewidth = chartOpts?.linewidth ? chartOpts?.lod_linewidth ? 2 # line width for LOD curves
pointcolor = chartOpts?.pointcolor ? chartOpts?.lod_pointcolor ? "#E9CFEC" # color for points at markers
pointsize = chartOpts?.pointsize ? chartOpts?.lod_pointsize ? 0 # size of points at markers (default = 0 corresponding to no visible points at markers)
pointstroke = chartOpts?.pointstroke ? chartOpts?.lod_pointstroke ? "black" # color of outer circle for points at markers
title = chartOpts?.title ? chartOpts?.lod_title ? "" # title of chart
xlab = chartOpts?.xlab ? chartOpts?.lod_xlab ? null # x-axis label
ylab = chartOpts?.ylab ? chartOpts?.lod_ylab ? "LOD score" # y-axis label
rotate_ylab = chartOpts?.rotate_ylab ? chartOpts?.lod_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
widgetdivid = d3.select(widgetdiv).attr('id')
# make sure list args have all necessary bits
margin = d3panels.check_listarg_v_default(margin, {left:60, top:40, right:40, bottom: 40, inner:5})
axispos = d3panels.check_listarg_v_default(axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5})
mylodchart = d3panels.lodchart({
height:height
width:width
margin:margin
axispos:axispos
titlepos:titlepos
ylim:ylim
nyticks:nyticks
yticks:yticks
chrGap:chrGap
rectcolor:rectcolor
altrectcolor:altrectcolor
linecolor:linecolor
linewidth:linewidth
pointcolor:pointcolor
pointsize:pointsize
pointstroke:pointstroke
title:title
xlab:xlab
ylab:ylab
rotate_ylab:rotate_ylab
tipclass:widgetdivid})
mylodchart(d3.select(widgetdiv).select("svg"), data)
# animate points at markers on click
mylodchart.markerSelect()
.on "click", (d) ->
r = d3.select(this).attr("r")
d3.select(this)
.transition().duration(500).attr("r", r*3)
.transition().duration(500).attr("r", r)
if chartOpts.heading?
d3.select("div#htmlwidget_container")
.insert("h2", ":first-child")
.html(chartOpts.heading)
.style("font-family", "sans-serif")
if chartOpts.caption?
d3.select("body")
.append("p")
.attr("class", "caption")
.html(chartOpts.caption)
if chartOpts.footer?
d3.select("body")
.append("div")
.html(chartOpts.footer)
.style("font-family", "sans-serif")
| true | # iplotScanone_noeff: LOD curves (nothing else)
# PI:NAME:<NAME>END_PI
iplotScanone_noeff = (widgetdiv, data, chartOpts) ->
# chartOpts start
height = chartOpts?.height ? 450 # height of image in pixels
width = chartOpts?.width ? 900 # width of image in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
ylim = chartOpts?.ylim ? chartOpts?.lod_ylim ? null # y-axis limits
nyticks = chartOpts?.nyticks ? chartOpts?.lod_nyticks ? 5 # number of ticks in y-axis
yticks = chartOpts?.yticks ? chartOpts?.lod_yticks ? null # vector of tick positions for y-axis
chrGap = chartOpts?.chrGap ? 6 # gap between chromosomes in pixels
rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of background rectangle
altrectcolor = chartOpts?.altrectcolor ? "#C8C8C8" # color of alternate background rectangle
linecolor = chartOpts?.linecolor ? chartOpts?.lod_linecolor ? "darkslateblue" # line color for LOD curves
linewidth = chartOpts?.linewidth ? chartOpts?.lod_linewidth ? 2 # line width for LOD curves
pointcolor = chartOpts?.pointcolor ? chartOpts?.lod_pointcolor ? "#E9CFEC" # color for points at markers
pointsize = chartOpts?.pointsize ? chartOpts?.lod_pointsize ? 0 # size of points at markers (default = 0 corresponding to no visible points at markers)
pointstroke = chartOpts?.pointstroke ? chartOpts?.lod_pointstroke ? "black" # color of outer circle for points at markers
title = chartOpts?.title ? chartOpts?.lod_title ? "" # title of chart
xlab = chartOpts?.xlab ? chartOpts?.lod_xlab ? null # x-axis label
ylab = chartOpts?.ylab ? chartOpts?.lod_ylab ? "LOD score" # y-axis label
rotate_ylab = chartOpts?.rotate_ylab ? chartOpts?.lod_rotate_ylab ? null # indicates whether to rotate the y-axis label 90 degrees
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
widgetdivid = d3.select(widgetdiv).attr('id')
# make sure list args have all necessary bits
margin = d3panels.check_listarg_v_default(margin, {left:60, top:40, right:40, bottom: 40, inner:5})
axispos = d3panels.check_listarg_v_default(axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5})
mylodchart = d3panels.lodchart({
height:height
width:width
margin:margin
axispos:axispos
titlepos:titlepos
ylim:ylim
nyticks:nyticks
yticks:yticks
chrGap:chrGap
rectcolor:rectcolor
altrectcolor:altrectcolor
linecolor:linecolor
linewidth:linewidth
pointcolor:pointcolor
pointsize:pointsize
pointstroke:pointstroke
title:title
xlab:xlab
ylab:ylab
rotate_ylab:rotate_ylab
tipclass:widgetdivid})
mylodchart(d3.select(widgetdiv).select("svg"), data)
# animate points at markers on click
mylodchart.markerSelect()
.on "click", (d) ->
r = d3.select(this).attr("r")
d3.select(this)
.transition().duration(500).attr("r", r*3)
.transition().duration(500).attr("r", r)
if chartOpts.heading?
d3.select("div#htmlwidget_container")
.insert("h2", ":first-child")
.html(chartOpts.heading)
.style("font-family", "sans-serif")
if chartOpts.caption?
d3.select("body")
.append("p")
.attr("class", "caption")
.html(chartOpts.caption)
if chartOpts.footer?
d3.select("body")
.append("div")
.html(chartOpts.footer)
.style("font-family", "sans-serif")
|
[
{
"context": "t version', opts, err\n return\n key = EJSON.stringify _.pick(\n res, 'ownerName', 're",
"end": 14444,
"score": 0.6218315958976746,
"start": 14440,
"tag": "KEY",
"value": "JSON"
},
{
"context": "reactive contenteditables\n # (https://github.com/Swa... | packages/nog-flow/nog-flow-ui.coffee | nogproject/nog | 0 | {defaultErrorHandler} = NogError
{escapeHtml} = NogFmt
{ NogFlow } = share
WorkspaceContent = new Mongo.Collection('workspaceContent')
routerPath = (route, opts) ->
href = FlowRouter.path route, opts
href = href.replace /%2F/g, '/'
href
iskind = (entry, kind) -> _.isObject(entry.meta[kind])
iskindDatalist = (tree) -> iskind tree, 'datalist'
iskindResults = (tree) -> iskind tree, 'results'
iskindPrograms = (tree) -> iskind tree, 'programs'
iskindJob = (tree) -> iskind tree, 'job'
iskindJobs = (tree) -> iskind tree, 'jobs'
iskindResults = (tree) -> iskind tree, 'results'
iskindPackage = (tree) -> iskind tree, 'package'
iskindWorkspace = (tree) -> iskind tree, 'workspace'
iskindProgramRegistry = (tree) -> iskind tree, 'programRegistry'
iskindCatalog = (tree) -> iskind tree, 'catalog'
mayModifyRepo = (repo) ->
aopts = {ownerName: repo.owner, repoName: repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
# Provide a file scope function to reset the stable commit from anywhere until
# we have a better solution. A possible solution would be to put the stable
# commit into the query part of the URL. We rely on the URL for hrefs anyway.
# There can only be a single instance of treeContent at a time. So we can
# simply use the global state directly.
treeContentInstance = null
clearStable = ->
unless treeContentInstance
return
treeContentInstance.commitId.set null
updateContent = (updated) ->
if updated
return NogContent.repos.findOne({owner: ownerName, name: repoName},
{reactive: false})
Template.workspace.helpers
ownerName: -> FlowRouter.getParam('ownerName')
repoName: -> FlowRouter.getParam('repoName')
Template.workspaceContent.onCreated ->
@repo = ReactiveVar()
@counter = 0
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
if (repo = NogContent.repos.findOne({owner: ownerName, name: repoName}))?
repoId = repo._id
NogRepoSettings.call.addToRecentRepos {repoId}, (err, res) ->
if err
return defaultErrorHandler err
@autorun =>
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
sub = @subscribe 'workspaceContent', {ownerName, repoName}
if sub.ready()
token = WorkspaceContent.findOne(sub.subscriptionId)
unless @counter == token.updates
@counter = token.updates
@repo.set(NogContent.repos.findOne({owner: ownerName, name: repoName},
{reactive: false}))
Template.workspaceContent.helpers
ownerName: -> FlowRouter.getParam('ownerName')
repoName: -> FlowRouter.getParam('repoName')
viewerInfo: ->
if (repo = Template.instance().repo.get())?
if (commit = NogContent.commits.findOne(repo.refs['branches/master']))?
if (tree = NogContent.trees.findOne(commit.tree))?
{
fullName: repo.fullName
type: 'tree'
treePath: ''
iskindWorkspace: iskindWorkspace(tree)
currentIsWorkspace: true
iskindCatalog: iskindCatalog(tree)
}
repoContext: ->
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
tpl = Template.instance()
{
repo: tpl.repo.get()
}
Template.workspaceRepoMasterContent.helpers
datalistInfos: ->
dat = Template.currentData()
commitId = dat.repo.refs['branches/master']
if commit = NogContent.commits.findOne(commitId)
if tree = NogContent.trees.findOne(commit.tree)
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if iskindDatalist subtree
datalist = subtree
return {
repo: dat.repo
datalist: datalist
}
programsInfos: ->
dat = Template.currentData()
commitId = dat.repo.refs['branches/master']
if commit = NogContent.commits.findOne(commitId)
if tree = NogContent.trees.findOne(commit.tree)
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if iskindPrograms subtree
programs = subtree
return {
repo: dat.repo
programs: programs
}
jobsInfos: ->
dat = Template.currentData()
commitId = dat.repo.refs['branches/master']
if commit = NogContent.commits.findOne(commitId)
if tree = NogContent.trees.findOne commit.tree
{
repo: @repo
tree: tree
}
resultsInfos: ->
if commit = NogContent.commits.findOne @repo.refs['branches/master']
if tree = NogContent.trees.findOne commit.tree
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if iskindResults subtree
results = subtree
{
repo: @repo
results: results
}
oldWorkspaceVersion: ->
if commit = NogContent.commits.findOne @repo.refs['branches/master']
if tree = NogContent.trees.findOne commit.tree
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if subtree.name == 'results' and not iskindResults subtree
return true
errata: ->
unless (commit = NogContent.commits.findOne @repo.refs['branches/master'])?
return null
unless (tree = NogContent.trees.findOne(commit.tree))?
return null
return tree.errata
isWorkspace: ->
if commit = NogContent.commits.findOne @repo.refs['branches/master']
if tree = NogContent.trees.findOne commit.tree
if iskindWorkspace tree
return true
Template.workspaceFlowData.onCreated ->
@fileLimit = 10
@nEntries = 0
dat = Template.currentData()
@filesPath = '/' + dat.repo.owner + '/' + dat.repo.name + '/files/datalist'
@autorun =>
if Template.currentData().datalist
@nEntries = Template.currentData().datalist.entries.length
Template.workspaceFlowData.helpers
mayModify: -> mayModifyRepo @repo
hasDatalist: ->
dat = Template.currentData()
if dat.datalist
return true
else
return false
numberOfDataEntries: ->
Template.instance().nEntries
selectedFiles: ->
tpl = Template.instance()
dat = Template.currentData()
count = 0
for e, idx in dat.datalist.entries
if count >= tpl.fileLimit
break
switch e.type
when 'object'
entry = NogContent.objects.findOne(e.sha1)
icon = 'file-o'
name = entry.name
when 'tree'
entry = NogContent.trees.findOne(e.sha1)
icon = 'folder'
name = entry.name
if entry
count += 1
{
icon
name
}
path: ->
tpl = Template.instance()
return tpl.filesPath
hasMoreFiles: ->
tpl = Template.instance()
if tpl.nEntries <= tpl.fileLimit
return false
else
return true
numberofShownFiles: ->
tpl = Template.instance()
if tpl.nEntries <= tpl.fileLimit
return tpl.nEntries
else
return tpl.fileLimit
emptyDatalist: ->
tpl = Template.instance()
if tpl.nEntries == 0
return true
else
return false
Template.workspaceFlowData.events
'click .js-browse-datalist': (ev) ->
path = '/' + @repo.owner + '/' + @repo.name + '/files/datalist'
NogModal.start path, {
backref: FlowRouter.current().path
title: 'View-only mode'
viewOnly: true
}
'click .js-browse-add-files': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/', {
backref: FlowRouter.current().path
title: "Adding files to #{repoName}"
addingData: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click .js-browse-search': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/search', {
backref: FlowRouter.current().path
title: "Adding files to #{repoName}"
addingData: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click .js-upload': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
dat = Template.currentData()
refTreePath = 'master/datalist'
res = NogContent.resolveRefTreePath(dat.repo, refTreePath)
Modal.show 'nogFilesUploadModal', {
ownerName: res.repo.owner
repoName: res.repo.name
numericPath: res.numericPath
}
Template.workspaceFlowPrograms.onCreated ->
@selection = new ReactiveDict()
@nEntries = 0
@isSelected = (idx) =>
@selection.equals(idx, true)
@select = (idx) =>
@selection.set(idx, true)
@deselect = (idx) =>
@selection.set(idx, false)
@clearSelection = =>
for i in [0...@nEntries]
@deselect i
@selectOne = (idx) =>
@clearSelection()
@select idx
@getSelection = =>
s = []
for i in [0...@nEntries]
if @isSelected(i)
s.push i
s
@autorun =>
dat = Template.currentData()
if dat.programs
@nEntries = dat.programs?.entries.length ? 0
Template.workspaceFlowPrograms.helpers
programInfo: ->
tpl = Template.instance()
dat = Template.currentData()
progInfo = {}
if dat.programs
for p, idx in dat.programs.entries
if prog = NogContent.trees.findOne(p.sha1)
if tpl.isSelected(idx)
progInfo = {
program: prog
repo: dat.repo
commitId: dat.repo.refs['branches/master']
}
progInfo
numberOfPrograms: ->
dat = Template.currentData()
return dat.programs.entries.length
programList: ->
tpl = Template.instance()
dat = Template.currentData()
sel = tpl.getSelection()
if sel.length == 0
if Session.get("selectedProgram")?
tpl.selectOne(Session.get("selectedProgram"))
else
tpl.selectOne(0)
Session.set("selectedProgram", 0)
if dat.programs
progList = []
for e, idx in dat.programs.entries
if tree = NogContent.trees.findOne(e.sha1)
vString = ''
if prog = NogContent.trees.findOne(tree.entries[0].sha1)
vPatch = prog.meta['package']['frozen'][0]['patch']
vMinor = prog.meta['package']['frozen'][0]['minor']
vMajor = prog.meta['package']['frozen'][0]['major']
vString = '@' + vMajor + '.' + vMinor + '.' + vPatch
progList.push {
name: tree.name,
displayName: tree.name + vString
index: idx,
classSelected: if tpl.isSelected(idx) then 'info' else null
}
{
entries: progList
}
hasProgramList: ->
if Template.currentData().programs
return true
else
return false
Template.workspaceFlowPrograms.events
'click .js-browse-add-program': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/', {
backref: FlowRouter.current().path
title: "Adding program to #{repoName}"
addingPrograms: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click .js-browse-search-program': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/search', {
backref: FlowRouter.current().path
title: "Adding program to #{repoName}"
addingPrograms: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click tr': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.selectOne @index
Session.set("selectedProgram", @index)
Template.workspaceFlowProgramsSel.helpers
isValid: ->
dat = Template.currentData()
if !dat.program
return false
if !dat.program.meta.package
return false
if !dat.program.entries
return false
return true
name: ->
dat = Template.currentData()
name = ''
if dat.program?.name?
name = dat.program.name
return name
latestVersion: ->
dat = Template.currentData()
if dat.program.entries[0]
return NogContent.trees.findOne(dat.program.entries[0].sha1).name
resolvedParams: ->
dat = Template.currentData()
repo = dat.repo
refTreePath = 'master/programs/' + dat.program.name
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/params'
)
unless resolved?
return
# Redirect 'Save Parameter' back to here.
resolved.actionRedirect = routerPath 'workspace', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
resolvedRuntime: ->
dat = Template.currentData()
repo = dat.repo
refTreePath = 'master/programs/' + dat.program.name
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/runtime'
)
unless resolved?
return
# Redirect 'Save Runtime Setting' back to here.
resolved.actionRedirect = routerPath 'workspace', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
resolvedReadme: ->
dat = Template.currentData()
repo = dat.repo
refTreePath = 'master/programs/' + dat.program.name
NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/index!0/README.md'
)
mayRunProgram: -> mayModifyRepo @repo
versionString = (v) ->
if v.major?
"#{v.major}.#{v.minor}.#{v.patch}"
else if v.date?
v.date
else if v.sha1?
v.sha1
else
'unknown'
upstreamVersionsCache = new ReactiveDict
getLatestUpstreamVersion = (origin) ->
[ownerName, repoName] = origin.repoFullName.split('/')
unless (repo = NogContent.repos.findOne {owner: ownerName, name: repoName})?
return null
fixedOrigin = {
ownerName
repoName,
packageName: origin.name
commitId: repo.refs['branches/master']
}
cacheKey = EJSON.stringify fixedOrigin, {canonical: true}
ver = upstreamVersionsCache.get cacheKey
unless _.isUndefined(ver)
return ver
getVersion = (opts) ->
NogFlow.call.getPackageVersion opts, (err, res) ->
if err
console.log 'Failed to get version', opts, err
return
key = EJSON.stringify _.pick(
res, 'ownerName', 'repoName', 'packageName', 'commitId'
), {
canonical: true
}
upstreamVersionsCache.set key, res.version
getVersion {ownerName, repoName, packageName: origin.name}
return null
Template.workspaceFlowProgramsSelDeps.helpers
mayUpdateDep: ->
mayModifyRepo Template.parentData().repo
deps: ->
dat = Template.currentData()
if dat.program.entries[0]
if latest = NogContent.trees.findOne(dat.program.entries[0].sha1)
pkg = latest.meta.package
deps = {}
for d in pkg.dependencies
deps[d.name] = d
for f in pkg.frozen
version = versionString(f)
dep = {
name: f.name
version
sha1: f.sha1
}
if (origin = deps[f.name])?
upstream = getLatestUpstreamVersion origin
if upstream?
dep.upstreamVersion = versionString upstream
dep.upstreamSha1 = upstream.sha1
dep.isUpdateAvailable = (
dep.upstreamVersion? and version != dep.upstreamVersion
)
[ownerName, repoName] = origin.repoFullName.split('/')
dep.origin = {
ownerName
repoName
name: origin.repoFullName
href: '' +
'/' + origin.repoFullName +
'/files/programs/' + origin.name
}
dep
Template.workspaceFlowProgramsSelDepsUpdate.onCreated ->
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelDepsUpdate.helpers
action: -> Template.instance().action.get()
Template.workspaceFlowProgramsSelDepsUpdate.events
'click .js-update-dep': (ev) ->
ev.preventDefault()
tpl = Template.instance()
pdat = Template.parentData()
refTreePath = 'master/programs/' + pdat.program.name
resolved = NogContent.resolveRefTreePath pdat.repo, refTreePath
opts =
ownerName: pdat.repo.owner
repoName: pdat.repo.name
commitId: pdat.commitId
package:
numericPath: resolved.numericPath
dependency:
name: @name
oldSha1: @sha1
newSha1: @upstreamSha1
origin:
ownerName: @origin.ownerName
repoName: @origin.repoName
tpl.action.set 'Updating...'
NogFlow.call.updatePackageDependency opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
Template.workspaceFlowProgramsSelParams.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelParams.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
# This helper passes raw html to the template as a workaround for the known
# issue of Blaze wrongly rendering reactive contenteditables
# (https://github.com/Swavek/contenteditable). In our case this caused
# multiply rendered parts of string when pressing return and delete during
# parameter manipulation.
editable: ->
params = @last.content.meta.program.params
params = EJSON.stringify params, {indent: true, canonical: true}
params = escapeHtml params
'<pre class="js-params" contenteditable="true">' + params + '</pre>'
Template.workspaceFlowProgramsSelParams.events
'click .js-save-params': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-params').text()
try
params = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(params, @last.content.meta.program.params)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
params
}
tpl.action.set 'Saving...'
Session.set({'blockProgramRunButton': 'Saving'})
NogFlow.call.updateProgramParams opts, (err, res) =>
Session.set({'blockProgramRunButton': null})
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.workspaceFlowProgramsSelRuntime.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelRuntime.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
# This helper passes raw html to the template as a workaround as described in
# template 'workspaceFlowProgramsSelParams'.
editable: ->
runtime = @last.content.meta.program.runtime
runtime = EJSON.stringify runtime, {indent: true, canonical: true}
runtime = escapeHtml runtime
'<pre class="js-runtime" contenteditable="true">' + runtime + '</pre>'
Template.workspaceFlowProgramsSelRuntime.events
'click .js-save-runtime': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-runtime').text()
try
runtime = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(runtime, @last.content.meta.program.runtime)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
runtime
}
tpl.action.set 'Saving...'
NogFlow.call.updateProgramRuntime opts, (err, res) =>
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.workspaceFlowProgramsSelReadme.helpers
programName: ->
Template.parentData().program.name
Template.workspaceFlowProgramsSelRunButton.onCreated ->
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelRunButton.helpers
action: -> Template.instance().action.get()
blocked: -> Session.get('blockProgramRunButton')
Template.workspaceFlowProgramsSelRunButton.events
'click .js-run': (ev) ->
ev.preventDefault()
opts = {
ownerName: @repo.owner
repoName: @repo.name
commitId: @repo.refs['branches/master']
sha1: @program._id
}
tpl = Template.instance()
tpl.action.set 'Submitting Job...'
NogFlow.call.runProgram opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.workspaceFlowJobs.onCreated ->
Session.set("workspaceShowAllJobs", false)
@isDeleting = new ReactiveVar(false)
@jobIds = []
@jobEntries = {}
@resultJobIds = []
@autorun =>
@jobIds = []
@jobEntries = {}
@resultJobIds = []
dat = Template.currentData()
for entry in dat.tree.entries
if entry.type == 'tree'
if subtree = NogContent.trees.findOne(entry.sha1)
if iskindJobs subtree
for jobTree in subtree.entries
if jobTree.type == 'tree'
if jobEntry = NogContent.trees.findOne(jobTree.sha1)
if iskindJob jobEntry
if (jobId = jobEntry.meta?.job?.id)?
@jobIds.push(jobId)
@jobEntries[jobId] = jobEntry
else
if iskindResults subtree
for resultTree in subtree.entries
if resultTree.type == 'tree'
if resultEntry = NogContent.trees.findOne(resultTree.sha1)
if (jobId = resultEntry.meta?.jobResult?.jobId)?
@resultJobIds.push(jobId)
@subscribe 'jobStatus', @jobIds
Template.workspaceFlowJobs.helpers
jobs: ->
templateInstance = Template.instance()
NogExec.jobs.find {'data.jobId': {$in: Template.instance().jobIds}},
sort: {updated:-1},
transform: (item) =>
jobId = item.data.jobId
item.programName =
templateInstance.jobEntries[jobId]?.meta?.job?.program?.name
item
showJob: ->
if Session.equals('workspaceShowAllJobs', true)
return true
templateInstance = Template.instance()
switch @status
when 'running', 'ready' then return true
when 'failed', 'cancelled'
# Show only if job is most recent for the particular program.
return Template.workspaceFlowJobs.isMostRecentJobOfProgram(@, templateInstance.jobEntries)
when 'completed'
# Show if there is result with corresponding job id
# Show only if job is most recent for the particular program.
return (@data.jobId in templateInstance.resultJobIds) or
Template.workspaceFlowJobs.isMostRecentJobOfProgram(@, templateInstance.jobEntries)
else return false
showAllJobs: ->
Session.equals('workspaceShowAllJobs', true)
isDeleting: ->
Template.instance().isDeleting.get()
Template.workspaceFlowJobs.isMostRecentJobOfProgram = (job, jobEntries) ->
for k, entry of jobEntries
if entry.meta?.job?.program?.name is job.programName
if entry.meta?.job?.id?
otherJob = NogExec.jobs.findOne {'data.jobId': entry.meta.job.id}
if otherJob? and otherJob.updated > job.updated
return false
return true
Template.workspaceFlowJobs.events
'click .js-show-all-jobs-toggle': (ev) ->
ev.preventDefault()
currentValue = Session.get("workspaceShowAllJobs")
Session.set("workspaceShowAllJobs", !currentValue)
'click .js-delete-all-jobs': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
templateInstance = Template.instance()
dat = Template.currentData()
for entry,idx in dat.tree.entries
if entry.type == 'tree'
if subtree = NogContent.trees.findOne(entry.sha1)
if iskindJobs subtree
jobsTree = subtree
numericPath = [idx]
opts = {
ownerName: dat.repo.owner
repoName: dat.repo.name
numericPath: numericPath
commitId: dat.repo.refs['branches/master']
children: [0...jobsTree.entries.length]
}
templateInstance.isDeleting.set(true)
NogFiles.call.deleteChildren opts, (err, res) ->
templateInstance.isDeleting.set(false)
if err
return defaultErrorHandler err
Template.workspaceFlowJobInfo.helpers
progressPercent: ->
Math.round(@progress.percent)
jobInProgress: ->
@status == 'running'
jobId: ->
@data.jobId
lastUpdate: ->
moment(@updated).fromNow()
createdDate: ->
@created
statusClass: ->
switch @status
when 'completed' then 'text-success'
when 'failed' then 'text-danger'
when 'cancelled' then 'text-muted'
else null
reasonLines: ->
@reason.split('\n')
Template.workspaceFlowResults.onCreated ->
@selection = new ReactiveDict()
@nEntries = 0
@isSelected = (idx) =>
@selection.equals(idx, true)
@select = (idx) =>
@selection.set(idx, true)
@deselect = (idx) =>
@selection.set(idx, false)
@clearSelection = =>
for i in [0...@nEntries]
@deselect i
@selectOne = (idx) =>
@clearSelection()
@select idx
@getSelection = =>
s = []
for i in [0...@nEntries]
if @isSelected(i)
s.push i
s
@autorun =>
dat = Template.currentData()
if dat.results
@nEntries = dat.results?.entries.length ? 0
Template.workspaceFlowResults.helpers
resultsExists: ->
tpl = Template.instance()
hasResults = false
unless t = @results?.entries[tpl.getSelection()]
return
if res = NogContent.trees.findOne(t.sha1)
hasResult = true
hasResult
resultsList: ->
tpl = Template.instance()
dat = Template.currentData()
sel = tpl.getSelection()
if sel.length == 0
if Session.get("selectedResult")?
tpl.selectOne(Session.get("selectedResult"))
else
tpl.selectOne(0)
Session.set("selectedResult", 0)
if dat.results
resList = []
for e, idx in dat.results.entries
tree = NogContent.trees.findOne(e.sha1)
vString = ''
if tree.meta['programVersion']
vString = tree.meta['programVersion']
resList.push {
name: tree.name
displayName: tree.name + vString
index: idx,
classSelected: if tpl.isSelected(idx) then 'info' else null
}
{
entries: resList
}
resultSet: ->
dat = Template.currentData()
tpl = Template.instance()
idx = tpl.getSelection()
unless t = dat.results?.entries[idx]
return
children = []
varList = []
if res = NogContent.trees.findOne(t.sha1)
resName = res.name
repo = dat.repo
resPath = 'master/results/' + resName
varList.push {
description: res.meta.description
path: resPath
}
for v, idx in res.entries
if v.type == 'tree'
if variant = NogContent.trees.findOne(v.sha1)
varList.push {
description: variant.meta.description
path: resPath + '/' + variant.name
}
id = 0
for item in varList
for p in ['index.md', 'README.md', 'summary.md', 'report.md']
treePath = item.path + '/' + p
if (child = NogContent.resolveRefTreePath repo, treePath)?
children.push {
name: item.path.split('/').reverse()[0]
child: child
description: item.description
id: id
}
id = id + 1
return {
children: children,
isSingleResult: children.length is 1
}
Template.workspaceFlowResults.events
'click .js-browse-results': (ev) ->
ev.preventDefault()
tpl = Template.instance()
t = @results.entries[tpl.getSelection()]
res = NogContent.trees.findOne(t.sha1)
path = '/' + @repo.owner + '/' + @repo.name + '/files/results/' + res.name
NogModal.start path, {
backref: FlowRouter.current().path
title: 'View-only mode'
viewOnly: true
}
'click tr': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.selectOne @index
Session.set("selectedResult", @index)
| 223576 | {defaultErrorHandler} = NogError
{escapeHtml} = NogFmt
{ NogFlow } = share
WorkspaceContent = new Mongo.Collection('workspaceContent')
routerPath = (route, opts) ->
href = FlowRouter.path route, opts
href = href.replace /%2F/g, '/'
href
iskind = (entry, kind) -> _.isObject(entry.meta[kind])
iskindDatalist = (tree) -> iskind tree, 'datalist'
iskindResults = (tree) -> iskind tree, 'results'
iskindPrograms = (tree) -> iskind tree, 'programs'
iskindJob = (tree) -> iskind tree, 'job'
iskindJobs = (tree) -> iskind tree, 'jobs'
iskindResults = (tree) -> iskind tree, 'results'
iskindPackage = (tree) -> iskind tree, 'package'
iskindWorkspace = (tree) -> iskind tree, 'workspace'
iskindProgramRegistry = (tree) -> iskind tree, 'programRegistry'
iskindCatalog = (tree) -> iskind tree, 'catalog'
mayModifyRepo = (repo) ->
aopts = {ownerName: repo.owner, repoName: repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
# Provide a file scope function to reset the stable commit from anywhere until
# we have a better solution. A possible solution would be to put the stable
# commit into the query part of the URL. We rely on the URL for hrefs anyway.
# There can only be a single instance of treeContent at a time. So we can
# simply use the global state directly.
treeContentInstance = null
clearStable = ->
unless treeContentInstance
return
treeContentInstance.commitId.set null
updateContent = (updated) ->
if updated
return NogContent.repos.findOne({owner: ownerName, name: repoName},
{reactive: false})
Template.workspace.helpers
ownerName: -> FlowRouter.getParam('ownerName')
repoName: -> FlowRouter.getParam('repoName')
Template.workspaceContent.onCreated ->
@repo = ReactiveVar()
@counter = 0
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
if (repo = NogContent.repos.findOne({owner: ownerName, name: repoName}))?
repoId = repo._id
NogRepoSettings.call.addToRecentRepos {repoId}, (err, res) ->
if err
return defaultErrorHandler err
@autorun =>
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
sub = @subscribe 'workspaceContent', {ownerName, repoName}
if sub.ready()
token = WorkspaceContent.findOne(sub.subscriptionId)
unless @counter == token.updates
@counter = token.updates
@repo.set(NogContent.repos.findOne({owner: ownerName, name: repoName},
{reactive: false}))
Template.workspaceContent.helpers
ownerName: -> FlowRouter.getParam('ownerName')
repoName: -> FlowRouter.getParam('repoName')
viewerInfo: ->
if (repo = Template.instance().repo.get())?
if (commit = NogContent.commits.findOne(repo.refs['branches/master']))?
if (tree = NogContent.trees.findOne(commit.tree))?
{
fullName: repo.fullName
type: 'tree'
treePath: ''
iskindWorkspace: iskindWorkspace(tree)
currentIsWorkspace: true
iskindCatalog: iskindCatalog(tree)
}
repoContext: ->
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
tpl = Template.instance()
{
repo: tpl.repo.get()
}
Template.workspaceRepoMasterContent.helpers
datalistInfos: ->
dat = Template.currentData()
commitId = dat.repo.refs['branches/master']
if commit = NogContent.commits.findOne(commitId)
if tree = NogContent.trees.findOne(commit.tree)
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if iskindDatalist subtree
datalist = subtree
return {
repo: dat.repo
datalist: datalist
}
programsInfos: ->
dat = Template.currentData()
commitId = dat.repo.refs['branches/master']
if commit = NogContent.commits.findOne(commitId)
if tree = NogContent.trees.findOne(commit.tree)
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if iskindPrograms subtree
programs = subtree
return {
repo: dat.repo
programs: programs
}
jobsInfos: ->
dat = Template.currentData()
commitId = dat.repo.refs['branches/master']
if commit = NogContent.commits.findOne(commitId)
if tree = NogContent.trees.findOne commit.tree
{
repo: @repo
tree: tree
}
resultsInfos: ->
if commit = NogContent.commits.findOne @repo.refs['branches/master']
if tree = NogContent.trees.findOne commit.tree
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if iskindResults subtree
results = subtree
{
repo: @repo
results: results
}
oldWorkspaceVersion: ->
if commit = NogContent.commits.findOne @repo.refs['branches/master']
if tree = NogContent.trees.findOne commit.tree
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if subtree.name == 'results' and not iskindResults subtree
return true
errata: ->
unless (commit = NogContent.commits.findOne @repo.refs['branches/master'])?
return null
unless (tree = NogContent.trees.findOne(commit.tree))?
return null
return tree.errata
isWorkspace: ->
if commit = NogContent.commits.findOne @repo.refs['branches/master']
if tree = NogContent.trees.findOne commit.tree
if iskindWorkspace tree
return true
Template.workspaceFlowData.onCreated ->
@fileLimit = 10
@nEntries = 0
dat = Template.currentData()
@filesPath = '/' + dat.repo.owner + '/' + dat.repo.name + '/files/datalist'
@autorun =>
if Template.currentData().datalist
@nEntries = Template.currentData().datalist.entries.length
Template.workspaceFlowData.helpers
mayModify: -> mayModifyRepo @repo
hasDatalist: ->
dat = Template.currentData()
if dat.datalist
return true
else
return false
numberOfDataEntries: ->
Template.instance().nEntries
selectedFiles: ->
tpl = Template.instance()
dat = Template.currentData()
count = 0
for e, idx in dat.datalist.entries
if count >= tpl.fileLimit
break
switch e.type
when 'object'
entry = NogContent.objects.findOne(e.sha1)
icon = 'file-o'
name = entry.name
when 'tree'
entry = NogContent.trees.findOne(e.sha1)
icon = 'folder'
name = entry.name
if entry
count += 1
{
icon
name
}
path: ->
tpl = Template.instance()
return tpl.filesPath
hasMoreFiles: ->
tpl = Template.instance()
if tpl.nEntries <= tpl.fileLimit
return false
else
return true
numberofShownFiles: ->
tpl = Template.instance()
if tpl.nEntries <= tpl.fileLimit
return tpl.nEntries
else
return tpl.fileLimit
emptyDatalist: ->
tpl = Template.instance()
if tpl.nEntries == 0
return true
else
return false
Template.workspaceFlowData.events
'click .js-browse-datalist': (ev) ->
path = '/' + @repo.owner + '/' + @repo.name + '/files/datalist'
NogModal.start path, {
backref: FlowRouter.current().path
title: 'View-only mode'
viewOnly: true
}
'click .js-browse-add-files': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/', {
backref: FlowRouter.current().path
title: "Adding files to #{repoName}"
addingData: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click .js-browse-search': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/search', {
backref: FlowRouter.current().path
title: "Adding files to #{repoName}"
addingData: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click .js-upload': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
dat = Template.currentData()
refTreePath = 'master/datalist'
res = NogContent.resolveRefTreePath(dat.repo, refTreePath)
Modal.show 'nogFilesUploadModal', {
ownerName: res.repo.owner
repoName: res.repo.name
numericPath: res.numericPath
}
Template.workspaceFlowPrograms.onCreated ->
@selection = new ReactiveDict()
@nEntries = 0
@isSelected = (idx) =>
@selection.equals(idx, true)
@select = (idx) =>
@selection.set(idx, true)
@deselect = (idx) =>
@selection.set(idx, false)
@clearSelection = =>
for i in [0...@nEntries]
@deselect i
@selectOne = (idx) =>
@clearSelection()
@select idx
@getSelection = =>
s = []
for i in [0...@nEntries]
if @isSelected(i)
s.push i
s
@autorun =>
dat = Template.currentData()
if dat.programs
@nEntries = dat.programs?.entries.length ? 0
Template.workspaceFlowPrograms.helpers
programInfo: ->
tpl = Template.instance()
dat = Template.currentData()
progInfo = {}
if dat.programs
for p, idx in dat.programs.entries
if prog = NogContent.trees.findOne(p.sha1)
if tpl.isSelected(idx)
progInfo = {
program: prog
repo: dat.repo
commitId: dat.repo.refs['branches/master']
}
progInfo
numberOfPrograms: ->
dat = Template.currentData()
return dat.programs.entries.length
programList: ->
tpl = Template.instance()
dat = Template.currentData()
sel = tpl.getSelection()
if sel.length == 0
if Session.get("selectedProgram")?
tpl.selectOne(Session.get("selectedProgram"))
else
tpl.selectOne(0)
Session.set("selectedProgram", 0)
if dat.programs
progList = []
for e, idx in dat.programs.entries
if tree = NogContent.trees.findOne(e.sha1)
vString = ''
if prog = NogContent.trees.findOne(tree.entries[0].sha1)
vPatch = prog.meta['package']['frozen'][0]['patch']
vMinor = prog.meta['package']['frozen'][0]['minor']
vMajor = prog.meta['package']['frozen'][0]['major']
vString = '@' + vMajor + '.' + vMinor + '.' + vPatch
progList.push {
name: tree.name,
displayName: tree.name + vString
index: idx,
classSelected: if tpl.isSelected(idx) then 'info' else null
}
{
entries: progList
}
hasProgramList: ->
if Template.currentData().programs
return true
else
return false
Template.workspaceFlowPrograms.events
'click .js-browse-add-program': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/', {
backref: FlowRouter.current().path
title: "Adding program to #{repoName}"
addingPrograms: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click .js-browse-search-program': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/search', {
backref: FlowRouter.current().path
title: "Adding program to #{repoName}"
addingPrograms: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click tr': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.selectOne @index
Session.set("selectedProgram", @index)
Template.workspaceFlowProgramsSel.helpers
isValid: ->
dat = Template.currentData()
if !dat.program
return false
if !dat.program.meta.package
return false
if !dat.program.entries
return false
return true
name: ->
dat = Template.currentData()
name = ''
if dat.program?.name?
name = dat.program.name
return name
latestVersion: ->
dat = Template.currentData()
if dat.program.entries[0]
return NogContent.trees.findOne(dat.program.entries[0].sha1).name
resolvedParams: ->
dat = Template.currentData()
repo = dat.repo
refTreePath = 'master/programs/' + dat.program.name
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/params'
)
unless resolved?
return
# Redirect 'Save Parameter' back to here.
resolved.actionRedirect = routerPath 'workspace', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
resolvedRuntime: ->
dat = Template.currentData()
repo = dat.repo
refTreePath = 'master/programs/' + dat.program.name
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/runtime'
)
unless resolved?
return
# Redirect 'Save Runtime Setting' back to here.
resolved.actionRedirect = routerPath 'workspace', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
resolvedReadme: ->
dat = Template.currentData()
repo = dat.repo
refTreePath = 'master/programs/' + dat.program.name
NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/index!0/README.md'
)
mayRunProgram: -> mayModifyRepo @repo
versionString = (v) ->
if v.major?
"#{v.major}.#{v.minor}.#{v.patch}"
else if v.date?
v.date
else if v.sha1?
v.sha1
else
'unknown'
upstreamVersionsCache = new ReactiveDict
getLatestUpstreamVersion = (origin) ->
[ownerName, repoName] = origin.repoFullName.split('/')
unless (repo = NogContent.repos.findOne {owner: ownerName, name: repoName})?
return null
fixedOrigin = {
ownerName
repoName,
packageName: origin.name
commitId: repo.refs['branches/master']
}
cacheKey = EJSON.stringify fixedOrigin, {canonical: true}
ver = upstreamVersionsCache.get cacheKey
unless _.isUndefined(ver)
return ver
getVersion = (opts) ->
NogFlow.call.getPackageVersion opts, (err, res) ->
if err
console.log 'Failed to get version', opts, err
return
key = E<KEY>.stringify _.pick(
res, 'ownerName', 'repoName', 'packageName', 'commitId'
), {
canonical: true
}
upstreamVersionsCache.set key, res.version
getVersion {ownerName, repoName, packageName: origin.name}
return null
Template.workspaceFlowProgramsSelDeps.helpers
mayUpdateDep: ->
mayModifyRepo Template.parentData().repo
deps: ->
dat = Template.currentData()
if dat.program.entries[0]
if latest = NogContent.trees.findOne(dat.program.entries[0].sha1)
pkg = latest.meta.package
deps = {}
for d in pkg.dependencies
deps[d.name] = d
for f in pkg.frozen
version = versionString(f)
dep = {
name: f.name
version
sha1: f.sha1
}
if (origin = deps[f.name])?
upstream = getLatestUpstreamVersion origin
if upstream?
dep.upstreamVersion = versionString upstream
dep.upstreamSha1 = upstream.sha1
dep.isUpdateAvailable = (
dep.upstreamVersion? and version != dep.upstreamVersion
)
[ownerName, repoName] = origin.repoFullName.split('/')
dep.origin = {
ownerName
repoName
name: origin.repoFullName
href: '' +
'/' + origin.repoFullName +
'/files/programs/' + origin.name
}
dep
Template.workspaceFlowProgramsSelDepsUpdate.onCreated ->
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelDepsUpdate.helpers
action: -> Template.instance().action.get()
Template.workspaceFlowProgramsSelDepsUpdate.events
'click .js-update-dep': (ev) ->
ev.preventDefault()
tpl = Template.instance()
pdat = Template.parentData()
refTreePath = 'master/programs/' + pdat.program.name
resolved = NogContent.resolveRefTreePath pdat.repo, refTreePath
opts =
ownerName: pdat.repo.owner
repoName: pdat.repo.name
commitId: pdat.commitId
package:
numericPath: resolved.numericPath
dependency:
name: @name
oldSha1: @sha1
newSha1: @upstreamSha1
origin:
ownerName: @origin.ownerName
repoName: @origin.repoName
tpl.action.set 'Updating...'
NogFlow.call.updatePackageDependency opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
Template.workspaceFlowProgramsSelParams.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelParams.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
# This helper passes raw html to the template as a workaround for the known
# issue of Blaze wrongly rendering reactive contenteditables
# (https://github.com/Swavek/contenteditable). In our case this caused
# multiply rendered parts of string when pressing return and delete during
# parameter manipulation.
editable: ->
params = @last.content.meta.program.params
params = EJSON.stringify params, {indent: true, canonical: true}
params = escapeHtml params
'<pre class="js-params" contenteditable="true">' + params + '</pre>'
Template.workspaceFlowProgramsSelParams.events
'click .js-save-params': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-params').text()
try
params = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(params, @last.content.meta.program.params)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
params
}
tpl.action.set 'Saving...'
Session.set({'blockProgramRunButton': 'Saving'})
NogFlow.call.updateProgramParams opts, (err, res) =>
Session.set({'blockProgramRunButton': null})
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.workspaceFlowProgramsSelRuntime.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelRuntime.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
# This helper passes raw html to the template as a workaround as described in
# template 'workspaceFlowProgramsSelParams'.
editable: ->
runtime = @last.content.meta.program.runtime
runtime = EJSON.stringify runtime, {indent: true, canonical: true}
runtime = escapeHtml runtime
'<pre class="js-runtime" contenteditable="true">' + runtime + '</pre>'
Template.workspaceFlowProgramsSelRuntime.events
'click .js-save-runtime': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-runtime').text()
try
runtime = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(runtime, @last.content.meta.program.runtime)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
runtime
}
tpl.action.set 'Saving...'
NogFlow.call.updateProgramRuntime opts, (err, res) =>
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.workspaceFlowProgramsSelReadme.helpers
programName: ->
Template.parentData().program.name
Template.workspaceFlowProgramsSelRunButton.onCreated ->
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelRunButton.helpers
action: -> Template.instance().action.get()
blocked: -> Session.get('blockProgramRunButton')
Template.workspaceFlowProgramsSelRunButton.events
'click .js-run': (ev) ->
ev.preventDefault()
opts = {
ownerName: @repo.owner
repoName: @repo.name
commitId: @repo.refs['branches/master']
sha1: @program._id
}
tpl = Template.instance()
tpl.action.set 'Submitting Job...'
NogFlow.call.runProgram opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.workspaceFlowJobs.onCreated ->
Session.set("workspaceShowAllJobs", false)
@isDeleting = new ReactiveVar(false)
@jobIds = []
@jobEntries = {}
@resultJobIds = []
@autorun =>
@jobIds = []
@jobEntries = {}
@resultJobIds = []
dat = Template.currentData()
for entry in dat.tree.entries
if entry.type == 'tree'
if subtree = NogContent.trees.findOne(entry.sha1)
if iskindJobs subtree
for jobTree in subtree.entries
if jobTree.type == 'tree'
if jobEntry = NogContent.trees.findOne(jobTree.sha1)
if iskindJob jobEntry
if (jobId = jobEntry.meta?.job?.id)?
@jobIds.push(jobId)
@jobEntries[jobId] = jobEntry
else
if iskindResults subtree
for resultTree in subtree.entries
if resultTree.type == 'tree'
if resultEntry = NogContent.trees.findOne(resultTree.sha1)
if (jobId = resultEntry.meta?.jobResult?.jobId)?
@resultJobIds.push(jobId)
@subscribe 'jobStatus', @jobIds
Template.workspaceFlowJobs.helpers
jobs: ->
templateInstance = Template.instance()
NogExec.jobs.find {'data.jobId': {$in: Template.instance().jobIds}},
sort: {updated:-1},
transform: (item) =>
jobId = item.data.jobId
item.programName =
templateInstance.jobEntries[jobId]?.meta?.job?.program?.name
item
showJob: ->
if Session.equals('workspaceShowAllJobs', true)
return true
templateInstance = Template.instance()
switch @status
when 'running', 'ready' then return true
when 'failed', 'cancelled'
# Show only if job is most recent for the particular program.
return Template.workspaceFlowJobs.isMostRecentJobOfProgram(@, templateInstance.jobEntries)
when 'completed'
# Show if there is result with corresponding job id
# Show only if job is most recent for the particular program.
return (@data.jobId in templateInstance.resultJobIds) or
Template.workspaceFlowJobs.isMostRecentJobOfProgram(@, templateInstance.jobEntries)
else return false
showAllJobs: ->
Session.equals('workspaceShowAllJobs', true)
isDeleting: ->
Template.instance().isDeleting.get()
Template.workspaceFlowJobs.isMostRecentJobOfProgram = (job, jobEntries) ->
for k, entry of jobEntries
if entry.meta?.job?.program?.name is job.programName
if entry.meta?.job?.id?
otherJob = NogExec.jobs.findOne {'data.jobId': entry.meta.job.id}
if otherJob? and otherJob.updated > job.updated
return false
return true
Template.workspaceFlowJobs.events
'click .js-show-all-jobs-toggle': (ev) ->
ev.preventDefault()
currentValue = Session.get("workspaceShowAllJobs")
Session.set("workspaceShowAllJobs", !currentValue)
'click .js-delete-all-jobs': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
templateInstance = Template.instance()
dat = Template.currentData()
for entry,idx in dat.tree.entries
if entry.type == 'tree'
if subtree = NogContent.trees.findOne(entry.sha1)
if iskindJobs subtree
jobsTree = subtree
numericPath = [idx]
opts = {
ownerName: dat.repo.owner
repoName: dat.repo.name
numericPath: numericPath
commitId: dat.repo.refs['branches/master']
children: [0...jobsTree.entries.length]
}
templateInstance.isDeleting.set(true)
NogFiles.call.deleteChildren opts, (err, res) ->
templateInstance.isDeleting.set(false)
if err
return defaultErrorHandler err
Template.workspaceFlowJobInfo.helpers
progressPercent: ->
Math.round(@progress.percent)
jobInProgress: ->
@status == 'running'
jobId: ->
@data.jobId
lastUpdate: ->
moment(@updated).fromNow()
createdDate: ->
@created
statusClass: ->
switch @status
when 'completed' then 'text-success'
when 'failed' then 'text-danger'
when 'cancelled' then 'text-muted'
else null
reasonLines: ->
@reason.split('\n')
Template.workspaceFlowResults.onCreated ->
@selection = new ReactiveDict()
@nEntries = 0
@isSelected = (idx) =>
@selection.equals(idx, true)
@select = (idx) =>
@selection.set(idx, true)
@deselect = (idx) =>
@selection.set(idx, false)
@clearSelection = =>
for i in [0...@nEntries]
@deselect i
@selectOne = (idx) =>
@clearSelection()
@select idx
@getSelection = =>
s = []
for i in [0...@nEntries]
if @isSelected(i)
s.push i
s
@autorun =>
dat = Template.currentData()
if dat.results
@nEntries = dat.results?.entries.length ? 0
Template.workspaceFlowResults.helpers
resultsExists: ->
tpl = Template.instance()
hasResults = false
unless t = @results?.entries[tpl.getSelection()]
return
if res = NogContent.trees.findOne(t.sha1)
hasResult = true
hasResult
resultsList: ->
tpl = Template.instance()
dat = Template.currentData()
sel = tpl.getSelection()
if sel.length == 0
if Session.get("selectedResult")?
tpl.selectOne(Session.get("selectedResult"))
else
tpl.selectOne(0)
Session.set("selectedResult", 0)
if dat.results
resList = []
for e, idx in dat.results.entries
tree = NogContent.trees.findOne(e.sha1)
vString = ''
if tree.meta['programVersion']
vString = tree.meta['programVersion']
resList.push {
name: tree.name
displayName: tree.name + vString
index: idx,
classSelected: if tpl.isSelected(idx) then 'info' else null
}
{
entries: resList
}
resultSet: ->
dat = Template.currentData()
tpl = Template.instance()
idx = tpl.getSelection()
unless t = dat.results?.entries[idx]
return
children = []
varList = []
if res = NogContent.trees.findOne(t.sha1)
resName = res.name
repo = dat.repo
resPath = 'master/results/' + resName
varList.push {
description: res.meta.description
path: resPath
}
for v, idx in res.entries
if v.type == 'tree'
if variant = NogContent.trees.findOne(v.sha1)
varList.push {
description: variant.meta.description
path: resPath + '/' + variant.name
}
id = 0
for item in varList
for p in ['index.md', 'README.md', 'summary.md', 'report.md']
treePath = item.path + '/' + p
if (child = NogContent.resolveRefTreePath repo, treePath)?
children.push {
name: item.path.split('/').reverse()[0]
child: child
description: item.description
id: id
}
id = id + 1
return {
children: children,
isSingleResult: children.length is 1
}
Template.workspaceFlowResults.events
'click .js-browse-results': (ev) ->
ev.preventDefault()
tpl = Template.instance()
t = @results.entries[tpl.getSelection()]
res = NogContent.trees.findOne(t.sha1)
path = '/' + @repo.owner + '/' + @repo.name + '/files/results/' + res.name
NogModal.start path, {
backref: FlowRouter.current().path
title: 'View-only mode'
viewOnly: true
}
'click tr': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.selectOne @index
Session.set("selectedResult", @index)
| true | {defaultErrorHandler} = NogError
{escapeHtml} = NogFmt
{ NogFlow } = share
WorkspaceContent = new Mongo.Collection('workspaceContent')
routerPath = (route, opts) ->
href = FlowRouter.path route, opts
href = href.replace /%2F/g, '/'
href
iskind = (entry, kind) -> _.isObject(entry.meta[kind])
iskindDatalist = (tree) -> iskind tree, 'datalist'
iskindResults = (tree) -> iskind tree, 'results'
iskindPrograms = (tree) -> iskind tree, 'programs'
iskindJob = (tree) -> iskind tree, 'job'
iskindJobs = (tree) -> iskind tree, 'jobs'
iskindResults = (tree) -> iskind tree, 'results'
iskindPackage = (tree) -> iskind tree, 'package'
iskindWorkspace = (tree) -> iskind tree, 'workspace'
iskindProgramRegistry = (tree) -> iskind tree, 'programRegistry'
iskindCatalog = (tree) -> iskind tree, 'catalog'
mayModifyRepo = (repo) ->
aopts = {ownerName: repo.owner, repoName: repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
# Provide a file scope function to reset the stable commit from anywhere until
# we have a better solution. A possible solution would be to put the stable
# commit into the query part of the URL. We rely on the URL for hrefs anyway.
# There can only be a single instance of treeContent at a time. So we can
# simply use the global state directly.
treeContentInstance = null
clearStable = ->
unless treeContentInstance
return
treeContentInstance.commitId.set null
updateContent = (updated) ->
if updated
return NogContent.repos.findOne({owner: ownerName, name: repoName},
{reactive: false})
Template.workspace.helpers
ownerName: -> FlowRouter.getParam('ownerName')
repoName: -> FlowRouter.getParam('repoName')
Template.workspaceContent.onCreated ->
@repo = ReactiveVar()
@counter = 0
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
if (repo = NogContent.repos.findOne({owner: ownerName, name: repoName}))?
repoId = repo._id
NogRepoSettings.call.addToRecentRepos {repoId}, (err, res) ->
if err
return defaultErrorHandler err
@autorun =>
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
sub = @subscribe 'workspaceContent', {ownerName, repoName}
if sub.ready()
token = WorkspaceContent.findOne(sub.subscriptionId)
unless @counter == token.updates
@counter = token.updates
@repo.set(NogContent.repos.findOne({owner: ownerName, name: repoName},
{reactive: false}))
Template.workspaceContent.helpers
ownerName: -> FlowRouter.getParam('ownerName')
repoName: -> FlowRouter.getParam('repoName')
viewerInfo: ->
if (repo = Template.instance().repo.get())?
if (commit = NogContent.commits.findOne(repo.refs['branches/master']))?
if (tree = NogContent.trees.findOne(commit.tree))?
{
fullName: repo.fullName
type: 'tree'
treePath: ''
iskindWorkspace: iskindWorkspace(tree)
currentIsWorkspace: true
iskindCatalog: iskindCatalog(tree)
}
repoContext: ->
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
tpl = Template.instance()
{
repo: tpl.repo.get()
}
Template.workspaceRepoMasterContent.helpers
datalistInfos: ->
dat = Template.currentData()
commitId = dat.repo.refs['branches/master']
if commit = NogContent.commits.findOne(commitId)
if tree = NogContent.trees.findOne(commit.tree)
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if iskindDatalist subtree
datalist = subtree
return {
repo: dat.repo
datalist: datalist
}
programsInfos: ->
dat = Template.currentData()
commitId = dat.repo.refs['branches/master']
if commit = NogContent.commits.findOne(commitId)
if tree = NogContent.trees.findOne(commit.tree)
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if iskindPrograms subtree
programs = subtree
return {
repo: dat.repo
programs: programs
}
jobsInfos: ->
dat = Template.currentData()
commitId = dat.repo.refs['branches/master']
if commit = NogContent.commits.findOne(commitId)
if tree = NogContent.trees.findOne commit.tree
{
repo: @repo
tree: tree
}
resultsInfos: ->
if commit = NogContent.commits.findOne @repo.refs['branches/master']
if tree = NogContent.trees.findOne commit.tree
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if iskindResults subtree
results = subtree
{
repo: @repo
results: results
}
oldWorkspaceVersion: ->
if commit = NogContent.commits.findOne @repo.refs['branches/master']
if tree = NogContent.trees.findOne commit.tree
for e, idx in tree.entries
if e.type == 'tree'
if subtree = NogContent.trees.findOne(e.sha1)
if subtree.name == 'results' and not iskindResults subtree
return true
errata: ->
unless (commit = NogContent.commits.findOne @repo.refs['branches/master'])?
return null
unless (tree = NogContent.trees.findOne(commit.tree))?
return null
return tree.errata
isWorkspace: ->
if commit = NogContent.commits.findOne @repo.refs['branches/master']
if tree = NogContent.trees.findOne commit.tree
if iskindWorkspace tree
return true
Template.workspaceFlowData.onCreated ->
@fileLimit = 10
@nEntries = 0
dat = Template.currentData()
@filesPath = '/' + dat.repo.owner + '/' + dat.repo.name + '/files/datalist'
@autorun =>
if Template.currentData().datalist
@nEntries = Template.currentData().datalist.entries.length
Template.workspaceFlowData.helpers
mayModify: -> mayModifyRepo @repo
hasDatalist: ->
dat = Template.currentData()
if dat.datalist
return true
else
return false
numberOfDataEntries: ->
Template.instance().nEntries
selectedFiles: ->
tpl = Template.instance()
dat = Template.currentData()
count = 0
for e, idx in dat.datalist.entries
if count >= tpl.fileLimit
break
switch e.type
when 'object'
entry = NogContent.objects.findOne(e.sha1)
icon = 'file-o'
name = entry.name
when 'tree'
entry = NogContent.trees.findOne(e.sha1)
icon = 'folder'
name = entry.name
if entry
count += 1
{
icon
name
}
path: ->
tpl = Template.instance()
return tpl.filesPath
hasMoreFiles: ->
tpl = Template.instance()
if tpl.nEntries <= tpl.fileLimit
return false
else
return true
numberofShownFiles: ->
tpl = Template.instance()
if tpl.nEntries <= tpl.fileLimit
return tpl.nEntries
else
return tpl.fileLimit
emptyDatalist: ->
tpl = Template.instance()
if tpl.nEntries == 0
return true
else
return false
Template.workspaceFlowData.events
'click .js-browse-datalist': (ev) ->
path = '/' + @repo.owner + '/' + @repo.name + '/files/datalist'
NogModal.start path, {
backref: FlowRouter.current().path
title: 'View-only mode'
viewOnly: true
}
'click .js-browse-add-files': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/', {
backref: FlowRouter.current().path
title: "Adding files to #{repoName}"
addingData: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click .js-browse-search': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/search', {
backref: FlowRouter.current().path
title: "Adding files to #{repoName}"
addingData: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click .js-upload': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
dat = Template.currentData()
refTreePath = 'master/datalist'
res = NogContent.resolveRefTreePath(dat.repo, refTreePath)
Modal.show 'nogFilesUploadModal', {
ownerName: res.repo.owner
repoName: res.repo.name
numericPath: res.numericPath
}
Template.workspaceFlowPrograms.onCreated ->
@selection = new ReactiveDict()
@nEntries = 0
@isSelected = (idx) =>
@selection.equals(idx, true)
@select = (idx) =>
@selection.set(idx, true)
@deselect = (idx) =>
@selection.set(idx, false)
@clearSelection = =>
for i in [0...@nEntries]
@deselect i
@selectOne = (idx) =>
@clearSelection()
@select idx
@getSelection = =>
s = []
for i in [0...@nEntries]
if @isSelected(i)
s.push i
s
@autorun =>
dat = Template.currentData()
if dat.programs
@nEntries = dat.programs?.entries.length ? 0
Template.workspaceFlowPrograms.helpers
programInfo: ->
tpl = Template.instance()
dat = Template.currentData()
progInfo = {}
if dat.programs
for p, idx in dat.programs.entries
if prog = NogContent.trees.findOne(p.sha1)
if tpl.isSelected(idx)
progInfo = {
program: prog
repo: dat.repo
commitId: dat.repo.refs['branches/master']
}
progInfo
numberOfPrograms: ->
dat = Template.currentData()
return dat.programs.entries.length
programList: ->
tpl = Template.instance()
dat = Template.currentData()
sel = tpl.getSelection()
if sel.length == 0
if Session.get("selectedProgram")?
tpl.selectOne(Session.get("selectedProgram"))
else
tpl.selectOne(0)
Session.set("selectedProgram", 0)
if dat.programs
progList = []
for e, idx in dat.programs.entries
if tree = NogContent.trees.findOne(e.sha1)
vString = ''
if prog = NogContent.trees.findOne(tree.entries[0].sha1)
vPatch = prog.meta['package']['frozen'][0]['patch']
vMinor = prog.meta['package']['frozen'][0]['minor']
vMajor = prog.meta['package']['frozen'][0]['major']
vString = '@' + vMajor + '.' + vMinor + '.' + vPatch
progList.push {
name: tree.name,
displayName: tree.name + vString
index: idx,
classSelected: if tpl.isSelected(idx) then 'info' else null
}
{
entries: progList
}
hasProgramList: ->
if Template.currentData().programs
return true
else
return false
Template.workspaceFlowPrograms.events
'click .js-browse-add-program': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/', {
backref: FlowRouter.current().path
title: "Adding program to #{repoName}"
addingPrograms: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click .js-browse-search-program': (ev) ->
repoName = @repo.owner + '/' + @repo.name
NogModal.start '/search', {
backref: FlowRouter.current().path
title: "Adding program to #{repoName}"
addingPrograms: true
targetRepo: {owner: @repo.owner, name: @repo.name, repo: @repo}
}
'click tr': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.selectOne @index
Session.set("selectedProgram", @index)
Template.workspaceFlowProgramsSel.helpers
isValid: ->
dat = Template.currentData()
if !dat.program
return false
if !dat.program.meta.package
return false
if !dat.program.entries
return false
return true
name: ->
dat = Template.currentData()
name = ''
if dat.program?.name?
name = dat.program.name
return name
latestVersion: ->
dat = Template.currentData()
if dat.program.entries[0]
return NogContent.trees.findOne(dat.program.entries[0].sha1).name
resolvedParams: ->
dat = Template.currentData()
repo = dat.repo
refTreePath = 'master/programs/' + dat.program.name
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/params'
)
unless resolved?
return
# Redirect 'Save Parameter' back to here.
resolved.actionRedirect = routerPath 'workspace', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
resolvedRuntime: ->
dat = Template.currentData()
repo = dat.repo
refTreePath = 'master/programs/' + dat.program.name
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/runtime'
)
unless resolved?
return
# Redirect 'Save Runtime Setting' back to here.
resolved.actionRedirect = routerPath 'workspace', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
resolvedReadme: ->
dat = Template.currentData()
repo = dat.repo
refTreePath = 'master/programs/' + dat.program.name
NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/index!0/README.md'
)
mayRunProgram: -> mayModifyRepo @repo
versionString = (v) ->
if v.major?
"#{v.major}.#{v.minor}.#{v.patch}"
else if v.date?
v.date
else if v.sha1?
v.sha1
else
'unknown'
upstreamVersionsCache = new ReactiveDict
getLatestUpstreamVersion = (origin) ->
[ownerName, repoName] = origin.repoFullName.split('/')
unless (repo = NogContent.repos.findOne {owner: ownerName, name: repoName})?
return null
fixedOrigin = {
ownerName
repoName,
packageName: origin.name
commitId: repo.refs['branches/master']
}
cacheKey = EJSON.stringify fixedOrigin, {canonical: true}
ver = upstreamVersionsCache.get cacheKey
unless _.isUndefined(ver)
return ver
getVersion = (opts) ->
NogFlow.call.getPackageVersion opts, (err, res) ->
if err
console.log 'Failed to get version', opts, err
return
key = EPI:KEY:<KEY>END_PI.stringify _.pick(
res, 'ownerName', 'repoName', 'packageName', 'commitId'
), {
canonical: true
}
upstreamVersionsCache.set key, res.version
getVersion {ownerName, repoName, packageName: origin.name}
return null
Template.workspaceFlowProgramsSelDeps.helpers
mayUpdateDep: ->
mayModifyRepo Template.parentData().repo
deps: ->
dat = Template.currentData()
if dat.program.entries[0]
if latest = NogContent.trees.findOne(dat.program.entries[0].sha1)
pkg = latest.meta.package
deps = {}
for d in pkg.dependencies
deps[d.name] = d
for f in pkg.frozen
version = versionString(f)
dep = {
name: f.name
version
sha1: f.sha1
}
if (origin = deps[f.name])?
upstream = getLatestUpstreamVersion origin
if upstream?
dep.upstreamVersion = versionString upstream
dep.upstreamSha1 = upstream.sha1
dep.isUpdateAvailable = (
dep.upstreamVersion? and version != dep.upstreamVersion
)
[ownerName, repoName] = origin.repoFullName.split('/')
dep.origin = {
ownerName
repoName
name: origin.repoFullName
href: '' +
'/' + origin.repoFullName +
'/files/programs/' + origin.name
}
dep
Template.workspaceFlowProgramsSelDepsUpdate.onCreated ->
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelDepsUpdate.helpers
action: -> Template.instance().action.get()
Template.workspaceFlowProgramsSelDepsUpdate.events
'click .js-update-dep': (ev) ->
ev.preventDefault()
tpl = Template.instance()
pdat = Template.parentData()
refTreePath = 'master/programs/' + pdat.program.name
resolved = NogContent.resolveRefTreePath pdat.repo, refTreePath
opts =
ownerName: pdat.repo.owner
repoName: pdat.repo.name
commitId: pdat.commitId
package:
numericPath: resolved.numericPath
dependency:
name: @name
oldSha1: @sha1
newSha1: @upstreamSha1
origin:
ownerName: @origin.ownerName
repoName: @origin.repoName
tpl.action.set 'Updating...'
NogFlow.call.updatePackageDependency opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
Template.workspaceFlowProgramsSelParams.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelParams.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
# This helper passes raw html to the template as a workaround for the known
# issue of Blaze wrongly rendering reactive contenteditables
# (https://github.com/Swavek/contenteditable). In our case this caused
# multiply rendered parts of string when pressing return and delete during
# parameter manipulation.
editable: ->
params = @last.content.meta.program.params
params = EJSON.stringify params, {indent: true, canonical: true}
params = escapeHtml params
'<pre class="js-params" contenteditable="true">' + params + '</pre>'
Template.workspaceFlowProgramsSelParams.events
'click .js-save-params': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-params').text()
try
params = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(params, @last.content.meta.program.params)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
params
}
tpl.action.set 'Saving...'
Session.set({'blockProgramRunButton': 'Saving'})
NogFlow.call.updateProgramParams opts, (err, res) =>
Session.set({'blockProgramRunButton': null})
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.workspaceFlowProgramsSelRuntime.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelRuntime.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
# This helper passes raw html to the template as a workaround as described in
# template 'workspaceFlowProgramsSelParams'.
editable: ->
runtime = @last.content.meta.program.runtime
runtime = EJSON.stringify runtime, {indent: true, canonical: true}
runtime = escapeHtml runtime
'<pre class="js-runtime" contenteditable="true">' + runtime + '</pre>'
Template.workspaceFlowProgramsSelRuntime.events
'click .js-save-runtime': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-runtime').text()
try
runtime = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(runtime, @last.content.meta.program.runtime)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
runtime
}
tpl.action.set 'Saving...'
NogFlow.call.updateProgramRuntime opts, (err, res) =>
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.workspaceFlowProgramsSelReadme.helpers
programName: ->
Template.parentData().program.name
Template.workspaceFlowProgramsSelRunButton.onCreated ->
@action = new ReactiveVar()
Template.workspaceFlowProgramsSelRunButton.helpers
action: -> Template.instance().action.get()
blocked: -> Session.get('blockProgramRunButton')
Template.workspaceFlowProgramsSelRunButton.events
'click .js-run': (ev) ->
ev.preventDefault()
opts = {
ownerName: @repo.owner
repoName: @repo.name
commitId: @repo.refs['branches/master']
sha1: @program._id
}
tpl = Template.instance()
tpl.action.set 'Submitting Job...'
NogFlow.call.runProgram opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.workspaceFlowJobs.onCreated ->
Session.set("workspaceShowAllJobs", false)
@isDeleting = new ReactiveVar(false)
@jobIds = []
@jobEntries = {}
@resultJobIds = []
@autorun =>
@jobIds = []
@jobEntries = {}
@resultJobIds = []
dat = Template.currentData()
for entry in dat.tree.entries
if entry.type == 'tree'
if subtree = NogContent.trees.findOne(entry.sha1)
if iskindJobs subtree
for jobTree in subtree.entries
if jobTree.type == 'tree'
if jobEntry = NogContent.trees.findOne(jobTree.sha1)
if iskindJob jobEntry
if (jobId = jobEntry.meta?.job?.id)?
@jobIds.push(jobId)
@jobEntries[jobId] = jobEntry
else
if iskindResults subtree
for resultTree in subtree.entries
if resultTree.type == 'tree'
if resultEntry = NogContent.trees.findOne(resultTree.sha1)
if (jobId = resultEntry.meta?.jobResult?.jobId)?
@resultJobIds.push(jobId)
@subscribe 'jobStatus', @jobIds
Template.workspaceFlowJobs.helpers
jobs: ->
templateInstance = Template.instance()
NogExec.jobs.find {'data.jobId': {$in: Template.instance().jobIds}},
sort: {updated:-1},
transform: (item) =>
jobId = item.data.jobId
item.programName =
templateInstance.jobEntries[jobId]?.meta?.job?.program?.name
item
showJob: ->
if Session.equals('workspaceShowAllJobs', true)
return true
templateInstance = Template.instance()
switch @status
when 'running', 'ready' then return true
when 'failed', 'cancelled'
# Show only if job is most recent for the particular program.
return Template.workspaceFlowJobs.isMostRecentJobOfProgram(@, templateInstance.jobEntries)
when 'completed'
# Show if there is result with corresponding job id
# Show only if job is most recent for the particular program.
return (@data.jobId in templateInstance.resultJobIds) or
Template.workspaceFlowJobs.isMostRecentJobOfProgram(@, templateInstance.jobEntries)
else return false
showAllJobs: ->
Session.equals('workspaceShowAllJobs', true)
isDeleting: ->
Template.instance().isDeleting.get()
Template.workspaceFlowJobs.isMostRecentJobOfProgram = (job, jobEntries) ->
for k, entry of jobEntries
if entry.meta?.job?.program?.name is job.programName
if entry.meta?.job?.id?
otherJob = NogExec.jobs.findOne {'data.jobId': entry.meta.job.id}
if otherJob? and otherJob.updated > job.updated
return false
return true
Template.workspaceFlowJobs.events
'click .js-show-all-jobs-toggle': (ev) ->
ev.preventDefault()
currentValue = Session.get("workspaceShowAllJobs")
Session.set("workspaceShowAllJobs", !currentValue)
'click .js-delete-all-jobs': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
templateInstance = Template.instance()
dat = Template.currentData()
for entry,idx in dat.tree.entries
if entry.type == 'tree'
if subtree = NogContent.trees.findOne(entry.sha1)
if iskindJobs subtree
jobsTree = subtree
numericPath = [idx]
opts = {
ownerName: dat.repo.owner
repoName: dat.repo.name
numericPath: numericPath
commitId: dat.repo.refs['branches/master']
children: [0...jobsTree.entries.length]
}
templateInstance.isDeleting.set(true)
NogFiles.call.deleteChildren opts, (err, res) ->
templateInstance.isDeleting.set(false)
if err
return defaultErrorHandler err
Template.workspaceFlowJobInfo.helpers
progressPercent: ->
Math.round(@progress.percent)
jobInProgress: ->
@status == 'running'
jobId: ->
@data.jobId
lastUpdate: ->
moment(@updated).fromNow()
createdDate: ->
@created
statusClass: ->
switch @status
when 'completed' then 'text-success'
when 'failed' then 'text-danger'
when 'cancelled' then 'text-muted'
else null
reasonLines: ->
@reason.split('\n')
Template.workspaceFlowResults.onCreated ->
@selection = new ReactiveDict()
@nEntries = 0
@isSelected = (idx) =>
@selection.equals(idx, true)
@select = (idx) =>
@selection.set(idx, true)
@deselect = (idx) =>
@selection.set(idx, false)
@clearSelection = =>
for i in [0...@nEntries]
@deselect i
@selectOne = (idx) =>
@clearSelection()
@select idx
@getSelection = =>
s = []
for i in [0...@nEntries]
if @isSelected(i)
s.push i
s
@autorun =>
dat = Template.currentData()
if dat.results
@nEntries = dat.results?.entries.length ? 0
Template.workspaceFlowResults.helpers
resultsExists: ->
tpl = Template.instance()
hasResults = false
unless t = @results?.entries[tpl.getSelection()]
return
if res = NogContent.trees.findOne(t.sha1)
hasResult = true
hasResult
resultsList: ->
tpl = Template.instance()
dat = Template.currentData()
sel = tpl.getSelection()
if sel.length == 0
if Session.get("selectedResult")?
tpl.selectOne(Session.get("selectedResult"))
else
tpl.selectOne(0)
Session.set("selectedResult", 0)
if dat.results
resList = []
for e, idx in dat.results.entries
tree = NogContent.trees.findOne(e.sha1)
vString = ''
if tree.meta['programVersion']
vString = tree.meta['programVersion']
resList.push {
name: tree.name
displayName: tree.name + vString
index: idx,
classSelected: if tpl.isSelected(idx) then 'info' else null
}
{
entries: resList
}
resultSet: ->
dat = Template.currentData()
tpl = Template.instance()
idx = tpl.getSelection()
unless t = dat.results?.entries[idx]
return
children = []
varList = []
if res = NogContent.trees.findOne(t.sha1)
resName = res.name
repo = dat.repo
resPath = 'master/results/' + resName
varList.push {
description: res.meta.description
path: resPath
}
for v, idx in res.entries
if v.type == 'tree'
if variant = NogContent.trees.findOne(v.sha1)
varList.push {
description: variant.meta.description
path: resPath + '/' + variant.name
}
id = 0
for item in varList
for p in ['index.md', 'README.md', 'summary.md', 'report.md']
treePath = item.path + '/' + p
if (child = NogContent.resolveRefTreePath repo, treePath)?
children.push {
name: item.path.split('/').reverse()[0]
child: child
description: item.description
id: id
}
id = id + 1
return {
children: children,
isSingleResult: children.length is 1
}
Template.workspaceFlowResults.events
'click .js-browse-results': (ev) ->
ev.preventDefault()
tpl = Template.instance()
t = @results.entries[tpl.getSelection()]
res = NogContent.trees.findOne(t.sha1)
path = '/' + @repo.owner + '/' + @repo.name + '/files/results/' + res.name
NogModal.start path, {
backref: FlowRouter.current().path
title: 'View-only mode'
viewOnly: true
}
'click tr': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.selectOne @index
Session.set("selectedResult", @index)
|
[
{
"context": "#############\n#\n#\tMoocita collections\n# Created by Markus on 26/10/2015.\n#\n################################",
"end": 99,
"score": 0.9992696046829224,
"start": 93,
"tag": "NAME",
"value": "Markus"
}
] | server/publications/feedback.coffee | agottschalk10/worklearn | 0 | #######################################################
#
# Moocita collections
# Created by Markus on 26/10/2015.
#
#######################################################
#######################################################
# item header
#######################################################
#######################################################
_feedback_fields =
fields:
rating: 1
content: 1
owner_id: 1
parent_id: 1
published: 1
solution_id: 1
challenge_id: 1
#######################################################
Meteor.publish "my_feedback", () ->
user_id = this.userId
filter =
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback", user_id
return crs
#######################################################
Meteor.publish "my_feedback_by_challenge_id", (challenge_id) ->
check challenge_id, String
user_id = this.userId
filter =
challenge_id: challenge_id
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback_by_challenge_id", user_id
return crs
#######################################################
Meteor.publish "my_feedback_by_solution_id", (solution_id) ->
check solution_id, String
user_id = this.userId
filter =
solution_id: solution_id
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback_by_solution_id", user_id
return crs
#######################################################
Meteor.publish "my_feedback_by_review_id", (review_id) ->
check review_id, String
user_id = this.userId
filter =
parent_id: review_id
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback_by_review_id", user_id
return crs
#######################################################
Meteor.publish "feedback_by_review_id", (review_id) ->
check review_id, String
user_id = this.userId
filter =
review_id: review_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, _feedback_fields,
_feedback_fields, "feedback_by_review_id", user_id
return crs
| 21207 | #######################################################
#
# Moocita collections
# Created by <NAME> on 26/10/2015.
#
#######################################################
#######################################################
# item header
#######################################################
#######################################################
_feedback_fields =
fields:
rating: 1
content: 1
owner_id: 1
parent_id: 1
published: 1
solution_id: 1
challenge_id: 1
#######################################################
Meteor.publish "my_feedback", () ->
user_id = this.userId
filter =
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback", user_id
return crs
#######################################################
Meteor.publish "my_feedback_by_challenge_id", (challenge_id) ->
check challenge_id, String
user_id = this.userId
filter =
challenge_id: challenge_id
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback_by_challenge_id", user_id
return crs
#######################################################
Meteor.publish "my_feedback_by_solution_id", (solution_id) ->
check solution_id, String
user_id = this.userId
filter =
solution_id: solution_id
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback_by_solution_id", user_id
return crs
#######################################################
Meteor.publish "my_feedback_by_review_id", (review_id) ->
check review_id, String
user_id = this.userId
filter =
parent_id: review_id
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback_by_review_id", user_id
return crs
#######################################################
Meteor.publish "feedback_by_review_id", (review_id) ->
check review_id, String
user_id = this.userId
filter =
review_id: review_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, _feedback_fields,
_feedback_fields, "feedback_by_review_id", user_id
return crs
| true | #######################################################
#
# Moocita collections
# Created by PI:NAME:<NAME>END_PI on 26/10/2015.
#
#######################################################
#######################################################
# item header
#######################################################
#######################################################
_feedback_fields =
fields:
rating: 1
content: 1
owner_id: 1
parent_id: 1
published: 1
solution_id: 1
challenge_id: 1
#######################################################
Meteor.publish "my_feedback", () ->
user_id = this.userId
filter =
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback", user_id
return crs
#######################################################
Meteor.publish "my_feedback_by_challenge_id", (challenge_id) ->
check challenge_id, String
user_id = this.userId
filter =
challenge_id: challenge_id
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback_by_challenge_id", user_id
return crs
#######################################################
Meteor.publish "my_feedback_by_solution_id", (solution_id) ->
check solution_id, String
user_id = this.userId
filter =
solution_id: solution_id
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback_by_solution_id", user_id
return crs
#######################################################
Meteor.publish "my_feedback_by_review_id", (review_id) ->
check review_id, String
user_id = this.userId
filter =
parent_id: review_id
owner_id: user_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, filter,
_feedback_fields, "my_feedback_by_review_id", user_id
return crs
#######################################################
Meteor.publish "feedback_by_review_id", (review_id) ->
check review_id, String
user_id = this.userId
filter =
review_id: review_id
crs = Feedback.find filter, _feedback_fields
log_publication "Feedback", crs, _feedback_fields,
_feedback_fields, "feedback_by_review_id", user_id
return crs
|
[
{
"context": "cs/#info.info\n\nFramer.Info =\n\ttitle: \"\"\n\tauthor: \"Tony\"\n\ttwitter: \"\"\n\tdescription: \"\"\n\n\n# Setup\n# Import",
"end": 146,
"score": 0.9990808963775635,
"start": 142,
"tag": "NAME",
"value": "Tony"
}
] | 55soundCloud.framer/app.coffee | gremjua-forks/100daysofframer | 26 | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: ""
author: "Tony"
twitter: ""
description: ""
# Setup
# Import sketch file "soundCloud"
sketch = Framer.Importer.load("imported/soundCloud@1x")
Utils.globalLayers(sketch)
new BackgroundLayer backgroundColor: "#000"
# Variables
Framer.Defaults.Animation = time: 0.3
defaultSpring = curve: "spring(150, 13, 0)"
show = {show: opacity: 1}
hide = {hide: opacity: 0}
bounceHide = {bounceHide: scaleY: 0}
dragging = {dragging: scale: 1.9, y: Align.center(80)}
bgScaleUp = 1.1
bgBlur = 70
Framer["pause1"] = false
Framer["pause2"] = false
Framer["isDragging1"] = false
Framer["isDragging2"] = false
Framer["elapsedSec1"] = 0
Framer["elapsedSec2"] = 0
Framer["currentTime1"] = ""
Framer["currentTime2"] = ""
Framer["songLength1"] = 79
Framer["songLength2"] = 283
# Base Layers and States
page = new PageComponent
size: Screen, scrollVertical: false
# States
for layer in [buttonsLine1, buttonsLine2, overlay1, overlay2]
layer.opacity = 0
layer.states.add show
for layer in [artistBg1, artistBg2, titleBg1, titleBg2, buttonsBase1, buttonsBase2, nextButton1, playButton1, nextButton2, playButton2, icons1, icons2, title1, title2, artist1, artist2]
layer.states.add hide
# Functions
# Utility
# Second to MM:SS Function
timeFromSeconds = (seconds) ->
if seconds > 0
return new Date(seconds * 1000).toISOString().substr(15, 4)
else
return "0:00"
# Interaction Functions
pausePlay = (artboard) ->
num = 1 if artboard is Artboard1
num = 2 if artboard is Artboard2
sketch["overlay#{num}"].states.next()
if sketch["bg#{num}"].blur is 0
sketch["bg#{num}"].animate properties: blur: bgBlur, scale: bgScaleUp
else sketch["bg#{num}"].animate properties: blur: 0, scale: 1
sketch["buttonsLine#{num}"].states.next()
sketch["buttonsBase#{num}"].states.next()
sketch["titleBg#{num}"].states.next()
sketch["artistBg#{num}"].states.next()
Framer["timeStampBg#{num}"].states.next()
for layer in Framer["trackArea#{num}"].children
layer.states.next()
if Framer["pause#{num}"] is false
Framer["pause#{num}"] = true
else Framer["pause#{num}"] = false
trackMoveStop(num)
trackMoveStop = (num) ->
midPoint = Framer["track#{num}"].width/2
distRemain = Framer["track#{num}"].x - midPoint
songTime = Framer["songLength#{num}"]
animationTime = Utils.modulate(distRemain, [0, -midPoint*2], [79, 0])
if Framer["pause#{num}"] is false
Framer["track#{num}"].animate
properties:
x: -Framer["track#{c}"].width/2
curve: "linear"
time: animationTime
Framer["animation#{num}"] = new Animation
layer: sketch["bg#{num}"]
properties: maxX: Screen.width
curve: "linear"
time: animationTime
Framer["animation#{num}"].start()
else
Framer["track#{num}"].animateStop()
if Framer["animation#{num}"]
Framer["animation#{num}"].stop()
dragStart = (track) ->
page.scrollHorizontal = false
num = 1 if track is "track1"
num = 2 if track is "track2"
Framer["isDragging#{num}"] = true
sketch["overlay#{num}"].states.switch("show")
sketch["icons#{num}"].states.switch("hide")
sketch["title#{num}"].states.switch("hide")
sketch["artist#{num}"].states.switch("hide")
sketch["nextButton#{num}"].opacity = 0
sketch["playButton#{num}"].opacity = 0
sketch["bg#{num}"].animate properties: blur: bgBlur
sketch["bg#{num}"].animate properties: scale: bgScaleUp
Framer["timeStampBg#{num}"].states.switch("hide")
Framer["textGroup#{num}"].states.switch("dragging")
if Framer["animation#{num}"]
Framer["animation#{num}"].stop()
dragEnd = (track) ->
Utils.delay 0.5, ->
page.scrollHorizontal = true
num = 1 if track is "track1"
num = 2 if track is "track2"
Framer["isDragging#{num}"] = false
sketch["overlay#{num}"].states.switch("default")
sketch["icons#{num}"].states.switch("default")
sketch["title#{num}"].states.switch("default")
sketch["artist#{num}"].states.switch("default")
Framer["timeStampBg#{num}"].states.switch("default")
Framer["textGroup#{num}"].states.switch("default")
sketch["nextButton#{num}"].animate properties: opacity: 1
sketch["playButton#{num}"].animate properties: opacity: 1
sketch["bg#{num}"].animate properties: blur: 0
sketch["bg#{num}"].animate properties: scale: 1
if Framer["pause#{num}"] is true
sketch["bg#{num}"].animate properties: blur: bgBlur
sketch["bg#{num}"].animate properties: scale: bgScaleUp
sketch["overlay#{num}"].states.switch("show")
Framer["timeStampBg#{num}"].states.switch("hide")
trackMoveStop(num)
drag = (track) ->
num = 1 if track is "track1"
num = 2 if track is "track2"
x = Framer[track].x
song = Framer["songLength#{num}"]
trackStart = Framer[track].width/2
trackEnd = -Framer[track].width/2
currentTime = Math.round(Utils.modulate(x, [trackStart, trackEnd], [0, song]))
Framer["elapsedSec#{num}"] = currentTime
Framer["elasedText#{num}"].html = timeFromSeconds(currentTime)
move = (track) ->
num = 1 if track is "track1"
num = 2 if track is "track2"
x = Framer[track].x
trackStart = Framer[track].width/2
trackEnd = -Framer[track].width/2
travelLength = sketch["bg#{num}"].width - Screen.width
pos = Math.round(Utils.modulate(x, [trackStart, trackEnd], [0, -travelLength]))
sketch["bg#{num}"].x = pos
for layer in Framer["trackArea#{num}"].children
if layer.screenFrame.x < Framer[track].width/2 - 3
layer.backgroundColor = "orange"
else
layer.backgroundColor = "#fff"
# Calc Track Progress
Utils.interval 1, ->
for layer, t in [Artboard1, Artboard2]
c = t + 1
if Framer["pause#{c}"] is false
if Framer["elapsedSec#{c}"] >= Framer["songLength#{c}"]
Framer["elapsedSec#{c}"] == Framer["songLength#{c}"]
else
Framer["elapsedSec#{c}"] += 1
# Track Layers and Events
for layer, t in [Artboard1, Artboard2]
c = t + 1
Framer["clipBox#{c}"] = new Layer
size: Screen, backgroundColor: "", x: t * Screen.width
parent: page.content, clip: true, name: "clipBox#{c}"
layer.x = 0
layer.parent = Framer["clipBox#{c}"]
# Create track for each artboard
Framer["track#{c}"] = new Layer
height: 250, width: Screen.width, backgroundColor: ""
maxY: Screen.height - 250, x: Screen.width / 2
parent: Framer["clipBox#{c}"], name: "track#{c}"
Framer["trackArea#{c}"] = new Layer
height: Framer["track#{c}"].height, width: Framer["track#{c}"].width
backgroundColor: "", x: 0, parent: Framer["track#{c}"]
name: "trackArea#{c}"
barY = Framer["track#{c}"].height - 100
barW = 6
trackLine = new Layer
width: Framer["track#{c}"].width
height: 3, backgroundColor: "#fff"
x: 0, y: barY, parent: Framer["track#{c}"], name: "trackLine#{c}"
Framer["elaspedTrackLine#{c}"] = new Layer
width: 0
height: 3, backgroundColor: "orange"
maxX: Framer["track#{c}"].width/2, y: trackLine.screenFrame.y
parent: Framer["clipBox#{c}"], name: "elaspedTrackLine#{c}"
# Create music bars for each track
for i in [0...Math.round(Screen.width / (barW + 2.5))]
bar = new Layer
width: barW, height: Utils.randomNumber(60, 150)
maxY: barY, x: i * (barW + 2.5), originY: 1
backgroundColor: "#fff", parent: Framer["trackArea#{c}"]
opacity: 0.9
bar.states.add bounceHide
bar.states.animationOptions = defaultSpring
barShadow = bar.copy()
barShadow.props =
parent: Framer["trackArea#{c}"], y: barY
scaleY: 0.7, originY: 0, opacity: 0.4
barShadow.states.add bounceHide
barShadow.states.animationOptions = defaultSpring
# Create Time Stamp
Framer["timeStampBg#{c}"] = new Layer
width: 220, height: 50, backgroundColor: "#000"
x: Align.center, y: Align.center(292)
parent: Framer["clipBox#{c}"], name: "timeStampBg#{c}"
Framer["timeStampBg#{c}"].states.add hide
Framer["textGroup#{c}"] = new Layer
width: 220, height: 50, backgroundColor: ""
x: Align.center, y: Align.center(292)
parent: Framer["clipBox#{c}"], name: "textGroup#{c}"
Framer["textGroup#{c}"].states.add dragging
Framer["elasedText#{c}"] = new Layer
html: "0:00", parent: Framer["textGroup#{c}"], backgroundColor: ""
width: 70, height: 40, x: Align.center(-59), y: Align.center(5)
name: "elapsedText#{c}"
style: fontFamily: "monospace", fontSize: "2rem"
Framer["totalText#{c}"] = new Layer
html: timeFromSeconds(Framer["songLength#{c}"])
parent: Framer["textGroup#{c}"], backgroundColor: ""
width: 70, height: 40, x: Align.center(52), y: Align.center(5)
name: "totalText#{c}"
style: fontFamily: "monospace", textAlign: "right", fontSize: "2rem"
Framer["divider#{c}"] = new Layer
width: 1, height: 25, backgroundColor: "#fff", x: Align.center
y: Align.center(1), parent: Framer["textGroup#{c}"], name: "divider"
# Make the track draggable
Framer["track#{c}"].draggable.enabled = true
Framer["track#{c}"].draggable.vertical = false
Framer["track#{c}"].draggable.constraints =
x: -(Framer["track#{c}"].width/2), width: Framer["track#{c}"].width * 2
Framer["track#{c}"].draggable.overdrag = false
Framer["track#{c}"].draggable.momentumOptions = friction: 18
# Drag event
Framer["track#{c}"].onTouchStart ->
dragStart(@name)
Framer["track#{c}"].onDrag ->
drag(@name)
Framer["track#{c}"].onDragEnd ->
dragEnd(@name)
Framer["track#{c}"].onMove ->
move(@name)
# Pause click event
layer.onClick ->
pausePlay(this)
Utils.interval 1, ->
for layer, t in [Artboard1, Artboard2]
c = t + 1
if Framer["isDragging#{c}"] is false
Framer["currentTime#{c}"] = timeFromSeconds(Framer["elapsedSec#{c}"])
Framer["elasedText#{c}"].html = Framer["currentTime#{c}"]
for layer in Framer["trackArea#{c}"].children
if layer.screenFrame.x < Framer["trackArea#{c}"].width/2 - 2
layer.backgroundColor = "orange"
else
layer.backgroundColor = "#fff"
pausePlay(Artboard1)
pausePlay(Artboard2)
| 126756 | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: ""
author: "<NAME>"
twitter: ""
description: ""
# Setup
# Import sketch file "soundCloud"
sketch = Framer.Importer.load("imported/soundCloud@1x")
Utils.globalLayers(sketch)
new BackgroundLayer backgroundColor: "#000"
# Variables
Framer.Defaults.Animation = time: 0.3
defaultSpring = curve: "spring(150, 13, 0)"
show = {show: opacity: 1}
hide = {hide: opacity: 0}
bounceHide = {bounceHide: scaleY: 0}
dragging = {dragging: scale: 1.9, y: Align.center(80)}
bgScaleUp = 1.1
bgBlur = 70
Framer["pause1"] = false
Framer["pause2"] = false
Framer["isDragging1"] = false
Framer["isDragging2"] = false
Framer["elapsedSec1"] = 0
Framer["elapsedSec2"] = 0
Framer["currentTime1"] = ""
Framer["currentTime2"] = ""
Framer["songLength1"] = 79
Framer["songLength2"] = 283
# Base Layers and States
page = new PageComponent
size: Screen, scrollVertical: false
# States
for layer in [buttonsLine1, buttonsLine2, overlay1, overlay2]
layer.opacity = 0
layer.states.add show
for layer in [artistBg1, artistBg2, titleBg1, titleBg2, buttonsBase1, buttonsBase2, nextButton1, playButton1, nextButton2, playButton2, icons1, icons2, title1, title2, artist1, artist2]
layer.states.add hide
# Functions
# Utility
# Second to MM:SS Function
timeFromSeconds = (seconds) ->
if seconds > 0
return new Date(seconds * 1000).toISOString().substr(15, 4)
else
return "0:00"
# Interaction Functions
pausePlay = (artboard) ->
num = 1 if artboard is Artboard1
num = 2 if artboard is Artboard2
sketch["overlay#{num}"].states.next()
if sketch["bg#{num}"].blur is 0
sketch["bg#{num}"].animate properties: blur: bgBlur, scale: bgScaleUp
else sketch["bg#{num}"].animate properties: blur: 0, scale: 1
sketch["buttonsLine#{num}"].states.next()
sketch["buttonsBase#{num}"].states.next()
sketch["titleBg#{num}"].states.next()
sketch["artistBg#{num}"].states.next()
Framer["timeStampBg#{num}"].states.next()
for layer in Framer["trackArea#{num}"].children
layer.states.next()
if Framer["pause#{num}"] is false
Framer["pause#{num}"] = true
else Framer["pause#{num}"] = false
trackMoveStop(num)
trackMoveStop = (num) ->
midPoint = Framer["track#{num}"].width/2
distRemain = Framer["track#{num}"].x - midPoint
songTime = Framer["songLength#{num}"]
animationTime = Utils.modulate(distRemain, [0, -midPoint*2], [79, 0])
if Framer["pause#{num}"] is false
Framer["track#{num}"].animate
properties:
x: -Framer["track#{c}"].width/2
curve: "linear"
time: animationTime
Framer["animation#{num}"] = new Animation
layer: sketch["bg#{num}"]
properties: maxX: Screen.width
curve: "linear"
time: animationTime
Framer["animation#{num}"].start()
else
Framer["track#{num}"].animateStop()
if Framer["animation#{num}"]
Framer["animation#{num}"].stop()
dragStart = (track) ->
page.scrollHorizontal = false
num = 1 if track is "track1"
num = 2 if track is "track2"
Framer["isDragging#{num}"] = true
sketch["overlay#{num}"].states.switch("show")
sketch["icons#{num}"].states.switch("hide")
sketch["title#{num}"].states.switch("hide")
sketch["artist#{num}"].states.switch("hide")
sketch["nextButton#{num}"].opacity = 0
sketch["playButton#{num}"].opacity = 0
sketch["bg#{num}"].animate properties: blur: bgBlur
sketch["bg#{num}"].animate properties: scale: bgScaleUp
Framer["timeStampBg#{num}"].states.switch("hide")
Framer["textGroup#{num}"].states.switch("dragging")
if Framer["animation#{num}"]
Framer["animation#{num}"].stop()
dragEnd = (track) ->
Utils.delay 0.5, ->
page.scrollHorizontal = true
num = 1 if track is "track1"
num = 2 if track is "track2"
Framer["isDragging#{num}"] = false
sketch["overlay#{num}"].states.switch("default")
sketch["icons#{num}"].states.switch("default")
sketch["title#{num}"].states.switch("default")
sketch["artist#{num}"].states.switch("default")
Framer["timeStampBg#{num}"].states.switch("default")
Framer["textGroup#{num}"].states.switch("default")
sketch["nextButton#{num}"].animate properties: opacity: 1
sketch["playButton#{num}"].animate properties: opacity: 1
sketch["bg#{num}"].animate properties: blur: 0
sketch["bg#{num}"].animate properties: scale: 1
if Framer["pause#{num}"] is true
sketch["bg#{num}"].animate properties: blur: bgBlur
sketch["bg#{num}"].animate properties: scale: bgScaleUp
sketch["overlay#{num}"].states.switch("show")
Framer["timeStampBg#{num}"].states.switch("hide")
trackMoveStop(num)
drag = (track) ->
num = 1 if track is "track1"
num = 2 if track is "track2"
x = Framer[track].x
song = Framer["songLength#{num}"]
trackStart = Framer[track].width/2
trackEnd = -Framer[track].width/2
currentTime = Math.round(Utils.modulate(x, [trackStart, trackEnd], [0, song]))
Framer["elapsedSec#{num}"] = currentTime
Framer["elasedText#{num}"].html = timeFromSeconds(currentTime)
move = (track) ->
num = 1 if track is "track1"
num = 2 if track is "track2"
x = Framer[track].x
trackStart = Framer[track].width/2
trackEnd = -Framer[track].width/2
travelLength = sketch["bg#{num}"].width - Screen.width
pos = Math.round(Utils.modulate(x, [trackStart, trackEnd], [0, -travelLength]))
sketch["bg#{num}"].x = pos
for layer in Framer["trackArea#{num}"].children
if layer.screenFrame.x < Framer[track].width/2 - 3
layer.backgroundColor = "orange"
else
layer.backgroundColor = "#fff"
# Calc Track Progress
Utils.interval 1, ->
for layer, t in [Artboard1, Artboard2]
c = t + 1
if Framer["pause#{c}"] is false
if Framer["elapsedSec#{c}"] >= Framer["songLength#{c}"]
Framer["elapsedSec#{c}"] == Framer["songLength#{c}"]
else
Framer["elapsedSec#{c}"] += 1
# Track Layers and Events
for layer, t in [Artboard1, Artboard2]
c = t + 1
Framer["clipBox#{c}"] = new Layer
size: Screen, backgroundColor: "", x: t * Screen.width
parent: page.content, clip: true, name: "clipBox#{c}"
layer.x = 0
layer.parent = Framer["clipBox#{c}"]
# Create track for each artboard
Framer["track#{c}"] = new Layer
height: 250, width: Screen.width, backgroundColor: ""
maxY: Screen.height - 250, x: Screen.width / 2
parent: Framer["clipBox#{c}"], name: "track#{c}"
Framer["trackArea#{c}"] = new Layer
height: Framer["track#{c}"].height, width: Framer["track#{c}"].width
backgroundColor: "", x: 0, parent: Framer["track#{c}"]
name: "trackArea#{c}"
barY = Framer["track#{c}"].height - 100
barW = 6
trackLine = new Layer
width: Framer["track#{c}"].width
height: 3, backgroundColor: "#fff"
x: 0, y: barY, parent: Framer["track#{c}"], name: "trackLine#{c}"
Framer["elaspedTrackLine#{c}"] = new Layer
width: 0
height: 3, backgroundColor: "orange"
maxX: Framer["track#{c}"].width/2, y: trackLine.screenFrame.y
parent: Framer["clipBox#{c}"], name: "elaspedTrackLine#{c}"
# Create music bars for each track
for i in [0...Math.round(Screen.width / (barW + 2.5))]
bar = new Layer
width: barW, height: Utils.randomNumber(60, 150)
maxY: barY, x: i * (barW + 2.5), originY: 1
backgroundColor: "#fff", parent: Framer["trackArea#{c}"]
opacity: 0.9
bar.states.add bounceHide
bar.states.animationOptions = defaultSpring
barShadow = bar.copy()
barShadow.props =
parent: Framer["trackArea#{c}"], y: barY
scaleY: 0.7, originY: 0, opacity: 0.4
barShadow.states.add bounceHide
barShadow.states.animationOptions = defaultSpring
# Create Time Stamp
Framer["timeStampBg#{c}"] = new Layer
width: 220, height: 50, backgroundColor: "#000"
x: Align.center, y: Align.center(292)
parent: Framer["clipBox#{c}"], name: "timeStampBg#{c}"
Framer["timeStampBg#{c}"].states.add hide
Framer["textGroup#{c}"] = new Layer
width: 220, height: 50, backgroundColor: ""
x: Align.center, y: Align.center(292)
parent: Framer["clipBox#{c}"], name: "textGroup#{c}"
Framer["textGroup#{c}"].states.add dragging
Framer["elasedText#{c}"] = new Layer
html: "0:00", parent: Framer["textGroup#{c}"], backgroundColor: ""
width: 70, height: 40, x: Align.center(-59), y: Align.center(5)
name: "elapsedText#{c}"
style: fontFamily: "monospace", fontSize: "2rem"
Framer["totalText#{c}"] = new Layer
html: timeFromSeconds(Framer["songLength#{c}"])
parent: Framer["textGroup#{c}"], backgroundColor: ""
width: 70, height: 40, x: Align.center(52), y: Align.center(5)
name: "totalText#{c}"
style: fontFamily: "monospace", textAlign: "right", fontSize: "2rem"
Framer["divider#{c}"] = new Layer
width: 1, height: 25, backgroundColor: "#fff", x: Align.center
y: Align.center(1), parent: Framer["textGroup#{c}"], name: "divider"
# Make the track draggable
Framer["track#{c}"].draggable.enabled = true
Framer["track#{c}"].draggable.vertical = false
Framer["track#{c}"].draggable.constraints =
x: -(Framer["track#{c}"].width/2), width: Framer["track#{c}"].width * 2
Framer["track#{c}"].draggable.overdrag = false
Framer["track#{c}"].draggable.momentumOptions = friction: 18
# Drag event
Framer["track#{c}"].onTouchStart ->
dragStart(@name)
Framer["track#{c}"].onDrag ->
drag(@name)
Framer["track#{c}"].onDragEnd ->
dragEnd(@name)
Framer["track#{c}"].onMove ->
move(@name)
# Pause click event
layer.onClick ->
pausePlay(this)
Utils.interval 1, ->
for layer, t in [Artboard1, Artboard2]
c = t + 1
if Framer["isDragging#{c}"] is false
Framer["currentTime#{c}"] = timeFromSeconds(Framer["elapsedSec#{c}"])
Framer["elasedText#{c}"].html = Framer["currentTime#{c}"]
for layer in Framer["trackArea#{c}"].children
if layer.screenFrame.x < Framer["trackArea#{c}"].width/2 - 2
layer.backgroundColor = "orange"
else
layer.backgroundColor = "#fff"
pausePlay(Artboard1)
pausePlay(Artboard2)
| true | # Project Info
# This info is presented in a widget when you share.
# http://framerjs.com/docs/#info.info
Framer.Info =
title: ""
author: "PI:NAME:<NAME>END_PI"
twitter: ""
description: ""
# Setup
# Import sketch file "soundCloud"
sketch = Framer.Importer.load("imported/soundCloud@1x")
Utils.globalLayers(sketch)
new BackgroundLayer backgroundColor: "#000"
# Variables
Framer.Defaults.Animation = time: 0.3
defaultSpring = curve: "spring(150, 13, 0)"
show = {show: opacity: 1}
hide = {hide: opacity: 0}
bounceHide = {bounceHide: scaleY: 0}
dragging = {dragging: scale: 1.9, y: Align.center(80)}
bgScaleUp = 1.1
bgBlur = 70
Framer["pause1"] = false
Framer["pause2"] = false
Framer["isDragging1"] = false
Framer["isDragging2"] = false
Framer["elapsedSec1"] = 0
Framer["elapsedSec2"] = 0
Framer["currentTime1"] = ""
Framer["currentTime2"] = ""
Framer["songLength1"] = 79
Framer["songLength2"] = 283
# Base Layers and States
page = new PageComponent
size: Screen, scrollVertical: false
# States
for layer in [buttonsLine1, buttonsLine2, overlay1, overlay2]
layer.opacity = 0
layer.states.add show
for layer in [artistBg1, artistBg2, titleBg1, titleBg2, buttonsBase1, buttonsBase2, nextButton1, playButton1, nextButton2, playButton2, icons1, icons2, title1, title2, artist1, artist2]
layer.states.add hide
# Functions
# Utility
# Second to MM:SS Function
timeFromSeconds = (seconds) ->
if seconds > 0
return new Date(seconds * 1000).toISOString().substr(15, 4)
else
return "0:00"
# Interaction Functions
pausePlay = (artboard) ->
num = 1 if artboard is Artboard1
num = 2 if artboard is Artboard2
sketch["overlay#{num}"].states.next()
if sketch["bg#{num}"].blur is 0
sketch["bg#{num}"].animate properties: blur: bgBlur, scale: bgScaleUp
else sketch["bg#{num}"].animate properties: blur: 0, scale: 1
sketch["buttonsLine#{num}"].states.next()
sketch["buttonsBase#{num}"].states.next()
sketch["titleBg#{num}"].states.next()
sketch["artistBg#{num}"].states.next()
Framer["timeStampBg#{num}"].states.next()
for layer in Framer["trackArea#{num}"].children
layer.states.next()
if Framer["pause#{num}"] is false
Framer["pause#{num}"] = true
else Framer["pause#{num}"] = false
trackMoveStop(num)
trackMoveStop = (num) ->
midPoint = Framer["track#{num}"].width/2
distRemain = Framer["track#{num}"].x - midPoint
songTime = Framer["songLength#{num}"]
animationTime = Utils.modulate(distRemain, [0, -midPoint*2], [79, 0])
if Framer["pause#{num}"] is false
Framer["track#{num}"].animate
properties:
x: -Framer["track#{c}"].width/2
curve: "linear"
time: animationTime
Framer["animation#{num}"] = new Animation
layer: sketch["bg#{num}"]
properties: maxX: Screen.width
curve: "linear"
time: animationTime
Framer["animation#{num}"].start()
else
Framer["track#{num}"].animateStop()
if Framer["animation#{num}"]
Framer["animation#{num}"].stop()
dragStart = (track) ->
page.scrollHorizontal = false
num = 1 if track is "track1"
num = 2 if track is "track2"
Framer["isDragging#{num}"] = true
sketch["overlay#{num}"].states.switch("show")
sketch["icons#{num}"].states.switch("hide")
sketch["title#{num}"].states.switch("hide")
sketch["artist#{num}"].states.switch("hide")
sketch["nextButton#{num}"].opacity = 0
sketch["playButton#{num}"].opacity = 0
sketch["bg#{num}"].animate properties: blur: bgBlur
sketch["bg#{num}"].animate properties: scale: bgScaleUp
Framer["timeStampBg#{num}"].states.switch("hide")
Framer["textGroup#{num}"].states.switch("dragging")
if Framer["animation#{num}"]
Framer["animation#{num}"].stop()
dragEnd = (track) ->
Utils.delay 0.5, ->
page.scrollHorizontal = true
num = 1 if track is "track1"
num = 2 if track is "track2"
Framer["isDragging#{num}"] = false
sketch["overlay#{num}"].states.switch("default")
sketch["icons#{num}"].states.switch("default")
sketch["title#{num}"].states.switch("default")
sketch["artist#{num}"].states.switch("default")
Framer["timeStampBg#{num}"].states.switch("default")
Framer["textGroup#{num}"].states.switch("default")
sketch["nextButton#{num}"].animate properties: opacity: 1
sketch["playButton#{num}"].animate properties: opacity: 1
sketch["bg#{num}"].animate properties: blur: 0
sketch["bg#{num}"].animate properties: scale: 1
if Framer["pause#{num}"] is true
sketch["bg#{num}"].animate properties: blur: bgBlur
sketch["bg#{num}"].animate properties: scale: bgScaleUp
sketch["overlay#{num}"].states.switch("show")
Framer["timeStampBg#{num}"].states.switch("hide")
trackMoveStop(num)
drag = (track) ->
num = 1 if track is "track1"
num = 2 if track is "track2"
x = Framer[track].x
song = Framer["songLength#{num}"]
trackStart = Framer[track].width/2
trackEnd = -Framer[track].width/2
currentTime = Math.round(Utils.modulate(x, [trackStart, trackEnd], [0, song]))
Framer["elapsedSec#{num}"] = currentTime
Framer["elasedText#{num}"].html = timeFromSeconds(currentTime)
move = (track) ->
num = 1 if track is "track1"
num = 2 if track is "track2"
x = Framer[track].x
trackStart = Framer[track].width/2
trackEnd = -Framer[track].width/2
travelLength = sketch["bg#{num}"].width - Screen.width
pos = Math.round(Utils.modulate(x, [trackStart, trackEnd], [0, -travelLength]))
sketch["bg#{num}"].x = pos
for layer in Framer["trackArea#{num}"].children
if layer.screenFrame.x < Framer[track].width/2 - 3
layer.backgroundColor = "orange"
else
layer.backgroundColor = "#fff"
# Calc Track Progress
Utils.interval 1, ->
for layer, t in [Artboard1, Artboard2]
c = t + 1
if Framer["pause#{c}"] is false
if Framer["elapsedSec#{c}"] >= Framer["songLength#{c}"]
Framer["elapsedSec#{c}"] == Framer["songLength#{c}"]
else
Framer["elapsedSec#{c}"] += 1
# Track Layers and Events
for layer, t in [Artboard1, Artboard2]
c = t + 1
Framer["clipBox#{c}"] = new Layer
size: Screen, backgroundColor: "", x: t * Screen.width
parent: page.content, clip: true, name: "clipBox#{c}"
layer.x = 0
layer.parent = Framer["clipBox#{c}"]
# Create track for each artboard
Framer["track#{c}"] = new Layer
height: 250, width: Screen.width, backgroundColor: ""
maxY: Screen.height - 250, x: Screen.width / 2
parent: Framer["clipBox#{c}"], name: "track#{c}"
Framer["trackArea#{c}"] = new Layer
height: Framer["track#{c}"].height, width: Framer["track#{c}"].width
backgroundColor: "", x: 0, parent: Framer["track#{c}"]
name: "trackArea#{c}"
barY = Framer["track#{c}"].height - 100
barW = 6
trackLine = new Layer
width: Framer["track#{c}"].width
height: 3, backgroundColor: "#fff"
x: 0, y: barY, parent: Framer["track#{c}"], name: "trackLine#{c}"
Framer["elaspedTrackLine#{c}"] = new Layer
width: 0
height: 3, backgroundColor: "orange"
maxX: Framer["track#{c}"].width/2, y: trackLine.screenFrame.y
parent: Framer["clipBox#{c}"], name: "elaspedTrackLine#{c}"
# Create music bars for each track
for i in [0...Math.round(Screen.width / (barW + 2.5))]
bar = new Layer
width: barW, height: Utils.randomNumber(60, 150)
maxY: barY, x: i * (barW + 2.5), originY: 1
backgroundColor: "#fff", parent: Framer["trackArea#{c}"]
opacity: 0.9
bar.states.add bounceHide
bar.states.animationOptions = defaultSpring
barShadow = bar.copy()
barShadow.props =
parent: Framer["trackArea#{c}"], y: barY
scaleY: 0.7, originY: 0, opacity: 0.4
barShadow.states.add bounceHide
barShadow.states.animationOptions = defaultSpring
# Create Time Stamp
Framer["timeStampBg#{c}"] = new Layer
width: 220, height: 50, backgroundColor: "#000"
x: Align.center, y: Align.center(292)
parent: Framer["clipBox#{c}"], name: "timeStampBg#{c}"
Framer["timeStampBg#{c}"].states.add hide
Framer["textGroup#{c}"] = new Layer
width: 220, height: 50, backgroundColor: ""
x: Align.center, y: Align.center(292)
parent: Framer["clipBox#{c}"], name: "textGroup#{c}"
Framer["textGroup#{c}"].states.add dragging
Framer["elasedText#{c}"] = new Layer
html: "0:00", parent: Framer["textGroup#{c}"], backgroundColor: ""
width: 70, height: 40, x: Align.center(-59), y: Align.center(5)
name: "elapsedText#{c}"
style: fontFamily: "monospace", fontSize: "2rem"
Framer["totalText#{c}"] = new Layer
html: timeFromSeconds(Framer["songLength#{c}"])
parent: Framer["textGroup#{c}"], backgroundColor: ""
width: 70, height: 40, x: Align.center(52), y: Align.center(5)
name: "totalText#{c}"
style: fontFamily: "monospace", textAlign: "right", fontSize: "2rem"
Framer["divider#{c}"] = new Layer
width: 1, height: 25, backgroundColor: "#fff", x: Align.center
y: Align.center(1), parent: Framer["textGroup#{c}"], name: "divider"
# Make the track draggable
Framer["track#{c}"].draggable.enabled = true
Framer["track#{c}"].draggable.vertical = false
Framer["track#{c}"].draggable.constraints =
x: -(Framer["track#{c}"].width/2), width: Framer["track#{c}"].width * 2
Framer["track#{c}"].draggable.overdrag = false
Framer["track#{c}"].draggable.momentumOptions = friction: 18
# Drag event
Framer["track#{c}"].onTouchStart ->
dragStart(@name)
Framer["track#{c}"].onDrag ->
drag(@name)
Framer["track#{c}"].onDragEnd ->
dragEnd(@name)
Framer["track#{c}"].onMove ->
move(@name)
# Pause click event
layer.onClick ->
pausePlay(this)
Utils.interval 1, ->
for layer, t in [Artboard1, Artboard2]
c = t + 1
if Framer["isDragging#{c}"] is false
Framer["currentTime#{c}"] = timeFromSeconds(Framer["elapsedSec#{c}"])
Framer["elasedText#{c}"].html = Framer["currentTime#{c}"]
for layer in Framer["trackArea#{c}"].children
if layer.screenFrame.x < Framer["trackArea#{c}"].width/2 - 2
layer.backgroundColor = "orange"
else
layer.backgroundColor = "#fff"
pausePlay(Artboard1)
pausePlay(Artboard2)
|
[
{
"context": " content: content\n author: author\n created_at: new Date()\n\n ",
"end": 2366,
"score": 0.9340375661849976,
"start": 2360,
"tag": "NAME",
"value": "author"
},
{
"context": "lone @get('authors')\n authors.pus... | shared/coffee/ck.model.coffee | encorelab/CommonKnowledge | 1 | if typeof exports isnt "undefined" and exports isnt null
# we're in node
jQuery = require("jquery")
_ = require("underscore")
Backbone = require("backbone")
Backbone.$ = jQuery
Drowsy = require("backbone.drowsy").Drowsy
#var Wakeful = require('Backbone.Drowsy/wakeful').Wakeful;
CK = {}
exports.CK = CK
else
window.CK = window.CK or {}
CK = window.CK
jQuery = window.$
_ = window._
Drowsy = window.Drowsy
class CK.Model
@requiredCollections = [
'contributions',
'tags',
'states',
'proposals',
'investigations'
]
@init: (url, db) ->
deferredConfigure = jQuery.Deferred()
unless url?
throw new Error "Cannot configure model because no DrowsyDromedary URL was given!"
unless db?
throw new Error "Cannot configure model because no database name was given!"
@baseURL = url
@dbURL= "#{url}/#{db}"
@server = new Drowsy.Server(url)
@db = @server.database(db)
@createNecessaryCollections(@requiredCollections).then =>
@defineModelClasses()
deferredConfigure.resolve()
return deferredConfigure
@createNecessaryCollections: (requiredCollections) ->
dfs = []
df = jQuery.Deferred()
@db.collections (colls) =>
existingCollections = _.pluck(colls, 'name')
for col in requiredCollections
unless col in existingCollections
console.log "Creating collection '#{col}' under #{CK.Model.dbURL}"
dfs.push(@db.createCollection col)
jQuery.when.apply(jQuery, dfs).done -> df.resolve()
return df
@defineModelClasses: ->
class VotableMixin
addVote: (username) ->
votes = _.clone @get('votes')
votes ?= []
votes.push(username)
@set 'votes', votes
removeVote: (username) ->
votes = _.without @get('votes'), username
@set 'votes', votes
class BuildOnableMixin
addBuildOn: (author, content) ->
build_ons = _.clone @get('build_ons')
build_ons ?= []
bo =
content: content
author: author
created_at: new Date()
build_ons.push(bo)
@set 'build_ons', build_ons
class TaggableMixin
addTag: (tag, tagger) =>
unless tag instanceof CK.Model.Tag
console.error("Cannot addTag ", tag ," because it is not a CK.Model.Tag instance!")
throw "Invalid tag (doesn't exist)"
unless tag.id
console.error("Cannot addTag ", tag ," to contribution ", @ ," because it doesn't have an id!")
throw "Invalid tag (no id)"
existingTagRelationships = @get('tags') || []
if _.any(existingTagRelationships, (tr) => tr.id is tag.id)
console.warn("Cannot addTag ", tag ," to contribution ", @ , " because it already has this tag.")
return this
tagRel = @tagRel tag, tagger
existingTagRelationships.push(tagRel)
@set 'tags', existingTagRelationships
return this
removeTag: (tag, tagger) =>
reducedTags = _.reject @get('tags'), (t) =>
(t.id is tag.id || t.name is tag.get('name')) and
(not tagger? || t.tagger is tagger)
@set('tags', reducedTags)
return this
hasTag: (tag, tagger) =>
_.any @get('tags'), (t) =>
t.id.toLowerCase() is tag.id and
(not tagger? || t.tagger is tagger)
class @Contribution extends @db.Document('contributions')
_.extend(@prototype, TaggableMixin.prototype)
tagRel: (tag, tagger) ->
return {
id: tag.id.toLowerCase()
name: tag.get('name')
tagger: tagger
tagged_at: new Date()
}
class @Proposal extends @db.Document('proposals')
_.extend(@prototype, VotableMixin.prototype)
validate: (attrs) ->
unless _.all(attrs.votes, (a) -> typeof a is 'string')
return "'votes' must be an array of strings but is #{JSON.stringify(attrs.votes)}"
setTag: (tag) ->
@_tag = null
@set 'tag',
id: tag.id.toLowerCase()
name: tag.get('name')
colorClass: tag.get('colorClass')
getColorClass: ->
if @has 'tag'
@get('tag').colorClass
else
null
getTag: ->
return null unless @has('tag')
# memoize
@_tag ?= CK.Model.awake.tags.get @get('tag').id
class @Investigation extends @db.Document('investigations')
_.extend(@prototype, VotableMixin.prototype)
_.extend(@prototype, BuildOnableMixin.prototype)
validate: (attrs) ->
unless _.all(attrs.authors, (a) -> typeof a is 'string')
return "'authors' must be an array of strings but is #{JSON.stringify(attrs.authors)}"
addAuthor: (username) ->
authors = _.clone @get('authors')
authors.push(username)
@set 'authors', authors
removeAuthor: (username) ->
authors = _.without @get('authors'), username
@set 'authors', authors
hasAuthor: (username) ->
_.contains @get('authors'), username
getProposal: ->
return null unless @get('proposal_id')
# memoize
@_proposal ?= CK.Model.awake.proposals.get @get('proposal_id')
getTag: ->
@getProposal().getTag()
class @Contributions extends @db.Collection('contributions')
model: CK.Model.Contribution
class @Proposals extends @db.Collection('proposals')
model: CK.Model.Proposal
class @Investigations extends @db.Collection('investigations')
model: CK.Model.Investigation
class @Tag extends @db.Document('tags')
class @Tags extends @db.Collection('tags')
model: CK.Model.Tag
class @State extends @db.Document('states')
class @States extends @db.Collection('states')
model: CK.Model.State
@initWakefulCollections = (wakefulUrl) ->
deferreds = []
camelCase = (str) ->
str.replace(/([\-_][a-z]|^[a-z])/g, ($1) -> $1.toUpperCase().replace(/[\-_]/,''))
@awake = {}
for collName in @requiredCollections
coll = new @[camelCase(collName)]()
coll.wake wakefulUrl
@awake[collName] = coll
deferreds.push coll.fetch()
jQuery.when.apply jQuery, deferreds
| 27131 | if typeof exports isnt "undefined" and exports isnt null
# we're in node
jQuery = require("jquery")
_ = require("underscore")
Backbone = require("backbone")
Backbone.$ = jQuery
Drowsy = require("backbone.drowsy").Drowsy
#var Wakeful = require('Backbone.Drowsy/wakeful').Wakeful;
CK = {}
exports.CK = CK
else
window.CK = window.CK or {}
CK = window.CK
jQuery = window.$
_ = window._
Drowsy = window.Drowsy
class CK.Model
@requiredCollections = [
'contributions',
'tags',
'states',
'proposals',
'investigations'
]
@init: (url, db) ->
deferredConfigure = jQuery.Deferred()
unless url?
throw new Error "Cannot configure model because no DrowsyDromedary URL was given!"
unless db?
throw new Error "Cannot configure model because no database name was given!"
@baseURL = url
@dbURL= "#{url}/#{db}"
@server = new Drowsy.Server(url)
@db = @server.database(db)
@createNecessaryCollections(@requiredCollections).then =>
@defineModelClasses()
deferredConfigure.resolve()
return deferredConfigure
@createNecessaryCollections: (requiredCollections) ->
dfs = []
df = jQuery.Deferred()
@db.collections (colls) =>
existingCollections = _.pluck(colls, 'name')
for col in requiredCollections
unless col in existingCollections
console.log "Creating collection '#{col}' under #{CK.Model.dbURL}"
dfs.push(@db.createCollection col)
jQuery.when.apply(jQuery, dfs).done -> df.resolve()
return df
@defineModelClasses: ->
class VotableMixin
addVote: (username) ->
votes = _.clone @get('votes')
votes ?= []
votes.push(username)
@set 'votes', votes
removeVote: (username) ->
votes = _.without @get('votes'), username
@set 'votes', votes
class BuildOnableMixin
addBuildOn: (author, content) ->
build_ons = _.clone @get('build_ons')
build_ons ?= []
bo =
content: content
author: <NAME>
created_at: new Date()
build_ons.push(bo)
@set 'build_ons', build_ons
class TaggableMixin
addTag: (tag, tagger) =>
unless tag instanceof CK.Model.Tag
console.error("Cannot addTag ", tag ," because it is not a CK.Model.Tag instance!")
throw "Invalid tag (doesn't exist)"
unless tag.id
console.error("Cannot addTag ", tag ," to contribution ", @ ," because it doesn't have an id!")
throw "Invalid tag (no id)"
existingTagRelationships = @get('tags') || []
if _.any(existingTagRelationships, (tr) => tr.id is tag.id)
console.warn("Cannot addTag ", tag ," to contribution ", @ , " because it already has this tag.")
return this
tagRel = @tagRel tag, tagger
existingTagRelationships.push(tagRel)
@set 'tags', existingTagRelationships
return this
removeTag: (tag, tagger) =>
reducedTags = _.reject @get('tags'), (t) =>
(t.id is tag.id || t.name is tag.get('name')) and
(not tagger? || t.tagger is tagger)
@set('tags', reducedTags)
return this
hasTag: (tag, tagger) =>
_.any @get('tags'), (t) =>
t.id.toLowerCase() is tag.id and
(not tagger? || t.tagger is tagger)
class @Contribution extends @db.Document('contributions')
_.extend(@prototype, TaggableMixin.prototype)
tagRel: (tag, tagger) ->
return {
id: tag.id.toLowerCase()
name: tag.get('name')
tagger: tagger
tagged_at: new Date()
}
class @Proposal extends @db.Document('proposals')
_.extend(@prototype, VotableMixin.prototype)
validate: (attrs) ->
unless _.all(attrs.votes, (a) -> typeof a is 'string')
return "'votes' must be an array of strings but is #{JSON.stringify(attrs.votes)}"
setTag: (tag) ->
@_tag = null
@set 'tag',
id: tag.id.toLowerCase()
name: tag.get('name')
colorClass: tag.get('colorClass')
getColorClass: ->
if @has 'tag'
@get('tag').colorClass
else
null
getTag: ->
return null unless @has('tag')
# memoize
@_tag ?= CK.Model.awake.tags.get @get('tag').id
class @Investigation extends @db.Document('investigations')
_.extend(@prototype, VotableMixin.prototype)
_.extend(@prototype, BuildOnableMixin.prototype)
validate: (attrs) ->
unless _.all(attrs.authors, (a) -> typeof a is 'string')
return "'authors' must be an array of strings but is #{JSON.stringify(attrs.authors)}"
addAuthor: (username) ->
authors = _.clone @get('authors')
authors.push(username)
@set 'authors', authors
removeAuthor: (username) ->
authors = _.without @get('authors'), username
@set 'authors', authors
hasAuthor: (username) ->
_.contains @get('authors'), username
getProposal: ->
return null unless @get('proposal_id')
# memoize
@_proposal ?= CK.Model.awake.proposals.get @get('proposal_id')
getTag: ->
@getProposal().getTag()
class @Contributions extends @db.Collection('contributions')
model: CK.Model.Contribution
class @Proposals extends @db.Collection('proposals')
model: CK.Model.Proposal
class @Investigations extends @db.Collection('investigations')
model: CK.Model.Investigation
class @Tag extends @db.Document('tags')
class @Tags extends @db.Collection('tags')
model: CK.Model.Tag
class @State extends @db.Document('states')
class @States extends @db.Collection('states')
model: CK.Model.State
@initWakefulCollections = (wakefulUrl) ->
deferreds = []
camelCase = (str) ->
str.replace(/([\-_][a-z]|^[a-z])/g, ($1) -> $1.toUpperCase().replace(/[\-_]/,''))
@awake = {}
for collName in @requiredCollections
coll = new @[camelCase(collName)]()
coll.wake wakefulUrl
@awake[collName] = coll
deferreds.push coll.fetch()
jQuery.when.apply jQuery, deferreds
| true | if typeof exports isnt "undefined" and exports isnt null
# we're in node
jQuery = require("jquery")
_ = require("underscore")
Backbone = require("backbone")
Backbone.$ = jQuery
Drowsy = require("backbone.drowsy").Drowsy
#var Wakeful = require('Backbone.Drowsy/wakeful').Wakeful;
CK = {}
exports.CK = CK
else
window.CK = window.CK or {}
CK = window.CK
jQuery = window.$
_ = window._
Drowsy = window.Drowsy
class CK.Model
@requiredCollections = [
'contributions',
'tags',
'states',
'proposals',
'investigations'
]
@init: (url, db) ->
deferredConfigure = jQuery.Deferred()
unless url?
throw new Error "Cannot configure model because no DrowsyDromedary URL was given!"
unless db?
throw new Error "Cannot configure model because no database name was given!"
@baseURL = url
@dbURL= "#{url}/#{db}"
@server = new Drowsy.Server(url)
@db = @server.database(db)
@createNecessaryCollections(@requiredCollections).then =>
@defineModelClasses()
deferredConfigure.resolve()
return deferredConfigure
@createNecessaryCollections: (requiredCollections) ->
dfs = []
df = jQuery.Deferred()
@db.collections (colls) =>
existingCollections = _.pluck(colls, 'name')
for col in requiredCollections
unless col in existingCollections
console.log "Creating collection '#{col}' under #{CK.Model.dbURL}"
dfs.push(@db.createCollection col)
jQuery.when.apply(jQuery, dfs).done -> df.resolve()
return df
@defineModelClasses: ->
class VotableMixin
addVote: (username) ->
votes = _.clone @get('votes')
votes ?= []
votes.push(username)
@set 'votes', votes
removeVote: (username) ->
votes = _.without @get('votes'), username
@set 'votes', votes
class BuildOnableMixin
addBuildOn: (author, content) ->
build_ons = _.clone @get('build_ons')
build_ons ?= []
bo =
content: content
author: PI:NAME:<NAME>END_PI
created_at: new Date()
build_ons.push(bo)
@set 'build_ons', build_ons
class TaggableMixin
addTag: (tag, tagger) =>
unless tag instanceof CK.Model.Tag
console.error("Cannot addTag ", tag ," because it is not a CK.Model.Tag instance!")
throw "Invalid tag (doesn't exist)"
unless tag.id
console.error("Cannot addTag ", tag ," to contribution ", @ ," because it doesn't have an id!")
throw "Invalid tag (no id)"
existingTagRelationships = @get('tags') || []
if _.any(existingTagRelationships, (tr) => tr.id is tag.id)
console.warn("Cannot addTag ", tag ," to contribution ", @ , " because it already has this tag.")
return this
tagRel = @tagRel tag, tagger
existingTagRelationships.push(tagRel)
@set 'tags', existingTagRelationships
return this
removeTag: (tag, tagger) =>
reducedTags = _.reject @get('tags'), (t) =>
(t.id is tag.id || t.name is tag.get('name')) and
(not tagger? || t.tagger is tagger)
@set('tags', reducedTags)
return this
hasTag: (tag, tagger) =>
_.any @get('tags'), (t) =>
t.id.toLowerCase() is tag.id and
(not tagger? || t.tagger is tagger)
class @Contribution extends @db.Document('contributions')
_.extend(@prototype, TaggableMixin.prototype)
tagRel: (tag, tagger) ->
return {
id: tag.id.toLowerCase()
name: tag.get('name')
tagger: tagger
tagged_at: new Date()
}
class @Proposal extends @db.Document('proposals')
_.extend(@prototype, VotableMixin.prototype)
validate: (attrs) ->
unless _.all(attrs.votes, (a) -> typeof a is 'string')
return "'votes' must be an array of strings but is #{JSON.stringify(attrs.votes)}"
setTag: (tag) ->
@_tag = null
@set 'tag',
id: tag.id.toLowerCase()
name: tag.get('name')
colorClass: tag.get('colorClass')
getColorClass: ->
if @has 'tag'
@get('tag').colorClass
else
null
getTag: ->
return null unless @has('tag')
# memoize
@_tag ?= CK.Model.awake.tags.get @get('tag').id
class @Investigation extends @db.Document('investigations')
_.extend(@prototype, VotableMixin.prototype)
_.extend(@prototype, BuildOnableMixin.prototype)
validate: (attrs) ->
unless _.all(attrs.authors, (a) -> typeof a is 'string')
return "'authors' must be an array of strings but is #{JSON.stringify(attrs.authors)}"
addAuthor: (username) ->
authors = _.clone @get('authors')
authors.push(username)
@set 'authors', authors
removeAuthor: (username) ->
authors = _.without @get('authors'), username
@set 'authors', authors
hasAuthor: (username) ->
_.contains @get('authors'), username
getProposal: ->
return null unless @get('proposal_id')
# memoize
@_proposal ?= CK.Model.awake.proposals.get @get('proposal_id')
getTag: ->
@getProposal().getTag()
class @Contributions extends @db.Collection('contributions')
model: CK.Model.Contribution
class @Proposals extends @db.Collection('proposals')
model: CK.Model.Proposal
class @Investigations extends @db.Collection('investigations')
model: CK.Model.Investigation
class @Tag extends @db.Document('tags')
class @Tags extends @db.Collection('tags')
model: CK.Model.Tag
class @State extends @db.Document('states')
class @States extends @db.Collection('states')
model: CK.Model.State
@initWakefulCollections = (wakefulUrl) ->
deferreds = []
camelCase = (str) ->
str.replace(/([\-_][a-z]|^[a-z])/g, ($1) -> $1.toUpperCase().replace(/[\-_]/,''))
@awake = {}
for collName in @requiredCollections
coll = new @[camelCase(collName)]()
coll.wake wakefulUrl
@awake[collName] = coll
deferreds.push coll.fetch()
jQuery.when.apply jQuery, deferreds
|
[
{
"context": "{x: 1.8*@width / 6, y: 1.2*@height / 3.5},\n \"autres\": {x: 3.1 *@width / 6, y: 1.4*@height / 3},\n ",
"end": 2263,
"score": 0.5924499034881592,
"start": 2257,
"tag": "NAME",
"value": "autres"
},
{
"context": ": {x: 3.1 * @width / 6, y: 1*@height / 3},\n ... | coffee/vis.coffee | JeanAbbiateci/art-for-dummies-bubbles | 1 |
class BubbleChart
constructor: (data) ->
@data = data
@width = 690
@height = 660
@tooltip = CustomTooltip("gates_tooltip", 185)
@center = {x: 2 * @width / 3, y: 1*@height / 3}
@year_centers = {
"2008": {x: 1.8 *@width / 6, y: 1*@height / 3},
"2009": {x: 3.13 *@width / 6, y: 1.05*@height / 3},
"2010": {x: 4.2 * @width / 6, y: 1.05*@height / 3}
"2011": {x: 2.1 * @width / 6, y: 1.6*@height / 3}
"2012": {x: 3.8* @width / 6, y: 1.2 *@height / 2}
}
@top_centers = {
"1": {x: 2.9 *@width / 6, y: 1.1*@height / 3},
"2": {x: 3.5 *@width / 6, y: 1.2*@height / 3},
"3": {x: 3.8 * @width / 6, y: 1.5*@height / 3}
"4": {x: 3.7 * @width / 6, y: 1.8*@height / 3}
"5": {x: 3.27 * @width / 6, y: 1.9 *@height / 3}
"6": {x: 2.8*@width / 6, y: 1.95*@height / 3},
"7": {x: 2.42 *@width / 6, y: 1.86*@height / 3},
"8": {x: 2.2 * @width / 6, y: 1.7*@height / 3}
"9": {x: 2.8 * @width / 8, y: 1.5*@height / 3}
"10": {x:3.1* @width / 8, y: 1.3*@height / 3}
"0": {x: 12 * @width / 6, y: 6*@height / 3}
}
@sexe_centers = {
"2": {x: 3.9*@width / 6, y: 1.9*@height / 4},
"1": {x: 2.6 *@width / 6, y: 1.9*@height / 4},
}
@mort_centers = {
"2": {x: 2.4*@width / 6, y: @height / 2},
"1": {x: 3.7 *@width / 6, y: @height / 2},
}
@nat1_centers = {
"Chine": {x: 4.15*@width / 6, y: 1.6*@height / 3},
"Etats-Unis": {x: 2.05 * @width / 6, y: 1.05*@height / 3},
"Europe": {x: 2.9 * @width / 6, y: 1.3*@height / 3},
"Russie": {x: 3.7 * @width / 6, y: 1.2*@height / 4},
"Argentine": {x: 1.7 * @width / 6, y: 2.2*@height / 4},
"Japon": {x: 4.4 * @width / 6, y: 1.15*@height / 3},
}
@maitre_centers = {
"1": {x: 1.7*@width / 6, y: @height / 3},
"2": {x: 3 *@width / 6, y: @height / 3},
"3": {x: 4.5 * @width / 6, y: @height / 3},
"4": {x: 1.7 * @width / 6, y: 1.9*@height / 3},
"5": {x: 3 * @width / 6, y: 1.9*@height / 3},
"6": {x: 4.5 *@width / 6, y: 1.9*@height / 3},
"0": {x: 15 * @width / 6, y: -4*@height / 3}
}
@auction1_centers = {
"Paris": {x: 1.8*@width / 6, y: 1.2*@height / 3.5},
"autres": {x: 3.1 *@width / 6, y: 1.4*@height / 3},
"Hong-Kong": {x: 3.1 * @width / 6, y: 1*@height / 3},
"Londres": {x: 4 * @width / 6, y: 1.6*@height / 3},
"Pékin": {x: 4.5 * @width / 6, y: 1*@height / 3},
"New-York": {x: 2.1 * @width / 6, y: 1.8*@height / 3},
}
@surface_centers = {
"A": {x: 2*@width / 6, y: @height / 2.5},
"B": {x: 2 *@width / 6, y: @height / 2.5},
"C": {x: 3.1 * @width / 6, y: @height / 2.5}
"D": {x: 4.2 * @width / 6, y: @height / 2.5}
"E": {x: 4.2* @width / 6, y: 1.8*@height / 3}
"F": {x: 1.8*@width / 6, y: 2*@height / 3},
"G": {x: 2.7 *@width / 6, y: 2*@height / 3},
"Z": {x: 12 * @width / 6, y: 2*@height / 3}
"none": {x: 12 * @width / 6, y: 2*@height / 3}
}
@datesiecle_centers = {
"14th": {x: 1.25*@width / 5, y: 1*@height / 3.4},
"16th": {x: 2.47 *@width / 5, y: 1*@height / 2.9},
"17th": {x: 3.05 * @width / 5, y: 1*@height / 3.1}
"18th": {x: 3.78 * @width / 5, y: 1*@height / 3.4}
"19th": {x: 1.7 * @width / 5, y: 1.7*@height / 3}
"20th": {x: 2.5*@width / 5, y: 1.8*@height / 3},
"21th": {x: 3.4*@width / 5, y: 1.45*@height / 3},
"none": {x: 12 * @width / 6, y: -8*@height / 3}
}
@date20_centers = {
"1900": {x: 1.5*@width / 6, y: 0.95*@height / 4},
"1910": {x: 2.5 *@width / 6, y: 1.1*@height / 4},
"1920": {x: 3.5 * @width / 6, y: 1*@height / 4}
"1930": {x: 4.5 * @width / 6, y: 1.1*@height / 4},
"1940": {x: 1.5 * @width / 6, y: 1.95*@height / 4}
"1950": {x: 2.5*@width / 6, y: 1.95*@height / 4},
"1960": {x: 3.5 *@width / 6, y: 2.12*@height / 4},
"1970": {x: 4.5 * @width / 6, y: 1.95*@height / 4}
"1980": {x: 1.5 * @width / 6, y: 3.1*@height / 4},
"1990": {x: 2.5 * @width / 6, y: 3*@height / 4},
"2000": {x: 3.5 * @width / 6, y: 2.9*@height / 4},
"2010": {x:4.55 * @width / 6, y: 3.04*@height / 4},
"none": {x: 12 * @width / 6, y: -10*@height / 3},
}
@layout_gravity = -0.01
@damper = 0.1
@vis = null
@nodes = []
@force = null
@circles = null
@fill_color = d3.scale.ordinal()
.domain(["D", "B", "A","C","none"])
.range(["#e1005d", "#7D7963", "#BDBDBD","#178aca","#fff"])
max_amount = d3.max(@data, (d) -> parseInt(d.total_amount))
@radius_scale = d3.scale.pow().exponent(0.9).domain([0, max_amount]).range([2, 40])
this.create_nodes()
this.create_vis()
create_nodes: () =>
@data.forEach (d) =>
node = {
id: d.id
radius: @radius_scale(parseInt(d.total_amount))
value: d.total_amount
name: d.nom
top: d.top
maitre: d.maitre
nat: d.nat
nat1: d.nat1
title: d.title
sexe: d.sexe
mort: d.mort
datevente: d.datavente
auction: d.auction
year: d.start_year
auction1: d.auction1
media: d.media
media1: d.media1
surface: d.surface
date: d.date
datesiecle: d.datesiecle
date20: d.date20
img: d.img
x: Math.random() * 900
y: Math.random() * 800
}
@nodes.push node
@nodes.sort (a,b) -> b.value - a.value
create_vis: () =>
@vis = d3.select("#vis").append("svg")
.attr("width", @width)
.attr("height", @height)
.attr("id", "svg_vis")
@circles = @vis.selectAll("circle")
.data(@nodes, (d) -> d.id)
that = this
@circles.enter().append("circle")
.attr("r", 0)
.attr("fill", (d) => @fill_color(d.media1))
.attr("stroke-width", 1.2)
.attr("stroke","#666")
.attr("id", (d) -> "bubble_#{d.id}")
.on("mouseover", (d,i) -> that.show_details(d,i,this))
.on("mouseout", (d,i) -> that.hide_details(d,i,this))
@circles.transition().duration(2000).attr("r", (d) -> d.radius)
charge: (d) ->
-Math.pow(d.radius, 2.0) / 8
start: () =>
@force = d3.layout.force()
.nodes(@nodes)
.size([@width, @height])
display_group_all: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_center(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_auction1s()
this.hide_datesiecles()
this.hide_date20s()
this.hide_surfaces()
this.hide_maitres()
this.hide_nat1s()
this.hide_morts()
this.hide_tops()
this.hide_sexes()
move_towards_center: (alpha) =>
(d) =>
d.x = d.x + (@center.x - d.x) * (@damper + 0.02) * alpha
d.y = d.y + (@center.y - d.y) * (@damper + 0.02) * alpha
display_by_year: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_year(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_tops()
this.hide_datesiecles()
this.hide_date20s()
this.hide_auction1s()
this.hide_surfaces()
this.hide_maitres()
this.hide_nat1s()
this.hide_morts()
this.hide_sexes()
this.display_years()
display_by_top: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_top(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_maitres()
this.hide_datesiecles()
this.hide_auction1s()
this.hide_date20s()
this.hide_surfaces()
this.hide_nat1s()
this.hide_morts()
this.hide_sexes()
this.display_tops()
display_by_sexe: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_sexe(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_nat1s()
this.hide_auction1s()
this.hide_date20s()
this.hide_surfaces()
this.hide_maitres()
this.hide_morts()
this.hide_datesiecles()
this.hide_tops()
this.display_sexes()
display_by_mort: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_mort(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_nat1s()
this.hide_maitres()
this.hide_surfaces()
this.hide_datesiecles()
this.hide_date20s()
this.hide_auction1s()
this.hide_sexes()
this.hide_tops()
this.display_morts()
display_by_nat1: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_nat1(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_surfaces()
this.hide_maitres()
this.hide_date20s()
this.hide_auction1s()
this.hide_datesiecles()
this.hide_sexes()
this.hide_tops()
this.display_nat1s()
display_by_maitre: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_maitre(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_auction1s()
this.hide_surfaces()
this.hide_date20s()
this.hide_datesiecles()
this.hide_sexes()
this.hide_tops()
this.hide_nat1s()
this.display_maitres()
display_by_auction1: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_auction1(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_datesiecles()
this.hide_surfaces()
this.hide_maitres()
this.hide_date20s()
this.hide_sexes()
this.hide_tops()
this.hide_nat1s()
this.display_auction1s()
display_by_surface: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_surface(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_datesiecles()
this.hide_auction1s()
this.hide_maitres()
this.hide_date20s()
this.hide_sexes()
this.hide_tops()
this.hide_nat1s()
this.display_surfaces()
display_by_datesiecle: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_datesiecle(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_date20s()
this.hide_maitres()
this.hide_auction1s()
this.hide_sexes()
this.hide_tops()
this.hide_surfaces()
this.hide_nat1s()
this.display_datesiecles()
display_by_date20: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_date20(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_datesiecles()
this.hide_auction1s()
this.hide_maitres()
this.hide_sexes()
this.hide_tops()
this.hide_surfaces()
this.hide_nat1s()
this.display_date20s()
move_towards_year: (alpha) =>
(d) =>
target = @year_centers[d.year]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_top: (alpha) =>
(d) =>
target = @top_centers[d.top]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_sexe: (alpha) =>
(d) =>
target = @sexe_centers[d.sexe]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_mort: (alpha) =>
(d) =>
target = @mort_centers[d.mort]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_nat1: (alpha) =>
(d) =>
target = @nat1_centers[d.nat1]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_maitre: (alpha) =>
(d) =>
target = @maitre_centers[d.maitre]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_auction1: (alpha) =>
(d) =>
target = @auction1_centers[d.auction1]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_surface: (alpha) =>
(d) =>
target = @surface_centers[d.surface]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_datesiecle: (alpha) =>
(d) =>
target = @datesiecle_centers[d.datesiecle]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_date20: (alpha) =>
(d) =>
target = @date20_centers[d.date20]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
display_years: () =>
years_x = {"2008": 165, "2009": 353, "2010": 555,"2011": 205,"2012": 500}
years_y = {"2008": 40, "2009": 80, "2010": 40,"2011": 290,"2012": 335}
years_data = d3.keys(years_x)
years = @vis.selectAll(".years")
.data(years_data)
years.enter().append("text")
.attr("class", "years")
.attr("x", (d) => years_x[d] )
.attr("y", (d) => years_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_tops: () =>
tops_x = {"Top 10":328,"(2008-2012)":328}
tops_y = {"Top 10":340,"(2008-2012)":360}
tops_data = d3.keys(tops_x)
tops = @vis.selectAll(".tops")
.data(tops_data)
tops.enter().append("text")
.attr("class", "tops")
.attr("x", (d) => tops_x[d] )
.attr("y", (d) => tops_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_sexes: () =>
sexes_x = {"hommes": 310, "femmes": 590}
sexes_y = {"hommes": 60, "femmes": 275}
sexes_data = d3.keys(sexes_x)
sexes = @vis.selectAll(".sexes")
.data(sexes_data)
sexes.enter().append("text")
.attr("class", "sexes")
.attr("x", (d) => sexes_x[d] )
.attr("y", (d) => sexes_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_morts: () =>
morts_x = {"vivants": 145, "morts": 450}
morts_y = {"vivants": 240, "morts": 90}
morts_data = d3.keys(morts_x)
morts = @vis.selectAll(".morts")
.data(morts_data)
morts.enter().append("text")
.attr("class", "morts")
.attr("x", (d) => morts_x[d] )
.attr("y", (d) => morts_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_nat1s: () =>
nat1s_x = {"Etats-Unis": 150, "Argentine": 100,"Europe": 390,"Chine":610,"Japon":110,"Russie":520,"Japon":620}
nat1s_y = {"Etats-Unis": 30, "Argentine": 410,"Europe": 80,"Chine":280,"Japon":600,"Russie":55,"Japon":175}
nat1s_data = d3.keys(nat1s_x)
nat1s = @vis.selectAll(".nat1s")
.data(nat1s_data)
nat1s.enter().append("text")
.attr("class", "nat1s")
.attr("x", (d) => nat1s_x[d] )
.attr("y", (d) => nat1s_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_maitres: () =>
maitres_x = {"Bacon": 140,"Giacometti": 345,"Monet": 550,"Picasso": 145,"Richter": 355,"Warhol": 550,}
maitres_y = {"Bacon": 90,"Giacometti": 90,"Monet": 90,"Picasso": 360,"Richter": 360,"Warhol": 360}
maitres_data = d3.keys(maitres_x)
maitres = @vis.selectAll(".maitres")
.data(maitres_data)
maitres.enter().append("text")
.attr("class", "maitres")
.attr("x", (d) => maitres_x[d] )
.attr("y", (d) => maitres_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_auction1s: () =>
auction1s_x = {"Paris":150,"Hong-Kong":370,"Autres":360,"New-York":175,"Londres":500,"Pékin":590}
auction1s_y = {"Paris":65,"Hong-Kong":65,"Autres":170,"New-York":235,"Londres":225,"Pékin":55}
auction1s_data = d3.keys(auction1s_x)
auction1s = @vis.selectAll(".auction1s")
.data(auction1s_data)
auction1s.enter().append("text")
.attr("class", "auction1s")
.attr("x", (d) => auction1s_x[d] )
.attr("y", (d) => auction1s_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_surfaces: () =>
surfaces_x = {"PEINTURE - DESSIN - AQUARELLE": 350, "-1m²": 160, "1-2m²": 370,"2-3m²": 570, "+3m²": 570,"SCULPTURE":220,"-1m de haut":110,"+1m de haut":300 }
surfaces_y = {"PEINTURE - DESSIN - AQUARELLE": 40, "-1m²": 90, "1-2m²": 90,"2-3m²": 90, "+3m²": 400,"SCULPTURE":415,"-1m de haut":450,"+1m de haut":450}
surfaces_data = d3.keys(surfaces_x)
surfaces = @vis.selectAll(".surfaces")
.data(surfaces_data)
surfaces.enter().append("text")
.attr("class", "surfaces")
.attr("x", (d) => surfaces_x[d] )
.attr("y", (d) => surfaces_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_datesiecles: () =>
datesiecles_x = {"14ème": 90, "15ème": 220, "16ème": 350,"17ème": 480,"18ème": 610,"19ème":100,"20ème":350,"21ème":600}
datesiecles_y = {"14ème": 40, "15ème": 40, "16ème": 40,"17ème": 40,"18ème": 40,"19ème":210,"20ème":210,"21ème":210}
datesiecles_data = d3.keys(datesiecles_x)
datesiecles = @vis.selectAll(".datesiecles")
.data(datesiecles_data)
datesiecles.enter().append("text")
.attr("class", "datesiecles")
.attr("x", (d) => datesiecles_x[d] )
.attr("y", (d) => datesiecles_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_date20s: () =>
date20s_x = {"1900-1910": 90,"1910-1920": 270,"1920-1930": 426,"1930-1940": 585,"1940-1950": 78,"1950-1960": 250,"1960-1970": 426,"1970-1980": 620,"1980-1990": 95,"1990-2000": 250,"2000-2010": 426,"+ 2010": 590}
date20s_y = {"1900-1910": 30,"1910-1920": 30,"1920-1930": 30,"1930-1940": 30,"1940-1950": 254,"1950-1960": 254,"1960-1970": 254,"1970-1980": 254,"1980-1990": 520,"1990-2000": 520,"2000-2010": 555,"+ 2010": 555}
date20s_data = d3.keys(date20s_x)
date20s = @vis.selectAll(".date20s")
.data(date20s_data)
date20s.enter().append("text")
.attr("class", "date20s")
.attr("x", (d) => date20s_x[d] )
.attr("y", (d) => date20s_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
hide_years: () =>
years = @vis.selectAll(".years").remove()
show_details: (data, i, element) =>
d3.select(element).attr("stroke","#000")
content = "<span class=\"name\"></span><span class=\"value\">#{addCommas(data.value)} dollars</span><br><hr>"
content += "<span class=\"name\"></span><span class=\"value\"><big> #{data.title}</big></span><br>"
content += "<span class=\"name\"></span><span class=\"value\"><small> #{data.name} (#{data.nat})</small></span>"
content += "<span class=\"name\"></span><span class=\"value\"><small> - #{data.date}</small></span><br><hr>"
content +="<span class=\"name\"><img src='img/#{data.img}'></img></span>"
@tooltip.showTooltip(content,d3.event)
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_tops: () =>
tops = @vis.selectAll(".tops").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_sexes: () =>
sexes = @vis.selectAll(".sexes").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_morts: () =>
morts = @vis.selectAll(".morts").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_nat1s: () =>
nat1s = @vis.selectAll(".nat1s").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_maitres: () =>
maitres = @vis.selectAll(".maitres").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_auction1s: () =>
auction1s = @vis.selectAll(".auction1s").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_surfaces: () =>
surfaces = @vis.selectAll(".surfaces").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_datesiecles: () =>
datesiecles = @vis.selectAll(".datesiecles").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_date20s: () =>
date20s = @vis.selectAll(".date20s").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
root = exports ? this
$ ->
chart = null
render_vis = (csv) ->
chart = new BubbleChart csv
chart.start()
root.display_year()
root.display_all = () =>
chart.display_group_all()
root.display_year = () =>
chart.display_by_year()
root.display_top = () =>
chart.display_by_top()
root.display_sexe = () =>
chart.display_by_sexe()
root.display_mort = () =>
chart.display_by_mort()
root.display_nat1 = () =>
chart.display_by_nat1()
root.display_maitre = () =>
chart.display_by_maitre()
root.display_auction1 = () =>
chart.display_by_auction1()
root.display_surface = () =>
chart.display_by_surface()
root.display_datesiecle = () =>
chart.display_by_datesiecle()
root.display_date20 = () =>
chart.display_by_date20()
root.toggle_view = (view_type) =>
if view_type == 'year'
root.display_year()
else if view_type == 'top'
root.display_top()
else if view_type == 'sexe'
root.display_sexe()
else if view_type == 'mort'
root.display_mort()
else if view_type == 'nat1'
root.display_nat1()
else if view_type == 'maitre'
root.display_maitre()
else if view_type == 'auction1'
root.display_auction1()
else if view_type == 'media1'
root.display_media1()
else if view_type == 'surface'
root.display_surface()
else if view_type == 'datesiecle'
root.display_datesiecle()
else if view_type == 'date20'
root.display_date20()
else
root.display_all()
d3.csv "data/dataeng.csv", render_vis | 130759 |
class BubbleChart
constructor: (data) ->
@data = data
@width = 690
@height = 660
@tooltip = CustomTooltip("gates_tooltip", 185)
@center = {x: 2 * @width / 3, y: 1*@height / 3}
@year_centers = {
"2008": {x: 1.8 *@width / 6, y: 1*@height / 3},
"2009": {x: 3.13 *@width / 6, y: 1.05*@height / 3},
"2010": {x: 4.2 * @width / 6, y: 1.05*@height / 3}
"2011": {x: 2.1 * @width / 6, y: 1.6*@height / 3}
"2012": {x: 3.8* @width / 6, y: 1.2 *@height / 2}
}
@top_centers = {
"1": {x: 2.9 *@width / 6, y: 1.1*@height / 3},
"2": {x: 3.5 *@width / 6, y: 1.2*@height / 3},
"3": {x: 3.8 * @width / 6, y: 1.5*@height / 3}
"4": {x: 3.7 * @width / 6, y: 1.8*@height / 3}
"5": {x: 3.27 * @width / 6, y: 1.9 *@height / 3}
"6": {x: 2.8*@width / 6, y: 1.95*@height / 3},
"7": {x: 2.42 *@width / 6, y: 1.86*@height / 3},
"8": {x: 2.2 * @width / 6, y: 1.7*@height / 3}
"9": {x: 2.8 * @width / 8, y: 1.5*@height / 3}
"10": {x:3.1* @width / 8, y: 1.3*@height / 3}
"0": {x: 12 * @width / 6, y: 6*@height / 3}
}
@sexe_centers = {
"2": {x: 3.9*@width / 6, y: 1.9*@height / 4},
"1": {x: 2.6 *@width / 6, y: 1.9*@height / 4},
}
@mort_centers = {
"2": {x: 2.4*@width / 6, y: @height / 2},
"1": {x: 3.7 *@width / 6, y: @height / 2},
}
@nat1_centers = {
"Chine": {x: 4.15*@width / 6, y: 1.6*@height / 3},
"Etats-Unis": {x: 2.05 * @width / 6, y: 1.05*@height / 3},
"Europe": {x: 2.9 * @width / 6, y: 1.3*@height / 3},
"Russie": {x: 3.7 * @width / 6, y: 1.2*@height / 4},
"Argentine": {x: 1.7 * @width / 6, y: 2.2*@height / 4},
"Japon": {x: 4.4 * @width / 6, y: 1.15*@height / 3},
}
@maitre_centers = {
"1": {x: 1.7*@width / 6, y: @height / 3},
"2": {x: 3 *@width / 6, y: @height / 3},
"3": {x: 4.5 * @width / 6, y: @height / 3},
"4": {x: 1.7 * @width / 6, y: 1.9*@height / 3},
"5": {x: 3 * @width / 6, y: 1.9*@height / 3},
"6": {x: 4.5 *@width / 6, y: 1.9*@height / 3},
"0": {x: 15 * @width / 6, y: -4*@height / 3}
}
@auction1_centers = {
"Paris": {x: 1.8*@width / 6, y: 1.2*@height / 3.5},
"<NAME>": {x: 3.1 *@width / 6, y: 1.4*@height / 3},
"Hong-Kong": {x: 3.1 * @width / 6, y: 1*@height / 3},
"<NAME>": {x: 4 * @width / 6, y: 1.6*@height / 3},
"<NAME>": {x: 4.5 * @width / 6, y: 1*@height / 3},
"New-York": {x: 2.1 * @width / 6, y: 1.8*@height / 3},
}
@surface_centers = {
"A": {x: 2*@width / 6, y: @height / 2.5},
"B": {x: 2 *@width / 6, y: @height / 2.5},
"C": {x: 3.1 * @width / 6, y: @height / 2.5}
"D": {x: 4.2 * @width / 6, y: @height / 2.5}
"E": {x: 4.2* @width / 6, y: 1.8*@height / 3}
"F": {x: 1.8*@width / 6, y: 2*@height / 3},
"G": {x: 2.7 *@width / 6, y: 2*@height / 3},
"Z": {x: 12 * @width / 6, y: 2*@height / 3}
"none": {x: 12 * @width / 6, y: 2*@height / 3}
}
@datesiecle_centers = {
"14th": {x: 1.25*@width / 5, y: 1*@height / 3.4},
"16th": {x: 2.47 *@width / 5, y: 1*@height / 2.9},
"17th": {x: 3.05 * @width / 5, y: 1*@height / 3.1}
"18th": {x: 3.78 * @width / 5, y: 1*@height / 3.4}
"19th": {x: 1.7 * @width / 5, y: 1.7*@height / 3}
"20th": {x: 2.5*@width / 5, y: 1.8*@height / 3},
"21th": {x: 3.4*@width / 5, y: 1.45*@height / 3},
"none": {x: 12 * @width / 6, y: -8*@height / 3}
}
@date20_centers = {
"1900": {x: 1.5*@width / 6, y: 0.95*@height / 4},
"1910": {x: 2.5 *@width / 6, y: 1.1*@height / 4},
"1920": {x: 3.5 * @width / 6, y: 1*@height / 4}
"1930": {x: 4.5 * @width / 6, y: 1.1*@height / 4},
"1940": {x: 1.5 * @width / 6, y: 1.95*@height / 4}
"1950": {x: 2.5*@width / 6, y: 1.95*@height / 4},
"1960": {x: 3.5 *@width / 6, y: 2.12*@height / 4},
"1970": {x: 4.5 * @width / 6, y: 1.95*@height / 4}
"1980": {x: 1.5 * @width / 6, y: 3.1*@height / 4},
"1990": {x: 2.5 * @width / 6, y: 3*@height / 4},
"2000": {x: 3.5 * @width / 6, y: 2.9*@height / 4},
"2010": {x:4.55 * @width / 6, y: 3.04*@height / 4},
"none": {x: 12 * @width / 6, y: -10*@height / 3},
}
@layout_gravity = -0.01
@damper = 0.1
@vis = null
@nodes = []
@force = null
@circles = null
@fill_color = d3.scale.ordinal()
.domain(["D", "B", "A","C","none"])
.range(["#e1005d", "#7D7963", "#BDBDBD","#178aca","#fff"])
max_amount = d3.max(@data, (d) -> parseInt(d.total_amount))
@radius_scale = d3.scale.pow().exponent(0.9).domain([0, max_amount]).range([2, 40])
this.create_nodes()
this.create_vis()
create_nodes: () =>
@data.forEach (d) =>
node = {
id: d.id
radius: @radius_scale(parseInt(d.total_amount))
value: d.total_amount
name: d.nom
top: d.top
maitre: d.maitre
nat: d.nat
nat1: d.nat1
title: d.title
sexe: d.sexe
mort: d.mort
datevente: d.datavente
auction: d.auction
year: d.start_year
auction1: d.auction1
media: d.media
media1: d.media1
surface: d.surface
date: d.date
datesiecle: d.datesiecle
date20: d.date20
img: d.img
x: Math.random() * 900
y: Math.random() * 800
}
@nodes.push node
@nodes.sort (a,b) -> b.value - a.value
create_vis: () =>
@vis = d3.select("#vis").append("svg")
.attr("width", @width)
.attr("height", @height)
.attr("id", "svg_vis")
@circles = @vis.selectAll("circle")
.data(@nodes, (d) -> d.id)
that = this
@circles.enter().append("circle")
.attr("r", 0)
.attr("fill", (d) => @fill_color(d.media1))
.attr("stroke-width", 1.2)
.attr("stroke","#666")
.attr("id", (d) -> "bubble_#{d.id}")
.on("mouseover", (d,i) -> that.show_details(d,i,this))
.on("mouseout", (d,i) -> that.hide_details(d,i,this))
@circles.transition().duration(2000).attr("r", (d) -> d.radius)
charge: (d) ->
-Math.pow(d.radius, 2.0) / 8
start: () =>
@force = d3.layout.force()
.nodes(@nodes)
.size([@width, @height])
display_group_all: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_center(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_auction1s()
this.hide_datesiecles()
this.hide_date20s()
this.hide_surfaces()
this.hide_maitres()
this.hide_nat1s()
this.hide_morts()
this.hide_tops()
this.hide_sexes()
move_towards_center: (alpha) =>
(d) =>
d.x = d.x + (@center.x - d.x) * (@damper + 0.02) * alpha
d.y = d.y + (@center.y - d.y) * (@damper + 0.02) * alpha
display_by_year: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_year(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_tops()
this.hide_datesiecles()
this.hide_date20s()
this.hide_auction1s()
this.hide_surfaces()
this.hide_maitres()
this.hide_nat1s()
this.hide_morts()
this.hide_sexes()
this.display_years()
display_by_top: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_top(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_maitres()
this.hide_datesiecles()
this.hide_auction1s()
this.hide_date20s()
this.hide_surfaces()
this.hide_nat1s()
this.hide_morts()
this.hide_sexes()
this.display_tops()
display_by_sexe: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_sexe(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_nat1s()
this.hide_auction1s()
this.hide_date20s()
this.hide_surfaces()
this.hide_maitres()
this.hide_morts()
this.hide_datesiecles()
this.hide_tops()
this.display_sexes()
display_by_mort: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_mort(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_nat1s()
this.hide_maitres()
this.hide_surfaces()
this.hide_datesiecles()
this.hide_date20s()
this.hide_auction1s()
this.hide_sexes()
this.hide_tops()
this.display_morts()
display_by_nat1: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_nat1(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_surfaces()
this.hide_maitres()
this.hide_date20s()
this.hide_auction1s()
this.hide_datesiecles()
this.hide_sexes()
this.hide_tops()
this.display_nat1s()
display_by_maitre: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_maitre(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_auction1s()
this.hide_surfaces()
this.hide_date20s()
this.hide_datesiecles()
this.hide_sexes()
this.hide_tops()
this.hide_nat1s()
this.display_maitres()
display_by_auction1: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_auction1(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_datesiecles()
this.hide_surfaces()
this.hide_maitres()
this.hide_date20s()
this.hide_sexes()
this.hide_tops()
this.hide_nat1s()
this.display_auction1s()
display_by_surface: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_surface(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_datesiecles()
this.hide_auction1s()
this.hide_maitres()
this.hide_date20s()
this.hide_sexes()
this.hide_tops()
this.hide_nat1s()
this.display_surfaces()
display_by_datesiecle: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_datesiecle(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_date20s()
this.hide_maitres()
this.hide_auction1s()
this.hide_sexes()
this.hide_tops()
this.hide_surfaces()
this.hide_nat1s()
this.display_datesiecles()
display_by_date20: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_date20(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_datesiecles()
this.hide_auction1s()
this.hide_maitres()
this.hide_sexes()
this.hide_tops()
this.hide_surfaces()
this.hide_nat1s()
this.display_date20s()
move_towards_year: (alpha) =>
(d) =>
target = @year_centers[d.year]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_top: (alpha) =>
(d) =>
target = @top_centers[d.top]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_sexe: (alpha) =>
(d) =>
target = @sexe_centers[d.sexe]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_mort: (alpha) =>
(d) =>
target = @mort_centers[d.mort]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_nat1: (alpha) =>
(d) =>
target = @nat1_centers[d.nat1]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_maitre: (alpha) =>
(d) =>
target = @maitre_centers[d.maitre]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_auction1: (alpha) =>
(d) =>
target = @auction1_centers[d.auction1]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_surface: (alpha) =>
(d) =>
target = @surface_centers[d.surface]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_datesiecle: (alpha) =>
(d) =>
target = @datesiecle_centers[d.datesiecle]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_date20: (alpha) =>
(d) =>
target = @date20_centers[d.date20]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
display_years: () =>
years_x = {"2008": 165, "2009": 353, "2010": 555,"2011": 205,"2012": 500}
years_y = {"2008": 40, "2009": 80, "2010": 40,"2011": 290,"2012": 335}
years_data = d3.keys(years_x)
years = @vis.selectAll(".years")
.data(years_data)
years.enter().append("text")
.attr("class", "years")
.attr("x", (d) => years_x[d] )
.attr("y", (d) => years_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_tops: () =>
tops_x = {"Top 10":328,"(2008-2012)":328}
tops_y = {"Top 10":340,"(2008-2012)":360}
tops_data = d3.keys(tops_x)
tops = @vis.selectAll(".tops")
.data(tops_data)
tops.enter().append("text")
.attr("class", "tops")
.attr("x", (d) => tops_x[d] )
.attr("y", (d) => tops_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_sexes: () =>
sexes_x = {"hommes": 310, "femmes": 590}
sexes_y = {"hommes": 60, "femmes": 275}
sexes_data = d3.keys(sexes_x)
sexes = @vis.selectAll(".sexes")
.data(sexes_data)
sexes.enter().append("text")
.attr("class", "sexes")
.attr("x", (d) => sexes_x[d] )
.attr("y", (d) => sexes_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_morts: () =>
morts_x = {"vivants": 145, "morts": 450}
morts_y = {"vivants": 240, "morts": 90}
morts_data = d3.keys(morts_x)
morts = @vis.selectAll(".morts")
.data(morts_data)
morts.enter().append("text")
.attr("class", "morts")
.attr("x", (d) => morts_x[d] )
.attr("y", (d) => morts_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_nat1s: () =>
nat1s_x = {"Etats-Unis": 150, "Argentine": 100,"Europe": 390,"Chine":610,"Japon":110,"Russie":520,"Japon":620}
nat1s_y = {"Etats-Unis": 30, "Argentine": 410,"Europe": 80,"Chine":280,"Japon":600,"Russie":55,"Japon":175}
nat1s_data = d3.keys(nat1s_x)
nat1s = @vis.selectAll(".nat1s")
.data(nat1s_data)
nat1s.enter().append("text")
.attr("class", "nat1s")
.attr("x", (d) => nat1s_x[d] )
.attr("y", (d) => nat1s_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_maitres: () =>
maitres_x = {"<NAME>": 140,"<NAME>": 345,"Mon<NAME>": 550,"Picasso": 145,"Richter": 355,"Warhol": 550,}
maitres_y = {"<NAME>": 90,"<NAME>": 90,"Mon<NAME>": 90,"Picasso": 360,"Richter": 360,"Warhol": 360}
maitres_data = d3.keys(maitres_x)
maitres = @vis.selectAll(".maitres")
.data(maitres_data)
maitres.enter().append("text")
.attr("class", "maitres")
.attr("x", (d) => maitres_x[d] )
.attr("y", (d) => maitres_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_auction1s: () =>
auction1s_x = {"Paris":150,"Hong-Kong":370,"Autres":360,"New-York":175,"Londres":500,"Pékin":590}
auction1s_y = {"Paris":65,"Hong-Kong":65,"Autres":170,"New-York":235,"Londres":225,"Pékin":55}
auction1s_data = d3.keys(auction1s_x)
auction1s = @vis.selectAll(".auction1s")
.data(auction1s_data)
auction1s.enter().append("text")
.attr("class", "auction1s")
.attr("x", (d) => auction1s_x[d] )
.attr("y", (d) => auction1s_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_surfaces: () =>
surfaces_x = {"PEINTURE - DESSIN - AQUARELLE": 350, "-1m²": 160, "1-2m²": 370,"2-3m²": 570, "+3m²": 570,"SCULPTURE":220,"-1m de haut":110,"+1m de haut":300 }
surfaces_y = {"PEINTURE - DESSIN - AQUARELLE": 40, "-1m²": 90, "1-2m²": 90,"2-3m²": 90, "+3m²": 400,"SCULPTURE":415,"-1m de haut":450,"+1m de haut":450}
surfaces_data = d3.keys(surfaces_x)
surfaces = @vis.selectAll(".surfaces")
.data(surfaces_data)
surfaces.enter().append("text")
.attr("class", "surfaces")
.attr("x", (d) => surfaces_x[d] )
.attr("y", (d) => surfaces_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_datesiecles: () =>
datesiecles_x = {"14ème": 90, "15ème": 220, "16ème": 350,"17ème": 480,"18ème": 610,"19ème":100,"20ème":350,"21ème":600}
datesiecles_y = {"14ème": 40, "15ème": 40, "16ème": 40,"17ème": 40,"18ème": 40,"19ème":210,"20ème":210,"21ème":210}
datesiecles_data = d3.keys(datesiecles_x)
datesiecles = @vis.selectAll(".datesiecles")
.data(datesiecles_data)
datesiecles.enter().append("text")
.attr("class", "datesiecles")
.attr("x", (d) => datesiecles_x[d] )
.attr("y", (d) => datesiecles_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_date20s: () =>
date20s_x = {"1900-1910": 90,"1910-1920": 270,"1920-1930": 426,"1930-1940": 585,"1940-1950": 78,"1950-1960": 250,"1960-1970": 426,"1970-1980": 620,"1980-1990": 95,"1990-2000": 250,"2000-2010": 426,"+ 2010": 590}
date20s_y = {"1900-1910": 30,"1910-1920": 30,"1920-1930": 30,"1930-1940": 30,"1940-1950": 254,"1950-1960": 254,"1960-1970": 254,"1970-1980": 254,"1980-1990": 520,"1990-2000": 520,"2000-2010": 555,"+ 2010": 555}
date20s_data = d3.keys(date20s_x)
date20s = @vis.selectAll(".date20s")
.data(date20s_data)
date20s.enter().append("text")
.attr("class", "date20s")
.attr("x", (d) => date20s_x[d] )
.attr("y", (d) => date20s_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
hide_years: () =>
years = @vis.selectAll(".years").remove()
show_details: (data, i, element) =>
d3.select(element).attr("stroke","#000")
content = "<span class=\"name\"></span><span class=\"value\">#{addCommas(data.value)} dollars</span><br><hr>"
content += "<span class=\"name\"></span><span class=\"value\"><big> #{data.title}</big></span><br>"
content += "<span class=\"name\"></span><span class=\"value\"><small> #{data.name} (#{data.nat})</small></span>"
content += "<span class=\"name\"></span><span class=\"value\"><small> - #{data.date}</small></span><br><hr>"
content +="<span class=\"name\"><img src='img/#{data.img}'></img></span>"
@tooltip.showTooltip(content,d3.event)
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_tops: () =>
tops = @vis.selectAll(".tops").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_sexes: () =>
sexes = @vis.selectAll(".sexes").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_morts: () =>
morts = @vis.selectAll(".morts").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_nat1s: () =>
nat1s = @vis.selectAll(".nat1s").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_maitres: () =>
maitres = @vis.selectAll(".maitres").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_auction1s: () =>
auction1s = @vis.selectAll(".auction1s").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_surfaces: () =>
surfaces = @vis.selectAll(".surfaces").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_datesiecles: () =>
datesiecles = @vis.selectAll(".datesiecles").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_date20s: () =>
date20s = @vis.selectAll(".date20s").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
root = exports ? this
$ ->
chart = null
render_vis = (csv) ->
chart = new BubbleChart csv
chart.start()
root.display_year()
root.display_all = () =>
chart.display_group_all()
root.display_year = () =>
chart.display_by_year()
root.display_top = () =>
chart.display_by_top()
root.display_sexe = () =>
chart.display_by_sexe()
root.display_mort = () =>
chart.display_by_mort()
root.display_nat1 = () =>
chart.display_by_nat1()
root.display_maitre = () =>
chart.display_by_maitre()
root.display_auction1 = () =>
chart.display_by_auction1()
root.display_surface = () =>
chart.display_by_surface()
root.display_datesiecle = () =>
chart.display_by_datesiecle()
root.display_date20 = () =>
chart.display_by_date20()
root.toggle_view = (view_type) =>
if view_type == 'year'
root.display_year()
else if view_type == 'top'
root.display_top()
else if view_type == 'sexe'
root.display_sexe()
else if view_type == 'mort'
root.display_mort()
else if view_type == 'nat1'
root.display_nat1()
else if view_type == 'maitre'
root.display_maitre()
else if view_type == 'auction1'
root.display_auction1()
else if view_type == 'media1'
root.display_media1()
else if view_type == 'surface'
root.display_surface()
else if view_type == 'datesiecle'
root.display_datesiecle()
else if view_type == 'date20'
root.display_date20()
else
root.display_all()
d3.csv "data/dataeng.csv", render_vis | true |
class BubbleChart
constructor: (data) ->
@data = data
@width = 690
@height = 660
@tooltip = CustomTooltip("gates_tooltip", 185)
@center = {x: 2 * @width / 3, y: 1*@height / 3}
@year_centers = {
"2008": {x: 1.8 *@width / 6, y: 1*@height / 3},
"2009": {x: 3.13 *@width / 6, y: 1.05*@height / 3},
"2010": {x: 4.2 * @width / 6, y: 1.05*@height / 3}
"2011": {x: 2.1 * @width / 6, y: 1.6*@height / 3}
"2012": {x: 3.8* @width / 6, y: 1.2 *@height / 2}
}
@top_centers = {
"1": {x: 2.9 *@width / 6, y: 1.1*@height / 3},
"2": {x: 3.5 *@width / 6, y: 1.2*@height / 3},
"3": {x: 3.8 * @width / 6, y: 1.5*@height / 3}
"4": {x: 3.7 * @width / 6, y: 1.8*@height / 3}
"5": {x: 3.27 * @width / 6, y: 1.9 *@height / 3}
"6": {x: 2.8*@width / 6, y: 1.95*@height / 3},
"7": {x: 2.42 *@width / 6, y: 1.86*@height / 3},
"8": {x: 2.2 * @width / 6, y: 1.7*@height / 3}
"9": {x: 2.8 * @width / 8, y: 1.5*@height / 3}
"10": {x:3.1* @width / 8, y: 1.3*@height / 3}
"0": {x: 12 * @width / 6, y: 6*@height / 3}
}
@sexe_centers = {
"2": {x: 3.9*@width / 6, y: 1.9*@height / 4},
"1": {x: 2.6 *@width / 6, y: 1.9*@height / 4},
}
@mort_centers = {
"2": {x: 2.4*@width / 6, y: @height / 2},
"1": {x: 3.7 *@width / 6, y: @height / 2},
}
@nat1_centers = {
"Chine": {x: 4.15*@width / 6, y: 1.6*@height / 3},
"Etats-Unis": {x: 2.05 * @width / 6, y: 1.05*@height / 3},
"Europe": {x: 2.9 * @width / 6, y: 1.3*@height / 3},
"Russie": {x: 3.7 * @width / 6, y: 1.2*@height / 4},
"Argentine": {x: 1.7 * @width / 6, y: 2.2*@height / 4},
"Japon": {x: 4.4 * @width / 6, y: 1.15*@height / 3},
}
@maitre_centers = {
"1": {x: 1.7*@width / 6, y: @height / 3},
"2": {x: 3 *@width / 6, y: @height / 3},
"3": {x: 4.5 * @width / 6, y: @height / 3},
"4": {x: 1.7 * @width / 6, y: 1.9*@height / 3},
"5": {x: 3 * @width / 6, y: 1.9*@height / 3},
"6": {x: 4.5 *@width / 6, y: 1.9*@height / 3},
"0": {x: 15 * @width / 6, y: -4*@height / 3}
}
@auction1_centers = {
"Paris": {x: 1.8*@width / 6, y: 1.2*@height / 3.5},
"PI:NAME:<NAME>END_PI": {x: 3.1 *@width / 6, y: 1.4*@height / 3},
"Hong-Kong": {x: 3.1 * @width / 6, y: 1*@height / 3},
"PI:NAME:<NAME>END_PI": {x: 4 * @width / 6, y: 1.6*@height / 3},
"PI:NAME:<NAME>END_PI": {x: 4.5 * @width / 6, y: 1*@height / 3},
"New-York": {x: 2.1 * @width / 6, y: 1.8*@height / 3},
}
@surface_centers = {
"A": {x: 2*@width / 6, y: @height / 2.5},
"B": {x: 2 *@width / 6, y: @height / 2.5},
"C": {x: 3.1 * @width / 6, y: @height / 2.5}
"D": {x: 4.2 * @width / 6, y: @height / 2.5}
"E": {x: 4.2* @width / 6, y: 1.8*@height / 3}
"F": {x: 1.8*@width / 6, y: 2*@height / 3},
"G": {x: 2.7 *@width / 6, y: 2*@height / 3},
"Z": {x: 12 * @width / 6, y: 2*@height / 3}
"none": {x: 12 * @width / 6, y: 2*@height / 3}
}
@datesiecle_centers = {
"14th": {x: 1.25*@width / 5, y: 1*@height / 3.4},
"16th": {x: 2.47 *@width / 5, y: 1*@height / 2.9},
"17th": {x: 3.05 * @width / 5, y: 1*@height / 3.1}
"18th": {x: 3.78 * @width / 5, y: 1*@height / 3.4}
"19th": {x: 1.7 * @width / 5, y: 1.7*@height / 3}
"20th": {x: 2.5*@width / 5, y: 1.8*@height / 3},
"21th": {x: 3.4*@width / 5, y: 1.45*@height / 3},
"none": {x: 12 * @width / 6, y: -8*@height / 3}
}
@date20_centers = {
"1900": {x: 1.5*@width / 6, y: 0.95*@height / 4},
"1910": {x: 2.5 *@width / 6, y: 1.1*@height / 4},
"1920": {x: 3.5 * @width / 6, y: 1*@height / 4}
"1930": {x: 4.5 * @width / 6, y: 1.1*@height / 4},
"1940": {x: 1.5 * @width / 6, y: 1.95*@height / 4}
"1950": {x: 2.5*@width / 6, y: 1.95*@height / 4},
"1960": {x: 3.5 *@width / 6, y: 2.12*@height / 4},
"1970": {x: 4.5 * @width / 6, y: 1.95*@height / 4}
"1980": {x: 1.5 * @width / 6, y: 3.1*@height / 4},
"1990": {x: 2.5 * @width / 6, y: 3*@height / 4},
"2000": {x: 3.5 * @width / 6, y: 2.9*@height / 4},
"2010": {x:4.55 * @width / 6, y: 3.04*@height / 4},
"none": {x: 12 * @width / 6, y: -10*@height / 3},
}
@layout_gravity = -0.01
@damper = 0.1
@vis = null
@nodes = []
@force = null
@circles = null
@fill_color = d3.scale.ordinal()
.domain(["D", "B", "A","C","none"])
.range(["#e1005d", "#7D7963", "#BDBDBD","#178aca","#fff"])
max_amount = d3.max(@data, (d) -> parseInt(d.total_amount))
@radius_scale = d3.scale.pow().exponent(0.9).domain([0, max_amount]).range([2, 40])
this.create_nodes()
this.create_vis()
create_nodes: () =>
@data.forEach (d) =>
node = {
id: d.id
radius: @radius_scale(parseInt(d.total_amount))
value: d.total_amount
name: d.nom
top: d.top
maitre: d.maitre
nat: d.nat
nat1: d.nat1
title: d.title
sexe: d.sexe
mort: d.mort
datevente: d.datavente
auction: d.auction
year: d.start_year
auction1: d.auction1
media: d.media
media1: d.media1
surface: d.surface
date: d.date
datesiecle: d.datesiecle
date20: d.date20
img: d.img
x: Math.random() * 900
y: Math.random() * 800
}
@nodes.push node
@nodes.sort (a,b) -> b.value - a.value
create_vis: () =>
@vis = d3.select("#vis").append("svg")
.attr("width", @width)
.attr("height", @height)
.attr("id", "svg_vis")
@circles = @vis.selectAll("circle")
.data(@nodes, (d) -> d.id)
that = this
@circles.enter().append("circle")
.attr("r", 0)
.attr("fill", (d) => @fill_color(d.media1))
.attr("stroke-width", 1.2)
.attr("stroke","#666")
.attr("id", (d) -> "bubble_#{d.id}")
.on("mouseover", (d,i) -> that.show_details(d,i,this))
.on("mouseout", (d,i) -> that.hide_details(d,i,this))
@circles.transition().duration(2000).attr("r", (d) -> d.radius)
charge: (d) ->
-Math.pow(d.radius, 2.0) / 8
start: () =>
@force = d3.layout.force()
.nodes(@nodes)
.size([@width, @height])
display_group_all: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_center(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_auction1s()
this.hide_datesiecles()
this.hide_date20s()
this.hide_surfaces()
this.hide_maitres()
this.hide_nat1s()
this.hide_morts()
this.hide_tops()
this.hide_sexes()
move_towards_center: (alpha) =>
(d) =>
d.x = d.x + (@center.x - d.x) * (@damper + 0.02) * alpha
d.y = d.y + (@center.y - d.y) * (@damper + 0.02) * alpha
display_by_year: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_year(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_tops()
this.hide_datesiecles()
this.hide_date20s()
this.hide_auction1s()
this.hide_surfaces()
this.hide_maitres()
this.hide_nat1s()
this.hide_morts()
this.hide_sexes()
this.display_years()
display_by_top: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_top(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_maitres()
this.hide_datesiecles()
this.hide_auction1s()
this.hide_date20s()
this.hide_surfaces()
this.hide_nat1s()
this.hide_morts()
this.hide_sexes()
this.display_tops()
display_by_sexe: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_sexe(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_nat1s()
this.hide_auction1s()
this.hide_date20s()
this.hide_surfaces()
this.hide_maitres()
this.hide_morts()
this.hide_datesiecles()
this.hide_tops()
this.display_sexes()
display_by_mort: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_mort(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_nat1s()
this.hide_maitres()
this.hide_surfaces()
this.hide_datesiecles()
this.hide_date20s()
this.hide_auction1s()
this.hide_sexes()
this.hide_tops()
this.display_morts()
display_by_nat1: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_nat1(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_surfaces()
this.hide_maitres()
this.hide_date20s()
this.hide_auction1s()
this.hide_datesiecles()
this.hide_sexes()
this.hide_tops()
this.display_nat1s()
display_by_maitre: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_maitre(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_auction1s()
this.hide_surfaces()
this.hide_date20s()
this.hide_datesiecles()
this.hide_sexes()
this.hide_tops()
this.hide_nat1s()
this.display_maitres()
display_by_auction1: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_auction1(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_datesiecles()
this.hide_surfaces()
this.hide_maitres()
this.hide_date20s()
this.hide_sexes()
this.hide_tops()
this.hide_nat1s()
this.display_auction1s()
display_by_surface: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_surface(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_datesiecles()
this.hide_auction1s()
this.hide_maitres()
this.hide_date20s()
this.hide_sexes()
this.hide_tops()
this.hide_nat1s()
this.display_surfaces()
display_by_datesiecle: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_datesiecle(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_date20s()
this.hide_maitres()
this.hide_auction1s()
this.hide_sexes()
this.hide_tops()
this.hide_surfaces()
this.hide_nat1s()
this.display_datesiecles()
display_by_date20: () =>
@force.gravity(@layout_gravity)
.charge(this.charge)
.friction(0.9)
.on "tick", (e) =>
@circles.each(this.move_towards_date20(e.alpha))
.attr("cx", (d) -> d.x)
.attr("cy", (d) -> d.y)
@force.start()
this.hide_years()
this.hide_morts()
this.hide_maitres()
this.hide_datesiecles()
this.hide_auction1s()
this.hide_maitres()
this.hide_sexes()
this.hide_tops()
this.hide_surfaces()
this.hide_nat1s()
this.display_date20s()
move_towards_year: (alpha) =>
(d) =>
target = @year_centers[d.year]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_top: (alpha) =>
(d) =>
target = @top_centers[d.top]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_sexe: (alpha) =>
(d) =>
target = @sexe_centers[d.sexe]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_mort: (alpha) =>
(d) =>
target = @mort_centers[d.mort]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_nat1: (alpha) =>
(d) =>
target = @nat1_centers[d.nat1]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_maitre: (alpha) =>
(d) =>
target = @maitre_centers[d.maitre]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_auction1: (alpha) =>
(d) =>
target = @auction1_centers[d.auction1]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_surface: (alpha) =>
(d) =>
target = @surface_centers[d.surface]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_datesiecle: (alpha) =>
(d) =>
target = @datesiecle_centers[d.datesiecle]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
move_towards_date20: (alpha) =>
(d) =>
target = @date20_centers[d.date20]
d.x = d.x + (target.x - d.x) * (@damper + 0.02) * alpha * 1.1
d.y = d.y + (target.y - d.y) * (@damper + 0.02) * alpha * 1.1
display_years: () =>
years_x = {"2008": 165, "2009": 353, "2010": 555,"2011": 205,"2012": 500}
years_y = {"2008": 40, "2009": 80, "2010": 40,"2011": 290,"2012": 335}
years_data = d3.keys(years_x)
years = @vis.selectAll(".years")
.data(years_data)
years.enter().append("text")
.attr("class", "years")
.attr("x", (d) => years_x[d] )
.attr("y", (d) => years_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_tops: () =>
tops_x = {"Top 10":328,"(2008-2012)":328}
tops_y = {"Top 10":340,"(2008-2012)":360}
tops_data = d3.keys(tops_x)
tops = @vis.selectAll(".tops")
.data(tops_data)
tops.enter().append("text")
.attr("class", "tops")
.attr("x", (d) => tops_x[d] )
.attr("y", (d) => tops_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_sexes: () =>
sexes_x = {"hommes": 310, "femmes": 590}
sexes_y = {"hommes": 60, "femmes": 275}
sexes_data = d3.keys(sexes_x)
sexes = @vis.selectAll(".sexes")
.data(sexes_data)
sexes.enter().append("text")
.attr("class", "sexes")
.attr("x", (d) => sexes_x[d] )
.attr("y", (d) => sexes_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_morts: () =>
morts_x = {"vivants": 145, "morts": 450}
morts_y = {"vivants": 240, "morts": 90}
morts_data = d3.keys(morts_x)
morts = @vis.selectAll(".morts")
.data(morts_data)
morts.enter().append("text")
.attr("class", "morts")
.attr("x", (d) => morts_x[d] )
.attr("y", (d) => morts_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_nat1s: () =>
nat1s_x = {"Etats-Unis": 150, "Argentine": 100,"Europe": 390,"Chine":610,"Japon":110,"Russie":520,"Japon":620}
nat1s_y = {"Etats-Unis": 30, "Argentine": 410,"Europe": 80,"Chine":280,"Japon":600,"Russie":55,"Japon":175}
nat1s_data = d3.keys(nat1s_x)
nat1s = @vis.selectAll(".nat1s")
.data(nat1s_data)
nat1s.enter().append("text")
.attr("class", "nat1s")
.attr("x", (d) => nat1s_x[d] )
.attr("y", (d) => nat1s_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_maitres: () =>
maitres_x = {"PI:NAME:<NAME>END_PI": 140,"PI:NAME:<NAME>END_PI": 345,"MonPI:NAME:<NAME>END_PI": 550,"Picasso": 145,"Richter": 355,"Warhol": 550,}
maitres_y = {"PI:NAME:<NAME>END_PI": 90,"PI:NAME:<NAME>END_PI": 90,"MonPI:NAME:<NAME>END_PI": 90,"Picasso": 360,"Richter": 360,"Warhol": 360}
maitres_data = d3.keys(maitres_x)
maitres = @vis.selectAll(".maitres")
.data(maitres_data)
maitres.enter().append("text")
.attr("class", "maitres")
.attr("x", (d) => maitres_x[d] )
.attr("y", (d) => maitres_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_auction1s: () =>
auction1s_x = {"Paris":150,"Hong-Kong":370,"Autres":360,"New-York":175,"Londres":500,"Pékin":590}
auction1s_y = {"Paris":65,"Hong-Kong":65,"Autres":170,"New-York":235,"Londres":225,"Pékin":55}
auction1s_data = d3.keys(auction1s_x)
auction1s = @vis.selectAll(".auction1s")
.data(auction1s_data)
auction1s.enter().append("text")
.attr("class", "auction1s")
.attr("x", (d) => auction1s_x[d] )
.attr("y", (d) => auction1s_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_surfaces: () =>
surfaces_x = {"PEINTURE - DESSIN - AQUARELLE": 350, "-1m²": 160, "1-2m²": 370,"2-3m²": 570, "+3m²": 570,"SCULPTURE":220,"-1m de haut":110,"+1m de haut":300 }
surfaces_y = {"PEINTURE - DESSIN - AQUARELLE": 40, "-1m²": 90, "1-2m²": 90,"2-3m²": 90, "+3m²": 400,"SCULPTURE":415,"-1m de haut":450,"+1m de haut":450}
surfaces_data = d3.keys(surfaces_x)
surfaces = @vis.selectAll(".surfaces")
.data(surfaces_data)
surfaces.enter().append("text")
.attr("class", "surfaces")
.attr("x", (d) => surfaces_x[d] )
.attr("y", (d) => surfaces_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_datesiecles: () =>
datesiecles_x = {"14ème": 90, "15ème": 220, "16ème": 350,"17ème": 480,"18ème": 610,"19ème":100,"20ème":350,"21ème":600}
datesiecles_y = {"14ème": 40, "15ème": 40, "16ème": 40,"17ème": 40,"18ème": 40,"19ème":210,"20ème":210,"21ème":210}
datesiecles_data = d3.keys(datesiecles_x)
datesiecles = @vis.selectAll(".datesiecles")
.data(datesiecles_data)
datesiecles.enter().append("text")
.attr("class", "datesiecles")
.attr("x", (d) => datesiecles_x[d] )
.attr("y", (d) => datesiecles_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
display_date20s: () =>
date20s_x = {"1900-1910": 90,"1910-1920": 270,"1920-1930": 426,"1930-1940": 585,"1940-1950": 78,"1950-1960": 250,"1960-1970": 426,"1970-1980": 620,"1980-1990": 95,"1990-2000": 250,"2000-2010": 426,"+ 2010": 590}
date20s_y = {"1900-1910": 30,"1910-1920": 30,"1920-1930": 30,"1930-1940": 30,"1940-1950": 254,"1950-1960": 254,"1960-1970": 254,"1970-1980": 254,"1980-1990": 520,"1990-2000": 520,"2000-2010": 555,"+ 2010": 555}
date20s_data = d3.keys(date20s_x)
date20s = @vis.selectAll(".date20s")
.data(date20s_data)
date20s.enter().append("text")
.attr("class", "date20s")
.attr("x", (d) => date20s_x[d] )
.attr("y", (d) => date20s_y[d] )
.attr("text-anchor", "middle")
.text((d) -> d)
hide_years: () =>
years = @vis.selectAll(".years").remove()
show_details: (data, i, element) =>
d3.select(element).attr("stroke","#000")
content = "<span class=\"name\"></span><span class=\"value\">#{addCommas(data.value)} dollars</span><br><hr>"
content += "<span class=\"name\"></span><span class=\"value\"><big> #{data.title}</big></span><br>"
content += "<span class=\"name\"></span><span class=\"value\"><small> #{data.name} (#{data.nat})</small></span>"
content += "<span class=\"name\"></span><span class=\"value\"><small> - #{data.date}</small></span><br><hr>"
content +="<span class=\"name\"><img src='img/#{data.img}'></img></span>"
@tooltip.showTooltip(content,d3.event)
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_tops: () =>
tops = @vis.selectAll(".tops").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_sexes: () =>
sexes = @vis.selectAll(".sexes").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_morts: () =>
morts = @vis.selectAll(".morts").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_nat1s: () =>
nat1s = @vis.selectAll(".nat1s").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_maitres: () =>
maitres = @vis.selectAll(".maitres").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_auction1s: () =>
auction1s = @vis.selectAll(".auction1s").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_surfaces: () =>
surfaces = @vis.selectAll(".surfaces").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_datesiecles: () =>
datesiecles = @vis.selectAll(".datesiecles").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
hide_date20s: () =>
date20s = @vis.selectAll(".date20s").remove()
hide_details: (data, i, element) =>
d3.select(element).attr("stroke", "#818181")
@tooltip.hideTooltip()
root = exports ? this
$ ->
chart = null
render_vis = (csv) ->
chart = new BubbleChart csv
chart.start()
root.display_year()
root.display_all = () =>
chart.display_group_all()
root.display_year = () =>
chart.display_by_year()
root.display_top = () =>
chart.display_by_top()
root.display_sexe = () =>
chart.display_by_sexe()
root.display_mort = () =>
chart.display_by_mort()
root.display_nat1 = () =>
chart.display_by_nat1()
root.display_maitre = () =>
chart.display_by_maitre()
root.display_auction1 = () =>
chart.display_by_auction1()
root.display_surface = () =>
chart.display_by_surface()
root.display_datesiecle = () =>
chart.display_by_datesiecle()
root.display_date20 = () =>
chart.display_by_date20()
root.toggle_view = (view_type) =>
if view_type == 'year'
root.display_year()
else if view_type == 'top'
root.display_top()
else if view_type == 'sexe'
root.display_sexe()
else if view_type == 'mort'
root.display_mort()
else if view_type == 'nat1'
root.display_nat1()
else if view_type == 'maitre'
root.display_maitre()
else if view_type == 'auction1'
root.display_auction1()
else if view_type == 'media1'
root.display_media1()
else if view_type == 'surface'
root.display_surface()
else if view_type == 'datesiecle'
root.display_datesiecle()
else if view_type == 'date20'
root.display_date20()
else
root.display_all()
d3.csv "data/dataeng.csv", render_vis |
[
{
"context": "n1up = (max ,i, done) ->\n keys = []\n keys.push \"f:test#{i}\"\n keys.push \"is:test#{i}\"\n keys.push \"ir:test#{i",
"end": 608,
"score": 0.9687022566795349,
"start": 597,
"tag": "KEY",
"value": "f:test#{i}\""
},
{
"context": " keys = []\n keys.push \"f:test#{i}... | test/load/imageloadtest.coffee | SchoolOfFreelancing/SureSpot | 1 | request = require("request")
http = require 'http'
assert = require("assert")
should = require("should")
redis = require("redis")
util = require("util")
fs = require("fs")
io = require 'socket.io-client'
async = require 'async'
_ = require 'underscore'
crypto = require 'crypto'
rc = redis.createClient()
#rc.select 1
testImageLocation = "../testImage"
testkeydir = '../testkeys'
baseUri = "https://localhost:443"
minclient = 0
maxclient = 999
clients = maxclient - minclient + 1
jars = []
http.globalAgent.maxSockets = 20000
clean = 0
clean1up = (max ,i, done) ->
keys = []
keys.push "f:test#{i}"
keys.push "is:test#{i}"
keys.push "ir:test#{i}"
keys.push "m:test#{i}:test#{i + 1}:id"
keys.push "m:test#{i}:test#{i + 1}"
keys.push "c:test#{i}"
keys.push "c:u:test#{i}"
keys.push "c:u:test#{i}:id"
#rc.del keys1, (err, blah) ->
# return done err if err?
rc.del keys, (err, blah) ->
return done err if err?
if i+1 < max
clean1up max, i+1, done
else
done()
cleanup = (done) ->
clean1up clients, 0, done
login = (username, password, jar, authSig, done, callback) ->
request.post
agent: false
url: baseUri + "/login"
jar: jar
json:
username: username
password: password
authSig: authSig
(err, res, body) ->
if err
done err
else
if res.statusCode != 204
console.log username
res.statusCode.should.equal 204
cookie = jar.get({ url: baseUri }).map((c) -> c.name + "=" + c.value).join("; ")
callback res, body, cookie
loginUsers = (i, key, callback) ->
j = request.jar()
jars[i - minclient] = j
#console.log 'i: ' + i
login 'test' + i, 'test' + i, j, key, callback, (res, body, cookie) ->
callback null, cookie
makeLogin = (i, key) ->
return (callback) ->
loginUsers i, key, callback
makeConnect = (cookie) ->
return (callback) ->
connectChats cookie, callback
connectChats = (cookie, callback) ->
client = io.connect baseUri, { 'force new connection': true, 'reconnect': false, 'connect timeout': 120000}, cookie
client.on 'connect', ->
callback null, client
send = (socket, i, callback) ->
if i % 2 is 0
jsonMessage = {to: "test" + (i + 1), from: "test#{i}", iv: i, data: "message data", mimeType: "text/plain", toVersion: 1, fromVersion: 1}
socket.send JSON.stringify(jsonMessage)
callback null, true
else
socket.once "message", (message) ->
receivedMessage = JSON.parse message
callback null, receivedMessage.data is 'message data'
makeSend = (socket, i) ->
return (callback) ->
send socket, i, callback
friendUser = (i, callback) ->
request.post
agent: false
#maxSockets: 6000
jar: jars[i - minclient]
url: baseUri + "/invite/test#{(i + 1)}"
(err, res, body) ->
if err
callback err
else
if res.statusCode != 204
console.log "invite failed statusCode#{res.statusCode}, i: " + i
res.statusCode.should.equal 204
request.post
agent: false
#maxSockets: 6000
jar: jars[(i - minclient + 1)]
url: baseUri + "/invites/test#{i}/accept"
(err, res, body) ->
if err
callback err
else
if res.statusCode != 204
console.log "invite accept failed statusCode#{res.statusCode}, i: " + (i + 1)
res.statusCode.should.equal 204
callback null
makeFriendUser = (i) ->
return (callback) ->
friendUser i, callback
describe "surespot image load test", () ->
#before (done) -> cleanup done
sigs = []
tasks = []
cookies = undefined
sockets = undefined
it "load sigs", (done) ->
for i in [minclient..maxclient]
#priv = fs.readFileSync "testkeys/test#{i}_priv.pem", 'utf-8'
#pub = fs.readFileSync "testkeys/test#{i}_pub.pem", 'utf-8'
sig = fs.readFileSync "#{testkeydir}/test#{i}.sig", 'utf-8'
sigs[i-minclient] = sig
done()
it "login #{clients} users", (done) ->
tasks = []
#create connect clients tasks
for i in [minclient..maxclient] by 1
tasks.push makeLogin i, sigs[i - minclient]
#execute the tasks which creates the cookie jars
async.parallel tasks, (err, httpcookies) ->
if err?
done err
else
cookies = httpcookies
done()
it 'friend users', (done) ->
tasks = []
for i in [minclient..maxclient] by 2
tasks.push makeFriendUser i
async.parallel tasks, (err, callback) ->
if err
done err
else
done()
it "connect #{clients} chats", (done) ->
connects = []
for cookie in cookies
connects.push makeConnect(cookie)
async.parallel connects, (err, clients) ->
if err?
done err
else
sockets = clients
done()
it "send and receive a message", (done) ->
sends = []
i = 0
for socket in sockets
sends.push makeSend(socket, minclient + i++)
async.parallel sends, (err, results) ->
if err?
done err
else
_.every results, (result) -> result.should.be.true
done()
it "upload an image", (done) ->
upload = (i, callback) ->
if i % 2 is 0
r = request.post
agent: false
#maxSockets: 6000
jar: jars[i - minclient]
url: baseUri + "/images/1/test#{i+1}/1"
(err, res, body) ->
if err
callback err
else
res.statusCode.should.equal 200
callback null, true
form = r.form()
form.append "image", fs.createReadStream "#{testImageLocation}"
else
socket.once "message", (message) ->
#receivedMessage = JSON.parse message
callback null, true
makeUploads = (i) ->
return (callback) ->
upload i, callback
uploads = []
i = 0
for socket in sockets
uploads.push makeUploads(minclient + i++)
async.parallel uploads, (err, results) ->
if err?
done err
else
_.every results, (result) -> result.should.be.true
done()
#after (done) -> cleanup done
| 26180 | request = require("request")
http = require 'http'
assert = require("assert")
should = require("should")
redis = require("redis")
util = require("util")
fs = require("fs")
io = require 'socket.io-client'
async = require 'async'
_ = require 'underscore'
crypto = require 'crypto'
rc = redis.createClient()
#rc.select 1
testImageLocation = "../testImage"
testkeydir = '../testkeys'
baseUri = "https://localhost:443"
minclient = 0
maxclient = 999
clients = maxclient - minclient + 1
jars = []
http.globalAgent.maxSockets = 20000
clean = 0
clean1up = (max ,i, done) ->
keys = []
keys.push "<KEY>
keys.push "<KEY>
keys.push "<KEY>
keys.push "<KEY> + 1}:<KEY>"
keys.push "<KEY> + <KEY>
keys.push "<KEY>
keys.push "<KEY>
keys.push "<KEY>"
#rc.del keys1, (err, blah) ->
# return done err if err?
rc.del keys, (err, blah) ->
return done err if err?
if i+1 < max
clean1up max, i+1, done
else
done()
cleanup = (done) ->
clean1up clients, 0, done
login = (username, password, jar, authSig, done, callback) ->
request.post
agent: false
url: baseUri + "/login"
jar: jar
json:
username: username
password: <PASSWORD>
authSig: authSig
(err, res, body) ->
if err
done err
else
if res.statusCode != 204
console.log username
res.statusCode.should.equal 204
cookie = jar.get({ url: baseUri }).map((c) -> c.name + "=" + c.value).join("; ")
callback res, body, cookie
loginUsers = (i, key, callback) ->
j = request.jar()
jars[i - minclient] = j
#console.log 'i: ' + i
login 'test' + i, 'test' + i, j, key, callback, (res, body, cookie) ->
callback null, cookie
makeLogin = (i, key) ->
return (callback) ->
loginUsers i, key, callback
makeConnect = (cookie) ->
return (callback) ->
connectChats cookie, callback
connectChats = (cookie, callback) ->
client = io.connect baseUri, { 'force new connection': true, 'reconnect': false, 'connect timeout': 120000}, cookie
client.on 'connect', ->
callback null, client
send = (socket, i, callback) ->
if i % 2 is 0
jsonMessage = {to: "test" + (i + 1), from: "test#{i}", iv: i, data: "message data", mimeType: "text/plain", toVersion: 1, fromVersion: 1}
socket.send JSON.stringify(jsonMessage)
callback null, true
else
socket.once "message", (message) ->
receivedMessage = JSON.parse message
callback null, receivedMessage.data is 'message data'
makeSend = (socket, i) ->
return (callback) ->
send socket, i, callback
friendUser = (i, callback) ->
request.post
agent: false
#maxSockets: 6000
jar: jars[i - minclient]
url: baseUri + "/invite/test#{(i + 1)}"
(err, res, body) ->
if err
callback err
else
if res.statusCode != 204
console.log "invite failed statusCode#{res.statusCode}, i: " + i
res.statusCode.should.equal 204
request.post
agent: false
#maxSockets: 6000
jar: jars[(i - minclient + 1)]
url: baseUri + "/invites/test#{i}/accept"
(err, res, body) ->
if err
callback err
else
if res.statusCode != 204
console.log "invite accept failed statusCode#{res.statusCode}, i: " + (i + 1)
res.statusCode.should.equal 204
callback null
makeFriendUser = (i) ->
return (callback) ->
friendUser i, callback
describe "surespot image load test", () ->
#before (done) -> cleanup done
sigs = []
tasks = []
cookies = undefined
sockets = undefined
it "load sigs", (done) ->
for i in [minclient..maxclient]
#priv = fs.readFileSync "testkeys/test#{i}_priv.pem", 'utf-8'
#pub = fs.readFileSync "testkeys/test#{i}_pub.pem", 'utf-8'
sig = fs.readFileSync "#{testkeydir}/test#{i}.sig", 'utf-8'
sigs[i-minclient] = sig
done()
it "login #{clients} users", (done) ->
tasks = []
#create connect clients tasks
for i in [minclient..maxclient] by 1
tasks.push makeLogin i, sigs[i - minclient]
#execute the tasks which creates the cookie jars
async.parallel tasks, (err, httpcookies) ->
if err?
done err
else
cookies = httpcookies
done()
it 'friend users', (done) ->
tasks = []
for i in [minclient..maxclient] by 2
tasks.push makeFriendUser i
async.parallel tasks, (err, callback) ->
if err
done err
else
done()
it "connect #{clients} chats", (done) ->
connects = []
for cookie in cookies
connects.push makeConnect(cookie)
async.parallel connects, (err, clients) ->
if err?
done err
else
sockets = clients
done()
it "send and receive a message", (done) ->
sends = []
i = 0
for socket in sockets
sends.push makeSend(socket, minclient + i++)
async.parallel sends, (err, results) ->
if err?
done err
else
_.every results, (result) -> result.should.be.true
done()
it "upload an image", (done) ->
upload = (i, callback) ->
if i % 2 is 0
r = request.post
agent: false
#maxSockets: 6000
jar: jars[i - minclient]
url: baseUri + "/images/1/test#{i+1}/1"
(err, res, body) ->
if err
callback err
else
res.statusCode.should.equal 200
callback null, true
form = r.form()
form.append "image", fs.createReadStream "#{testImageLocation}"
else
socket.once "message", (message) ->
#receivedMessage = JSON.parse message
callback null, true
makeUploads = (i) ->
return (callback) ->
upload i, callback
uploads = []
i = 0
for socket in sockets
uploads.push makeUploads(minclient + i++)
async.parallel uploads, (err, results) ->
if err?
done err
else
_.every results, (result) -> result.should.be.true
done()
#after (done) -> cleanup done
| true | request = require("request")
http = require 'http'
assert = require("assert")
should = require("should")
redis = require("redis")
util = require("util")
fs = require("fs")
io = require 'socket.io-client'
async = require 'async'
_ = require 'underscore'
crypto = require 'crypto'
rc = redis.createClient()
#rc.select 1
testImageLocation = "../testImage"
testkeydir = '../testkeys'
baseUri = "https://localhost:443"
minclient = 0
maxclient = 999
clients = maxclient - minclient + 1
jars = []
http.globalAgent.maxSockets = 20000
clean = 0
clean1up = (max ,i, done) ->
keys = []
keys.push "PI:KEY:<KEY>END_PI
keys.push "PI:KEY:<KEY>END_PI
keys.push "PI:KEY:<KEY>END_PI
keys.push "PI:KEY:<KEY>END_PI + 1}:PI:KEY:<KEY>END_PI"
keys.push "PI:KEY:<KEY>END_PI + PI:KEY:<KEY>END_PI
keys.push "PI:KEY:<KEY>END_PI
keys.push "PI:KEY:<KEY>END_PI
keys.push "PI:KEY:<KEY>END_PI"
#rc.del keys1, (err, blah) ->
# return done err if err?
rc.del keys, (err, blah) ->
return done err if err?
if i+1 < max
clean1up max, i+1, done
else
done()
cleanup = (done) ->
clean1up clients, 0, done
login = (username, password, jar, authSig, done, callback) ->
request.post
agent: false
url: baseUri + "/login"
jar: jar
json:
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
authSig: authSig
(err, res, body) ->
if err
done err
else
if res.statusCode != 204
console.log username
res.statusCode.should.equal 204
cookie = jar.get({ url: baseUri }).map((c) -> c.name + "=" + c.value).join("; ")
callback res, body, cookie
loginUsers = (i, key, callback) ->
j = request.jar()
jars[i - minclient] = j
#console.log 'i: ' + i
login 'test' + i, 'test' + i, j, key, callback, (res, body, cookie) ->
callback null, cookie
makeLogin = (i, key) ->
return (callback) ->
loginUsers i, key, callback
makeConnect = (cookie) ->
return (callback) ->
connectChats cookie, callback
connectChats = (cookie, callback) ->
client = io.connect baseUri, { 'force new connection': true, 'reconnect': false, 'connect timeout': 120000}, cookie
client.on 'connect', ->
callback null, client
send = (socket, i, callback) ->
if i % 2 is 0
jsonMessage = {to: "test" + (i + 1), from: "test#{i}", iv: i, data: "message data", mimeType: "text/plain", toVersion: 1, fromVersion: 1}
socket.send JSON.stringify(jsonMessage)
callback null, true
else
socket.once "message", (message) ->
receivedMessage = JSON.parse message
callback null, receivedMessage.data is 'message data'
makeSend = (socket, i) ->
return (callback) ->
send socket, i, callback
friendUser = (i, callback) ->
request.post
agent: false
#maxSockets: 6000
jar: jars[i - minclient]
url: baseUri + "/invite/test#{(i + 1)}"
(err, res, body) ->
if err
callback err
else
if res.statusCode != 204
console.log "invite failed statusCode#{res.statusCode}, i: " + i
res.statusCode.should.equal 204
request.post
agent: false
#maxSockets: 6000
jar: jars[(i - minclient + 1)]
url: baseUri + "/invites/test#{i}/accept"
(err, res, body) ->
if err
callback err
else
if res.statusCode != 204
console.log "invite accept failed statusCode#{res.statusCode}, i: " + (i + 1)
res.statusCode.should.equal 204
callback null
makeFriendUser = (i) ->
return (callback) ->
friendUser i, callback
describe "surespot image load test", () ->
#before (done) -> cleanup done
sigs = []
tasks = []
cookies = undefined
sockets = undefined
it "load sigs", (done) ->
for i in [minclient..maxclient]
#priv = fs.readFileSync "testkeys/test#{i}_priv.pem", 'utf-8'
#pub = fs.readFileSync "testkeys/test#{i}_pub.pem", 'utf-8'
sig = fs.readFileSync "#{testkeydir}/test#{i}.sig", 'utf-8'
sigs[i-minclient] = sig
done()
it "login #{clients} users", (done) ->
tasks = []
#create connect clients tasks
for i in [minclient..maxclient] by 1
tasks.push makeLogin i, sigs[i - minclient]
#execute the tasks which creates the cookie jars
async.parallel tasks, (err, httpcookies) ->
if err?
done err
else
cookies = httpcookies
done()
it 'friend users', (done) ->
tasks = []
for i in [minclient..maxclient] by 2
tasks.push makeFriendUser i
async.parallel tasks, (err, callback) ->
if err
done err
else
done()
it "connect #{clients} chats", (done) ->
connects = []
for cookie in cookies
connects.push makeConnect(cookie)
async.parallel connects, (err, clients) ->
if err?
done err
else
sockets = clients
done()
it "send and receive a message", (done) ->
sends = []
i = 0
for socket in sockets
sends.push makeSend(socket, minclient + i++)
async.parallel sends, (err, results) ->
if err?
done err
else
_.every results, (result) -> result.should.be.true
done()
it "upload an image", (done) ->
upload = (i, callback) ->
if i % 2 is 0
r = request.post
agent: false
#maxSockets: 6000
jar: jars[i - minclient]
url: baseUri + "/images/1/test#{i+1}/1"
(err, res, body) ->
if err
callback err
else
res.statusCode.should.equal 200
callback null, true
form = r.form()
form.append "image", fs.createReadStream "#{testImageLocation}"
else
socket.once "message", (message) ->
#receivedMessage = JSON.parse message
callback null, true
makeUploads = (i) ->
return (callback) ->
upload i, callback
uploads = []
i = 0
for socket in sockets
uploads.push makeUploads(minclient + i++)
async.parallel uploads, (err, results) ->
if err?
done err
else
_.every results, (result) -> result.should.be.true
done()
#after (done) -> cleanup done
|
[
{
"context": " response\n\n )\n return false\n\n @clientId = \"370442298553-1027sk5ib0e6h1s01j9k0tl8gs166k69.apps.googleusercontent.com\"\n # \"370442298553-0sd4gu24c5tbdhfvesi7ugjhvt0tfa",
"end": 1777,
"score": 0.9640110731124878,
"start": 1705,
"tag": "KEY",
"value": "370442298553-... | coffee/cybozu.coffee | c0ze/cybozu | 0 | class Cybozu
@refreshRate = 5 * 60 * 1000
@positiveKeywordsRegexes = []
@negativeKeywordsRegexes = []
initialize: () ->
refresh()
refresh: () ->
chrome.storage.sync.get null, (items) =>
icon_list = $("#content-wrapper > div.contentPersonalAdmin > div > table > tbody > tr > td > table > tbody > tr:nth-child(2) > td > div > div > fieldset > div")
link = "<a href=\"#\" class=\"adminButton\" style=\"width:8em\"><img src=\"https://static.cybozu.com/o/10.2.4.10-20150226/image/export32.png\" align=\"absmiddle\"><br>Import to Google<br>Calendar</a>"
icon_list.append(link)
# console.log icon_list
button_list = $("#content-wrapper > div.contentPersonalAdmin > div > form > table > tbody > tr > td > table > tbody > tr:nth-child(2) > td > div > div.vr_formCommitWrapper > p")
button = "<input type=\"button\" class=\"vr_stdButton\" name=\"Import\" value=\"Import to Google\" onclick='window.postMessage({ action: \"cybozu:import\" }, \"*\");'>"
button_list.append(button)
importToGoogle: () ->
chrome.runtime.sendMessage { message: "cybozu:something", count: "5" }, (data) ->
console.log data
form = $("#content-wrapper > div.contentPersonalAdmin > div > form")
formData = form.serialize() + "&Export=%E6%9B%B8%E3%81%8D%E5%87%BA%E3%81%99"
url = "ag.cgi/schedule.csv"
$.ajax(
type: "POST",
url: url,
data: formData,
success: (data) ->
alert data
results = Papa.parse data
headers = results.data[0]
chrome.runtime.sendMessage { message: "cybozu:import-calendar", data: data }, (response) ->
console.log response
)
return false
@clientId = "370442298553-1027sk5ib0e6h1s01j9k0tl8gs166k69.apps.googleusercontent.com"
# "370442298553-0sd4gu24c5tbdhfvesi7ugjhvt0tfag3.apps.googleusercontent.com"
@apiKey = "AIzaSyCuIZZa6nyhf_QIrjDNKQeQzgdnMvuDF34"
@scopes = ["https://www.googleapis.com/auth/calendar"]
initGapi: (gapi) ->
console.log "initting gapi"
console.log gapi
gapi.auth.authorize({
client_id: @clientId,
scope: @scopes,
immediate: true }, (result) ->
console.log result
)
gapi.client.setApiKey(@apiKey);
checkAuth2: () ->
# window.gapi.client.setApiKey("AIzaSyCuIZZa6nyhf_QIrjDNKQeQzgdnMvuDF34")
window.gapi.auth.authorize({
client_id: window.cybozu.clientId,
scope: scopes,
immediate: true
}, (result) ->
console.log result
)
window.cybozu = new Cybozu()
inject = $("<script>")
inject.prop("src", chrome.extension.getURL("js/pushstate.js"))
$("head").append(inject)
inject = $("<script>")
inject.prop("src", "https://apis.google.com/js/client.js?onload=window.cybozu.initGapi")
$("body").append(inject)
$(() ->
window.cybozu.refresh()
# window.cybozu.initGapi(window.gapi)
)
window.addEventListener "message", (event) ->
if event.data.action == "cybozu:import"
window.cybozu.importToGoogle()
| 2181 | class Cybozu
@refreshRate = 5 * 60 * 1000
@positiveKeywordsRegexes = []
@negativeKeywordsRegexes = []
initialize: () ->
refresh()
refresh: () ->
chrome.storage.sync.get null, (items) =>
icon_list = $("#content-wrapper > div.contentPersonalAdmin > div > table > tbody > tr > td > table > tbody > tr:nth-child(2) > td > div > div > fieldset > div")
link = "<a href=\"#\" class=\"adminButton\" style=\"width:8em\"><img src=\"https://static.cybozu.com/o/10.2.4.10-20150226/image/export32.png\" align=\"absmiddle\"><br>Import to Google<br>Calendar</a>"
icon_list.append(link)
# console.log icon_list
button_list = $("#content-wrapper > div.contentPersonalAdmin > div > form > table > tbody > tr > td > table > tbody > tr:nth-child(2) > td > div > div.vr_formCommitWrapper > p")
button = "<input type=\"button\" class=\"vr_stdButton\" name=\"Import\" value=\"Import to Google\" onclick='window.postMessage({ action: \"cybozu:import\" }, \"*\");'>"
button_list.append(button)
importToGoogle: () ->
chrome.runtime.sendMessage { message: "cybozu:something", count: "5" }, (data) ->
console.log data
form = $("#content-wrapper > div.contentPersonalAdmin > div > form")
formData = form.serialize() + "&Export=%E6%9B%B8%E3%81%8D%E5%87%BA%E3%81%99"
url = "ag.cgi/schedule.csv"
$.ajax(
type: "POST",
url: url,
data: formData,
success: (data) ->
alert data
results = Papa.parse data
headers = results.data[0]
chrome.runtime.sendMessage { message: "cybozu:import-calendar", data: data }, (response) ->
console.log response
)
return false
@clientId = "<KEY>"
# "<KEY>8<KEY>"
@apiKey = "<KEY>"
@scopes = ["https://www.googleapis.com/auth/calendar"]
initGapi: (gapi) ->
console.log "initting gapi"
console.log gapi
gapi.auth.authorize({
client_id: @clientId,
scope: @scopes,
immediate: true }, (result) ->
console.log result
)
gapi.client.setApiKey(@apiKey);
checkAuth2: () ->
# window.gapi.client.setApiKey("<KEY>")
window.gapi.auth.authorize({
client_id: window.cybozu.clientId,
scope: scopes,
immediate: true
}, (result) ->
console.log result
)
window.cybozu = new Cybozu()
inject = $("<script>")
inject.prop("src", chrome.extension.getURL("js/pushstate.js"))
$("head").append(inject)
inject = $("<script>")
inject.prop("src", "https://apis.google.com/js/client.js?onload=window.cybozu.initGapi")
$("body").append(inject)
$(() ->
window.cybozu.refresh()
# window.cybozu.initGapi(window.gapi)
)
window.addEventListener "message", (event) ->
if event.data.action == "cybozu:import"
window.cybozu.importToGoogle()
| true | class Cybozu
@refreshRate = 5 * 60 * 1000
@positiveKeywordsRegexes = []
@negativeKeywordsRegexes = []
initialize: () ->
refresh()
refresh: () ->
chrome.storage.sync.get null, (items) =>
icon_list = $("#content-wrapper > div.contentPersonalAdmin > div > table > tbody > tr > td > table > tbody > tr:nth-child(2) > td > div > div > fieldset > div")
link = "<a href=\"#\" class=\"adminButton\" style=\"width:8em\"><img src=\"https://static.cybozu.com/o/10.2.4.10-20150226/image/export32.png\" align=\"absmiddle\"><br>Import to Google<br>Calendar</a>"
icon_list.append(link)
# console.log icon_list
button_list = $("#content-wrapper > div.contentPersonalAdmin > div > form > table > tbody > tr > td > table > tbody > tr:nth-child(2) > td > div > div.vr_formCommitWrapper > p")
button = "<input type=\"button\" class=\"vr_stdButton\" name=\"Import\" value=\"Import to Google\" onclick='window.postMessage({ action: \"cybozu:import\" }, \"*\");'>"
button_list.append(button)
importToGoogle: () ->
chrome.runtime.sendMessage { message: "cybozu:something", count: "5" }, (data) ->
console.log data
form = $("#content-wrapper > div.contentPersonalAdmin > div > form")
formData = form.serialize() + "&Export=%E6%9B%B8%E3%81%8D%E5%87%BA%E3%81%99"
url = "ag.cgi/schedule.csv"
$.ajax(
type: "POST",
url: url,
data: formData,
success: (data) ->
alert data
results = Papa.parse data
headers = results.data[0]
chrome.runtime.sendMessage { message: "cybozu:import-calendar", data: data }, (response) ->
console.log response
)
return false
@clientId = "PI:KEY:<KEY>END_PI"
# "PI:KEY:<KEY>END_PI8PI:KEY:<KEY>END_PI"
@apiKey = "PI:KEY:<KEY>END_PI"
@scopes = ["https://www.googleapis.com/auth/calendar"]
initGapi: (gapi) ->
console.log "initting gapi"
console.log gapi
gapi.auth.authorize({
client_id: @clientId,
scope: @scopes,
immediate: true }, (result) ->
console.log result
)
gapi.client.setApiKey(@apiKey);
checkAuth2: () ->
# window.gapi.client.setApiKey("PI:KEY:<KEY>END_PI")
window.gapi.auth.authorize({
client_id: window.cybozu.clientId,
scope: scopes,
immediate: true
}, (result) ->
console.log result
)
window.cybozu = new Cybozu()
inject = $("<script>")
inject.prop("src", chrome.extension.getURL("js/pushstate.js"))
$("head").append(inject)
inject = $("<script>")
inject.prop("src", "https://apis.google.com/js/client.js?onload=window.cybozu.initGapi")
$("body").append(inject)
$(() ->
window.cybozu.refresh()
# window.cybozu.initGapi(window.gapi)
)
window.addEventListener "message", (event) ->
if event.data.action == "cybozu:import"
window.cybozu.importToGoogle()
|
[
{
"context": "#\n# Copyright 2015 Volcra\n#\n# Licensed under the Apache License, Version 2.",
"end": 25,
"score": 0.9996498227119446,
"start": 19,
"tag": "NAME",
"value": "Volcra"
}
] | webpack.config.coffee | volcra/react-foundation | 0 | #
# Copyright 2015 Volcra
#
# 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.
#
path = require 'path'
webpack = require 'webpack'
module.exports =
cache: true
entry:
'react-foundation': './src/react-foundation.coffee'
output:
path: path.join __dirname, 'dist'
filename: '[name].js'
module:
loaders: [
{ test: /\.coffee$/, loader: 'coffee' },
{ test: /\.js$/, loader: 'jsx' },
{ test: /\.jsx$/, loader: 'jsx?insertPragma=React.DOM' }
]
| 94122 | #
# Copyright 2015 <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.
#
path = require 'path'
webpack = require 'webpack'
module.exports =
cache: true
entry:
'react-foundation': './src/react-foundation.coffee'
output:
path: path.join __dirname, 'dist'
filename: '[name].js'
module:
loaders: [
{ test: /\.coffee$/, loader: 'coffee' },
{ test: /\.js$/, loader: 'jsx' },
{ test: /\.jsx$/, loader: 'jsx?insertPragma=React.DOM' }
]
| true | #
# Copyright 2015 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.
#
path = require 'path'
webpack = require 'webpack'
module.exports =
cache: true
entry:
'react-foundation': './src/react-foundation.coffee'
output:
path: path.join __dirname, 'dist'
filename: '[name].js'
module:
loaders: [
{ test: /\.coffee$/, loader: 'coffee' },
{ test: /\.js$/, loader: 'jsx' },
{ test: /\.jsx$/, loader: 'jsx?insertPragma=React.DOM' }
]
|
[
{
"context": "r && membersError\n errorKey = 'private-space-members'\n maxMemberships = user.get('m",
"end": 3521,
"score": 0.9994081258773804,
"start": 3500,
"tag": "KEY",
"value": "private-space-members"
},
{
"context": "e if privateError\n ... | app/modules/projects/create/import/import-project.service.coffee | threefoldtech/Threefold-Circles-front | 0 | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: projects/create/import/import-project.service.coffee
###
class ImportProjectService extends taiga.Service
@.$inject = [
'tgCurrentUserService',
'$tgAuth',
'tgLightboxFactory',
'$translate',
'$tgConfirm',
'$location',
'$tgNavUrls'
]
constructor: (@currentUserService, @tgAuth, @lightboxFactory, @translate, @confirm, @location, @tgNavUrls) ->
importPromise: (promise) ->
return promise.then(@.importSuccess.bind(this), @.importError.bind(this))
importSuccess: (result) ->
promise = @currentUserService.loadProjects()
promise.then () =>
if result.status == 202 # Async mode
title = @translate.instant('PROJECT.IMPORT.ASYNC_IN_PROGRESS_TITLE')
message = @translate.instant('PROJECT.IMPORT.ASYNC_IN_PROGRESS_MESSAGE')
@location.path(@tgNavUrls.resolve('home'))
@confirm.success(title, message)
else # result.status == 201 # Sync mode
ctx = {project: result.data.slug}
@location.path(@tgNavUrls.resolve('project-admin-project-profile-details', ctx))
msg = @translate.instant('PROJECT.IMPORT.SYNC_SUCCESS')
@confirm.notify('success', msg)
return promise
importError: (result) ->
promise = @tgAuth.refresh()
promise.then () =>
restrictionError = @.getRestrictionError(result)
if restrictionError
@lightboxFactory.create('tg-lb-import-error', {
class: 'lightbox lightbox-import-error'
}, restrictionError)
else
errorMsg = @translate.instant("PROJECT.IMPORT.ERROR")
if result.status == 429 # TOO MANY REQUESTS
errorMsg = @translate.instant("PROJECT.IMPORT.ERROR_TOO_MANY_REQUEST")
else if result.data?._error_message
errorMsg = @translate.instant("PROJECT.IMPORT.ERROR_MESSAGE", {error_message: result.data._error_message})
@confirm.notify("error", errorMsg)
return promise
getRestrictionError: (result) ->
if result.headers
errorKey = ''
user = @currentUserService.getUser()
maxMemberships = null
if result.headers.isPrivate
privateError = !@currentUserService.canCreatePrivateProjects().valid
if user.get('max_memberships_private_projects') != null && result.headers.memberships >= user.get('max_memberships_private_projects')
membersError = true
else
membersError = false
if privateError && membersError
errorKey = 'private-space-members'
maxMemberships = user.get('max_memberships_private_projects')
else if privateError
errorKey = 'private-space'
else if membersError
errorKey = 'private-members'
maxMemberships = user.get('max_memberships_private_projects')
else
publicError = !@currentUserService.canCreatePublicProjects().valid
if user.get('max_memberships_public_projects') != null && result.headers.memberships >= user.get('max_memberships_public_projects')
membersError = true
else
membersError = false
if publicError && membersError
errorKey = 'public-space-members'
maxMemberships = user.get('max_memberships_public_projects')
else if publicError
errorKey = 'public-space'
else if membersError
errorKey = 'public-members'
maxMemberships = user.get('max_memberships_public_projects')
if !errorKey
return false
return {
key: errorKey,
values: {
max_memberships: maxMemberships,
members: result.headers.memberships
}
}
else
return false
angular.module("taigaProjects").service("tgImportProjectService", ImportProjectService)
| 103639 | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: projects/create/import/import-project.service.coffee
###
class ImportProjectService extends taiga.Service
@.$inject = [
'tgCurrentUserService',
'$tgAuth',
'tgLightboxFactory',
'$translate',
'$tgConfirm',
'$location',
'$tgNavUrls'
]
constructor: (@currentUserService, @tgAuth, @lightboxFactory, @translate, @confirm, @location, @tgNavUrls) ->
importPromise: (promise) ->
return promise.then(@.importSuccess.bind(this), @.importError.bind(this))
importSuccess: (result) ->
promise = @currentUserService.loadProjects()
promise.then () =>
if result.status == 202 # Async mode
title = @translate.instant('PROJECT.IMPORT.ASYNC_IN_PROGRESS_TITLE')
message = @translate.instant('PROJECT.IMPORT.ASYNC_IN_PROGRESS_MESSAGE')
@location.path(@tgNavUrls.resolve('home'))
@confirm.success(title, message)
else # result.status == 201 # Sync mode
ctx = {project: result.data.slug}
@location.path(@tgNavUrls.resolve('project-admin-project-profile-details', ctx))
msg = @translate.instant('PROJECT.IMPORT.SYNC_SUCCESS')
@confirm.notify('success', msg)
return promise
importError: (result) ->
promise = @tgAuth.refresh()
promise.then () =>
restrictionError = @.getRestrictionError(result)
if restrictionError
@lightboxFactory.create('tg-lb-import-error', {
class: 'lightbox lightbox-import-error'
}, restrictionError)
else
errorMsg = @translate.instant("PROJECT.IMPORT.ERROR")
if result.status == 429 # TOO MANY REQUESTS
errorMsg = @translate.instant("PROJECT.IMPORT.ERROR_TOO_MANY_REQUEST")
else if result.data?._error_message
errorMsg = @translate.instant("PROJECT.IMPORT.ERROR_MESSAGE", {error_message: result.data._error_message})
@confirm.notify("error", errorMsg)
return promise
getRestrictionError: (result) ->
if result.headers
errorKey = ''
user = @currentUserService.getUser()
maxMemberships = null
if result.headers.isPrivate
privateError = !@currentUserService.canCreatePrivateProjects().valid
if user.get('max_memberships_private_projects') != null && result.headers.memberships >= user.get('max_memberships_private_projects')
membersError = true
else
membersError = false
if privateError && membersError
errorKey = '<KEY>'
maxMemberships = user.get('max_memberships_private_projects')
else if privateError
errorKey = '<KEY>'
else if membersError
errorKey = '<KEY>'
maxMemberships = user.get('max_memberships_private_projects')
else
publicError = !@currentUserService.canCreatePublicProjects().valid
if user.get('max_memberships_public_projects') != null && result.headers.memberships >= user.get('max_memberships_public_projects')
membersError = true
else
membersError = false
if publicError && membersError
errorKey = '<KEY>'
maxMemberships = user.get('max_memberships_public_projects')
else if publicError
errorKey = '<KEY>'
else if membersError
errorKey = '<KEY>'
maxMemberships = user.get('max_memberships_public_projects')
if !errorKey
return false
return {
key: errorKey,
values: {
max_memberships: maxMemberships,
members: result.headers.memberships
}
}
else
return false
angular.module("taigaProjects").service("tgImportProjectService", ImportProjectService)
| true | ###
# Copyright (C) 2014-2018 Taiga Agile LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: projects/create/import/import-project.service.coffee
###
class ImportProjectService extends taiga.Service
@.$inject = [
'tgCurrentUserService',
'$tgAuth',
'tgLightboxFactory',
'$translate',
'$tgConfirm',
'$location',
'$tgNavUrls'
]
constructor: (@currentUserService, @tgAuth, @lightboxFactory, @translate, @confirm, @location, @tgNavUrls) ->
importPromise: (promise) ->
return promise.then(@.importSuccess.bind(this), @.importError.bind(this))
importSuccess: (result) ->
promise = @currentUserService.loadProjects()
promise.then () =>
if result.status == 202 # Async mode
title = @translate.instant('PROJECT.IMPORT.ASYNC_IN_PROGRESS_TITLE')
message = @translate.instant('PROJECT.IMPORT.ASYNC_IN_PROGRESS_MESSAGE')
@location.path(@tgNavUrls.resolve('home'))
@confirm.success(title, message)
else # result.status == 201 # Sync mode
ctx = {project: result.data.slug}
@location.path(@tgNavUrls.resolve('project-admin-project-profile-details', ctx))
msg = @translate.instant('PROJECT.IMPORT.SYNC_SUCCESS')
@confirm.notify('success', msg)
return promise
importError: (result) ->
promise = @tgAuth.refresh()
promise.then () =>
restrictionError = @.getRestrictionError(result)
if restrictionError
@lightboxFactory.create('tg-lb-import-error', {
class: 'lightbox lightbox-import-error'
}, restrictionError)
else
errorMsg = @translate.instant("PROJECT.IMPORT.ERROR")
if result.status == 429 # TOO MANY REQUESTS
errorMsg = @translate.instant("PROJECT.IMPORT.ERROR_TOO_MANY_REQUEST")
else if result.data?._error_message
errorMsg = @translate.instant("PROJECT.IMPORT.ERROR_MESSAGE", {error_message: result.data._error_message})
@confirm.notify("error", errorMsg)
return promise
getRestrictionError: (result) ->
if result.headers
errorKey = ''
user = @currentUserService.getUser()
maxMemberships = null
if result.headers.isPrivate
privateError = !@currentUserService.canCreatePrivateProjects().valid
if user.get('max_memberships_private_projects') != null && result.headers.memberships >= user.get('max_memberships_private_projects')
membersError = true
else
membersError = false
if privateError && membersError
errorKey = 'PI:KEY:<KEY>END_PI'
maxMemberships = user.get('max_memberships_private_projects')
else if privateError
errorKey = 'PI:KEY:<KEY>END_PI'
else if membersError
errorKey = 'PI:KEY:<KEY>END_PI'
maxMemberships = user.get('max_memberships_private_projects')
else
publicError = !@currentUserService.canCreatePublicProjects().valid
if user.get('max_memberships_public_projects') != null && result.headers.memberships >= user.get('max_memberships_public_projects')
membersError = true
else
membersError = false
if publicError && membersError
errorKey = 'PI:KEY:<KEY>END_PI'
maxMemberships = user.get('max_memberships_public_projects')
else if publicError
errorKey = 'PI:KEY:<KEY>END_PI'
else if membersError
errorKey = 'PI:KEY:<KEY>END_PI'
maxMemberships = user.get('max_memberships_public_projects')
if !errorKey
return false
return {
key: errorKey,
values: {
max_memberships: maxMemberships,
members: result.headers.memberships
}
}
else
return false
angular.module("taigaProjects").service("tgImportProjectService", ImportProjectService)
|
[
{
"context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o",
"end": 67,
"score": 0.9197463989257812,
"start": 62,
"tag": "NAME",
"value": "Hatio"
}
] | src/spec/SpecInfographic.coffee | heartyoh/infopik | 0 | # ==========================================
# Copyright 2014 Hatio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'KineticJS'
], (dou, kin) ->
"use strict"
createView = (attributes) ->
new kin.Group(attributes);
createHandle = (attributes) ->
return new Kin.Group(attributes)
{
type: 'infographic'
name: 'infographic'
containable: true
container_type: 'container'
description: 'Infographic Specification'
defaults: {
draggable: false
}
view_factory_fn: createView
handle_factory_fn: createHandle
toolbox_image: 'images/toolbox_infographic.png'
}
| 200913 | # ==========================================
# Copyright 2014 <NAME>, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'KineticJS'
], (dou, kin) ->
"use strict"
createView = (attributes) ->
new kin.Group(attributes);
createHandle = (attributes) ->
return new Kin.Group(attributes)
{
type: 'infographic'
name: 'infographic'
containable: true
container_type: 'container'
description: 'Infographic Specification'
defaults: {
draggable: false
}
view_factory_fn: createView
handle_factory_fn: createHandle
toolbox_image: 'images/toolbox_infographic.png'
}
| true | # ==========================================
# Copyright 2014 PI:NAME:<NAME>END_PI, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'KineticJS'
], (dou, kin) ->
"use strict"
createView = (attributes) ->
new kin.Group(attributes);
createHandle = (attributes) ->
return new Kin.Group(attributes)
{
type: 'infographic'
name: 'infographic'
containable: true
container_type: 'container'
description: 'Infographic Specification'
defaults: {
draggable: false
}
view_factory_fn: createView
handle_factory_fn: createHandle
toolbox_image: 'images/toolbox_infographic.png'
}
|
[
{
"context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.",
"end": 215,
"score": 0.9998075366020203,
"start": 198,
"tag": "NAME",
"value": "Benjamin Blundell"
},
{
"context": " PXL.js\n ... | src/util/log.coffee | OniDaito/pxljs | 1 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
Benjamin Blundell - ben@pxljs.com
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
Error Handling code
- TODO
* Line numbers maybe?
* Problem with using @ as we are including this file in many places with node :S
* Unfortunately, the way coffeescript works we have blablahblah = function() which means the functions dont have a name
- therefore getting the function name for logging is HARD
###
cache = []
# ## printStackTrace
printStackTrace = () ->
callstack = []
isCallstackPopulated = false
try
i.dont.exist+=0
catch e
if e.stack
lines = e.stack.split('\n')
for i in [0..lines.length-1]
callstack.push(lines[i])
callstack.shift()
isCallstackPopulated = true
else if window.opera and e.message
lines = e.message.split('\n');
for i in [0..lines.length-1]
callstack.push(entry)
callstack.shift()
isCallstackPopulated = true
if !isCallstackPopulated
currentFunction = arguments.callee.caller
while currentFunction
fn = currentFunction.toString()
fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf('')) || 'anonymous'
callstack.push(fname)
currentFunction = currentFunction.caller
callstack.join('\n')
printObjectName = (obj) ->
funcNameRegex = /function (.{1,})\(/;
results = (funcNameRegex).exec((obj).constructor.toString())
if results?
if results.length > 1
return results[1]
""
# ## PXLError
# Thow an exception and print the message
# - **msg** - a String
# - returns throws exception
PXLError = (msg) =>
f = "PXL Error : " + msg
console.error (f)
throw f
# ## PXLWarning
# Thow a warning and print the message
# - **msg** - a String
# - returns this
PXLWarning = (msg) =>
f = "PXL Warning : " + msg
console.warn (f)
console.warn printStackTrace()
@
# ## PXLWarningOnce
# Thow a warning only once and print the message
# Potentially a warning shouldnt occur more than once ;)
# - **msg** - a String
# - returns this
PXLWarningOnce = (msg) =>
result = msg in cache
if not result
f = "PXL Warning : " + msg
console.warn (f)
console.warn printStackTrace()
cache.push msg
@
# ## PXLDebug
# If in Debug print the message
# - **msg** - a String
# - returns this
PXLDebug = (msg) =>
if PXL.Context.debug
f = "PXL Debug : " + msg
console.log (f)
@
# ## PXLLog
# Log a message to the console
# - **msg** - a String
# - returns this
#
PXLLog = (msg) ->
f = "PXL Log : " + msg
myName = arguments.callee.toString()
myName = myName.substr('function '.length)
myName = myName.substr(0, myName.indexOf('('))
console.log (f)
@
module.exports =
PXLError : PXLError
PXLWarning : PXLWarning
PXLLog : PXLLog
PXLWarningOnce : PXLWarningOnce
PXLDebug : PXLDebug
| 206438 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
<NAME> - <EMAIL>
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
Error Handling code
- TODO
* Line numbers maybe?
* Problem with using @ as we are including this file in many places with node :S
* Unfortunately, the way coffeescript works we have blablahblah = function() which means the functions dont have a name
- therefore getting the function name for logging is HARD
###
cache = []
# ## printStackTrace
printStackTrace = () ->
callstack = []
isCallstackPopulated = false
try
i.dont.exist+=0
catch e
if e.stack
lines = e.stack.split('\n')
for i in [0..lines.length-1]
callstack.push(lines[i])
callstack.shift()
isCallstackPopulated = true
else if window.opera and e.message
lines = e.message.split('\n');
for i in [0..lines.length-1]
callstack.push(entry)
callstack.shift()
isCallstackPopulated = true
if !isCallstackPopulated
currentFunction = arguments.callee.caller
while currentFunction
fn = currentFunction.toString()
fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf('')) || 'anonymous'
callstack.push(fname)
currentFunction = currentFunction.caller
callstack.join('\n')
printObjectName = (obj) ->
funcNameRegex = /function (.{1,})\(/;
results = (funcNameRegex).exec((obj).constructor.toString())
if results?
if results.length > 1
return results[1]
""
# ## PXLError
# Thow an exception and print the message
# - **msg** - a String
# - returns throws exception
PXLError = (msg) =>
f = "PXL Error : " + msg
console.error (f)
throw f
# ## PXLWarning
# Thow a warning and print the message
# - **msg** - a String
# - returns this
PXLWarning = (msg) =>
f = "PXL Warning : " + msg
console.warn (f)
console.warn printStackTrace()
@
# ## PXLWarningOnce
# Thow a warning only once and print the message
# Potentially a warning shouldnt occur more than once ;)
# - **msg** - a String
# - returns this
PXLWarningOnce = (msg) =>
result = msg in cache
if not result
f = "PXL Warning : " + msg
console.warn (f)
console.warn printStackTrace()
cache.push msg
@
# ## PXLDebug
# If in Debug print the message
# - **msg** - a String
# - returns this
PXLDebug = (msg) =>
if PXL.Context.debug
f = "PXL Debug : " + msg
console.log (f)
@
# ## PXLLog
# Log a message to the console
# - **msg** - a String
# - returns this
#
PXLLog = (msg) ->
f = "PXL Log : " + msg
myName = arguments.callee.toString()
myName = myName.substr('function '.length)
myName = myName.substr(0, myName.indexOf('('))
console.log (f)
@
module.exports =
PXLError : PXLError
PXLWarning : PXLWarning
PXLLog : PXLLog
PXLWarningOnce : PXLWarningOnce
PXLDebug : PXLDebug
| true | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
Error Handling code
- TODO
* Line numbers maybe?
* Problem with using @ as we are including this file in many places with node :S
* Unfortunately, the way coffeescript works we have blablahblah = function() which means the functions dont have a name
- therefore getting the function name for logging is HARD
###
cache = []
# ## printStackTrace
printStackTrace = () ->
callstack = []
isCallstackPopulated = false
try
i.dont.exist+=0
catch e
if e.stack
lines = e.stack.split('\n')
for i in [0..lines.length-1]
callstack.push(lines[i])
callstack.shift()
isCallstackPopulated = true
else if window.opera and e.message
lines = e.message.split('\n');
for i in [0..lines.length-1]
callstack.push(entry)
callstack.shift()
isCallstackPopulated = true
if !isCallstackPopulated
currentFunction = arguments.callee.caller
while currentFunction
fn = currentFunction.toString()
fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf('')) || 'anonymous'
callstack.push(fname)
currentFunction = currentFunction.caller
callstack.join('\n')
printObjectName = (obj) ->
funcNameRegex = /function (.{1,})\(/;
results = (funcNameRegex).exec((obj).constructor.toString())
if results?
if results.length > 1
return results[1]
""
# ## PXLError
# Thow an exception and print the message
# - **msg** - a String
# - returns throws exception
PXLError = (msg) =>
f = "PXL Error : " + msg
console.error (f)
throw f
# ## PXLWarning
# Thow a warning and print the message
# - **msg** - a String
# - returns this
PXLWarning = (msg) =>
f = "PXL Warning : " + msg
console.warn (f)
console.warn printStackTrace()
@
# ## PXLWarningOnce
# Thow a warning only once and print the message
# Potentially a warning shouldnt occur more than once ;)
# - **msg** - a String
# - returns this
PXLWarningOnce = (msg) =>
result = msg in cache
if not result
f = "PXL Warning : " + msg
console.warn (f)
console.warn printStackTrace()
cache.push msg
@
# ## PXLDebug
# If in Debug print the message
# - **msg** - a String
# - returns this
PXLDebug = (msg) =>
if PXL.Context.debug
f = "PXL Debug : " + msg
console.log (f)
@
# ## PXLLog
# Log a message to the console
# - **msg** - a String
# - returns this
#
PXLLog = (msg) ->
f = "PXL Log : " + msg
myName = arguments.callee.toString()
myName = myName.substr('function '.length)
myName = myName.substr(0, myName.indexOf('('))
console.log (f)
@
module.exports =
PXLError : PXLError
PXLWarning : PXLWarning
PXLLog : PXLLog
PXLWarningOnce : PXLWarningOnce
PXLDebug : PXLDebug
|
[
{
"context": "###\njquery.slideMatrix v0.0.3\n(c) 2012 Ryan Lewis <ryanscottlewis@gmail.com> MIT License\n###\n\n(($, ",
"end": 49,
"score": 0.9998372793197632,
"start": 39,
"tag": "NAME",
"value": "Ryan Lewis"
},
{
"context": "##\njquery.slideMatrix v0.0.3\n(c) 2012 Ryan Lewis <ryan... | src/jquery.slideMatrix.coffee | RyanScottLewis/jquery-slideMatrix | 2 | ###
jquery.slideMatrix v0.0.3
(c) 2012 Ryan Lewis <ryanscottlewis@gmail.com> MIT License
###
(($, window) ->
$.fn.extend
slideMatrix: ->
optionsOrArgument = arguments[0]
switch optionsOrArgument
when 'slideTo'
argument = arguments[1]
currentItemPos = @currentItemPos()
nextPos = {}
if typeof argument == 'string'
nextElmData = @find( argument ).data()
nextPos.x = nextElmData.x || 0
nextPos.y = nextElmData.y || 0
else if typeof argument == 'object'
nextPos.x = argument.x || 0
nextPos.y = argument.y || 0
else if argument instanceof jQuery
nextElmData = argument.data()
nextPos.x = nextElmData.x || 0
nextPos.y = nextElmData.y || 0
nextItem = @find( ".slideMatrixItem[data-x='" + nextPos.x + "'][data-y='" + nextPos.y + "']" )
if nextItem?
if nextPos.x > currentItemPos.x
if nextItem.length == 0 && @settings.wraparound
console.log 'Should wrap!'
else
@slideToItem( nextItem, 'right' )
else if nextPos.x < currentItemPos.x
if nextPos.x < 0 && @settings.wraparound
console.log 'Should wrap!'
else if nextPos.x >= 0
@slideToItem( nextItem, 'left' )
else if nextPos.x == currentItemPos.x
if nextPos.y > currentItemPos.y
if nextItem.length == 0 && @settings.wraparound
console.log 'Should wrap!'
else
@slideToItem( nextItem, 'up' )
else if nextPos.y < currentItemPos.y
if nextPos < 0 && @settings.wraparound
console.log 'Should wrap!'
else
@slideToItem( nextItem, 'down' )
when 'slide'
direction = arguments[1]
currentItemPos = @currentItemPos()
nextItemPos = switch direction
when 'up'
{ x: currentItemPos.x, y: currentItemPos.y+1 }
when 'right'
{ x: currentItemPos.x+1, y: currentItemPos.y }
when 'down'
{ x: currentItemPos.x, y: currentItemPos.y-1 }
when 'left'
{ x: currentItemPos.x-1, y: currentItemPos.y }
nextItem = @find( ".slideMatrixItem[data-x='" + nextItemPos.x + "'][data-y='" + nextItemPos.y + "']" )
if nextItem.length == 0 && @settings.wraparound
console.log 'Should wrap!'
else if nextItem.length > 0
@slideToItem( nextItem, direction )
else
@defaultOptions =
initialItemFilter: ':first'
wraparound: false
slideSpeed: 250
@settings = $.extend( {}, @defaultOptions, optionsOrArgument )
@currentItemPos = ->
x: @currentItem.data('x') || 0
y: @currentItem.data('y') || 0
@sliding = false
@slideToItem = (item, direction) ->
cssAttr = if direction == 'up' || direction == 'down' then 'top' else 'left'
nextItemCssStartValue = switch direction
when 'up' then -@currentItem.height()
when 'right' then @currentItem.width()
when 'down' then @currentItem.height()
when 'left' then -@currentItem.width()
nextItemCssStart = (->o={}; o[ cssAttr ] = nextItemCssStartValue; o)()
nextItemCssEnd = (->o={}; o[ cssAttr ] = 0; o)()
currentItemCssEnd = (->o={}; o[ cssAttr ] = -nextItemCssStartValue; o)()
item.css( nextItemCssStart )
item.show()
unless @sliding == true
@sliding = true
@currentItem.animate currentItemCssEnd, @settings.slideSpeed
item.animate nextItemCssEnd, @settings.slideSpeed, =>
@currentItem.hide().css( left: 0, top: 0 )
@currentItem = item
@sliding = false
controls = $( "[data-target='" + @selector + "']" )
controls.click (e) =>
e.preventDefault()
unless @sliding == true
$control = $( e.target )
$target = $( $control.data('target') )
action = $control.data('action')
switch action
when 'slideTo'
if $control.data('selector')?
@slideMatrix( action, $control.data('selector') )
else
@slideMatrix( action, { x: $control.data('x'), y: $control.data('y') } )
when 'slide'
@slideMatrix( action, $control.data('direction') || 'right' )
else
return false
false
items = @find('.slideMatrixItem')
initialItem = items.filter( @settings.initialItemFilter )
items.hide()
initialItem.show()
@currentItem = initialItem
@
) jQuery, this
| 168152 | ###
jquery.slideMatrix v0.0.3
(c) 2012 <NAME> <<EMAIL>> MIT License
###
(($, window) ->
$.fn.extend
slideMatrix: ->
optionsOrArgument = arguments[0]
switch optionsOrArgument
when 'slideTo'
argument = arguments[1]
currentItemPos = @currentItemPos()
nextPos = {}
if typeof argument == 'string'
nextElmData = @find( argument ).data()
nextPos.x = nextElmData.x || 0
nextPos.y = nextElmData.y || 0
else if typeof argument == 'object'
nextPos.x = argument.x || 0
nextPos.y = argument.y || 0
else if argument instanceof jQuery
nextElmData = argument.data()
nextPos.x = nextElmData.x || 0
nextPos.y = nextElmData.y || 0
nextItem = @find( ".slideMatrixItem[data-x='" + nextPos.x + "'][data-y='" + nextPos.y + "']" )
if nextItem?
if nextPos.x > currentItemPos.x
if nextItem.length == 0 && @settings.wraparound
console.log 'Should wrap!'
else
@slideToItem( nextItem, 'right' )
else if nextPos.x < currentItemPos.x
if nextPos.x < 0 && @settings.wraparound
console.log 'Should wrap!'
else if nextPos.x >= 0
@slideToItem( nextItem, 'left' )
else if nextPos.x == currentItemPos.x
if nextPos.y > currentItemPos.y
if nextItem.length == 0 && @settings.wraparound
console.log 'Should wrap!'
else
@slideToItem( nextItem, 'up' )
else if nextPos.y < currentItemPos.y
if nextPos < 0 && @settings.wraparound
console.log 'Should wrap!'
else
@slideToItem( nextItem, 'down' )
when 'slide'
direction = arguments[1]
currentItemPos = @currentItemPos()
nextItemPos = switch direction
when 'up'
{ x: currentItemPos.x, y: currentItemPos.y+1 }
when 'right'
{ x: currentItemPos.x+1, y: currentItemPos.y }
when 'down'
{ x: currentItemPos.x, y: currentItemPos.y-1 }
when 'left'
{ x: currentItemPos.x-1, y: currentItemPos.y }
nextItem = @find( ".slideMatrixItem[data-x='" + nextItemPos.x + "'][data-y='" + nextItemPos.y + "']" )
if nextItem.length == 0 && @settings.wraparound
console.log 'Should wrap!'
else if nextItem.length > 0
@slideToItem( nextItem, direction )
else
@defaultOptions =
initialItemFilter: ':first'
wraparound: false
slideSpeed: 250
@settings = $.extend( {}, @defaultOptions, optionsOrArgument )
@currentItemPos = ->
x: @currentItem.data('x') || 0
y: @currentItem.data('y') || 0
@sliding = false
@slideToItem = (item, direction) ->
cssAttr = if direction == 'up' || direction == 'down' then 'top' else 'left'
nextItemCssStartValue = switch direction
when 'up' then -@currentItem.height()
when 'right' then @currentItem.width()
when 'down' then @currentItem.height()
when 'left' then -@currentItem.width()
nextItemCssStart = (->o={}; o[ cssAttr ] = nextItemCssStartValue; o)()
nextItemCssEnd = (->o={}; o[ cssAttr ] = 0; o)()
currentItemCssEnd = (->o={}; o[ cssAttr ] = -nextItemCssStartValue; o)()
item.css( nextItemCssStart )
item.show()
unless @sliding == true
@sliding = true
@currentItem.animate currentItemCssEnd, @settings.slideSpeed
item.animate nextItemCssEnd, @settings.slideSpeed, =>
@currentItem.hide().css( left: 0, top: 0 )
@currentItem = item
@sliding = false
controls = $( "[data-target='" + @selector + "']" )
controls.click (e) =>
e.preventDefault()
unless @sliding == true
$control = $( e.target )
$target = $( $control.data('target') )
action = $control.data('action')
switch action
when 'slideTo'
if $control.data('selector')?
@slideMatrix( action, $control.data('selector') )
else
@slideMatrix( action, { x: $control.data('x'), y: $control.data('y') } )
when 'slide'
@slideMatrix( action, $control.data('direction') || 'right' )
else
return false
false
items = @find('.slideMatrixItem')
initialItem = items.filter( @settings.initialItemFilter )
items.hide()
initialItem.show()
@currentItem = initialItem
@
) jQuery, this
| true | ###
jquery.slideMatrix v0.0.3
(c) 2012 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> MIT License
###
(($, window) ->
$.fn.extend
slideMatrix: ->
optionsOrArgument = arguments[0]
switch optionsOrArgument
when 'slideTo'
argument = arguments[1]
currentItemPos = @currentItemPos()
nextPos = {}
if typeof argument == 'string'
nextElmData = @find( argument ).data()
nextPos.x = nextElmData.x || 0
nextPos.y = nextElmData.y || 0
else if typeof argument == 'object'
nextPos.x = argument.x || 0
nextPos.y = argument.y || 0
else if argument instanceof jQuery
nextElmData = argument.data()
nextPos.x = nextElmData.x || 0
nextPos.y = nextElmData.y || 0
nextItem = @find( ".slideMatrixItem[data-x='" + nextPos.x + "'][data-y='" + nextPos.y + "']" )
if nextItem?
if nextPos.x > currentItemPos.x
if nextItem.length == 0 && @settings.wraparound
console.log 'Should wrap!'
else
@slideToItem( nextItem, 'right' )
else if nextPos.x < currentItemPos.x
if nextPos.x < 0 && @settings.wraparound
console.log 'Should wrap!'
else if nextPos.x >= 0
@slideToItem( nextItem, 'left' )
else if nextPos.x == currentItemPos.x
if nextPos.y > currentItemPos.y
if nextItem.length == 0 && @settings.wraparound
console.log 'Should wrap!'
else
@slideToItem( nextItem, 'up' )
else if nextPos.y < currentItemPos.y
if nextPos < 0 && @settings.wraparound
console.log 'Should wrap!'
else
@slideToItem( nextItem, 'down' )
when 'slide'
direction = arguments[1]
currentItemPos = @currentItemPos()
nextItemPos = switch direction
when 'up'
{ x: currentItemPos.x, y: currentItemPos.y+1 }
when 'right'
{ x: currentItemPos.x+1, y: currentItemPos.y }
when 'down'
{ x: currentItemPos.x, y: currentItemPos.y-1 }
when 'left'
{ x: currentItemPos.x-1, y: currentItemPos.y }
nextItem = @find( ".slideMatrixItem[data-x='" + nextItemPos.x + "'][data-y='" + nextItemPos.y + "']" )
if nextItem.length == 0 && @settings.wraparound
console.log 'Should wrap!'
else if nextItem.length > 0
@slideToItem( nextItem, direction )
else
@defaultOptions =
initialItemFilter: ':first'
wraparound: false
slideSpeed: 250
@settings = $.extend( {}, @defaultOptions, optionsOrArgument )
@currentItemPos = ->
x: @currentItem.data('x') || 0
y: @currentItem.data('y') || 0
@sliding = false
@slideToItem = (item, direction) ->
cssAttr = if direction == 'up' || direction == 'down' then 'top' else 'left'
nextItemCssStartValue = switch direction
when 'up' then -@currentItem.height()
when 'right' then @currentItem.width()
when 'down' then @currentItem.height()
when 'left' then -@currentItem.width()
nextItemCssStart = (->o={}; o[ cssAttr ] = nextItemCssStartValue; o)()
nextItemCssEnd = (->o={}; o[ cssAttr ] = 0; o)()
currentItemCssEnd = (->o={}; o[ cssAttr ] = -nextItemCssStartValue; o)()
item.css( nextItemCssStart )
item.show()
unless @sliding == true
@sliding = true
@currentItem.animate currentItemCssEnd, @settings.slideSpeed
item.animate nextItemCssEnd, @settings.slideSpeed, =>
@currentItem.hide().css( left: 0, top: 0 )
@currentItem = item
@sliding = false
controls = $( "[data-target='" + @selector + "']" )
controls.click (e) =>
e.preventDefault()
unless @sliding == true
$control = $( e.target )
$target = $( $control.data('target') )
action = $control.data('action')
switch action
when 'slideTo'
if $control.data('selector')?
@slideMatrix( action, $control.data('selector') )
else
@slideMatrix( action, { x: $control.data('x'), y: $control.data('y') } )
when 'slide'
@slideMatrix( action, $control.data('direction') || 'right' )
else
return false
false
items = @find('.slideMatrixItem')
initialItem = items.filter( @settings.initialItemFilter )
items.hide()
initialItem.show()
@currentItem = initialItem
@
) jQuery, this
|
[
{
"context": " @game = new GamingAPI.Models.Game\n name: \"test1\"\n deck: \"My test description\"\n image: {",
"end": 330,
"score": 0.9967559576034546,
"start": 325,
"tag": "NAME",
"value": "test1"
},
{
"context": "ct(@view.$(\".js-game-name\").text()).toEqual \"Nam... | spec/javascripts/games/views/detailed_game_view_spec.js.coffee | Mack0856/gaming_api | 0 | describe "GamingAPI.Views.DetailedGameView", ->
beforeEach ->
@platform1 = new GamingAPI.Models.Platform({abbreviation: "XB1"})
@platform2 = new GamingAPI.Models.Platform({abbreviation: "PS4"})
@platform3 = new GamingAPI.Models.Platform({abbreviation: "PC"})
@game = new GamingAPI.Models.Game
name: "test1"
deck: "My test description"
image: { medium_url: "test url"}
platforms: new GamingAPI.Collections.Platforms([@platform1, @platform2, @platform3])
@view = new GamingAPI.Views.DetailedGameView(game: @game)
@view.render()
describe "render", ->
it "renders more information about a game", ->
expect(@view.$(".js-game-image").attr("src")).toEqual "test url"
expect(@view.$(".js-game-name").text()).toEqual "Name: test1"
expect(@view.$(".js-game-description").text()).toEqual "Description: My test description"
| 67987 | describe "GamingAPI.Views.DetailedGameView", ->
beforeEach ->
@platform1 = new GamingAPI.Models.Platform({abbreviation: "XB1"})
@platform2 = new GamingAPI.Models.Platform({abbreviation: "PS4"})
@platform3 = new GamingAPI.Models.Platform({abbreviation: "PC"})
@game = new GamingAPI.Models.Game
name: "<NAME>"
deck: "My test description"
image: { medium_url: "test url"}
platforms: new GamingAPI.Collections.Platforms([@platform1, @platform2, @platform3])
@view = new GamingAPI.Views.DetailedGameView(game: @game)
@view.render()
describe "render", ->
it "renders more information about a game", ->
expect(@view.$(".js-game-image").attr("src")).toEqual "test url"
expect(@view.$(".js-game-name").text()).toEqual "Name: <NAME>"
expect(@view.$(".js-game-description").text()).toEqual "Description: My test description"
| true | describe "GamingAPI.Views.DetailedGameView", ->
beforeEach ->
@platform1 = new GamingAPI.Models.Platform({abbreviation: "XB1"})
@platform2 = new GamingAPI.Models.Platform({abbreviation: "PS4"})
@platform3 = new GamingAPI.Models.Platform({abbreviation: "PC"})
@game = new GamingAPI.Models.Game
name: "PI:NAME:<NAME>END_PI"
deck: "My test description"
image: { medium_url: "test url"}
platforms: new GamingAPI.Collections.Platforms([@platform1, @platform2, @platform3])
@view = new GamingAPI.Views.DetailedGameView(game: @game)
@view.render()
describe "render", ->
it "renders more information about a game", ->
expect(@view.$(".js-game-image").attr("src")).toEqual "test url"
expect(@view.$(".js-game-name").text()).toEqual "Name: PI:NAME:<NAME>END_PI"
expect(@view.$(".js-game-description").text()).toEqual "Description: My test description"
|
[
{
"context": "\nnikita = require '@nikitajs/core'\n{tags, ssh, scratch} = require '../test'\nth",
"end": 28,
"score": 0.6927008628845215,
"start": 23,
"tag": "USERNAME",
"value": "itajs"
},
{
"context": "solved.conf\"\n content:\n FallbackDNS: \"1.1.1.1\"\n reload: f... | packages/filetypes/test/systemd/resolved.coffee | chibanemourad/node-nikita | 1 |
nikita = require '@nikitajs/core'
{tags, ssh, scratch} = require '../test'
they = require('ssh2-they').configure ssh...
return unless tags.posix
describe 'file.types.systemd.resolved', ->
they 'servers as a string', ({ssh}) ->
nikita
ssh: ssh
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
FallbackDNS: "1.1.1.1"
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1
"""
trim: true
.promise()
they 'servers as an array', ({ssh}) ->
nikita
ssh: ssh
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
FallbackDNS: ["1.1.1.1", "9.9.9.10", "8.8.8.8", "2606:4700:4700::1111"]
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1 9.9.9.10 8.8.8.8 2606:4700:4700::1111
"""
trim: true
.promise()
they 'merge values', ({ssh}) ->
nikita
ssh: ssh
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
DNS: "ns0.fdn.fr"
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
"""
trim: true
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
ReadEtcHosts: "true"
merge: true
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
ReadEtcHosts=true
"""
trim: true
.promise()
| 186200 |
nikita = require '@nikitajs/core'
{tags, ssh, scratch} = require '../test'
they = require('ssh2-they').configure ssh...
return unless tags.posix
describe 'file.types.systemd.resolved', ->
they 'servers as a string', ({ssh}) ->
nikita
ssh: ssh
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
FallbackDNS: "1.1.1.1"
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1
"""
trim: true
.promise()
they 'servers as an array', ({ssh}) ->
nikita
ssh: ssh
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
FallbackDNS: ["1.1.1.1", "172.16.58.3", "8.8.8.8", "fc00:db20:35b:7399::5"]
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1 172.16.58.3 8.8.8.8 2fc00:db20:35b:7399::5
"""
trim: true
.promise()
they 'merge values', ({ssh}) ->
nikita
ssh: ssh
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
DNS: "ns0.fdn.fr"
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
"""
trim: true
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
ReadEtcHosts: "true"
merge: true
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
ReadEtcHosts=true
"""
trim: true
.promise()
| true |
nikita = require '@nikitajs/core'
{tags, ssh, scratch} = require '../test'
they = require('ssh2-they').configure ssh...
return unless tags.posix
describe 'file.types.systemd.resolved', ->
they 'servers as a string', ({ssh}) ->
nikita
ssh: ssh
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
FallbackDNS: "1.1.1.1"
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1
"""
trim: true
.promise()
they 'servers as an array', ({ssh}) ->
nikita
ssh: ssh
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
FallbackDNS: ["1.1.1.1", "PI:IP_ADDRESS:172.16.58.3END_PI", "8.8.8.8", "PI:IP_ADDRESS:fc00:db20:35b:7399::5END_PI"]
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
FallbackDNS=1.1.1.1 PI:IP_ADDRESS:172.16.58.3END_PI 8.8.8.8 2PI:IP_ADDRESS:fc00:db20:35b:7399::5END_PI
"""
trim: true
.promise()
they 'merge values', ({ssh}) ->
nikita
ssh: ssh
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
DNS: "ns0.fdn.fr"
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
"""
trim: true
.file.types.systemd.resolved
target: "#{scratch}/resolved.conf"
content:
ReadEtcHosts: "true"
merge: true
reload: false
.file.assert
target: "#{scratch}/resolved.conf"
content: """
[Resolve]
DNS=ns0.fdn.fr
ReadEtcHosts=true
"""
trim: true
.promise()
|
[
{
"context": "'''\nwatchOS : ClockFaces\n\n@auther Jungho song (threeword.com)\n@since 2016.11.23\n'''\nclass expor",
"end": 45,
"score": 0.9998582005500793,
"start": 34,
"tag": "NAME",
"value": "Jungho song"
},
{
"context": " (complications = []) ->\n\t\t@label.html = @name = \"심플\"... | modules/watchos-kit-clockfaces.coffee | framer-modules/watchos | 2 | '''
watchOS : ClockFaces
@auther Jungho song (threeword.com)
@since 2016.11.23
'''
class exports.ClockFaces extends Layer
'''
complications:
utilitarian: []
modular: []
circular: []
'''
# Constructor
constructor: (options = {}) ->
options.name ?= "ClockFaces"
options.backgroundColor ?= "black"
super options
options.complications ?= {}
complications = _.defaults(options.complications, { utilitarian: [], modular: [], circular: [] })
# Page
@page = new PageComponent
name: "page"
width: @width, height: @height
scrollVertical: false
backgroundColor: ""
clip: false
parent: @
@page.content.clip = false
@page.states =
change: y: -13, scale: 284 / @height
selected: y: 0, scale: 1
# Clockface : Utilitarian
@utilitarian = new ClockFace(width: @width, height: @height).utilitarian complications.utilitarian
# Clockface : Modular
@modular = new ClockFace(width: @width, height: @height).modular complications.modular
# Clockface : Circular
@circular = new ClockFace(width: @width, height: @height).circular complications.circular
# Add page
@page.addPage @utilitarian
@page.addPage @modular
@page.addPage @circular
# Snap page
@page.snapToPage @modular, false
# Customize
@customize = new Layer
name: "customize"
x: Align.center, y: @page.maxY + 10
width: 157, height: 57
html: "사용자화"
style:
fontSize: "32px", fontWeight: "400"
lineHeight: "57px"
textAlign: "center"
borderRadius: 15
backgroundColor: "#333333"
scale: 1 / 0.7, originY: 0
parent: @page
@customize.sendToBack()
# 시계화면 : 이벤트
@isChangeDone = false
@isChangeMode = false
# Events
for child in @page.content.children
child.onClick => @selected()
# Long-Press(ForceTouch) : Start
@page.onLongPressStart =>
return if @isChangeMode
#
child.modeChange() for child, i in @page.content.children
@page.animate "change"
# Long-Press(ForceTouch) : End
@page.onLongPressEnd =>
return if @isChangeMode
#
@isChangeMode = true
Utils.delay .3, => @isChangeDone = true
# Screen.on Events.EdgeSwipeLeftStart, (event) ->
# print "start : #{event.point.x}"
# Screen.on Events.EdgeSwipeLeft, (event) ->
# # print event
# Screen.on Events.EdgeSwipeLeftEnd, (event) ->
# print "end : #{event.point}"
# Selected
selected: () ->
return unless @isChangeMode
return unless @isChangeDone
#
for child, i in @page.content.children
child.modeChange false
@page.animate "selected"
#
@isChangeMode = false
@isChangeDone = false
# Time start
timeStart: -> page.clock.start() for page in @page.content.children
# Time stop
timeStop: -> page.clock.stop() for page in @page.content.children
# Set clock face
setClockface: (index) ->
return if _.isEmpty(@page.content.children)
return if _.size(@page.content.children) - 1 < index
@page.snapToPage @page.content.children[index]
'''
Complication Images : https://developer.apple.com/watchos/human-interface-guidelines/icons-and-images/
Family:
modularSmall
modularLarge
utilitarianSmall
utilitarianSmallFlat
utilitarianLarge
circularSmall
extraLarge
Template:
tintColor: "색상"
columnAlignment: "leading" or "tailing"
Circular:
SmallSimpleText: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatecircularsmallsimpletext)
textProvider: "문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
SmallRingImage: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatecircularsmallringimage)
imageProvider: "이미지" (https://developer.apple.com/reference/clockkit/clkimageprovider)
ringStyle: "closed" or "open" (https://developer.apple.com/reference/clockkit/clkcomplicationringstyle)
fillFraction: 채우기 비율
Utilitarian:
SmallFlat: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitariansmallflat)
textProvider: "문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
imageProvider: "이미지" (https://developer.apple.com/reference/clockkit/clkimageprovider)
LargeFlat: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitarianlargeflat)
textProvider: "문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
imageProvider: "이미지" (https://developer.apple.com/reference/clockkit/clkimageprovider)
SmallRingImage: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitariansmallringimage)
imageProvider: "이미지" [require] (https://developer.apple.com/reference/clockkit/clkimageprovider)
ringStyle: "closed" or "open" (https://developer.apple.com/reference/clockkit/clkcomplicationringstyle)
fillFraction: 채우기 비율
SmallSquare: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitariansmallsquare)
imageProvider: "이미지" [require] (https://developer.apple.com/reference/clockkit/clkimageprovider)
Modular:
SmallStackText: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatemodularsmallstacktext)
line1TextProvider: "1라인 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
line2TextProvider: "2라인 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
highlightLine2: Boolean
SmallRingImage: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatemodularsmallringimage)
imageProvider: "이미지" [require] (https://developer.apple.com/reference/clockkit/clkimageprovider)
ringStyle: "closed" or "open" (https://developer.apple.com/reference/clockkit/clkcomplicationringstyle)
fillFraction: 채우기 비율
LargeTallBody: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatemodularlargetallbody)
headerTextProvider: "헤더 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
bodyTextProvider: "바디 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
ExtraLarge:
textProvider:
label: 라벨명
tintColor: 틴트색상
imageProvider:
onePieceImage: 첫번째 이미지
twoPieceImageBackground: 두번째 뒷 이미지
twoPieceImageForeground: 두번째 앞 이미지
tintColor: 틴트색상
'''
# Complication
class exports.Complication extends Layer
Events.ColumnAlignment = "columnAlignment"
Events.TintColor = 'tintColor'
Family = {}
Family.ModularSmall = "modularSmall"
Family.ModularLarge = "modularLarge"
Family.UtilitarianSmall = "utilitarianSmall"
Family.UtilitarianSmallFlat = "utilitarianSmallFlat"
Family.UtilitarianLarge = "utilitarianLarge"
Family.CircularSmall = "circularSmall"
Family.ExtraLarge = "extraLarge"
Template = {}
Template.SimpleImage = "simpleImage"
Template.SimpleText = "simpleText"
Template.RingImage = "ringImage"
Template.RingText = "ringText"
Template.StackText = "stackText"
Template.StackImage = "stackImage"
Template.ColumnsText = "columnsText"
Template.Columns = "columns"
Template.StandardBody = "standardBody"
Template.Table = "table"
Template.TallBody = "tallBody"
Template.Flat = "flat"
Template.Square = "square"
RingStyle = {}
RingStyle.Closed = "closed"
RingStyle.Open = "open"
ColumnAlignment = {}
ColumnAlignment.Leading = "leading"
ColumnAlignment.Trailing = "trailing"
this.Family = Family
this.Template = Template
this.RingStyle = RingStyle
this.ColumnAlignment = ColumnAlignment
@define 'columnAlignment',
get: () -> @_columnAlignment
set: (value) -> @emit("change:#{Events.ColumnAlignment}", @_columnAlignment = value)
@define 'tintColor',
get: () -> @_tintColor
set: (value) -> @emit("change:#{Events.TintColor}", @_tintColor = value)
# Constructor
constructor: (options = {}) ->
options.backgroundColor ?= ""
super options
options.family ?= Family.ModularSmall
options.template ?= Template.SimpleText
@family = options.family
@template = options.template
# ----------------------------------------------------------------------
# Family
# ----------------------------------------------------------------------
# Modular : Small
modularSmall: () ->
@family = Family.ModularSmall
@size = 100
@tintColor = "white"
return this
# Modular : Large
modularLarge: () ->
@family = Family.ModularLarge
@props = width: 312, height: 126
@tintColor = "white"
return this
# Utilitarian : Small
utilitarianSmall: () ->
@family = Family.UtilitarianSmall
@size = 51
@tintColor = "white"
return this
# Utilitarian : Small flat
utilitarianSmallFlat: (options = {}) ->
@family = Family.UtilitarianSmallFlat
@props = width: 120, height: 36
@tintColor = "white"
# Parameters
options.imageProvider ?= {}
options.textProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: "white" })
textProvider = _.defaults(options.textProvider, { tintColor: "white" })
image = new Layer
x: Align.left, y: Align.center
size: 20
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
text = new Layer
html: textProvider.label
style:
fontSize: "28px", fontWeight: "400"
lineHeight: "#{@height}px"
letterSpacing: "-0.2px"
textAlign: "left"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { height: @height }, { x: image.maxX + 3, y: Align.center }
if @contentFrame().width > @width
Util.text.autoFontSize text, { width: @width - image.width, height: @height }, { x: image.maxX + 3, y: Align.center }
# Event : Change column alignment
@on "change:#{Events.ColumnAlignment}", ->
if @columnAlignment is ColumnAlignment.Leading
image.props = x: Align.left, midY: text.midY
text.x = image.maxX + 3
else if @columnAlignment is ColumnAlignment.Trailing
image.props = x: Align.right, midY: text.midY
text.x = image.x - text.width - 3
return this
# Utilitarian : Large
utilitarianLarge: (options = {}) ->
@family = Family.UtilitarianLarge
@props = width: 312, height: 36
@tintColor = "white"
# Parameters
options.imageProvider ?= {}
options.textProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: "white" })
textProvider = _.defaults(options.textProvider, { tintColor: "white" })
image = new Layer
x: Align.left, y: Align.bottom
size: 20
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
text = new Layer
html: textProvider.label
style:
fontSize: "28px", fontWeight: "400"
lineHeight: "1"
letterSpacing: "-0.2px"
textAlign: "left"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { height: @height }, { x: image.maxX + 3, y: Align.bottom }
if @contentFrame().width > @width
Util.text.autoFontSize text, { width: @width - image.width, height: @height }, { x: image.maxX + 3, y: Align.bottom }
image.props = x: @midX - @contentFrame().width / 2, midY: text.midY
text.x = image.maxX + 3
return this
# Circular : Small
circularSmall: () ->
@family = Family.CircularSmall
@size = 68
@scale = 51/68
@tintColor = "#b3b3b3"
return this
# ExtraLarge
extraLarge: () ->
@family = Family.ExtraLarge
@tintColor = "white"
return this
# ----------------------------------------------------------------------
# Template
# ----------------------------------------------------------------------
# Simple text
simpleText: (options = {}) ->
@template = Template.SimpleText
# Parameters
options.textProvider ?= {}
textProvider = _.defaults(options.textProvider, { tintColor: @tintColor })
height = @height
text = new Layer
html: textProvider.label
style:
fontSize: "67px", fontWeight: "400"
lineHeight: "#{height}px"
letterSpacing: "-0.5px"
textAlign: "center"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { width: @width, height: height }, { x: Align.center, y: Align.center }
return this
# Stack text
stackText: (options = {}) ->
@template = Template.StackText
# Parameters
options.line1TextProvider ?= {}
options.line2TextProvider ?= {}
options.highlightLine2 ?= false
line1TextProvider = _.defaults(options.line1TextProvider, { tintColor: @tintColor })
line2TextProvider = _.defaults(options.line2TextProvider, { tintColor: @tintColor })
highlightLine2 = options.highlightLine2
line1TextHeight = 30
line1Text = new Layer
html: line1TextProvider.label
style:
fontSize: "67px", fontWeight: "500"
lineHeight: "1"
letterSpacing: "-0.4px"
padding: "0px 8px"
textAlign: "center"
color: line1TextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize line1Text, { width: @width, height: line1TextHeight }, { x: Align.center, y: Align.bottom(-55) } #Align.center( -@height * 1/3 * 1/2 )
line2TextHeight = 35
line2Text = new Layer
html: line2TextProvider.label
style:
fontSize: "67px", fontWeight: "500"
lineHeight: "1"
letterSpacing: "-0.4px"
padding: "0px 3.5px"
textAlign: "center"
color: line2TextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize line2Text, { width: @width, height: line2TextHeight }, { x: Align.center, y: Align.bottom(-18) } #line1Text.maxY - 10
return this
# Simple image
simpleImage: (options = {}) ->
@template = Template.SimpleImage
# Parameters
options.imageProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: @tintColor })
size = 100
switch @family
when Family.ModularSmall then size = 58 * 1.6
when Family.UtilitarianSmall then size = 44
when Family.CircularSmall then size = 36 * (1/@scale)
image = new Layer
point: Align.center
size: size
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
if @family is Family.CircularSmall
image.brightness = 0
image.contrast = 50
image.invert = 100
return this
# Square
square: (options = {}) ->
@simpleImage options
@template = Template.Square
return this
# Ring image
ringImage: (options = {}) ->
@template = Template.RingImage
# Parameters
options.imageProvider ?= {}
options.fillFraction ?= 0
options.ringStyle ?= RingStyle.Closed
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: @tintColor })
fillFraction = options.fillFraction
ringStyle = options.ringStyle
imageSize = 38; ringSize = 58; ringWidth = 5
switch @family
when Family.ModularSmall
imageSize = 38
ringSize = 58
ringWidth = 5
when Family.UtilitarianSmall
imageSize = 28
ringSize = 47
ringWidth = 4
when Family.CircularSmall
imageSize = 44
ringSize = 64
ringWidth = 6
when Family.ExtraLarge
imageSize = 133
image = new Layer
point: Align.center
size: imageSize
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
if @family is Family.CircularSmall
image.brightness = 0
image.contrast = 50
image.invert = 100
ring = new CircularProgressComponent
point: Align.center
size: ringSize
parent: @
ringColor = new Color(imageProvider.tintColor)
ring.strokeWidth = ringWidth
ring.progressColor = ringColor
ring.railsColor = ringColor.alpha(.3)
ring.setProgress fillFraction, false
return this
# Tall body
tallBody: (options = {})->
@template = Template.TallBody
# Parameters
options.headerTextProvider ?= {}
options.bodyTextProvider ?= {}
headerTextProvider = _.defaults(options.headerTextProvider, { tintColor: @tintColor })
bodyTextProvider = _.defaults(options.bodyTextProvider, { tintColor: @tintColor })
headerTextHeight = 46
headerText = new Layer
html: headerTextProvider.label
style:
fontSize: "33px", fontWeight: "400"
lineHeight: "#{headerTextHeight}px"
letterSpacing: "0.1px"
padding: "0px 12px"
textAlign: "left"
color: headerTextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize headerText, { width: @width, height: headerTextHeight }, { x: Align.left, y: Align.top }
bodyTextHeight = 80
bodyText = new Layer
html: bodyTextProvider.label
style:
fontSize: "80px", fontWeight: "400"
lineHeight: "#{bodyTextHeight}px"
letterSpacing: "-0.5px"
padding: "0px 12px"
textAlign: "left"
color: bodyTextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize bodyText, { width: @width, height: bodyTextHeight }, { x: Align.left, y: headerText.maxY }
return this
# Small flat
smallFlat: (options = {}) ->
@Template = Template.Flat
@props = width: 120, height: 36, scale: 1
# Parameters
options.imageProvider ?= {}
options.textProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: @tintColor })
textProvider = _.defaults(options.textProvider, { tintColor: @tintColor })
image = new Layer
x: Align.left, y: Align.center
size: 20
image: imageProvider.onePieceImage
brightness: 0, contrast: 50, invert: 100
backgroundColor: ""
parent: @
text = new Layer
html: textProvider.label
style:
fontSize: "28px", fontWeight: "500"
lineHeight: "#{@height}px"
letterSpacing: "-0.2px"
textAlign: "left"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { height: @height }, { x: image.maxX + 3, y: Align.center }
if @contentFrame().width > @width
Util.text.autoFontSize text, { width: @width - image.width, height: @height }, { x: image.maxX + 3, y: Align.center }
# Event : Change column alignment
@on "change:#{Events.ColumnAlignment}", ->
if @columnAlignment is ColumnAlignment.Leading
image.x = Align.left
text.x = image.maxX + 3
else if @columnAlignment is ColumnAlignment.Trailing
image.x = Align.right
text.x = image.x - text.width - 3
return this
# Dummy
dummy: (imageUrl = "") ->
@template = Template
@image = imageUrl
return this
# ClockFace
class ClockFace extends Layer
# Constructor
constructor: (options = {}) ->
options.backgroundColor ?= "rgba(255,255,255,.2)"
super options
# Background
@bg = new Layer
name: ".bg"
width: @width, height: @height
backgroundColor: "black"
borderRadius: 12
parent: @
@bg.frame = Utils.frameInset @bg, 10
# Complication
@complication = new Layer
name: ".complication"
width: @width, height: @height
backgroundColor: "black"
parent: @
# Label
@label = new Layer
name: ".label"
html: @name
style:
fontSize: "#{24 * 1/0.7*284/272}px", fontWeight: "400"
lineHeight: "1"
textAlign: "center"
backgroundColor: ""
parent: @
@label.on "change:html", ->
Util.text.autoSize @
@props = x: Align.center(-7), maxY: -13
# Change mode
modeChange: (type = true) ->
if type
@props =
borderRadius: 15
scale: 273 / 285
@complication.props =
borderRadius: 12
scale: 239 / 273
else
@props =
borderRadius: 0
scale: 1
@complication.props =
borderRadius: 0
scale: 1
# Circular
circular: (complications = []) ->
@label.html = @name = "심플"
@clock = new AnalogClock width: @width, height: @height, parent: @complication
for complication, i in complications
if complication
@complication.addChild complication
switch i
when 0
complication.props = x: Align.left, y: Align.top, originX: 0, originY: 0
complication.columnAlignment = exports.Complication.ColumnAlignment.Leading
when 1
complication.props = x: Align.right, y: Align.top, originX: 1, originY: 0
complication.columnAlignment = exports.Complication.ColumnAlignment.Trailing
when 2
complication.props = x: Align.left, y: Align.bottom, originX: 0, originY: 1
complication.columnAlignment = exports.Complication.ColumnAlignment.Leading
when 3
complication.props = x: Align.right, y: Align.bottom, originX: 1, originY: 1
complication.columnAlignment = exports.Complication.ColumnAlignment.Trailing
return this
# Utilitarian
utilitarian: (complications = []) ->
@label.html = @name = "유틸리티"
@clock = new AnalogClock width: @width, height: @height, parent: @complication
for complication, i in complications
if complication
@complication.addChild complication
switch i
when 0
complication.props = x: Align.left, y: Align.top
complication.columnAlignment = exports.Complication.ColumnAlignment.Leading
when 1
complication.props = x: Align.right, y: Align.top
complication.columnAlignment = exports.Complication.ColumnAlignment.Trailing
when 2 then complication.props = x: Align.center, y: Align.bottom
return this
# Modular
modular: (complications = []) ->
@label.html = @name = "모듈"
@clock = new DigitalClock width: @width, height: @height, parent: @complication
for complication, i in complications
if complication
@complication.addChild complication
switch i
when 0 then complication.props = x: Align.left, y: Align.top(38)
when 1 then complication.props = x: Align.left, y: Align.bottom
when 2 then complication.props = x: Align.center, y: Align.bottom
when 3 then complication.props = x: Align.right, y: Align.bottom
when 4 then complication.props = x: Align.center, y: Align.center(19)
return this
# Clock
class Clock extends Layer
# Constructor
constructor: (options = {}) ->
options.backgroundColor ?= ""
super options
# Start time
start: (timer) -> @timer = timer
# Stop time
stop: -> clearInterval @timer if @timer
# Clock : Digital
class DigitalClock extends Clock
# Constructor
constructor: (options = {}) ->
options.name = "DigitalClock"
options.html = Util.date.timeFormatter Util.date.getTime()
options.style =
fontSize: "85px", fontWeight: "300"
lineHeight: "1"
textAlign: "right"
letterSpacing: "-3px"
super options
Util.text.autoSize @
@props = x: Align.right(-12), y: Align.top(43)
# Start time
@start()
start: ->
super
@time = Util.date.getTime()
@html = Util.date.timeFormatter @time = Util.date.getTime()
Utils.delay 60 - @time.secs, =>
@html = Util.date.timeFormatter @time = Util.date.getTime()
@timer = Utils.interval 60, => @html = Util.date.timeFormatter @time = Util.date.getTime()
super @timer
# Clock : Analog
class AnalogClock extends Clock
# Constructor
constructor: (options = {}) ->
super options
@borderRadius = @width/2
# Edge
@edge = new Layer
name: ".edge"
point: Align.center
size: @width
backgroundColor: ""
parent: @
secAngle = 360 / 60
for i in [1..60]
# Hour
if i%%5 is 0
hourBar = new Layer
name: ".edge.hour"
html: i / 5
style:
fontSize: "40px", fontWeight: "400"
lineHeight: "1"
textAlign: "center"
color: "white"
backgroundColor: ""
parent: @edge
Util.text.autoSize hourBar
a = (-90 + (secAngle * i)) * (Math.PI / 180)
r = @edge.width/2 - hourBar.height + 3
hourBar.props =
x: @edge.width/2 - hourBar.width/2 + Math.cos(a) * r
y: @edge.height/2 - hourBar.height/2 + Math.sin(a) * r
# Minute
if i %% 5 is 0
minBar = new Layer
name: ".edge.min"
html: if i < 10 then "0#{i}" else i
style:
fontSize: "13px", fontWeight: "400"
lineHeight: "1"
textAlign: "center"
letterSpacing: "-1px"
color: "white"
backgroundColor: ""
parent: @edge
Util.text.autoSize minBar
a = (-90 + (secAngle * i)) * (Math.PI / 180)
r = @edge.width/2 - minBar.height + 9
r -= 2 if i is 15 or i is 45
minBar.props =
x: @edge.width/2 - minBar.width/2 + Math.cos(a) * r
y: @edge.height/2 - minBar.height/2 + Math.sin(a) * r
# Second
else
secBar = new Layer
name: ".sec"
x: Align.center, y: Align.bottom(-@edge.width/2 + 8)
width: 2, height: 8
backgroundColor: "rgba(255,255,255,.5)"
parent: new Layer name: ".edge.sec.parent", point: Align.center, size: 1, originX: .5, originY: 1, rotation: secAngle * i, backgroundColor: "", parent: @edge
# Arrow : Minute
@min = new Layer
name: ".min"
point: Align.center
size: 12
borderRadius: 7
backgroundColor: "white"
parent: @
@min.bottom = new Layer
name: ".min.bottom"
x: Align.center, y: Align.bottom(-@min.width/2 + 2)
width: 4, height: 20 + 2
borderRadius: 2
backgroundColor: "white"
parent: @min
@min.top = new Layer
name: ".min.top"
x: Align.center, maxY: @min.bottom.minY + 5
width: 10, height: @width/2 - 10 - 20 + 5
borderRadius: 5
backgroundColor: "white"
parent: @min
# Arrow : Hour
@hour = @min.copy()
@hour.parent = @
@hour.children[1].height -= 50
@hour.children[1].maxY = @hour.children[0].minY + 5
@min.sendToBack()
@hour.sendToBack()
# Arrow : Second
@sec = new Layer
name: ".sec"
point: Align.center
size: 8
borderRadius: 7
backgroundColor: "orange"
parent: @
@sec.bar = new Layer
name: ".sec.bar"
x: Align.center, y: Align.bottom(18)
width: 2, height: @width/2 + 22
backgroundColor: @sec.backgroundColor
parent: @sec
@sec.dot = new Layer
name: ".sec.dot"
point: Align.center
size: 2
borderRadius: 2
backgroundColor: "black"
parent: @sec
# Events
animationEnd = -> @rotation = 0 if @rotation is 360
@sec.onAnimationEnd animationEnd
@min.onAnimationEnd animationEnd
@hour.onAnimationEnd animationEnd
# Start time
@start()
update: (animate = true) =>
time = Util.date.getTime()
time.secs = 60 if time.secs is 0
time.mins = 60 if time.mins is 0
time.hours = time.hours - 12 if time.hours > 12
time.hours = 12 if time.hours is 0
secAngle = (360 / 60) * time.secs
minAngle = (360 / 60) * time.mins
minAngle += (360 / 60 / 60) * time.secs unless time.secs is 60
hourAngle = (360 / 12) * time.hours
hourAngle += (360 / 12 / 60) * time.mins unless time.mins is 60
@sec.animateStop()
@min.animateStop()
@hour.animateStop()
if animate
@sec.animate rotation: secAngle, options: { time: .98, curve: "linear" }
@min.animate rotation: minAngle, options: { curve: "linear" }
@hour.animate rotation: hourAngle, options: { curve: "linear" }
else
@sec.rotation = secAngle
@min.rotation = minAngle
@hour.rotation = hourAngle
start: ->
@update false
@timer = Utils.interval 1, @update
super @timer | 30524 | '''
watchOS : ClockFaces
@auther <NAME> (threeword.com)
@since 2016.11.23
'''
class exports.ClockFaces extends Layer
'''
complications:
utilitarian: []
modular: []
circular: []
'''
# Constructor
constructor: (options = {}) ->
options.name ?= "ClockFaces"
options.backgroundColor ?= "black"
super options
options.complications ?= {}
complications = _.defaults(options.complications, { utilitarian: [], modular: [], circular: [] })
# Page
@page = new PageComponent
name: "page"
width: @width, height: @height
scrollVertical: false
backgroundColor: ""
clip: false
parent: @
@page.content.clip = false
@page.states =
change: y: -13, scale: 284 / @height
selected: y: 0, scale: 1
# Clockface : Utilitarian
@utilitarian = new ClockFace(width: @width, height: @height).utilitarian complications.utilitarian
# Clockface : Modular
@modular = new ClockFace(width: @width, height: @height).modular complications.modular
# Clockface : Circular
@circular = new ClockFace(width: @width, height: @height).circular complications.circular
# Add page
@page.addPage @utilitarian
@page.addPage @modular
@page.addPage @circular
# Snap page
@page.snapToPage @modular, false
# Customize
@customize = new Layer
name: "customize"
x: Align.center, y: @page.maxY + 10
width: 157, height: 57
html: "사용자화"
style:
fontSize: "32px", fontWeight: "400"
lineHeight: "57px"
textAlign: "center"
borderRadius: 15
backgroundColor: "#333333"
scale: 1 / 0.7, originY: 0
parent: @page
@customize.sendToBack()
# 시계화면 : 이벤트
@isChangeDone = false
@isChangeMode = false
# Events
for child in @page.content.children
child.onClick => @selected()
# Long-Press(ForceTouch) : Start
@page.onLongPressStart =>
return if @isChangeMode
#
child.modeChange() for child, i in @page.content.children
@page.animate "change"
# Long-Press(ForceTouch) : End
@page.onLongPressEnd =>
return if @isChangeMode
#
@isChangeMode = true
Utils.delay .3, => @isChangeDone = true
# Screen.on Events.EdgeSwipeLeftStart, (event) ->
# print "start : #{event.point.x}"
# Screen.on Events.EdgeSwipeLeft, (event) ->
# # print event
# Screen.on Events.EdgeSwipeLeftEnd, (event) ->
# print "end : #{event.point}"
# Selected
selected: () ->
return unless @isChangeMode
return unless @isChangeDone
#
for child, i in @page.content.children
child.modeChange false
@page.animate "selected"
#
@isChangeMode = false
@isChangeDone = false
# Time start
timeStart: -> page.clock.start() for page in @page.content.children
# Time stop
timeStop: -> page.clock.stop() for page in @page.content.children
# Set clock face
setClockface: (index) ->
return if _.isEmpty(@page.content.children)
return if _.size(@page.content.children) - 1 < index
@page.snapToPage @page.content.children[index]
'''
Complication Images : https://developer.apple.com/watchos/human-interface-guidelines/icons-and-images/
Family:
modularSmall
modularLarge
utilitarianSmall
utilitarianSmallFlat
utilitarianLarge
circularSmall
extraLarge
Template:
tintColor: "색상"
columnAlignment: "leading" or "tailing"
Circular:
SmallSimpleText: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatecircularsmallsimpletext)
textProvider: "문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
SmallRingImage: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatecircularsmallringimage)
imageProvider: "이미지" (https://developer.apple.com/reference/clockkit/clkimageprovider)
ringStyle: "closed" or "open" (https://developer.apple.com/reference/clockkit/clkcomplicationringstyle)
fillFraction: 채우기 비율
Utilitarian:
SmallFlat: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitariansmallflat)
textProvider: "문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
imageProvider: "이미지" (https://developer.apple.com/reference/clockkit/clkimageprovider)
LargeFlat: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitarianlargeflat)
textProvider: "문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
imageProvider: "이미지" (https://developer.apple.com/reference/clockkit/clkimageprovider)
SmallRingImage: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitariansmallringimage)
imageProvider: "이미지" [require] (https://developer.apple.com/reference/clockkit/clkimageprovider)
ringStyle: "closed" or "open" (https://developer.apple.com/reference/clockkit/clkcomplicationringstyle)
fillFraction: 채우기 비율
SmallSquare: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitariansmallsquare)
imageProvider: "이미지" [require] (https://developer.apple.com/reference/clockkit/clkimageprovider)
Modular:
SmallStackText: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatemodularsmallstacktext)
line1TextProvider: "1라인 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
line2TextProvider: "2라인 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
highlightLine2: Boolean
SmallRingImage: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatemodularsmallringimage)
imageProvider: "이미지" [require] (https://developer.apple.com/reference/clockkit/clkimageprovider)
ringStyle: "closed" or "open" (https://developer.apple.com/reference/clockkit/clkcomplicationringstyle)
fillFraction: 채우기 비율
LargeTallBody: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatemodularlargetallbody)
headerTextProvider: "헤더 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
bodyTextProvider: "바디 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
ExtraLarge:
textProvider:
label: 라벨명
tintColor: 틴트색상
imageProvider:
onePieceImage: 첫번째 이미지
twoPieceImageBackground: 두번째 뒷 이미지
twoPieceImageForeground: 두번째 앞 이미지
tintColor: 틴트색상
'''
# Complication
class exports.Complication extends Layer
Events.ColumnAlignment = "columnAlignment"
Events.TintColor = 'tintColor'
Family = {}
Family.ModularSmall = "modularSmall"
Family.ModularLarge = "modularLarge"
Family.UtilitarianSmall = "utilitarianSmall"
Family.UtilitarianSmallFlat = "utilitarianSmallFlat"
Family.UtilitarianLarge = "utilitarianLarge"
Family.CircularSmall = "circularSmall"
Family.ExtraLarge = "extraLarge"
Template = {}
Template.SimpleImage = "simpleImage"
Template.SimpleText = "simpleText"
Template.RingImage = "ringImage"
Template.RingText = "ringText"
Template.StackText = "stackText"
Template.StackImage = "stackImage"
Template.ColumnsText = "columnsText"
Template.Columns = "columns"
Template.StandardBody = "standardBody"
Template.Table = "table"
Template.TallBody = "tallBody"
Template.Flat = "flat"
Template.Square = "square"
RingStyle = {}
RingStyle.Closed = "closed"
RingStyle.Open = "open"
ColumnAlignment = {}
ColumnAlignment.Leading = "leading"
ColumnAlignment.Trailing = "trailing"
this.Family = Family
this.Template = Template
this.RingStyle = RingStyle
this.ColumnAlignment = ColumnAlignment
@define 'columnAlignment',
get: () -> @_columnAlignment
set: (value) -> @emit("change:#{Events.ColumnAlignment}", @_columnAlignment = value)
@define 'tintColor',
get: () -> @_tintColor
set: (value) -> @emit("change:#{Events.TintColor}", @_tintColor = value)
# Constructor
constructor: (options = {}) ->
options.backgroundColor ?= ""
super options
options.family ?= Family.ModularSmall
options.template ?= Template.SimpleText
@family = options.family
@template = options.template
# ----------------------------------------------------------------------
# Family
# ----------------------------------------------------------------------
# Modular : Small
modularSmall: () ->
@family = Family.ModularSmall
@size = 100
@tintColor = "white"
return this
# Modular : Large
modularLarge: () ->
@family = Family.ModularLarge
@props = width: 312, height: 126
@tintColor = "white"
return this
# Utilitarian : Small
utilitarianSmall: () ->
@family = Family.UtilitarianSmall
@size = 51
@tintColor = "white"
return this
# Utilitarian : Small flat
utilitarianSmallFlat: (options = {}) ->
@family = Family.UtilitarianSmallFlat
@props = width: 120, height: 36
@tintColor = "white"
# Parameters
options.imageProvider ?= {}
options.textProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: "white" })
textProvider = _.defaults(options.textProvider, { tintColor: "white" })
image = new Layer
x: Align.left, y: Align.center
size: 20
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
text = new Layer
html: textProvider.label
style:
fontSize: "28px", fontWeight: "400"
lineHeight: "#{@height}px"
letterSpacing: "-0.2px"
textAlign: "left"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { height: @height }, { x: image.maxX + 3, y: Align.center }
if @contentFrame().width > @width
Util.text.autoFontSize text, { width: @width - image.width, height: @height }, { x: image.maxX + 3, y: Align.center }
# Event : Change column alignment
@on "change:#{Events.ColumnAlignment}", ->
if @columnAlignment is ColumnAlignment.Leading
image.props = x: Align.left, midY: text.midY
text.x = image.maxX + 3
else if @columnAlignment is ColumnAlignment.Trailing
image.props = x: Align.right, midY: text.midY
text.x = image.x - text.width - 3
return this
# Utilitarian : Large
utilitarianLarge: (options = {}) ->
@family = Family.UtilitarianLarge
@props = width: 312, height: 36
@tintColor = "white"
# Parameters
options.imageProvider ?= {}
options.textProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: "white" })
textProvider = _.defaults(options.textProvider, { tintColor: "white" })
image = new Layer
x: Align.left, y: Align.bottom
size: 20
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
text = new Layer
html: textProvider.label
style:
fontSize: "28px", fontWeight: "400"
lineHeight: "1"
letterSpacing: "-0.2px"
textAlign: "left"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { height: @height }, { x: image.maxX + 3, y: Align.bottom }
if @contentFrame().width > @width
Util.text.autoFontSize text, { width: @width - image.width, height: @height }, { x: image.maxX + 3, y: Align.bottom }
image.props = x: @midX - @contentFrame().width / 2, midY: text.midY
text.x = image.maxX + 3
return this
# Circular : Small
circularSmall: () ->
@family = Family.CircularSmall
@size = 68
@scale = 51/68
@tintColor = "#b3b3b3"
return this
# ExtraLarge
extraLarge: () ->
@family = Family.ExtraLarge
@tintColor = "white"
return this
# ----------------------------------------------------------------------
# Template
# ----------------------------------------------------------------------
# Simple text
simpleText: (options = {}) ->
@template = Template.SimpleText
# Parameters
options.textProvider ?= {}
textProvider = _.defaults(options.textProvider, { tintColor: @tintColor })
height = @height
text = new Layer
html: textProvider.label
style:
fontSize: "67px", fontWeight: "400"
lineHeight: "#{height}px"
letterSpacing: "-0.5px"
textAlign: "center"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { width: @width, height: height }, { x: Align.center, y: Align.center }
return this
# Stack text
stackText: (options = {}) ->
@template = Template.StackText
# Parameters
options.line1TextProvider ?= {}
options.line2TextProvider ?= {}
options.highlightLine2 ?= false
line1TextProvider = _.defaults(options.line1TextProvider, { tintColor: @tintColor })
line2TextProvider = _.defaults(options.line2TextProvider, { tintColor: @tintColor })
highlightLine2 = options.highlightLine2
line1TextHeight = 30
line1Text = new Layer
html: line1TextProvider.label
style:
fontSize: "67px", fontWeight: "500"
lineHeight: "1"
letterSpacing: "-0.4px"
padding: "0px 8px"
textAlign: "center"
color: line1TextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize line1Text, { width: @width, height: line1TextHeight }, { x: Align.center, y: Align.bottom(-55) } #Align.center( -@height * 1/3 * 1/2 )
line2TextHeight = 35
line2Text = new Layer
html: line2TextProvider.label
style:
fontSize: "67px", fontWeight: "500"
lineHeight: "1"
letterSpacing: "-0.4px"
padding: "0px 3.5px"
textAlign: "center"
color: line2TextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize line2Text, { width: @width, height: line2TextHeight }, { x: Align.center, y: Align.bottom(-18) } #line1Text.maxY - 10
return this
# Simple image
simpleImage: (options = {}) ->
@template = Template.SimpleImage
# Parameters
options.imageProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: @tintColor })
size = 100
switch @family
when Family.ModularSmall then size = 58 * 1.6
when Family.UtilitarianSmall then size = 44
when Family.CircularSmall then size = 36 * (1/@scale)
image = new Layer
point: Align.center
size: size
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
if @family is Family.CircularSmall
image.brightness = 0
image.contrast = 50
image.invert = 100
return this
# Square
square: (options = {}) ->
@simpleImage options
@template = Template.Square
return this
# Ring image
ringImage: (options = {}) ->
@template = Template.RingImage
# Parameters
options.imageProvider ?= {}
options.fillFraction ?= 0
options.ringStyle ?= RingStyle.Closed
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: @tintColor })
fillFraction = options.fillFraction
ringStyle = options.ringStyle
imageSize = 38; ringSize = 58; ringWidth = 5
switch @family
when Family.ModularSmall
imageSize = 38
ringSize = 58
ringWidth = 5
when Family.UtilitarianSmall
imageSize = 28
ringSize = 47
ringWidth = 4
when Family.CircularSmall
imageSize = 44
ringSize = 64
ringWidth = 6
when Family.ExtraLarge
imageSize = 133
image = new Layer
point: Align.center
size: imageSize
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
if @family is Family.CircularSmall
image.brightness = 0
image.contrast = 50
image.invert = 100
ring = new CircularProgressComponent
point: Align.center
size: ringSize
parent: @
ringColor = new Color(imageProvider.tintColor)
ring.strokeWidth = ringWidth
ring.progressColor = ringColor
ring.railsColor = ringColor.alpha(.3)
ring.setProgress fillFraction, false
return this
# Tall body
tallBody: (options = {})->
@template = Template.TallBody
# Parameters
options.headerTextProvider ?= {}
options.bodyTextProvider ?= {}
headerTextProvider = _.defaults(options.headerTextProvider, { tintColor: @tintColor })
bodyTextProvider = _.defaults(options.bodyTextProvider, { tintColor: @tintColor })
headerTextHeight = 46
headerText = new Layer
html: headerTextProvider.label
style:
fontSize: "33px", fontWeight: "400"
lineHeight: "#{headerTextHeight}px"
letterSpacing: "0.1px"
padding: "0px 12px"
textAlign: "left"
color: headerTextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize headerText, { width: @width, height: headerTextHeight }, { x: Align.left, y: Align.top }
bodyTextHeight = 80
bodyText = new Layer
html: bodyTextProvider.label
style:
fontSize: "80px", fontWeight: "400"
lineHeight: "#{bodyTextHeight}px"
letterSpacing: "-0.5px"
padding: "0px 12px"
textAlign: "left"
color: bodyTextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize bodyText, { width: @width, height: bodyTextHeight }, { x: Align.left, y: headerText.maxY }
return this
# Small flat
smallFlat: (options = {}) ->
@Template = Template.Flat
@props = width: 120, height: 36, scale: 1
# Parameters
options.imageProvider ?= {}
options.textProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: @tintColor })
textProvider = _.defaults(options.textProvider, { tintColor: @tintColor })
image = new Layer
x: Align.left, y: Align.center
size: 20
image: imageProvider.onePieceImage
brightness: 0, contrast: 50, invert: 100
backgroundColor: ""
parent: @
text = new Layer
html: textProvider.label
style:
fontSize: "28px", fontWeight: "500"
lineHeight: "#{@height}px"
letterSpacing: "-0.2px"
textAlign: "left"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { height: @height }, { x: image.maxX + 3, y: Align.center }
if @contentFrame().width > @width
Util.text.autoFontSize text, { width: @width - image.width, height: @height }, { x: image.maxX + 3, y: Align.center }
# Event : Change column alignment
@on "change:#{Events.ColumnAlignment}", ->
if @columnAlignment is ColumnAlignment.Leading
image.x = Align.left
text.x = image.maxX + 3
else if @columnAlignment is ColumnAlignment.Trailing
image.x = Align.right
text.x = image.x - text.width - 3
return this
# Dummy
dummy: (imageUrl = "") ->
@template = Template
@image = imageUrl
return this
# ClockFace
class ClockFace extends Layer
# Constructor
constructor: (options = {}) ->
options.backgroundColor ?= "rgba(255,255,255,.2)"
super options
# Background
@bg = new Layer
name: ".bg"
width: @width, height: @height
backgroundColor: "black"
borderRadius: 12
parent: @
@bg.frame = Utils.frameInset @bg, 10
# Complication
@complication = new Layer
name: ".complication"
width: @width, height: @height
backgroundColor: "black"
parent: @
# Label
@label = new Layer
name: ".label"
html: @name
style:
fontSize: "#{24 * 1/0.7*284/272}px", fontWeight: "400"
lineHeight: "1"
textAlign: "center"
backgroundColor: ""
parent: @
@label.on "change:html", ->
Util.text.autoSize @
@props = x: Align.center(-7), maxY: -13
# Change mode
modeChange: (type = true) ->
if type
@props =
borderRadius: 15
scale: 273 / 285
@complication.props =
borderRadius: 12
scale: 239 / 273
else
@props =
borderRadius: 0
scale: 1
@complication.props =
borderRadius: 0
scale: 1
# Circular
circular: (complications = []) ->
@label.html = @name = "<NAME>"
@clock = new AnalogClock width: @width, height: @height, parent: @complication
for complication, i in complications
if complication
@complication.addChild complication
switch i
when 0
complication.props = x: Align.left, y: Align.top, originX: 0, originY: 0
complication.columnAlignment = exports.Complication.ColumnAlignment.Leading
when 1
complication.props = x: Align.right, y: Align.top, originX: 1, originY: 0
complication.columnAlignment = exports.Complication.ColumnAlignment.Trailing
when 2
complication.props = x: Align.left, y: Align.bottom, originX: 0, originY: 1
complication.columnAlignment = exports.Complication.ColumnAlignment.Leading
when 3
complication.props = x: Align.right, y: Align.bottom, originX: 1, originY: 1
complication.columnAlignment = exports.Complication.ColumnAlignment.Trailing
return this
# Utilitarian
utilitarian: (complications = []) ->
@label.html = @name = "<NAME>"
@clock = new AnalogClock width: @width, height: @height, parent: @complication
for complication, i in complications
if complication
@complication.addChild complication
switch i
when 0
complication.props = x: Align.left, y: Align.top
complication.columnAlignment = exports.Complication.ColumnAlignment.Leading
when 1
complication.props = x: Align.right, y: Align.top
complication.columnAlignment = exports.Complication.ColumnAlignment.Trailing
when 2 then complication.props = x: Align.center, y: Align.bottom
return this
# Modular
modular: (complications = []) ->
@label.html = @name = "모듈"
@clock = new DigitalClock width: @width, height: @height, parent: @complication
for complication, i in complications
if complication
@complication.addChild complication
switch i
when 0 then complication.props = x: Align.left, y: Align.top(38)
when 1 then complication.props = x: Align.left, y: Align.bottom
when 2 then complication.props = x: Align.center, y: Align.bottom
when 3 then complication.props = x: Align.right, y: Align.bottom
when 4 then complication.props = x: Align.center, y: Align.center(19)
return this
# Clock
class Clock extends Layer
# Constructor
constructor: (options = {}) ->
options.backgroundColor ?= ""
super options
# Start time
start: (timer) -> @timer = timer
# Stop time
stop: -> clearInterval @timer if @timer
# Clock : Digital
class DigitalClock extends Clock
# Constructor
constructor: (options = {}) ->
options.name = "DigitalClock"
options.html = Util.date.timeFormatter Util.date.getTime()
options.style =
fontSize: "85px", fontWeight: "300"
lineHeight: "1"
textAlign: "right"
letterSpacing: "-3px"
super options
Util.text.autoSize @
@props = x: Align.right(-12), y: Align.top(43)
# Start time
@start()
start: ->
super
@time = Util.date.getTime()
@html = Util.date.timeFormatter @time = Util.date.getTime()
Utils.delay 60 - @time.secs, =>
@html = Util.date.timeFormatter @time = Util.date.getTime()
@timer = Utils.interval 60, => @html = Util.date.timeFormatter @time = Util.date.getTime()
super @timer
# Clock : Analog
class AnalogClock extends Clock
# Constructor
constructor: (options = {}) ->
super options
@borderRadius = @width/2
# Edge
@edge = new Layer
name: ".edge"
point: Align.center
size: @width
backgroundColor: ""
parent: @
secAngle = 360 / 60
for i in [1..60]
# Hour
if i%%5 is 0
hourBar = new Layer
name: ".edge.hour"
html: i / 5
style:
fontSize: "40px", fontWeight: "400"
lineHeight: "1"
textAlign: "center"
color: "white"
backgroundColor: ""
parent: @edge
Util.text.autoSize hourBar
a = (-90 + (secAngle * i)) * (Math.PI / 180)
r = @edge.width/2 - hourBar.height + 3
hourBar.props =
x: @edge.width/2 - hourBar.width/2 + Math.cos(a) * r
y: @edge.height/2 - hourBar.height/2 + Math.sin(a) * r
# Minute
if i %% 5 is 0
minBar = new Layer
name: ".edge.min"
html: if i < 10 then "0#{i}" else i
style:
fontSize: "13px", fontWeight: "400"
lineHeight: "1"
textAlign: "center"
letterSpacing: "-1px"
color: "white"
backgroundColor: ""
parent: @edge
Util.text.autoSize minBar
a = (-90 + (secAngle * i)) * (Math.PI / 180)
r = @edge.width/2 - minBar.height + 9
r -= 2 if i is 15 or i is 45
minBar.props =
x: @edge.width/2 - minBar.width/2 + Math.cos(a) * r
y: @edge.height/2 - minBar.height/2 + Math.sin(a) * r
# Second
else
secBar = new Layer
name: ".sec"
x: Align.center, y: Align.bottom(-@edge.width/2 + 8)
width: 2, height: 8
backgroundColor: "rgba(255,255,255,.5)"
parent: new Layer name: ".edge.sec.parent", point: Align.center, size: 1, originX: .5, originY: 1, rotation: secAngle * i, backgroundColor: "", parent: @edge
# Arrow : Minute
@min = new Layer
name: ".min"
point: Align.center
size: 12
borderRadius: 7
backgroundColor: "white"
parent: @
@min.bottom = new Layer
name: ".min.bottom"
x: Align.center, y: Align.bottom(-@min.width/2 + 2)
width: 4, height: 20 + 2
borderRadius: 2
backgroundColor: "white"
parent: @min
@min.top = new Layer
name: ".min.top"
x: Align.center, maxY: @min.bottom.minY + 5
width: 10, height: @width/2 - 10 - 20 + 5
borderRadius: 5
backgroundColor: "white"
parent: @min
# Arrow : Hour
@hour = @min.copy()
@hour.parent = @
@hour.children[1].height -= 50
@hour.children[1].maxY = @hour.children[0].minY + 5
@min.sendToBack()
@hour.sendToBack()
# Arrow : Second
@sec = new Layer
name: ".sec"
point: Align.center
size: 8
borderRadius: 7
backgroundColor: "orange"
parent: @
@sec.bar = new Layer
name: ".sec.bar"
x: Align.center, y: Align.bottom(18)
width: 2, height: @width/2 + 22
backgroundColor: @sec.backgroundColor
parent: @sec
@sec.dot = new Layer
name: ".sec.dot"
point: Align.center
size: 2
borderRadius: 2
backgroundColor: "black"
parent: @sec
# Events
animationEnd = -> @rotation = 0 if @rotation is 360
@sec.onAnimationEnd animationEnd
@min.onAnimationEnd animationEnd
@hour.onAnimationEnd animationEnd
# Start time
@start()
update: (animate = true) =>
time = Util.date.getTime()
time.secs = 60 if time.secs is 0
time.mins = 60 if time.mins is 0
time.hours = time.hours - 12 if time.hours > 12
time.hours = 12 if time.hours is 0
secAngle = (360 / 60) * time.secs
minAngle = (360 / 60) * time.mins
minAngle += (360 / 60 / 60) * time.secs unless time.secs is 60
hourAngle = (360 / 12) * time.hours
hourAngle += (360 / 12 / 60) * time.mins unless time.mins is 60
@sec.animateStop()
@min.animateStop()
@hour.animateStop()
if animate
@sec.animate rotation: secAngle, options: { time: .98, curve: "linear" }
@min.animate rotation: minAngle, options: { curve: "linear" }
@hour.animate rotation: hourAngle, options: { curve: "linear" }
else
@sec.rotation = secAngle
@min.rotation = minAngle
@hour.rotation = hourAngle
start: ->
@update false
@timer = Utils.interval 1, @update
super @timer | true | '''
watchOS : ClockFaces
@auther PI:NAME:<NAME>END_PI (threeword.com)
@since 2016.11.23
'''
class exports.ClockFaces extends Layer
'''
complications:
utilitarian: []
modular: []
circular: []
'''
# Constructor
constructor: (options = {}) ->
options.name ?= "ClockFaces"
options.backgroundColor ?= "black"
super options
options.complications ?= {}
complications = _.defaults(options.complications, { utilitarian: [], modular: [], circular: [] })
# Page
@page = new PageComponent
name: "page"
width: @width, height: @height
scrollVertical: false
backgroundColor: ""
clip: false
parent: @
@page.content.clip = false
@page.states =
change: y: -13, scale: 284 / @height
selected: y: 0, scale: 1
# Clockface : Utilitarian
@utilitarian = new ClockFace(width: @width, height: @height).utilitarian complications.utilitarian
# Clockface : Modular
@modular = new ClockFace(width: @width, height: @height).modular complications.modular
# Clockface : Circular
@circular = new ClockFace(width: @width, height: @height).circular complications.circular
# Add page
@page.addPage @utilitarian
@page.addPage @modular
@page.addPage @circular
# Snap page
@page.snapToPage @modular, false
# Customize
@customize = new Layer
name: "customize"
x: Align.center, y: @page.maxY + 10
width: 157, height: 57
html: "사용자화"
style:
fontSize: "32px", fontWeight: "400"
lineHeight: "57px"
textAlign: "center"
borderRadius: 15
backgroundColor: "#333333"
scale: 1 / 0.7, originY: 0
parent: @page
@customize.sendToBack()
# 시계화면 : 이벤트
@isChangeDone = false
@isChangeMode = false
# Events
for child in @page.content.children
child.onClick => @selected()
# Long-Press(ForceTouch) : Start
@page.onLongPressStart =>
return if @isChangeMode
#
child.modeChange() for child, i in @page.content.children
@page.animate "change"
# Long-Press(ForceTouch) : End
@page.onLongPressEnd =>
return if @isChangeMode
#
@isChangeMode = true
Utils.delay .3, => @isChangeDone = true
# Screen.on Events.EdgeSwipeLeftStart, (event) ->
# print "start : #{event.point.x}"
# Screen.on Events.EdgeSwipeLeft, (event) ->
# # print event
# Screen.on Events.EdgeSwipeLeftEnd, (event) ->
# print "end : #{event.point}"
# Selected
selected: () ->
return unless @isChangeMode
return unless @isChangeDone
#
for child, i in @page.content.children
child.modeChange false
@page.animate "selected"
#
@isChangeMode = false
@isChangeDone = false
# Time start
timeStart: -> page.clock.start() for page in @page.content.children
# Time stop
timeStop: -> page.clock.stop() for page in @page.content.children
# Set clock face
setClockface: (index) ->
return if _.isEmpty(@page.content.children)
return if _.size(@page.content.children) - 1 < index
@page.snapToPage @page.content.children[index]
'''
Complication Images : https://developer.apple.com/watchos/human-interface-guidelines/icons-and-images/
Family:
modularSmall
modularLarge
utilitarianSmall
utilitarianSmallFlat
utilitarianLarge
circularSmall
extraLarge
Template:
tintColor: "색상"
columnAlignment: "leading" or "tailing"
Circular:
SmallSimpleText: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatecircularsmallsimpletext)
textProvider: "문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
SmallRingImage: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatecircularsmallringimage)
imageProvider: "이미지" (https://developer.apple.com/reference/clockkit/clkimageprovider)
ringStyle: "closed" or "open" (https://developer.apple.com/reference/clockkit/clkcomplicationringstyle)
fillFraction: 채우기 비율
Utilitarian:
SmallFlat: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitariansmallflat)
textProvider: "문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
imageProvider: "이미지" (https://developer.apple.com/reference/clockkit/clkimageprovider)
LargeFlat: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitarianlargeflat)
textProvider: "문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
imageProvider: "이미지" (https://developer.apple.com/reference/clockkit/clkimageprovider)
SmallRingImage: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitariansmallringimage)
imageProvider: "이미지" [require] (https://developer.apple.com/reference/clockkit/clkimageprovider)
ringStyle: "closed" or "open" (https://developer.apple.com/reference/clockkit/clkcomplicationringstyle)
fillFraction: 채우기 비율
SmallSquare: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplateutilitariansmallsquare)
imageProvider: "이미지" [require] (https://developer.apple.com/reference/clockkit/clkimageprovider)
Modular:
SmallStackText: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatemodularsmallstacktext)
line1TextProvider: "1라인 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
line2TextProvider: "2라인 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
highlightLine2: Boolean
SmallRingImage: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatemodularsmallringimage)
imageProvider: "이미지" [require] (https://developer.apple.com/reference/clockkit/clkimageprovider)
ringStyle: "closed" or "open" (https://developer.apple.com/reference/clockkit/clkcomplicationringstyle)
fillFraction: 채우기 비율
LargeTallBody: (https://developer.apple.com/reference/clockkit/clkcomplicationtemplatemodularlargetallbody)
headerTextProvider: "헤더 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
bodyTextProvider: "바디 문자열" (https://developer.apple.com/reference/clockkit/clktextprovider)
ExtraLarge:
textProvider:
label: 라벨명
tintColor: 틴트색상
imageProvider:
onePieceImage: 첫번째 이미지
twoPieceImageBackground: 두번째 뒷 이미지
twoPieceImageForeground: 두번째 앞 이미지
tintColor: 틴트색상
'''
# Complication
class exports.Complication extends Layer
Events.ColumnAlignment = "columnAlignment"
Events.TintColor = 'tintColor'
Family = {}
Family.ModularSmall = "modularSmall"
Family.ModularLarge = "modularLarge"
Family.UtilitarianSmall = "utilitarianSmall"
Family.UtilitarianSmallFlat = "utilitarianSmallFlat"
Family.UtilitarianLarge = "utilitarianLarge"
Family.CircularSmall = "circularSmall"
Family.ExtraLarge = "extraLarge"
Template = {}
Template.SimpleImage = "simpleImage"
Template.SimpleText = "simpleText"
Template.RingImage = "ringImage"
Template.RingText = "ringText"
Template.StackText = "stackText"
Template.StackImage = "stackImage"
Template.ColumnsText = "columnsText"
Template.Columns = "columns"
Template.StandardBody = "standardBody"
Template.Table = "table"
Template.TallBody = "tallBody"
Template.Flat = "flat"
Template.Square = "square"
RingStyle = {}
RingStyle.Closed = "closed"
RingStyle.Open = "open"
ColumnAlignment = {}
ColumnAlignment.Leading = "leading"
ColumnAlignment.Trailing = "trailing"
this.Family = Family
this.Template = Template
this.RingStyle = RingStyle
this.ColumnAlignment = ColumnAlignment
@define 'columnAlignment',
get: () -> @_columnAlignment
set: (value) -> @emit("change:#{Events.ColumnAlignment}", @_columnAlignment = value)
@define 'tintColor',
get: () -> @_tintColor
set: (value) -> @emit("change:#{Events.TintColor}", @_tintColor = value)
# Constructor
constructor: (options = {}) ->
options.backgroundColor ?= ""
super options
options.family ?= Family.ModularSmall
options.template ?= Template.SimpleText
@family = options.family
@template = options.template
# ----------------------------------------------------------------------
# Family
# ----------------------------------------------------------------------
# Modular : Small
modularSmall: () ->
@family = Family.ModularSmall
@size = 100
@tintColor = "white"
return this
# Modular : Large
modularLarge: () ->
@family = Family.ModularLarge
@props = width: 312, height: 126
@tintColor = "white"
return this
# Utilitarian : Small
utilitarianSmall: () ->
@family = Family.UtilitarianSmall
@size = 51
@tintColor = "white"
return this
# Utilitarian : Small flat
utilitarianSmallFlat: (options = {}) ->
@family = Family.UtilitarianSmallFlat
@props = width: 120, height: 36
@tintColor = "white"
# Parameters
options.imageProvider ?= {}
options.textProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: "white" })
textProvider = _.defaults(options.textProvider, { tintColor: "white" })
image = new Layer
x: Align.left, y: Align.center
size: 20
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
text = new Layer
html: textProvider.label
style:
fontSize: "28px", fontWeight: "400"
lineHeight: "#{@height}px"
letterSpacing: "-0.2px"
textAlign: "left"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { height: @height }, { x: image.maxX + 3, y: Align.center }
if @contentFrame().width > @width
Util.text.autoFontSize text, { width: @width - image.width, height: @height }, { x: image.maxX + 3, y: Align.center }
# Event : Change column alignment
@on "change:#{Events.ColumnAlignment}", ->
if @columnAlignment is ColumnAlignment.Leading
image.props = x: Align.left, midY: text.midY
text.x = image.maxX + 3
else if @columnAlignment is ColumnAlignment.Trailing
image.props = x: Align.right, midY: text.midY
text.x = image.x - text.width - 3
return this
# Utilitarian : Large
utilitarianLarge: (options = {}) ->
@family = Family.UtilitarianLarge
@props = width: 312, height: 36
@tintColor = "white"
# Parameters
options.imageProvider ?= {}
options.textProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: "white" })
textProvider = _.defaults(options.textProvider, { tintColor: "white" })
image = new Layer
x: Align.left, y: Align.bottom
size: 20
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
text = new Layer
html: textProvider.label
style:
fontSize: "28px", fontWeight: "400"
lineHeight: "1"
letterSpacing: "-0.2px"
textAlign: "left"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { height: @height }, { x: image.maxX + 3, y: Align.bottom }
if @contentFrame().width > @width
Util.text.autoFontSize text, { width: @width - image.width, height: @height }, { x: image.maxX + 3, y: Align.bottom }
image.props = x: @midX - @contentFrame().width / 2, midY: text.midY
text.x = image.maxX + 3
return this
# Circular : Small
circularSmall: () ->
@family = Family.CircularSmall
@size = 68
@scale = 51/68
@tintColor = "#b3b3b3"
return this
# ExtraLarge
extraLarge: () ->
@family = Family.ExtraLarge
@tintColor = "white"
return this
# ----------------------------------------------------------------------
# Template
# ----------------------------------------------------------------------
# Simple text
simpleText: (options = {}) ->
@template = Template.SimpleText
# Parameters
options.textProvider ?= {}
textProvider = _.defaults(options.textProvider, { tintColor: @tintColor })
height = @height
text = new Layer
html: textProvider.label
style:
fontSize: "67px", fontWeight: "400"
lineHeight: "#{height}px"
letterSpacing: "-0.5px"
textAlign: "center"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { width: @width, height: height }, { x: Align.center, y: Align.center }
return this
# Stack text
stackText: (options = {}) ->
@template = Template.StackText
# Parameters
options.line1TextProvider ?= {}
options.line2TextProvider ?= {}
options.highlightLine2 ?= false
line1TextProvider = _.defaults(options.line1TextProvider, { tintColor: @tintColor })
line2TextProvider = _.defaults(options.line2TextProvider, { tintColor: @tintColor })
highlightLine2 = options.highlightLine2
line1TextHeight = 30
line1Text = new Layer
html: line1TextProvider.label
style:
fontSize: "67px", fontWeight: "500"
lineHeight: "1"
letterSpacing: "-0.4px"
padding: "0px 8px"
textAlign: "center"
color: line1TextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize line1Text, { width: @width, height: line1TextHeight }, { x: Align.center, y: Align.bottom(-55) } #Align.center( -@height * 1/3 * 1/2 )
line2TextHeight = 35
line2Text = new Layer
html: line2TextProvider.label
style:
fontSize: "67px", fontWeight: "500"
lineHeight: "1"
letterSpacing: "-0.4px"
padding: "0px 3.5px"
textAlign: "center"
color: line2TextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize line2Text, { width: @width, height: line2TextHeight }, { x: Align.center, y: Align.bottom(-18) } #line1Text.maxY - 10
return this
# Simple image
simpleImage: (options = {}) ->
@template = Template.SimpleImage
# Parameters
options.imageProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: @tintColor })
size = 100
switch @family
when Family.ModularSmall then size = 58 * 1.6
when Family.UtilitarianSmall then size = 44
when Family.CircularSmall then size = 36 * (1/@scale)
image = new Layer
point: Align.center
size: size
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
if @family is Family.CircularSmall
image.brightness = 0
image.contrast = 50
image.invert = 100
return this
# Square
square: (options = {}) ->
@simpleImage options
@template = Template.Square
return this
# Ring image
ringImage: (options = {}) ->
@template = Template.RingImage
# Parameters
options.imageProvider ?= {}
options.fillFraction ?= 0
options.ringStyle ?= RingStyle.Closed
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: @tintColor })
fillFraction = options.fillFraction
ringStyle = options.ringStyle
imageSize = 38; ringSize = 58; ringWidth = 5
switch @family
when Family.ModularSmall
imageSize = 38
ringSize = 58
ringWidth = 5
when Family.UtilitarianSmall
imageSize = 28
ringSize = 47
ringWidth = 4
when Family.CircularSmall
imageSize = 44
ringSize = 64
ringWidth = 6
when Family.ExtraLarge
imageSize = 133
image = new Layer
point: Align.center
size: imageSize
image: imageProvider.onePieceImage
backgroundColor: ""
parent: @
if @family is Family.CircularSmall
image.brightness = 0
image.contrast = 50
image.invert = 100
ring = new CircularProgressComponent
point: Align.center
size: ringSize
parent: @
ringColor = new Color(imageProvider.tintColor)
ring.strokeWidth = ringWidth
ring.progressColor = ringColor
ring.railsColor = ringColor.alpha(.3)
ring.setProgress fillFraction, false
return this
# Tall body
tallBody: (options = {})->
@template = Template.TallBody
# Parameters
options.headerTextProvider ?= {}
options.bodyTextProvider ?= {}
headerTextProvider = _.defaults(options.headerTextProvider, { tintColor: @tintColor })
bodyTextProvider = _.defaults(options.bodyTextProvider, { tintColor: @tintColor })
headerTextHeight = 46
headerText = new Layer
html: headerTextProvider.label
style:
fontSize: "33px", fontWeight: "400"
lineHeight: "#{headerTextHeight}px"
letterSpacing: "0.1px"
padding: "0px 12px"
textAlign: "left"
color: headerTextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize headerText, { width: @width, height: headerTextHeight }, { x: Align.left, y: Align.top }
bodyTextHeight = 80
bodyText = new Layer
html: bodyTextProvider.label
style:
fontSize: "80px", fontWeight: "400"
lineHeight: "#{bodyTextHeight}px"
letterSpacing: "-0.5px"
padding: "0px 12px"
textAlign: "left"
color: bodyTextProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize bodyText, { width: @width, height: bodyTextHeight }, { x: Align.left, y: headerText.maxY }
return this
# Small flat
smallFlat: (options = {}) ->
@Template = Template.Flat
@props = width: 120, height: 36, scale: 1
# Parameters
options.imageProvider ?= {}
options.textProvider ?= {}
imageProvider = _.defaults(options.imageProvider, { twoPieceImageBackground: "", twoPieceImageForeground: "", tintColor: @tintColor })
textProvider = _.defaults(options.textProvider, { tintColor: @tintColor })
image = new Layer
x: Align.left, y: Align.center
size: 20
image: imageProvider.onePieceImage
brightness: 0, contrast: 50, invert: 100
backgroundColor: ""
parent: @
text = new Layer
html: textProvider.label
style:
fontSize: "28px", fontWeight: "500"
lineHeight: "#{@height}px"
letterSpacing: "-0.2px"
textAlign: "left"
color: textProvider.tintColor
backgroundColor: ""
parent: @
Util.text.autoFontSize text, { height: @height }, { x: image.maxX + 3, y: Align.center }
if @contentFrame().width > @width
Util.text.autoFontSize text, { width: @width - image.width, height: @height }, { x: image.maxX + 3, y: Align.center }
# Event : Change column alignment
@on "change:#{Events.ColumnAlignment}", ->
if @columnAlignment is ColumnAlignment.Leading
image.x = Align.left
text.x = image.maxX + 3
else if @columnAlignment is ColumnAlignment.Trailing
image.x = Align.right
text.x = image.x - text.width - 3
return this
# Dummy
dummy: (imageUrl = "") ->
@template = Template
@image = imageUrl
return this
# ClockFace
class ClockFace extends Layer
# Constructor
constructor: (options = {}) ->
options.backgroundColor ?= "rgba(255,255,255,.2)"
super options
# Background
@bg = new Layer
name: ".bg"
width: @width, height: @height
backgroundColor: "black"
borderRadius: 12
parent: @
@bg.frame = Utils.frameInset @bg, 10
# Complication
@complication = new Layer
name: ".complication"
width: @width, height: @height
backgroundColor: "black"
parent: @
# Label
@label = new Layer
name: ".label"
html: @name
style:
fontSize: "#{24 * 1/0.7*284/272}px", fontWeight: "400"
lineHeight: "1"
textAlign: "center"
backgroundColor: ""
parent: @
@label.on "change:html", ->
Util.text.autoSize @
@props = x: Align.center(-7), maxY: -13
# Change mode
modeChange: (type = true) ->
if type
@props =
borderRadius: 15
scale: 273 / 285
@complication.props =
borderRadius: 12
scale: 239 / 273
else
@props =
borderRadius: 0
scale: 1
@complication.props =
borderRadius: 0
scale: 1
# Circular
circular: (complications = []) ->
@label.html = @name = "PI:NAME:<NAME>END_PI"
@clock = new AnalogClock width: @width, height: @height, parent: @complication
for complication, i in complications
if complication
@complication.addChild complication
switch i
when 0
complication.props = x: Align.left, y: Align.top, originX: 0, originY: 0
complication.columnAlignment = exports.Complication.ColumnAlignment.Leading
when 1
complication.props = x: Align.right, y: Align.top, originX: 1, originY: 0
complication.columnAlignment = exports.Complication.ColumnAlignment.Trailing
when 2
complication.props = x: Align.left, y: Align.bottom, originX: 0, originY: 1
complication.columnAlignment = exports.Complication.ColumnAlignment.Leading
when 3
complication.props = x: Align.right, y: Align.bottom, originX: 1, originY: 1
complication.columnAlignment = exports.Complication.ColumnAlignment.Trailing
return this
# Utilitarian
utilitarian: (complications = []) ->
@label.html = @name = "PI:NAME:<NAME>END_PI"
@clock = new AnalogClock width: @width, height: @height, parent: @complication
for complication, i in complications
if complication
@complication.addChild complication
switch i
when 0
complication.props = x: Align.left, y: Align.top
complication.columnAlignment = exports.Complication.ColumnAlignment.Leading
when 1
complication.props = x: Align.right, y: Align.top
complication.columnAlignment = exports.Complication.ColumnAlignment.Trailing
when 2 then complication.props = x: Align.center, y: Align.bottom
return this
# Modular
modular: (complications = []) ->
@label.html = @name = "모듈"
@clock = new DigitalClock width: @width, height: @height, parent: @complication
for complication, i in complications
if complication
@complication.addChild complication
switch i
when 0 then complication.props = x: Align.left, y: Align.top(38)
when 1 then complication.props = x: Align.left, y: Align.bottom
when 2 then complication.props = x: Align.center, y: Align.bottom
when 3 then complication.props = x: Align.right, y: Align.bottom
when 4 then complication.props = x: Align.center, y: Align.center(19)
return this
# Clock
class Clock extends Layer
# Constructor
constructor: (options = {}) ->
options.backgroundColor ?= ""
super options
# Start time
start: (timer) -> @timer = timer
# Stop time
stop: -> clearInterval @timer if @timer
# Clock : Digital
class DigitalClock extends Clock
# Constructor
constructor: (options = {}) ->
options.name = "DigitalClock"
options.html = Util.date.timeFormatter Util.date.getTime()
options.style =
fontSize: "85px", fontWeight: "300"
lineHeight: "1"
textAlign: "right"
letterSpacing: "-3px"
super options
Util.text.autoSize @
@props = x: Align.right(-12), y: Align.top(43)
# Start time
@start()
start: ->
super
@time = Util.date.getTime()
@html = Util.date.timeFormatter @time = Util.date.getTime()
Utils.delay 60 - @time.secs, =>
@html = Util.date.timeFormatter @time = Util.date.getTime()
@timer = Utils.interval 60, => @html = Util.date.timeFormatter @time = Util.date.getTime()
super @timer
# Clock : Analog
class AnalogClock extends Clock
# Constructor
constructor: (options = {}) ->
super options
@borderRadius = @width/2
# Edge
@edge = new Layer
name: ".edge"
point: Align.center
size: @width
backgroundColor: ""
parent: @
secAngle = 360 / 60
for i in [1..60]
# Hour
if i%%5 is 0
hourBar = new Layer
name: ".edge.hour"
html: i / 5
style:
fontSize: "40px", fontWeight: "400"
lineHeight: "1"
textAlign: "center"
color: "white"
backgroundColor: ""
parent: @edge
Util.text.autoSize hourBar
a = (-90 + (secAngle * i)) * (Math.PI / 180)
r = @edge.width/2 - hourBar.height + 3
hourBar.props =
x: @edge.width/2 - hourBar.width/2 + Math.cos(a) * r
y: @edge.height/2 - hourBar.height/2 + Math.sin(a) * r
# Minute
if i %% 5 is 0
minBar = new Layer
name: ".edge.min"
html: if i < 10 then "0#{i}" else i
style:
fontSize: "13px", fontWeight: "400"
lineHeight: "1"
textAlign: "center"
letterSpacing: "-1px"
color: "white"
backgroundColor: ""
parent: @edge
Util.text.autoSize minBar
a = (-90 + (secAngle * i)) * (Math.PI / 180)
r = @edge.width/2 - minBar.height + 9
r -= 2 if i is 15 or i is 45
minBar.props =
x: @edge.width/2 - minBar.width/2 + Math.cos(a) * r
y: @edge.height/2 - minBar.height/2 + Math.sin(a) * r
# Second
else
secBar = new Layer
name: ".sec"
x: Align.center, y: Align.bottom(-@edge.width/2 + 8)
width: 2, height: 8
backgroundColor: "rgba(255,255,255,.5)"
parent: new Layer name: ".edge.sec.parent", point: Align.center, size: 1, originX: .5, originY: 1, rotation: secAngle * i, backgroundColor: "", parent: @edge
# Arrow : Minute
@min = new Layer
name: ".min"
point: Align.center
size: 12
borderRadius: 7
backgroundColor: "white"
parent: @
@min.bottom = new Layer
name: ".min.bottom"
x: Align.center, y: Align.bottom(-@min.width/2 + 2)
width: 4, height: 20 + 2
borderRadius: 2
backgroundColor: "white"
parent: @min
@min.top = new Layer
name: ".min.top"
x: Align.center, maxY: @min.bottom.minY + 5
width: 10, height: @width/2 - 10 - 20 + 5
borderRadius: 5
backgroundColor: "white"
parent: @min
# Arrow : Hour
@hour = @min.copy()
@hour.parent = @
@hour.children[1].height -= 50
@hour.children[1].maxY = @hour.children[0].minY + 5
@min.sendToBack()
@hour.sendToBack()
# Arrow : Second
@sec = new Layer
name: ".sec"
point: Align.center
size: 8
borderRadius: 7
backgroundColor: "orange"
parent: @
@sec.bar = new Layer
name: ".sec.bar"
x: Align.center, y: Align.bottom(18)
width: 2, height: @width/2 + 22
backgroundColor: @sec.backgroundColor
parent: @sec
@sec.dot = new Layer
name: ".sec.dot"
point: Align.center
size: 2
borderRadius: 2
backgroundColor: "black"
parent: @sec
# Events
animationEnd = -> @rotation = 0 if @rotation is 360
@sec.onAnimationEnd animationEnd
@min.onAnimationEnd animationEnd
@hour.onAnimationEnd animationEnd
# Start time
@start()
update: (animate = true) =>
time = Util.date.getTime()
time.secs = 60 if time.secs is 0
time.mins = 60 if time.mins is 0
time.hours = time.hours - 12 if time.hours > 12
time.hours = 12 if time.hours is 0
secAngle = (360 / 60) * time.secs
minAngle = (360 / 60) * time.mins
minAngle += (360 / 60 / 60) * time.secs unless time.secs is 60
hourAngle = (360 / 12) * time.hours
hourAngle += (360 / 12 / 60) * time.mins unless time.mins is 60
@sec.animateStop()
@min.animateStop()
@hour.animateStop()
if animate
@sec.animate rotation: secAngle, options: { time: .98, curve: "linear" }
@min.animate rotation: minAngle, options: { curve: "linear" }
@hour.animate rotation: hourAngle, options: { curve: "linear" }
else
@sec.rotation = secAngle
@min.rotation = minAngle
@hour.rotation = hourAngle
start: ->
@update false
@timer = Utils.interval 1, @update
super @timer |
[
{
"context": "{\n _id: App.server.createUUID()\n name: \"Unnamed\"\n belongs_to: App.rooms.selected.get('id')\n ",
"end": 604,
"score": 0.9771727919578552,
"start": 597,
"tag": "NAME",
"value": "Unnamed"
}
] | cmdr_web/src/scripts/views/action_configure.coffee | wesleyan/cmdr-server | 2 | slinky_require('../core.coffee')
slinky_require('configure_list.coffee')
slinky_require('bind_view.coffee')
App.ActionsConfigureView = App.BindView.extend
initialize: () ->
App.rooms.bind "change:selection", @render, this
@configure_list = new App.ConfigureListView(App.actions)
@configure_list.bind "add", @add, this
@configure_list.bind "remove", @remove, this
App.actions.bind "change:selection", @change_selection, this
App.actions.bind "change:update", @render, this
@change_selection()
add: () ->
msg = {
_id: App.server.createUUID()
name: "Unnamed"
belongs_to: App.rooms.selected.get('id')
displayNameBinding: "name"
action: true
settings: {
promptProjector: false
source: null
module: null
}
}
App.server.create_doc(msg)
App.actions.add(msg)
@render()
remove: () ->
doc = App.actions.selected.attributes
doc.belongs_to = doc.belongs_to.id
App.server.remove_doc(doc)
App.rooms.selected.attributes.actions.remove(App.actions.selected)
App.actions.remove(App.actions.selected)
@render
set_up_bindings: (room) ->
@unbind_all()
if @action
@field_bind "input[name='name']", @action,
((r) -> r.get('name')),
((r, v) -> r.set(name: v))
@field_bind "input[name='prompt projector']", @action,
((r) -> r.get('settings').promptProjector),
((r, v) -> r.set(settings: _(r.get('settings')).extend(promptProjector: v)))
change_selection: () ->
@action = App.actions.selected
@set_up_bindings()
render: () ->
@model = App.rooms.selected
if @model
$(@el).html App.templates.action_configure()
$(".action-list", @el).html @configure_list.render().el
@set_up_bindings(@model)
$(".save-button", @el).click((e) => @save(e))
$(".cancel-button", @el).click((e) => @cancel(e))
this
save: () ->
# TODO: When save is clicked, the server should save everything that has changed
act = App.actions.selected.clone()
action = act.attributes
action["belongs_to"] = act.get("belongs_to").get("id")
App.server.save_doc(action)#App.actions.selected)
cancel: () ->
| 42081 | slinky_require('../core.coffee')
slinky_require('configure_list.coffee')
slinky_require('bind_view.coffee')
App.ActionsConfigureView = App.BindView.extend
initialize: () ->
App.rooms.bind "change:selection", @render, this
@configure_list = new App.ConfigureListView(App.actions)
@configure_list.bind "add", @add, this
@configure_list.bind "remove", @remove, this
App.actions.bind "change:selection", @change_selection, this
App.actions.bind "change:update", @render, this
@change_selection()
add: () ->
msg = {
_id: App.server.createUUID()
name: "<NAME>"
belongs_to: App.rooms.selected.get('id')
displayNameBinding: "name"
action: true
settings: {
promptProjector: false
source: null
module: null
}
}
App.server.create_doc(msg)
App.actions.add(msg)
@render()
remove: () ->
doc = App.actions.selected.attributes
doc.belongs_to = doc.belongs_to.id
App.server.remove_doc(doc)
App.rooms.selected.attributes.actions.remove(App.actions.selected)
App.actions.remove(App.actions.selected)
@render
set_up_bindings: (room) ->
@unbind_all()
if @action
@field_bind "input[name='name']", @action,
((r) -> r.get('name')),
((r, v) -> r.set(name: v))
@field_bind "input[name='prompt projector']", @action,
((r) -> r.get('settings').promptProjector),
((r, v) -> r.set(settings: _(r.get('settings')).extend(promptProjector: v)))
change_selection: () ->
@action = App.actions.selected
@set_up_bindings()
render: () ->
@model = App.rooms.selected
if @model
$(@el).html App.templates.action_configure()
$(".action-list", @el).html @configure_list.render().el
@set_up_bindings(@model)
$(".save-button", @el).click((e) => @save(e))
$(".cancel-button", @el).click((e) => @cancel(e))
this
save: () ->
# TODO: When save is clicked, the server should save everything that has changed
act = App.actions.selected.clone()
action = act.attributes
action["belongs_to"] = act.get("belongs_to").get("id")
App.server.save_doc(action)#App.actions.selected)
cancel: () ->
| true | slinky_require('../core.coffee')
slinky_require('configure_list.coffee')
slinky_require('bind_view.coffee')
App.ActionsConfigureView = App.BindView.extend
initialize: () ->
App.rooms.bind "change:selection", @render, this
@configure_list = new App.ConfigureListView(App.actions)
@configure_list.bind "add", @add, this
@configure_list.bind "remove", @remove, this
App.actions.bind "change:selection", @change_selection, this
App.actions.bind "change:update", @render, this
@change_selection()
add: () ->
msg = {
_id: App.server.createUUID()
name: "PI:NAME:<NAME>END_PI"
belongs_to: App.rooms.selected.get('id')
displayNameBinding: "name"
action: true
settings: {
promptProjector: false
source: null
module: null
}
}
App.server.create_doc(msg)
App.actions.add(msg)
@render()
remove: () ->
doc = App.actions.selected.attributes
doc.belongs_to = doc.belongs_to.id
App.server.remove_doc(doc)
App.rooms.selected.attributes.actions.remove(App.actions.selected)
App.actions.remove(App.actions.selected)
@render
set_up_bindings: (room) ->
@unbind_all()
if @action
@field_bind "input[name='name']", @action,
((r) -> r.get('name')),
((r, v) -> r.set(name: v))
@field_bind "input[name='prompt projector']", @action,
((r) -> r.get('settings').promptProjector),
((r, v) -> r.set(settings: _(r.get('settings')).extend(promptProjector: v)))
change_selection: () ->
@action = App.actions.selected
@set_up_bindings()
render: () ->
@model = App.rooms.selected
if @model
$(@el).html App.templates.action_configure()
$(".action-list", @el).html @configure_list.render().el
@set_up_bindings(@model)
$(".save-button", @el).click((e) => @save(e))
$(".cancel-button", @el).click((e) => @cancel(e))
this
save: () ->
# TODO: When save is clicked, the server should save everything that has changed
act = App.actions.selected.clone()
action = act.attributes
action["belongs_to"] = act.get("belongs_to").get("id")
App.server.save_doc(action)#App.actions.selected)
cancel: () ->
|
[
{
"context": "/user/login/',{\n login: email\n password: password\n })\n\n signOut: () ->\n @$http.post('/v1/use",
"end": 1429,
"score": 0.9985442161560059,
"start": 1421,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ssword, newPassword) ->\n data =\n ... | src/app/services/data.service.coffee | pavelkuchin/tracktrains-ui | 0 | ###
The MIT License (MIT)
Copyright (c) 2015 TrackSeats.info
The data service intended to request and send data to server.
The simpliest http calls wrapper with basic logic
Methods:
signIn(email, password) - the user authentication call
signOut() - the call for close user session
getSession() - return the current user
getTasks() - return the tasks list
disableTask(task) - disable task (it will not be executed)
enableTask(task) - enable task
deleteTask(task) - delete task
saveTask(task) - create a new task if task.resource_uri is undefined
update an existing task if task.resource_uri is defined
getStation(name) - return stations list which name begins from value of 'name'
parameter
getTrain(date, departure_station, destination_station, query) - return trains
for the specific 'date' from departure_station to destination_station
with filter by query
changePassword(current_password, password) - changes a password of the user
inviteFriend(friendsEmail) - sends an invitation to a friend
deleteAccount(user) - deletes an user account
signup(invite, password) - create an user with using invite and password
###
class DataService
constructor: (@$http) ->
signIn: (email, password) ->
@$http.post('/v1/user/login/',{
login: email
password: password
})
signOut: () ->
@$http.post('/v1/user/logout/', {})
getSession: () ->
@$http.get('/v1/user/session/')
getTasks: () ->
@$http.get('/v1/byrwtask/')
disableTask: (task) ->
@$http.patch(task.resource_uri, {is_active: false})
enableTask: (task) ->
@$http.patch(task.resource_uri, {is_active: true})
deleteTask: (task) ->
@$http.delete(task.resource_uri)
saveTask: (task) ->
if task.resource_uri
@$http.put(task.resource_uri, task)
else
@$http.post('/v1/byrwtask/', task)
getStation: (name) ->
@$http.get("/v1/byrwgateway/station/#{name}/")
getTrain: (date, departure, destination, query) ->
@$http.get("/v1/byrwgateway/train/",
params:
date: date
departure_point: departure
destination_point: destination
query: query
)
changePassword: (currentPassword, newPassword) ->
data =
password: currentPassword
new_password: newPassword
@$http.put("/v1/user/change_password/", data)
inviteFriend: (friendsEmail) ->
@$http.post("/v1/user/invite/#{friendsEmail}/", {})
deleteAccount: (user) ->
@$http.delete("/v1/user/#{user.id}/")
signup: (invite, password) ->
data =
password: password
@$http.post("/v1/user/signup/#{invite}/", data)
angular
.module('trackSeatsApp')
.service('DataService', DataService)
DataService.$inject = ['$http']
| 112583 | ###
The MIT License (MIT)
Copyright (c) 2015 TrackSeats.info
The data service intended to request and send data to server.
The simpliest http calls wrapper with basic logic
Methods:
signIn(email, password) - the user authentication call
signOut() - the call for close user session
getSession() - return the current user
getTasks() - return the tasks list
disableTask(task) - disable task (it will not be executed)
enableTask(task) - enable task
deleteTask(task) - delete task
saveTask(task) - create a new task if task.resource_uri is undefined
update an existing task if task.resource_uri is defined
getStation(name) - return stations list which name begins from value of 'name'
parameter
getTrain(date, departure_station, destination_station, query) - return trains
for the specific 'date' from departure_station to destination_station
with filter by query
changePassword(current_password, password) - changes a password of the user
inviteFriend(friendsEmail) - sends an invitation to a friend
deleteAccount(user) - deletes an user account
signup(invite, password) - create an user with using invite and password
###
class DataService
constructor: (@$http) ->
signIn: (email, password) ->
@$http.post('/v1/user/login/',{
login: email
password: <PASSWORD>
})
signOut: () ->
@$http.post('/v1/user/logout/', {})
getSession: () ->
@$http.get('/v1/user/session/')
getTasks: () ->
@$http.get('/v1/byrwtask/')
disableTask: (task) ->
@$http.patch(task.resource_uri, {is_active: false})
enableTask: (task) ->
@$http.patch(task.resource_uri, {is_active: true})
deleteTask: (task) ->
@$http.delete(task.resource_uri)
saveTask: (task) ->
if task.resource_uri
@$http.put(task.resource_uri, task)
else
@$http.post('/v1/byrwtask/', task)
getStation: (name) ->
@$http.get("/v1/byrwgateway/station/#{name}/")
getTrain: (date, departure, destination, query) ->
@$http.get("/v1/byrwgateway/train/",
params:
date: date
departure_point: departure
destination_point: destination
query: query
)
changePassword: (currentPassword, newPassword) ->
data =
password: <PASSWORD>
new_password: <PASSWORD>
@$http.put("/v1/user/change_password/", data)
inviteFriend: (friendsEmail) ->
@$http.post("/v1/user/invite/#{friendsEmail}/", {})
deleteAccount: (user) ->
@$http.delete("/v1/user/#{user.id}/")
signup: (invite, password) ->
data =
password: <PASSWORD>
@$http.post("/v1/user/signup/#{invite}/", data)
angular
.module('trackSeatsApp')
.service('DataService', DataService)
DataService.$inject = ['$http']
| true | ###
The MIT License (MIT)
Copyright (c) 2015 TrackSeats.info
The data service intended to request and send data to server.
The simpliest http calls wrapper with basic logic
Methods:
signIn(email, password) - the user authentication call
signOut() - the call for close user session
getSession() - return the current user
getTasks() - return the tasks list
disableTask(task) - disable task (it will not be executed)
enableTask(task) - enable task
deleteTask(task) - delete task
saveTask(task) - create a new task if task.resource_uri is undefined
update an existing task if task.resource_uri is defined
getStation(name) - return stations list which name begins from value of 'name'
parameter
getTrain(date, departure_station, destination_station, query) - return trains
for the specific 'date' from departure_station to destination_station
with filter by query
changePassword(current_password, password) - changes a password of the user
inviteFriend(friendsEmail) - sends an invitation to a friend
deleteAccount(user) - deletes an user account
signup(invite, password) - create an user with using invite and password
###
class DataService
constructor: (@$http) ->
signIn: (email, password) ->
@$http.post('/v1/user/login/',{
login: email
password: PI:PASSWORD:<PASSWORD>END_PI
})
signOut: () ->
@$http.post('/v1/user/logout/', {})
getSession: () ->
@$http.get('/v1/user/session/')
getTasks: () ->
@$http.get('/v1/byrwtask/')
disableTask: (task) ->
@$http.patch(task.resource_uri, {is_active: false})
enableTask: (task) ->
@$http.patch(task.resource_uri, {is_active: true})
deleteTask: (task) ->
@$http.delete(task.resource_uri)
saveTask: (task) ->
if task.resource_uri
@$http.put(task.resource_uri, task)
else
@$http.post('/v1/byrwtask/', task)
getStation: (name) ->
@$http.get("/v1/byrwgateway/station/#{name}/")
getTrain: (date, departure, destination, query) ->
@$http.get("/v1/byrwgateway/train/",
params:
date: date
departure_point: departure
destination_point: destination
query: query
)
changePassword: (currentPassword, newPassword) ->
data =
password: PI:PASSWORD:<PASSWORD>END_PI
new_password: PI:PASSWORD:<PASSWORD>END_PI
@$http.put("/v1/user/change_password/", data)
inviteFriend: (friendsEmail) ->
@$http.post("/v1/user/invite/#{friendsEmail}/", {})
deleteAccount: (user) ->
@$http.delete("/v1/user/#{user.id}/")
signup: (invite, password) ->
data =
password: PI:PASSWORD:<PASSWORD>END_PI
@$http.post("/v1/user/signup/#{invite}/", data)
angular
.module('trackSeatsApp')
.service('DataService', DataService)
DataService.$inject = ['$http']
|
[
{
"context": "te('artwork', {\n partner: {\n id: 'catty-partner'\n }\n artists: [\n fabricate",
"end": 540,
"score": 0.676982045173645,
"start": 527,
"tag": "USERNAME",
"value": "catty-partner"
},
{
"context": " fabricate('artist', {\n ... | src/desktop/apps/artwork/components/artists/test/templates/index.coffee | kanaabe/force | 0 | _ = require 'underscore'
jade = require 'jade'
cheerio = require 'cheerio'
path = require 'path'
fs = require 'fs'
{ fabricate } = require 'antigravity'
sinon = require 'sinon'
render = ->
filename = path.resolve __dirname, "../../index.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'Artist Module template', ->
describe 'when the artworks partner matches the featured partner', ->
beforeEach ->
@artwork = fabricate('artwork', {
partner: {
id: 'catty-partner'
}
artists: [
fabricate('artist', {
name: 'K Dot'
blurb: 'This is the Artsy blurb'
biography_blurb: {
text: "He is from Compton",
credit: 'Submitted by Catty Gallery'
partner_id: 'catty-partner'
}
bio: "We do not know"
exhibition_highlights: [
fabricate('show'),
fabricate('show'),
fabricate('show')
]
articles: [
{
thumbnail_image: { cropped: { url: 'image.jpg' } }
title: "Jeff Koons’ Gazing Balls Glimmer at Art Basel"
author: {
name: 'Artsy Editorial'
}
}
]
})
]
})
@html = render()(
artwork: @artwork
helpers: {
artists:
build: sinon.stub().returns ['biography', 'exhibition highlights', 'articles']
name: sinon.stub()
groupBy: _.groupBy
}
asset: (->)
sd: {}
)
@$ = cheerio.load(@html)
it 'should display the featured biography and credit', ->
@$('.side-tabs__nav').find('a[data-id=biography]').attr('data-id').should.equal 'biography'
@$('.artwork-artist__content__biography__text').html().should.containEql "He is from Compton"
@$('.artwork-artist__content__biography__credit').html().should.containEql "Submitted by Catty Gallery"
@$('.artwork-artist__content__short-bio').html().should.containEql "We do not know"
describe 'when the artworks partner does not match the featured partner', ->
beforeEach ->
@artwork = fabricate('artwork', {
partner: {
id: 'catty-partner'
}
artists: [
fabricate('artist', {
name: 'K Dot'
blurb: 'This is the Artsy blurb'
biography_blurb: {
text: "He is from Compton",
credit: 'Submitted by Catty Gallery'
partner_id: 'some-other-partner'
}
bio: "We do not know"
exhibition_highlights: [
fabricate('show'),
fabricate('show'),
fabricate('show')
]
articles: [
{
thumbnail_image: { cropped: { url: 'image.jpg' } }
title: "Jeff Koons’ Gazing Balls Glimmer at Art Basel"
author: {
name: 'Artsy Editorial'
}
}
]
})
]
})
@html = render()(
artwork: @artwork
helpers: {
artists:
build: sinon.stub().returns ['biography', 'exhibition highlights', 'articles']
name: sinon.stub()
groupBy: _.groupBy
}
asset: (->)
sd: {}
)
@$ = cheerio.load(@html)
it 'should display the featured biography and credit', ->
@$('.side-tabs__nav').find('a[data-id=biography]').attr('data-id').should.equal 'biography'
@$('.artwork-artist__content__biography__text').html().should.containEql "This is the Artsy blurb"
@$('.artwork-artist__content__biography__credit').length.should.equal 0
@$('.artwork-artist__content__short-bio').html().should.containEql "We do not know"
describe 'when the biography_blurb is blank and no tabs are present', ->
beforeEach ->
@artwork = fabricate('artwork', {
partner: {
id: 'catty-partner'
}
artists: [
fabricate('artist', {
name: 'K Dot'
blurb: null
biography_blurb: {
text: "",
credit: null
partner_id: null
}
bio: null
exhibition_highlights: []
articles: []
})
]
})
@html = render()(
artwork: @artwork
helpers: {
artists:
build: sinon.stub().returns []
name: sinon.stub()
groupBy: _.groupBy
}
asset: (->)
sd: {}
)
@$ = cheerio.load(@html)
it 'should not display any artist tabs', ->
@$('.side-tabs__nav').find('a[data-id=biography]').length.should.equal 0
@$('.side-tabs__nav').find('a[data-id=articles]').length.should.equal 0
@$('.side-tabs__nav').find('a[data-id=exhibition_highlights]').length.should.equal 0
| 32923 | _ = require 'underscore'
jade = require 'jade'
cheerio = require 'cheerio'
path = require 'path'
fs = require 'fs'
{ fabricate } = require 'antigravity'
sinon = require 'sinon'
render = ->
filename = path.resolve __dirname, "../../index.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'Artist Module template', ->
describe 'when the artworks partner matches the featured partner', ->
beforeEach ->
@artwork = fabricate('artwork', {
partner: {
id: 'catty-partner'
}
artists: [
fabricate('artist', {
name: '<NAME>'
blurb: 'This is the Artsy blurb'
biography_blurb: {
text: "He is from Compton",
credit: 'Submitted by Catty Gallery'
partner_id: 'catty-partner'
}
bio: "We do not know"
exhibition_highlights: [
fabricate('show'),
fabricate('show'),
fabricate('show')
]
articles: [
{
thumbnail_image: { cropped: { url: 'image.jpg' } }
title: "<NAME>’ Gazing Balls Glimmer at Art Basel"
author: {
name: '<NAME>'
}
}
]
})
]
})
@html = render()(
artwork: @artwork
helpers: {
artists:
build: sinon.stub().returns ['biography', 'exhibition highlights', 'articles']
name: sinon.stub()
groupBy: _.groupBy
}
asset: (->)
sd: {}
)
@$ = cheerio.load(@html)
it 'should display the featured biography and credit', ->
@$('.side-tabs__nav').find('a[data-id=biography]').attr('data-id').should.equal 'biography'
@$('.artwork-artist__content__biography__text').html().should.containEql "He is from Compton"
@$('.artwork-artist__content__biography__credit').html().should.containEql "Submitted by <NAME>"
@$('.artwork-artist__content__short-bio').html().should.containEql "We do not know"
describe 'when the artworks partner does not match the featured partner', ->
beforeEach ->
@artwork = fabricate('artwork', {
partner: {
id: 'catty-partner'
}
artists: [
fabricate('artist', {
name: '<NAME>'
blurb: 'This is the Artsy blurb'
biography_blurb: {
text: "He is from <NAME>",
credit: 'Submitted by <NAME>'
partner_id: 'some-other-partner'
}
bio: "We do not know"
exhibition_highlights: [
fabricate('show'),
fabricate('show'),
fabricate('show')
]
articles: [
{
thumbnail_image: { cropped: { url: 'image.jpg' } }
title: "<NAME>’ Gazing Balls Glimmer at Art Basel"
author: {
name: '<NAME>'
}
}
]
})
]
})
@html = render()(
artwork: @artwork
helpers: {
artists:
build: sinon.stub().returns ['biography', 'exhibition highlights', 'articles']
name: sinon.stub()
groupBy: _.groupBy
}
asset: (->)
sd: {}
)
@$ = cheerio.load(@html)
it 'should display the featured biography and credit', ->
@$('.side-tabs__nav').find('a[data-id=biography]').attr('data-id').should.equal 'biography'
@$('.artwork-artist__content__biography__text').html().should.containEql "This is the Artsy blurb"
@$('.artwork-artist__content__biography__credit').length.should.equal 0
@$('.artwork-artist__content__short-bio').html().should.containEql "We do not know"
describe 'when the biography_blurb is blank and no tabs are present', ->
beforeEach ->
@artwork = fabricate('artwork', {
partner: {
id: 'catty-partner'
}
artists: [
fabricate('artist', {
name: '<NAME>'
blurb: null
biography_blurb: {
text: "",
credit: null
partner_id: null
}
bio: null
exhibition_highlights: []
articles: []
})
]
})
@html = render()(
artwork: @artwork
helpers: {
artists:
build: sinon.stub().returns []
name: sinon.stub()
groupBy: _.groupBy
}
asset: (->)
sd: {}
)
@$ = cheerio.load(@html)
it 'should not display any artist tabs', ->
@$('.side-tabs__nav').find('a[data-id=biography]').length.should.equal 0
@$('.side-tabs__nav').find('a[data-id=articles]').length.should.equal 0
@$('.side-tabs__nav').find('a[data-id=exhibition_highlights]').length.should.equal 0
| true | _ = require 'underscore'
jade = require 'jade'
cheerio = require 'cheerio'
path = require 'path'
fs = require 'fs'
{ fabricate } = require 'antigravity'
sinon = require 'sinon'
render = ->
filename = path.resolve __dirname, "../../index.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'Artist Module template', ->
describe 'when the artworks partner matches the featured partner', ->
beforeEach ->
@artwork = fabricate('artwork', {
partner: {
id: 'catty-partner'
}
artists: [
fabricate('artist', {
name: 'PI:NAME:<NAME>END_PI'
blurb: 'This is the Artsy blurb'
biography_blurb: {
text: "He is from Compton",
credit: 'Submitted by Catty Gallery'
partner_id: 'catty-partner'
}
bio: "We do not know"
exhibition_highlights: [
fabricate('show'),
fabricate('show'),
fabricate('show')
]
articles: [
{
thumbnail_image: { cropped: { url: 'image.jpg' } }
title: "PI:NAME:<NAME>END_PI’ Gazing Balls Glimmer at Art Basel"
author: {
name: 'PI:NAME:<NAME>END_PI'
}
}
]
})
]
})
@html = render()(
artwork: @artwork
helpers: {
artists:
build: sinon.stub().returns ['biography', 'exhibition highlights', 'articles']
name: sinon.stub()
groupBy: _.groupBy
}
asset: (->)
sd: {}
)
@$ = cheerio.load(@html)
it 'should display the featured biography and credit', ->
@$('.side-tabs__nav').find('a[data-id=biography]').attr('data-id').should.equal 'biography'
@$('.artwork-artist__content__biography__text').html().should.containEql "He is from Compton"
@$('.artwork-artist__content__biography__credit').html().should.containEql "Submitted by PI:NAME:<NAME>END_PI"
@$('.artwork-artist__content__short-bio').html().should.containEql "We do not know"
describe 'when the artworks partner does not match the featured partner', ->
beforeEach ->
@artwork = fabricate('artwork', {
partner: {
id: 'catty-partner'
}
artists: [
fabricate('artist', {
name: 'PI:NAME:<NAME>END_PI'
blurb: 'This is the Artsy blurb'
biography_blurb: {
text: "He is from PI:NAME:<NAME>END_PI",
credit: 'Submitted by PI:NAME:<NAME>END_PI'
partner_id: 'some-other-partner'
}
bio: "We do not know"
exhibition_highlights: [
fabricate('show'),
fabricate('show'),
fabricate('show')
]
articles: [
{
thumbnail_image: { cropped: { url: 'image.jpg' } }
title: "PI:NAME:<NAME>END_PI’ Gazing Balls Glimmer at Art Basel"
author: {
name: 'PI:NAME:<NAME>END_PI'
}
}
]
})
]
})
@html = render()(
artwork: @artwork
helpers: {
artists:
build: sinon.stub().returns ['biography', 'exhibition highlights', 'articles']
name: sinon.stub()
groupBy: _.groupBy
}
asset: (->)
sd: {}
)
@$ = cheerio.load(@html)
it 'should display the featured biography and credit', ->
@$('.side-tabs__nav').find('a[data-id=biography]').attr('data-id').should.equal 'biography'
@$('.artwork-artist__content__biography__text').html().should.containEql "This is the Artsy blurb"
@$('.artwork-artist__content__biography__credit').length.should.equal 0
@$('.artwork-artist__content__short-bio').html().should.containEql "We do not know"
describe 'when the biography_blurb is blank and no tabs are present', ->
beforeEach ->
@artwork = fabricate('artwork', {
partner: {
id: 'catty-partner'
}
artists: [
fabricate('artist', {
name: 'PI:NAME:<NAME>END_PI'
blurb: null
biography_blurb: {
text: "",
credit: null
partner_id: null
}
bio: null
exhibition_highlights: []
articles: []
})
]
})
@html = render()(
artwork: @artwork
helpers: {
artists:
build: sinon.stub().returns []
name: sinon.stub()
groupBy: _.groupBy
}
asset: (->)
sd: {}
)
@$ = cheerio.load(@html)
it 'should not display any artist tabs', ->
@$('.side-tabs__nav').find('a[data-id=biography]').length.should.equal 0
@$('.side-tabs__nav').find('a[data-id=articles]').length.should.equal 0
@$('.side-tabs__nav').find('a[data-id=exhibition_highlights]').length.should.equal 0
|
[
{
"context": "customCoffee = new Coffee({\n functions: {\n marius: {\n color: 'red'\n },\n valjean: {",
"end": 195,
"score": 0.7971046566963196,
"start": 189,
"tag": "NAME",
"value": "marius"
},
{
"context": " marius: {\n color: 'red'\n },\n ... | test/src/cstest.coffee | sanyaade-teachings/spresensedroplet | 3 | helper = require '../../src/helper.coffee'
Coffee = require '../../src/languages/coffee.coffee'
asyncTest 'Parser configurability', ->
customCoffee = new Coffee({
functions: {
marius: {
color: 'red'
},
valjean: {},
eponine: {
value: true,
color: 'purplish'
},
fantine: {
value: true
},
cosette: {
command: true,
value: true
}
}
})
window.customSerialization = customSerialization = customCoffee.parse(
'''
marius eponine 10
alert random 100
cosette 20
''').serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "red",
"nodeContext": {
"prefix": "marius ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"marius ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "purplish",
"nodeContext": {
"prefix": "eponine ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
"eponine ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"10",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 0,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Callee",
"type": "socketStart",
"emptyString": "``"
},
"alert",
{
"type": "socketEnd"
},
" ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "blue",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 0,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Callee",
"type": "socketStart",
"emptyString": "``"
},
"random",
{
"type": "socketEnd"
},
" ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"100",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "cosette ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 0,
"type": "blockStart"
},
"cosette ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"20",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Custom known functions work')
return start()
asyncTest 'Dotted methods', ->
customCoffee = new Coffee({
functions: {
'console.log': {},
speak: {},
'Math.log': {
value: true
},
'*.toString': {
value: true
},
'?.fd': {
command: true
},
log: {
value: true
},
setTimeout: {
command: true,
value: true
}
}
})
customSerialization = customCoffee.parse(
'console.log Math.log log x.toString log.fd()\nfd()').serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "blue",
"nodeContext": {
"prefix": "console.log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"console.log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "Math.log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
"Math.log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
"log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "PropertyAccess",
"type": "socketStart",
"emptyString": "``"
},
"x",
{
"type": "socketEnd"
},
".toString ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "blue",
"nodeContext": {
"prefix": "",
"suffix": ".fd()",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "PropertyAccess",
"type": "socketStart",
"emptyString": "``"
},
"log",
{
"type": "socketEnd"
},
".fd()",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "fd()",
"suffix": "fd()",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"fd()",
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Dotted known functions work')
start()
asyncTest 'Merged code blocks', ->
coffee = new Coffee()
customSerialization = coffee.parse(
'''
x = (y) -> y * y
alert \'clickme\', ->
console.log \'ouch\'
'''
).serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "purple",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Assign"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Lvalue",
"type": "socketStart",
"emptyString": "``"
},
"x",
{
"type": "socketEnd"
},
" = (",
{
"dropdown": false,
"handwritten": false,
"parseContext": "__comment__",
"type": "socketStart",
"emptyString": ""
},
"y",
{
"type": "socketEnd"
},
") -> ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Block",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Operator*"
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator*",
"type": "socketStart",
"emptyString": "``"
},
"y",
{
"type": "socketEnd"
},
" * ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator*",
"type": "socketStart",
"emptyString": "``"
},
"y",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "alert ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"alert ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
"'clickme'",
{
"type": "socketEnd"
},
", ->",
{
"indentContext": null,
"prefix": " ",
"type": "indentStart"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "console.log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"console.log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"'ouch'",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "indentEnd"
},
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Merged code blocks work')
return start()
asyncTest 'Custom Colors', ->
customCoffee = new Coffee({
categories: {
functions: {color: '#111'},
returns: {color: '#222'},
comments: {color: '#333'},
arithmetic: {color: '#444'},
containers: {color: '#666'},
assignments: {color: '#777'},
loops: {color: '#888'},
conditionals: {color: '#999'},
value: {color: '#aaa'},
command: {color: '#bbb'}
}
})
customSerialization = customCoffee.parse(
'return b != (a += [c + d][0])').serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "#222",
"nodeContext": {
"prefix": "return ",
"suffix": "",
"type": "Return"
},
"parseContext": "__comment__",
"shape": 1,
"type": "blockStart"
},
"return ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "cyan",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Operator!=="
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator!==",
"type": "socketStart",
"emptyString": "``"
},
"b",
{
"type": "socketEnd"
},
" != ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator!==",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "#777",
"nodeContext": {
"prefix": "(",
"suffix": ")",
"type": "Assign"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"(",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Lvalue",
"type": "socketStart",
"emptyString": "``"
},
"a",
{
"type": "socketEnd"
},
" += ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "#aaa",
"nodeContext": {
"prefix": "",
"suffix": "]",
"type": "PropertyAccess"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "PropertyAccess",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "#666",
"nodeContext": {
"prefix": "[",
"suffix": "]",
"type": "Arr"
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
"[",
{
"indentContext": null,
"prefix": " ",
"type": "indentStart"
},
{
"color": "#444",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Operator+"
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator+",
"type": "socketStart",
"emptyString": "``"
},
"c",
{
"type": "socketEnd"
},
" + ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator+",
"type": "socketStart",
"emptyString": "``"
},
"d",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "indentEnd"
},
"]",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
"[",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
"0",
{
"type": "socketEnd"
},
"]",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
")",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Custom colors work')
start()
| 167318 | helper = require '../../src/helper.coffee'
Coffee = require '../../src/languages/coffee.coffee'
asyncTest 'Parser configurability', ->
customCoffee = new Coffee({
functions: {
<NAME>: {
color: 'red'
},
<NAME>: {},
eponine: {
value: true,
color: 'purplish'
},
fantine: {
value: true
},
cosette: {
command: true,
value: true
}
}
})
window.customSerialization = customSerialization = customCoffee.parse(
'''
<NAME> eponine 10
alert random 100
cosette 20
''').serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "red",
"nodeContext": {
"prefix": "<NAME> ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"<NAME> ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "purplish",
"nodeContext": {
"prefix": "<NAME> ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
"<NAME> ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"10",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 0,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Callee",
"type": "socketStart",
"emptyString": "``"
},
"alert",
{
"type": "socketEnd"
},
" ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "blue",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 0,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Callee",
"type": "socketStart",
"emptyString": "``"
},
"random",
{
"type": "socketEnd"
},
" ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"100",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "cosette ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 0,
"type": "blockStart"
},
"cosette ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"20",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Custom known functions work')
return start()
asyncTest 'Dotted methods', ->
customCoffee = new Coffee({
functions: {
'console.log': {},
speak: {},
'Math.log': {
value: true
},
'*.toString': {
value: true
},
'?.fd': {
command: true
},
log: {
value: true
},
setTimeout: {
command: true,
value: true
}
}
})
customSerialization = customCoffee.parse(
'console.log Math.log log x.toString log.fd()\nfd()').serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "blue",
"nodeContext": {
"prefix": "console.log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"console.log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "Math.log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
"Math.log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
"log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "PropertyAccess",
"type": "socketStart",
"emptyString": "``"
},
"x",
{
"type": "socketEnd"
},
".toString ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "blue",
"nodeContext": {
"prefix": "",
"suffix": ".fd()",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "PropertyAccess",
"type": "socketStart",
"emptyString": "``"
},
"log",
{
"type": "socketEnd"
},
".fd()",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "fd()",
"suffix": "fd()",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"fd()",
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Dotted known functions work')
start()
asyncTest 'Merged code blocks', ->
coffee = new Coffee()
customSerialization = coffee.parse(
'''
x = (y) -> y * y
alert \'clickme\', ->
console.log \'ouch\'
'''
).serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "purple",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Assign"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Lvalue",
"type": "socketStart",
"emptyString": "``"
},
"x",
{
"type": "socketEnd"
},
" = (",
{
"dropdown": false,
"handwritten": false,
"parseContext": "__comment__",
"type": "socketStart",
"emptyString": ""
},
"y",
{
"type": "socketEnd"
},
") -> ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Block",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Operator*"
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator*",
"type": "socketStart",
"emptyString": "``"
},
"y",
{
"type": "socketEnd"
},
" * ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator*",
"type": "socketStart",
"emptyString": "``"
},
"y",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "alert ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"alert ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
"'clickme'",
{
"type": "socketEnd"
},
", ->",
{
"indentContext": null,
"prefix": " ",
"type": "indentStart"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "console.log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"console.log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"'ouch'",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "indentEnd"
},
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Merged code blocks work')
return start()
asyncTest 'Custom Colors', ->
customCoffee = new Coffee({
categories: {
functions: {color: '#111'},
returns: {color: '#222'},
comments: {color: '#333'},
arithmetic: {color: '#444'},
containers: {color: '#666'},
assignments: {color: '#777'},
loops: {color: '#888'},
conditionals: {color: '#999'},
value: {color: '#aaa'},
command: {color: '#bbb'}
}
})
customSerialization = customCoffee.parse(
'return b != (a += [c + d][0])').serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "#222",
"nodeContext": {
"prefix": "return ",
"suffix": "",
"type": "Return"
},
"parseContext": "__comment__",
"shape": 1,
"type": "blockStart"
},
"return ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "cyan",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Operator!=="
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator!==",
"type": "socketStart",
"emptyString": "``"
},
"b",
{
"type": "socketEnd"
},
" != ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator!==",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "#777",
"nodeContext": {
"prefix": "(",
"suffix": ")",
"type": "Assign"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"(",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Lvalue",
"type": "socketStart",
"emptyString": "``"
},
"a",
{
"type": "socketEnd"
},
" += ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "#aaa",
"nodeContext": {
"prefix": "",
"suffix": "]",
"type": "PropertyAccess"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "PropertyAccess",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "#666",
"nodeContext": {
"prefix": "[",
"suffix": "]",
"type": "Arr"
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
"[",
{
"indentContext": null,
"prefix": " ",
"type": "indentStart"
},
{
"color": "#444",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Operator+"
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator+",
"type": "socketStart",
"emptyString": "``"
},
"c",
{
"type": "socketEnd"
},
" + ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator+",
"type": "socketStart",
"emptyString": "``"
},
"d",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "indentEnd"
},
"]",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
"[",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
"0",
{
"type": "socketEnd"
},
"]",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
")",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Custom colors work')
start()
| true | helper = require '../../src/helper.coffee'
Coffee = require '../../src/languages/coffee.coffee'
asyncTest 'Parser configurability', ->
customCoffee = new Coffee({
functions: {
PI:NAME:<NAME>END_PI: {
color: 'red'
},
PI:NAME:<NAME>END_PI: {},
eponine: {
value: true,
color: 'purplish'
},
fantine: {
value: true
},
cosette: {
command: true,
value: true
}
}
})
window.customSerialization = customSerialization = customCoffee.parse(
'''
PI:NAME:<NAME>END_PI eponine 10
alert random 100
cosette 20
''').serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "red",
"nodeContext": {
"prefix": "PI:NAME:<NAME>END_PI ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"PI:NAME:<NAME>END_PI ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "purplish",
"nodeContext": {
"prefix": "PI:NAME:<NAME>END_PI ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
"PI:NAME:<NAME>END_PI ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"10",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 0,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Callee",
"type": "socketStart",
"emptyString": "``"
},
"alert",
{
"type": "socketEnd"
},
" ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "blue",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 0,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Callee",
"type": "socketStart",
"emptyString": "``"
},
"random",
{
"type": "socketEnd"
},
" ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"100",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "cosette ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 0,
"type": "blockStart"
},
"cosette ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"20",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Custom known functions work')
return start()
asyncTest 'Dotted methods', ->
customCoffee = new Coffee({
functions: {
'console.log': {},
speak: {},
'Math.log': {
value: true
},
'*.toString': {
value: true
},
'?.fd': {
command: true
},
log: {
value: true
},
setTimeout: {
command: true,
value: true
}
}
})
customSerialization = customCoffee.parse(
'console.log Math.log log x.toString log.fd()\nfd()').serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "blue",
"nodeContext": {
"prefix": "console.log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"console.log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "Math.log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
"Math.log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
"log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "PropertyAccess",
"type": "socketStart",
"emptyString": "``"
},
"x",
{
"type": "socketEnd"
},
".toString ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "blue",
"nodeContext": {
"prefix": "",
"suffix": ".fd()",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "PropertyAccess",
"type": "socketStart",
"emptyString": "``"
},
"log",
{
"type": "socketEnd"
},
".fd()",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "fd()",
"suffix": "fd()",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"fd()",
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Dotted known functions work')
start()
asyncTest 'Merged code blocks', ->
coffee = new Coffee()
customSerialization = coffee.parse(
'''
x = (y) -> y * y
alert \'clickme\', ->
console.log \'ouch\'
'''
).serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "purple",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Assign"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Lvalue",
"type": "socketStart",
"emptyString": "``"
},
"x",
{
"type": "socketEnd"
},
" = (",
{
"dropdown": false,
"handwritten": false,
"parseContext": "__comment__",
"type": "socketStart",
"emptyString": ""
},
"y",
{
"type": "socketEnd"
},
") -> ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Block",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "green",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Operator*"
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator*",
"type": "socketStart",
"emptyString": "``"
},
"y",
{
"type": "socketEnd"
},
" * ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator*",
"type": "socketStart",
"emptyString": "``"
},
"y",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "alert ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"alert ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
"'clickme'",
{
"type": "socketEnd"
},
", ->",
{
"indentContext": null,
"prefix": " ",
"type": "indentStart"
},
{
"specialIndent": undefined,
"type": "newline"
},
{
"color": "blue",
"nodeContext": {
"prefix": "console.log ",
"suffix": "",
"type": "Call"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"console.log ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "LastCallArg",
"type": "socketStart",
"emptyString": "``"
},
"'ouch'",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "indentEnd"
},
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Merged code blocks work')
return start()
asyncTest 'Custom Colors', ->
customCoffee = new Coffee({
categories: {
functions: {color: '#111'},
returns: {color: '#222'},
comments: {color: '#333'},
arithmetic: {color: '#444'},
containers: {color: '#666'},
assignments: {color: '#777'},
loops: {color: '#888'},
conditionals: {color: '#999'},
value: {color: '#aaa'},
command: {color: '#bbb'}
}
})
customSerialization = customCoffee.parse(
'return b != (a += [c + d][0])').serialize()
expectedSerialization = [
{
"indentContext": undefined,
"type": "documentStart"
},
{
"color": "#222",
"nodeContext": {
"prefix": "return ",
"suffix": "",
"type": "Return"
},
"parseContext": "__comment__",
"shape": 1,
"type": "blockStart"
},
"return ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "cyan",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Operator!=="
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator!==",
"type": "socketStart",
"emptyString": "``"
},
"b",
{
"type": "socketEnd"
},
" != ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator!==",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "#777",
"nodeContext": {
"prefix": "(",
"suffix": ")",
"type": "Assign"
},
"parseContext": "__comment__",
"shape": 2,
"type": "blockStart"
},
"(",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Lvalue",
"type": "socketStart",
"emptyString": "``"
},
"a",
{
"type": "socketEnd"
},
" += ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "#aaa",
"nodeContext": {
"prefix": "",
"suffix": "]",
"type": "PropertyAccess"
},
"parseContext": "__comment__",
"shape": 3,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "PropertyAccess",
"type": "socketStart",
"emptyString": "``"
},
{
"color": "#666",
"nodeContext": {
"prefix": "[",
"suffix": "]",
"type": "Arr"
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
"[",
{
"indentContext": null,
"prefix": " ",
"type": "indentStart"
},
{
"color": "#444",
"nodeContext": {
"prefix": "",
"suffix": "",
"type": "Operator+"
},
"parseContext": "__comment__",
"shape": 4,
"type": "blockStart"
},
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator+",
"type": "socketStart",
"emptyString": "``"
},
"c",
{
"type": "socketEnd"
},
" + ",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Operator+",
"type": "socketStart",
"emptyString": "``"
},
"d",
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "indentEnd"
},
"]",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
"[",
{
"dropdown": false,
"handwritten": false,
"parseContext": "Expression",
"type": "socketStart",
"emptyString": "``"
},
"0",
{
"type": "socketEnd"
},
"]",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
")",
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "socketEnd"
},
{
"type": "blockEnd"
},
{
"type": "documentEnd"
}
]
deepEqual(
customSerialization,
expectedSerialization,
'Custom colors work')
start()
|
[
{
"context": "key: 'entities'\npatterns: [\n\n # NOTE\n # Detect a singular ampe",
"end": 14,
"score": 0.6435309052467346,
"start": 6,
"tag": "KEY",
"value": "entities"
}
] | grammars/repositories/inlines/entities.cson | doc22940/language-markdown | 138 | key: 'entities'
patterns: [
# NOTE
# Detect a singular ampersand pre- and superceded by whitespace, so it doesn't get picked up erronously by language-html which marks it as invalid. This rule has no other purpose than to prevent the aforementioned.
{
match: '(?<=^|\\s)(&)(?=$|\\s|,|!|\\?|\\.)'
name: 'ampersand.md'
}
{
# TODO
# Whoever wants to extract the full list of valid entity names from
# https://html.spec.whatwg.org/multipage/entities.json
# instead of using this insanely lazy alphanumeric match; be my guest.
match: '(&)([a-zA-Z0-9]{2,32})(;)'
name: 'entity.constant.md'
captures:
1: { name: 'punctuation.md' }
3: { name: 'punctuation.md' }
}
{
match: '(&#)([0-9]{1,8})(;)'
name: 'entity.constant.md'
captures:
1: { name: 'punctuation.md' }
3: { name: 'punctuation.md' }
}
{
match: '(&#[x|X])([0-9a-fA-F]{1,8})(;)'
name: 'entity.constant.md'
captures:
1: { name: 'punctuation.md' }
3: { name: 'punctuation.md' }
}
]
| 141040 | key: '<KEY>'
patterns: [
# NOTE
# Detect a singular ampersand pre- and superceded by whitespace, so it doesn't get picked up erronously by language-html which marks it as invalid. This rule has no other purpose than to prevent the aforementioned.
{
match: '(?<=^|\\s)(&)(?=$|\\s|,|!|\\?|\\.)'
name: 'ampersand.md'
}
{
# TODO
# Whoever wants to extract the full list of valid entity names from
# https://html.spec.whatwg.org/multipage/entities.json
# instead of using this insanely lazy alphanumeric match; be my guest.
match: '(&)([a-zA-Z0-9]{2,32})(;)'
name: 'entity.constant.md'
captures:
1: { name: 'punctuation.md' }
3: { name: 'punctuation.md' }
}
{
match: '(&#)([0-9]{1,8})(;)'
name: 'entity.constant.md'
captures:
1: { name: 'punctuation.md' }
3: { name: 'punctuation.md' }
}
{
match: '(&#[x|X])([0-9a-fA-F]{1,8})(;)'
name: 'entity.constant.md'
captures:
1: { name: 'punctuation.md' }
3: { name: 'punctuation.md' }
}
]
| true | key: 'PI:KEY:<KEY>END_PI'
patterns: [
# NOTE
# Detect a singular ampersand pre- and superceded by whitespace, so it doesn't get picked up erronously by language-html which marks it as invalid. This rule has no other purpose than to prevent the aforementioned.
{
match: '(?<=^|\\s)(&)(?=$|\\s|,|!|\\?|\\.)'
name: 'ampersand.md'
}
{
# TODO
# Whoever wants to extract the full list of valid entity names from
# https://html.spec.whatwg.org/multipage/entities.json
# instead of using this insanely lazy alphanumeric match; be my guest.
match: '(&)([a-zA-Z0-9]{2,32})(;)'
name: 'entity.constant.md'
captures:
1: { name: 'punctuation.md' }
3: { name: 'punctuation.md' }
}
{
match: '(&#)([0-9]{1,8})(;)'
name: 'entity.constant.md'
captures:
1: { name: 'punctuation.md' }
3: { name: 'punctuation.md' }
}
{
match: '(&#[x|X])([0-9a-fA-F]{1,8})(;)'
name: 'entity.constant.md'
captures:
1: { name: 'punctuation.md' }
3: { name: 'punctuation.md' }
}
]
|
[
{
"context": " (fs|fs-nt)', '#REQUIRED')\n .dat('<owner>John</owner>')\n .ele('node')\n .ent('",
"end": 821,
"score": 0.988315999507904,
"start": 817,
"tag": "NAME",
"value": "John"
},
{
"context": " .nod('repo', {'type': 'git'}, 'git://github.com/oozcitak... | test/basic/streamwriter.coffee | MarkCSmith/xmlbuilder-js | 0 | suite 'Creating XML with stream writer:', ->
hook = null
setup 'hook stdout.write', ->
hook = captureStream(process.stdout)
return
teardown 'unhook stdout.write', ->
hook.unhook()
return
test 'Plain text writer', ->
xml('root')
.dtd('hello.dtd', 'sys')
.ins('pub_border', 'thin')
.ele('img', 'EMPTY')
.com('Image attributes follow')
.att('img', 'height', 'CDATA', '#REQUIRED')
.att('img', 'visible', '(yes|no)', '#DEFAULT', "yes")
.not('fs', { sysID: 'http://my.fs.com/reader' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0', sysID: 'http://my.fs.com/reader' })
.att('img', 'src', 'NOTATION (fs|fs-nt)', '#REQUIRED')
.dat('<owner>John</owner>')
.ele('node')
.ent('ent', 'my val')
.ent('ent', { sysID: 'http://www.myspec.com/ent' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ent('ent', { sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.pent('ent', 'my val')
.pent('ent', { sysID: 'http://www.myspec.com/ent' })
.pent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ele('nodearr', ['a', 'b'])
.root()
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.end(builder.streamWriter(process.stdout))
eq(
hook.captured()
'<?xml version="1.0"?>' +
'<!DOCTYPE root PUBLIC "hello.dtd" "sys" [' +
'<?pub_border thin?>' +
'<!ELEMENT img EMPTY>' +
'<!-- Image attributes follow -->' +
'<!ATTLIST img height CDATA #REQUIRED>' +
'<!ATTLIST img visible (yes|no) "yes">' +
'<!NOTATION fs SYSTEM "http://my.fs.com/reader">' +
'<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0">' +
'<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0" "http://my.fs.com/reader">' +
'<!ATTLIST img src NOTATION (fs|fs-nt) #REQUIRED>' +
'<![CDATA[<owner>John</owner>]]>' +
'<!ELEMENT node (#PCDATA)>' +
'<!ENTITY ent "my val">' +
'<!ENTITY ent SYSTEM "http://www.myspec.com/ent">' +
'<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">' +
'<!ENTITY ent SYSTEM "http://www.myspec.com/ent" NDATA entprg>' +
'<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent" NDATA entprg>' +
'<!ENTITY % ent "my val">' +
'<!ENTITY % ent SYSTEM "http://www.myspec.com/ent">' +
'<!ENTITY % ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">' +
'<!ELEMENT nodearr (a,b)>' +
']>' +
'<root>' +
'<xmlbuilder for="node-js">' +
'<!-- CoffeeScript is awesome. -->' +
'<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>' +
'</xmlbuilder>' +
'<cdata><![CDATA[<test att="val">this is a test</test>\nSecond line]]></cdata>' +
'<raw>&<>&</raw>' +
'<atttest att="val">text</atttest>' +
'<atttest att="val">text</atttest>' +
'</root>'
)
test 'Pretty printing', ->
xml('root')
.dtd('hello.dtd')
.ins('pub_border', 'thin')
.ele('img', 'EMPTY')
.com('Image attributes follow')
.att('img', 'height', 'CDATA', '#REQUIRED')
.att('img', 'visible', '(yes|no)', '#DEFAULT', "yes")
.not('fs', { sysID: 'http://my.fs.com/reader' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0', sysID: 'http://my.fs.com/reader' })
.att('img', 'src', 'NOTATION (fs|fs-nt)', '#REQUIRED')
.dat('<owner>John</owner>')
.ele('node')
.ent('ent', 'my val')
.ent('ent', { sysID: 'http://www.myspec.com/ent' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ent('ent', { sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.pent('ent', 'my val')
.pent('ent', { sysID: 'http://www.myspec.com/ent' })
.pent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ele('nodearr', ['a', 'b'])
.root()
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.ins('target', 'val')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.up()
.ele('empty')
.end(builder.streamWriter(process.stdout, { pretty: true, allowEmpty: true, indent: ' ' } ))
eq(
hook.captured()
"""
<?xml version="1.0"?>
<!DOCTYPE root SYSTEM "hello.dtd" [
<?pub_border thin?>
<!ELEMENT img EMPTY>
<!-- Image attributes follow -->
<!ATTLIST img height CDATA #REQUIRED>
<!ATTLIST img visible (yes|no) "yes">
<!NOTATION fs SYSTEM "http://my.fs.com/reader">
<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0">
<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0" "http://my.fs.com/reader">
<!ATTLIST img src NOTATION (fs|fs-nt) #REQUIRED>
<![CDATA[<owner>John</owner>]]>
<!ELEMENT node (#PCDATA)>
<!ENTITY ent "my val">
<!ENTITY ent SYSTEM "http://www.myspec.com/ent">
<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">
<!ENTITY ent SYSTEM "http://www.myspec.com/ent" NDATA entprg>
<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent" NDATA entprg>
<!ENTITY % ent "my val">
<!ENTITY % ent SYSTEM "http://www.myspec.com/ent">
<!ENTITY % ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">
<!ELEMENT nodearr (a,b)>
]>
<root>
<xmlbuilder for="node-js">
<!-- CoffeeScript is awesome. -->
<repo type="git">
git://github.com/oozcitak/xmlbuilder-js.git
<?target val?>
</repo>
</xmlbuilder>
<cdata>
<![CDATA[<test att="val">this is a test</test>
Second line]]>
</cdata>
<raw>&<>&</raw>
<atttest att="val">text</atttest>
<atttest att="val">text</atttest>
<empty></empty>
</root>
"""
)
test 'Pretty printing with offset', ->
xml('root')
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.end(builder.streamWriter(process.stdout, { pretty: true, indent: ' ', offset : 1 } ))
eq(
hook.captured()
"""
TEMPORARY_INDENT
<?xml version="1.0"?>
<root>
<xmlbuilder for="node-js">
<!-- CoffeeScript is awesome. -->
<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>
</xmlbuilder>
<cdata>
<![CDATA[<test att="val">this is a test</test>
Second line]]>
</cdata>
<raw>&<>&</raw>
<atttest att="val">text</atttest>
<atttest att="val">text</atttest>
</root>
""".replace(
///
TEMPORARY_INDENT\n
///
''
) #Heredoc format indenting is based on the first non-whitespace character, so we add extra, then replace it
)
test 'Pretty printing with empty indent', ->
xml('root')
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.root()
.commentBefore('pre').commentAfter('post')
.instructionBefore('pre' ,'val1').instructionAfter('post', 'val2')
.end(builder.streamWriter(process.stdout, { pretty: true, indent: '' } ))
eq(
hook.captured()
"""
<?xml version="1.0"?>
<!-- pre -->
<?pre val1?>
<root>
<xmlbuilder for="node-js">
<!-- CoffeeScript is awesome. -->
<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>
</xmlbuilder>
<cdata>
<![CDATA[<test att="val">this is a test</test>
Second line]]>
</cdata>
<raw>&<>&</raw>
<atttest att="val">text</atttest>
<atttest att="val">text</atttest>
</root>
<?post val2?>
<!-- post -->
"""
)
test 'Throw with unknown node types', ->
err(
() ->
root = xml('test4')
root.children.push(new String("Invalid node"))
root.end(builder.streamWriter(process.stdout))
Error
"Unknown XML node type: String"
)
err(
() ->
dtd = xml('test4').dtd()
dtd.children.push(new String("Invalid DTD node"))
dtd.end(builder.streamWriter(process.stdout))
Error
"Unknown DTD node type: String"
)
test 'Skipp null nodes', ->
xml('root', { headless:true })
.ele('nullnode', null)
.up()
.ele('data')
.end(builder.streamWriter(process.stdout))
eq(
hook.captured()
'<root>' +
'<data/>' +
'</root>'
)
| 18461 | suite 'Creating XML with stream writer:', ->
hook = null
setup 'hook stdout.write', ->
hook = captureStream(process.stdout)
return
teardown 'unhook stdout.write', ->
hook.unhook()
return
test 'Plain text writer', ->
xml('root')
.dtd('hello.dtd', 'sys')
.ins('pub_border', 'thin')
.ele('img', 'EMPTY')
.com('Image attributes follow')
.att('img', 'height', 'CDATA', '#REQUIRED')
.att('img', 'visible', '(yes|no)', '#DEFAULT', "yes")
.not('fs', { sysID: 'http://my.fs.com/reader' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0', sysID: 'http://my.fs.com/reader' })
.att('img', 'src', 'NOTATION (fs|fs-nt)', '#REQUIRED')
.dat('<owner><NAME></owner>')
.ele('node')
.ent('ent', 'my val')
.ent('ent', { sysID: 'http://www.myspec.com/ent' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ent('ent', { sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.pent('ent', 'my val')
.pent('ent', { sysID: 'http://www.myspec.com/ent' })
.pent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ele('nodearr', ['a', 'b'])
.root()
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.end(builder.streamWriter(process.stdout))
eq(
hook.captured()
'<?xml version="1.0"?>' +
'<!DOCTYPE root PUBLIC "hello.dtd" "sys" [' +
'<?pub_border thin?>' +
'<!ELEMENT img EMPTY>' +
'<!-- Image attributes follow -->' +
'<!ATTLIST img height CDATA #REQUIRED>' +
'<!ATTLIST img visible (yes|no) "yes">' +
'<!NOTATION fs SYSTEM "http://my.fs.com/reader">' +
'<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0">' +
'<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0" "http://my.fs.com/reader">' +
'<!ATTLIST img src NOTATION (fs|fs-nt) #REQUIRED>' +
'<![CDATA[<owner><NAME></owner>]]>' +
'<!ELEMENT node (#PCDATA)>' +
'<!ENTITY ent "my val">' +
'<!ENTITY ent SYSTEM "http://www.myspec.com/ent">' +
'<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">' +
'<!ENTITY ent SYSTEM "http://www.myspec.com/ent" NDATA entprg>' +
'<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent" NDATA entprg>' +
'<!ENTITY % ent "my val">' +
'<!ENTITY % ent SYSTEM "http://www.myspec.com/ent">' +
'<!ENTITY % ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">' +
'<!ELEMENT nodearr (a,b)>' +
']>' +
'<root>' +
'<xmlbuilder for="node-js">' +
'<!-- CoffeeScript is awesome. -->' +
'<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>' +
'</xmlbuilder>' +
'<cdata><![CDATA[<test att="val">this is a test</test>\nSecond line]]></cdata>' +
'<raw>&<>&</raw>' +
'<atttest att="val">text</atttest>' +
'<atttest att="val">text</atttest>' +
'</root>'
)
test 'Pretty printing', ->
xml('root')
.dtd('hello.dtd')
.ins('pub_border', 'thin')
.ele('img', 'EMPTY')
.com('Image attributes follow')
.att('img', 'height', 'CDATA', '#REQUIRED')
.att('img', 'visible', '(yes|no)', '#DEFAULT', "yes")
.not('fs', { sysID: 'http://my.fs.com/reader' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0', sysID: 'http://my.fs.com/reader' })
.att('img', 'src', 'NOTATION (fs|fs-nt)', '#REQUIRED')
.dat('<owner>John</owner>')
.ele('node')
.ent('ent', 'my val')
.ent('ent', { sysID: 'http://www.myspec.com/ent' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ent('ent', { sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.pent('ent', 'my val')
.pent('ent', { sysID: 'http://www.myspec.com/ent' })
.pent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ele('nodearr', ['a', 'b'])
.root()
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.ins('target', 'val')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.up()
.ele('empty')
.end(builder.streamWriter(process.stdout, { pretty: true, allowEmpty: true, indent: ' ' } ))
eq(
hook.captured()
"""
<?xml version="1.0"?>
<!DOCTYPE root SYSTEM "hello.dtd" [
<?pub_border thin?>
<!ELEMENT img EMPTY>
<!-- Image attributes follow -->
<!ATTLIST img height CDATA #REQUIRED>
<!ATTLIST img visible (yes|no) "yes">
<!NOTATION fs SYSTEM "http://my.fs.com/reader">
<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0">
<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0" "http://my.fs.com/reader">
<!ATTLIST img src NOTATION (fs|fs-nt) #REQUIRED>
<![CDATA[<owner><NAME></owner>]]>
<!ELEMENT node (#PCDATA)>
<!ENTITY ent "my val">
<!ENTITY ent SYSTEM "http://www.myspec.com/ent">
<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">
<!ENTITY ent SYSTEM "http://www.myspec.com/ent" NDATA entprg>
<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent" NDATA entprg>
<!ENTITY % ent "my val">
<!ENTITY % ent SYSTEM "http://www.myspec.com/ent">
<!ENTITY % ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">
<!ELEMENT nodearr (a,b)>
]>
<root>
<xmlbuilder for="node-js">
<!-- CoffeeScript is awesome. -->
<repo type="git">
git://github.com/oozcitak/xmlbuilder-js.git
<?target val?>
</repo>
</xmlbuilder>
<cdata>
<![CDATA[<test att="val">this is a test</test>
Second line]]>
</cdata>
<raw>&<>&</raw>
<atttest att="val">text</atttest>
<atttest att="val">text</atttest>
<empty></empty>
</root>
"""
)
test 'Pretty printing with offset', ->
xml('root')
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.end(builder.streamWriter(process.stdout, { pretty: true, indent: ' ', offset : 1 } ))
eq(
hook.captured()
"""
TEMPORARY_INDENT
<?xml version="1.0"?>
<root>
<xmlbuilder for="node-js">
<!-- CoffeeScript is awesome. -->
<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>
</xmlbuilder>
<cdata>
<![CDATA[<test att="val">this is a test</test>
Second line]]>
</cdata>
<raw>&<>&</raw>
<atttest att="val">text</atttest>
<atttest att="val">text</atttest>
</root>
""".replace(
///
TEMPORARY_INDENT\n
///
''
) #Heredoc format indenting is based on the first non-whitespace character, so we add extra, then replace it
)
test 'Pretty printing with empty indent', ->
xml('root')
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.root()
.commentBefore('pre').commentAfter('post')
.instructionBefore('pre' ,'val1').instructionAfter('post', 'val2')
.end(builder.streamWriter(process.stdout, { pretty: true, indent: '' } ))
eq(
hook.captured()
"""
<?xml version="1.0"?>
<!-- pre -->
<?pre val1?>
<root>
<xmlbuilder for="node-js">
<!-- CoffeeScript is awesome. -->
<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>
</xmlbuilder>
<cdata>
<![CDATA[<test att="val">this is a test</test>
Second line]]>
</cdata>
<raw>&<>&</raw>
<atttest att="val">text</atttest>
<atttest att="val">text</atttest>
</root>
<?post val2?>
<!-- post -->
"""
)
test 'Throw with unknown node types', ->
err(
() ->
root = xml('test4')
root.children.push(new String("Invalid node"))
root.end(builder.streamWriter(process.stdout))
Error
"Unknown XML node type: String"
)
err(
() ->
dtd = xml('test4').dtd()
dtd.children.push(new String("Invalid DTD node"))
dtd.end(builder.streamWriter(process.stdout))
Error
"Unknown DTD node type: String"
)
test 'Skipp null nodes', ->
xml('root', { headless:true })
.ele('nullnode', null)
.up()
.ele('data')
.end(builder.streamWriter(process.stdout))
eq(
hook.captured()
'<root>' +
'<data/>' +
'</root>'
)
| true | suite 'Creating XML with stream writer:', ->
hook = null
setup 'hook stdout.write', ->
hook = captureStream(process.stdout)
return
teardown 'unhook stdout.write', ->
hook.unhook()
return
test 'Plain text writer', ->
xml('root')
.dtd('hello.dtd', 'sys')
.ins('pub_border', 'thin')
.ele('img', 'EMPTY')
.com('Image attributes follow')
.att('img', 'height', 'CDATA', '#REQUIRED')
.att('img', 'visible', '(yes|no)', '#DEFAULT', "yes")
.not('fs', { sysID: 'http://my.fs.com/reader' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0', sysID: 'http://my.fs.com/reader' })
.att('img', 'src', 'NOTATION (fs|fs-nt)', '#REQUIRED')
.dat('<owner>PI:NAME:<NAME>END_PI</owner>')
.ele('node')
.ent('ent', 'my val')
.ent('ent', { sysID: 'http://www.myspec.com/ent' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ent('ent', { sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.pent('ent', 'my val')
.pent('ent', { sysID: 'http://www.myspec.com/ent' })
.pent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ele('nodearr', ['a', 'b'])
.root()
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.end(builder.streamWriter(process.stdout))
eq(
hook.captured()
'<?xml version="1.0"?>' +
'<!DOCTYPE root PUBLIC "hello.dtd" "sys" [' +
'<?pub_border thin?>' +
'<!ELEMENT img EMPTY>' +
'<!-- Image attributes follow -->' +
'<!ATTLIST img height CDATA #REQUIRED>' +
'<!ATTLIST img visible (yes|no) "yes">' +
'<!NOTATION fs SYSTEM "http://my.fs.com/reader">' +
'<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0">' +
'<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0" "http://my.fs.com/reader">' +
'<!ATTLIST img src NOTATION (fs|fs-nt) #REQUIRED>' +
'<![CDATA[<owner>PI:NAME:<NAME>END_PI</owner>]]>' +
'<!ELEMENT node (#PCDATA)>' +
'<!ENTITY ent "my val">' +
'<!ENTITY ent SYSTEM "http://www.myspec.com/ent">' +
'<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">' +
'<!ENTITY ent SYSTEM "http://www.myspec.com/ent" NDATA entprg>' +
'<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent" NDATA entprg>' +
'<!ENTITY % ent "my val">' +
'<!ENTITY % ent SYSTEM "http://www.myspec.com/ent">' +
'<!ENTITY % ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">' +
'<!ELEMENT nodearr (a,b)>' +
']>' +
'<root>' +
'<xmlbuilder for="node-js">' +
'<!-- CoffeeScript is awesome. -->' +
'<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>' +
'</xmlbuilder>' +
'<cdata><![CDATA[<test att="val">this is a test</test>\nSecond line]]></cdata>' +
'<raw>&<>&</raw>' +
'<atttest att="val">text</atttest>' +
'<atttest att="val">text</atttest>' +
'</root>'
)
test 'Pretty printing', ->
xml('root')
.dtd('hello.dtd')
.ins('pub_border', 'thin')
.ele('img', 'EMPTY')
.com('Image attributes follow')
.att('img', 'height', 'CDATA', '#REQUIRED')
.att('img', 'visible', '(yes|no)', '#DEFAULT', "yes")
.not('fs', { sysID: 'http://my.fs.com/reader' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0' })
.not('fs-nt', { pubID: 'FS Network Reader 1.0', sysID: 'http://my.fs.com/reader' })
.att('img', 'src', 'NOTATION (fs|fs-nt)', '#REQUIRED')
.dat('<owner>John</owner>')
.ele('node')
.ent('ent', 'my val')
.ent('ent', { sysID: 'http://www.myspec.com/ent' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ent('ent', { sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.ent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent', nData: 'entprg' })
.pent('ent', 'my val')
.pent('ent', { sysID: 'http://www.myspec.com/ent' })
.pent('ent', { pubID: '-//MY//SPEC ENT//EN', sysID: 'http://www.myspec.com/ent' })
.ele('nodearr', ['a', 'b'])
.root()
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.ins('target', 'val')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.up()
.ele('empty')
.end(builder.streamWriter(process.stdout, { pretty: true, allowEmpty: true, indent: ' ' } ))
eq(
hook.captured()
"""
<?xml version="1.0"?>
<!DOCTYPE root SYSTEM "hello.dtd" [
<?pub_border thin?>
<!ELEMENT img EMPTY>
<!-- Image attributes follow -->
<!ATTLIST img height CDATA #REQUIRED>
<!ATTLIST img visible (yes|no) "yes">
<!NOTATION fs SYSTEM "http://my.fs.com/reader">
<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0">
<!NOTATION fs-nt PUBLIC "FS Network Reader 1.0" "http://my.fs.com/reader">
<!ATTLIST img src NOTATION (fs|fs-nt) #REQUIRED>
<![CDATA[<owner>PI:NAME:<NAME>END_PI</owner>]]>
<!ELEMENT node (#PCDATA)>
<!ENTITY ent "my val">
<!ENTITY ent SYSTEM "http://www.myspec.com/ent">
<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">
<!ENTITY ent SYSTEM "http://www.myspec.com/ent" NDATA entprg>
<!ENTITY ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent" NDATA entprg>
<!ENTITY % ent "my val">
<!ENTITY % ent SYSTEM "http://www.myspec.com/ent">
<!ENTITY % ent PUBLIC "-//MY//SPEC ENT//EN" "http://www.myspec.com/ent">
<!ELEMENT nodearr (a,b)>
]>
<root>
<xmlbuilder for="node-js">
<!-- CoffeeScript is awesome. -->
<repo type="git">
git://github.com/oozcitak/xmlbuilder-js.git
<?target val?>
</repo>
</xmlbuilder>
<cdata>
<![CDATA[<test att="val">this is a test</test>
Second line]]>
</cdata>
<raw>&<>&</raw>
<atttest att="val">text</atttest>
<atttest att="val">text</atttest>
<empty></empty>
</root>
"""
)
test 'Pretty printing with offset', ->
xml('root')
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.end(builder.streamWriter(process.stdout, { pretty: true, indent: ' ', offset : 1 } ))
eq(
hook.captured()
"""
TEMPORARY_INDENT
<?xml version="1.0"?>
<root>
<xmlbuilder for="node-js">
<!-- CoffeeScript is awesome. -->
<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>
</xmlbuilder>
<cdata>
<![CDATA[<test att="val">this is a test</test>
Second line]]>
</cdata>
<raw>&<>&</raw>
<atttest att="val">text</atttest>
<atttest att="val">text</atttest>
</root>
""".replace(
///
TEMPORARY_INDENT\n
///
''
) #Heredoc format indenting is based on the first non-whitespace character, so we add extra, then replace it
)
test 'Pretty printing with empty indent', ->
xml('root')
.ele('xmlbuilder', {'for': 'node-js' })
.com('CoffeeScript is awesome.')
.nod('repo', {'type': 'git'}, 'git://github.com/oozcitak/xmlbuilder-js.git')
.up()
.up()
.ele('cdata')
.cdata('<test att="val">this is a test</test>\nSecond line')
.up()
.ele('raw')
.raw('&<>&')
.up()
.ele('atttest', { 'att': 'val' }, 'text')
.up()
.ele('atttest', 'text')
.att('att', () -> 'val')
.root()
.commentBefore('pre').commentAfter('post')
.instructionBefore('pre' ,'val1').instructionAfter('post', 'val2')
.end(builder.streamWriter(process.stdout, { pretty: true, indent: '' } ))
eq(
hook.captured()
"""
<?xml version="1.0"?>
<!-- pre -->
<?pre val1?>
<root>
<xmlbuilder for="node-js">
<!-- CoffeeScript is awesome. -->
<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>
</xmlbuilder>
<cdata>
<![CDATA[<test att="val">this is a test</test>
Second line]]>
</cdata>
<raw>&<>&</raw>
<atttest att="val">text</atttest>
<atttest att="val">text</atttest>
</root>
<?post val2?>
<!-- post -->
"""
)
test 'Throw with unknown node types', ->
err(
() ->
root = xml('test4')
root.children.push(new String("Invalid node"))
root.end(builder.streamWriter(process.stdout))
Error
"Unknown XML node type: String"
)
err(
() ->
dtd = xml('test4').dtd()
dtd.children.push(new String("Invalid DTD node"))
dtd.end(builder.streamWriter(process.stdout))
Error
"Unknown DTD node type: String"
)
test 'Skipp null nodes', ->
xml('root', { headless:true })
.ele('nullnode', null)
.up()
.ele('data')
.end(builder.streamWriter(process.stdout))
eq(
hook.captured()
'<root>' +
'<data/>' +
'</root>'
)
|
[
{
"context": "}, big_secret: 'SHHH'}\n ]\n [{password: 'pwd'}, {password: '[REDACTED]'}]\n [\n {b: ",
"end": 502,
"score": 0.9987567663192749,
"start": 499,
"tag": "PASSWORD",
"value": "pwd"
},
{
"context": "'}\n ]\n [{password: 'pwd'}, {password: '[RE... | test/loofah.coffee | Clever/loofah | 4 | _ = require 'underscore'
assert = require 'assert'
os = require 'os'
Scrubbers = require ("#{__dirname}/../lib/loofah")
user_scrub = (keywords) ->
return (object) ->
_.omit object, 'omit_this_key'
describe 'Loofah', ->
describe 'object_keys', ->
_.each [
[{a: 'non sensitive'}, {a: 'non sensitive'}]
[
{b: {secret:'shhh', c: 'non sensitive'}, big_secret: 'SHHH'}
{b: {secret:'[REDACTED]', c: 'non sensitive'}, big_secret: 'SHHH'}
]
[{password: 'pwd'}, {password: '[REDACTED]'}]
[
{b: [{secret:['shhh'], c: ['non sensitive']}], big_secret: 'SHHH'}
{b: [{secret:['[REDACTED]'], c: ['non sensitive']}], big_secret: 'SHHH'}
]
[
{secret:[{b: [{a:[['shhh']]}]}]}
{secret:[{b: [{a:[['[REDACTED]']]}]}]}
]
], ([input, output]) ->
it 'scrubs keys with banned names', ->
assert.deepEqual (Scrubbers.object_keys(['secret', 'password']) input), output
_.each ['string', 2, undefined, null], (value) ->
it 'if not given an object, returns what it was given', ->
assert.equal (Scrubbers.object_keys(['secret', 'password']) value), value
describe 'substrings', ->
_.each [
[{a: 'a string of text contains thisIsOurApiKey'}, {a: 'a string of text contains [REDACTED]'}]
[{b: 'a string of text contains thisisourapikey'}, {b: 'a string of text contains thisisourapikey'}]
[{c: 'thisIsOurApiKeythisIsOurApiKeythisIsOurApiKey'}, {c: '[REDACTED][REDACTED][REDACTED]'}]
['thisIsOurApiKeythisIsOurApiKeythisIsOurApiKey', '[REDACTED][REDACTED][REDACTED]']
], ([input, output]) ->
it 'scrubs banned values in strings and objects', ->
assert.deepEqual (Scrubbers.substrings(['thisIsOurApiKey']) input), output
_.each [2, undefined, null], (value) ->
it 'if not given an object or string, returns what it was given', ->
assert.equal (Scrubbers.substrings(['some', 'kwargs']) value), value
describe 'url_query_params', ->
_.each [
[
{url: 'refresh_token=1234567890asdfghjkl&CliENT_Id=123456789.apps.googleusercontent.com&client_secret=123456789asdfghjkl&grant_type=refresh_token'}
{url: 'refresh_token=[REDACTED]&CliENT_Id=[REDACTED].apps.googleusercontent.com&client_secret=[REDACTED]&grant_type=refresh_token'}
]
[
'refresh_token=1234567890asdfghjkl&CliENT_Id=123456789.apps.googleusercontent.com&client_secret=123456789asdfghjkl&grant_type=refresh_token'
'refresh_token=[REDACTED]&CliENT_Id=[REDACTED].apps.googleusercontent.com&client_secret=[REDACTED]&grant_type=refresh_token'
]
], ([input, output]) ->
it 'replaces sensitive url encoded info in strings and objects with [REDACTED]', ->
assert.deepEqual (Scrubbers.url_query_params([/client_*/i, 'refresh_token']) input), output
_.each ['this username NAME is in a string', 2, undefined, null], (value) ->
it 'if not given a url, returns what it was given', ->
assert.deepEqual (Scrubbers.url_query_params(['username']) value), value
describe 'key_value_pairs', ->
_.each [
['Error: something went wrong', 'Error: something went wrong']
['Error: Username 12345@example.com was taken', 'Error: Username [REDACTED] was taken']
['Error: thisUsernames 12345@example.com was taken', 'Error: thisUsernames 12345@example.com was taken']
['username 12345@example.com was taken', 'username [REDACTED] was taken']
['Error: Username 12345@example.com', 'Error: Username [REDACTED]']
['Error: Username = 12345@example.com', 'Error: Username = [REDACTED]']
['Error: Username', 'Error: Username']
[{a:'Error: Username 12345@example.com'}, {a:'Error: Username [REDACTED]'}]
], ([input, output]) ->
it 'replaces sensitive data in plain text with [REDACTED]', ->
assert.deepEqual (Scrubbers.key_value_pairs(['username']) input), output
_.each [2, undefined, null], (value) ->
it 'if not given an object or string, returns what it was given', ->
assert.equal (Scrubbers.key_value_pairs(['username']) value), value
it 'allows you to specify delimiters', ->
assert.equal (Scrubbers.key_value_pairs(['username'], ['_']) 'username_NAME'), 'username_[REDACTED]'
describe 'error objects', ->
class CustomError extends Error
constructor: (@message, @custom = 'nada') ->
class StackError extends Error
constructor: (@message) -> Error.captureStackTrace @, arguments.callee
_.each [Error, CustomError, StackError], (ErrorClass) ->
_.each ['message', 'new_field'], (field) ->
it "correctly scrubs the #{field} in instances of #{ErrorClass.name}", ->
err = new ErrorClass 'test error'
orig_val = 'email 123454@example.com failed'
err[field] = orig_val
output = (Scrubbers.key_value_pairs(['email']) err)
assert.equal output[field], 'email [REDACTED] failed'
assert.equal err[field], orig_val
assert.notEqual output, err # Expect a copy, not the original object itself
assert.deepEqual _.omit(output, field), _.omit(err, field)
assert.equal output.stack, Scrubbers.key_value_pairs(['email']) output.stack
assert output instanceof Error
assert output instanceof ErrorClass
_.each [
input: {a: new Error('email 12345@example.com failed')}
expected: {a: new Error('email [REDACTED] failed')}
,
input: ['email xyz', new Error('email 12345@example.com failed')]
expected: ['email [REDACTED]', new Error('email [REDACTED] failed')]
], ({input, expected}) ->
it 'correctly deals with error objects embedded in other objects', ->
assert.deepEqual (Scrubbers.key_value_pairs(['email']) input), expected
describe 'composition and extension', ->
_.each [
[{user:'name'}, {user:'[REDACTED]'}]
[{id:'number'}, {id:'number'}]
[{a:'user'}, {a:'user'}]
[{b:'id 1234'}, {b:'id [REDACTED]'}]
[{c:'someurl?id=12345&user=name'}, {c:'someurl?id=[REDACTED]&user=name'}]
], ([input, output]) ->
it 'allows different illegal words for different functions', ->
scrub = _.compose(Scrubbers.key_value_pairs(['id']), Scrubbers.object_keys(['user']), Scrubbers.url_query_params(['id']),)
assert.deepEqual scrub(input), output
_.each [
[Scrubbers.object_keys(), {password: 'pwd', a: 'password'}, {password: '[REDACTED]', a: 'password'}]
[Scrubbers.key_value_pairs(), 'user NAME is taken', 'user [REDACTED] is taken']
[Scrubbers.url_query_params(), 'www.example.com/?client_id=abc&client_secret=123'
,'www.example.com/?client_id=[REDACTED]&client_secret=[REDACTED]']
], ([func, input, output]) ->
it 'has default args when none are given', ->
assert.deepEqual func(input), output
_.each [
[[{password: 'pwd'}, {secret: 'sth'}], [{password: '[REDACTED]'}, {secret: '[REDACTED]'}]]
[
{url: 'refresh_token=1234512345a&client_id=someid&client_secret=somethingelse'}
{url: 'refresh_token=[REDACTED]&client_id=[REDACTED]&client_secret=[REDACTED]'}
]
[{string: 'username = 12345@example.com'}, {string: 'username = [REDACTED]'}]
], ([input, output]) ->
it 'allows default composition', ->
assert.deepEqual (Scrubbers.default() input), output
_.each [
[{password: 'pwd'}, {password: '[REDACTED]'}]
[
{url: 'refresh_token=1234512345a&client_id=someid&client_secret=somethingelse'}
{url: 'refresh_token=[REDACTED]&client_id=[REDACTED]&client_secret=[REDACTED]'}
]
[{string: 'username = 12345@example.com'}, {string: 'username = [REDACTED]'}]
[{omit_this_key: 'val'}, {}]
], ([input, output]) ->
it 'allows user defined functions to be composed with default ones', ->
scrub = _.compose(Scrubbers.default(), user_scrub(['some', 'keywords']))
assert.deepEqual (scrub input), output
| 77227 | _ = require 'underscore'
assert = require 'assert'
os = require 'os'
Scrubbers = require ("#{__dirname}/../lib/loofah")
user_scrub = (keywords) ->
return (object) ->
_.omit object, 'omit_this_key'
describe 'Loofah', ->
describe 'object_keys', ->
_.each [
[{a: 'non sensitive'}, {a: 'non sensitive'}]
[
{b: {secret:'shhh', c: 'non sensitive'}, big_secret: 'SHHH'}
{b: {secret:'[REDACTED]', c: 'non sensitive'}, big_secret: 'SHHH'}
]
[{password: '<PASSWORD>'}, {password: '[<PASSWORD>]'}]
[
{b: [{secret:['shhh'], c: ['non sensitive']}], big_secret: 'SHHH'}
{b: [{secret:['[REDACTED]'], c: ['non sensitive']}], big_secret: 'SHHH'}
]
[
{secret:[{b: [{a:[['shhh']]}]}]}
{secret:[{b: [{a:[['[REDACTED]']]}]}]}
]
], ([input, output]) ->
it 'scrubs keys with banned names', ->
assert.deepEqual (Scrubbers.object_keys(['secret', 'password']) input), output
_.each ['string', 2, undefined, null], (value) ->
it 'if not given an object, returns what it was given', ->
assert.equal (Scrubbers.object_keys(['secret', 'password']) value), value
describe 'substrings', ->
_.each [
[{a: 'a string of text contains thisIsOurApiKey'}, {a: 'a string of text contains [REDACTED]'}]
[{b: 'a string of text contains thisisourapikey'}, {b: 'a string of text contains thisisourapikey'}]
[{c: 'thisIsOurApiKeythisIsOurApiKeythisIsOurApiKey'}, {c: '[REDACTED][REDACTED][REDACTED]'}]
['thisIsOurApiKeythisIsOurApiKeythisIsOurApiKey', '[REDACTED][REDACTED][REDACTED]']
], ([input, output]) ->
it 'scrubs banned values in strings and objects', ->
assert.deepEqual (Scrubbers.substrings(['thisIsOurApiKey']) input), output
_.each [2, undefined, null], (value) ->
it 'if not given an object or string, returns what it was given', ->
assert.equal (Scrubbers.substrings(['some', 'kwargs']) value), value
describe 'url_query_params', ->
_.each [
[
{url: 'refresh_token=<KEY>&CliENT_Id=123456789.apps.googleusercontent.com&client_secret=<KEY>&grant_type=refresh_token'}
{url: 'refresh_token=[REDACTED]&CliENT_Id=[REDACTED].apps.googleusercontent.com&client_secret=[REDACTED]&grant_type=refresh_token'}
]
[
'refresh_token=<KEY>&CliENT_Id=123456789.apps.googleusercontent.com&client_secret=<KEY>&grant_type=refresh_token'
'refresh_token=[REDACTED]&CliENT_Id=[REDACTED].apps.googleusercontent.com&client_secret=[REDACTED]&grant_type=refresh_token'
]
], ([input, output]) ->
it 'replaces sensitive url encoded info in strings and objects with [REDACTED]', ->
assert.deepEqual (Scrubbers.url_query_params([/client_*/i, 'refresh_token']) input), output
_.each ['this username NAME is in a string', 2, undefined, null], (value) ->
it 'if not given a url, returns what it was given', ->
assert.deepEqual (Scrubbers.url_query_params(['username']) value), value
describe 'key_value_pairs', ->
_.each [
['Error: something went wrong', 'Error: something went wrong']
['Error: Username <EMAIL> was taken', 'Error: Username [REDACTED] was taken']
['Error: thisUsernames <EMAIL> was taken', 'Error: thisUsernames <EMAIL> was taken']
['username <EMAIL> was taken', 'username [REDACTED] was taken']
['Error: Username <EMAIL>', 'Error: Username [REDACTED]']
['Error: Username = <EMAIL>', 'Error: Username = [REDACTED]']
['Error: Username', 'Error: Username']
[{a:'Error: Username <EMAIL>'}, {a:'Error: Username [REDACTED]'}]
], ([input, output]) ->
it 'replaces sensitive data in plain text with [REDACTED]', ->
assert.deepEqual (Scrubbers.key_value_pairs(['username']) input), output
_.each [2, undefined, null], (value) ->
it 'if not given an object or string, returns what it was given', ->
assert.equal (Scrubbers.key_value_pairs(['username']) value), value
it 'allows you to specify delimiters', ->
assert.equal (Scrubbers.key_value_pairs(['username'], ['_']) 'username_NAME'), 'username_[REDACTED]'
describe 'error objects', ->
class CustomError extends Error
constructor: (@message, @custom = 'nada') ->
class StackError extends Error
constructor: (@message) -> Error.captureStackTrace @, arguments.callee
_.each [Error, CustomError, StackError], (ErrorClass) ->
_.each ['message', 'new_field'], (field) ->
it "correctly scrubs the #{field} in instances of #{ErrorClass.name}", ->
err = new ErrorClass 'test error'
orig_val = 'email <EMAIL> failed'
err[field] = orig_val
output = (Scrubbers.key_value_pairs(['email']) err)
assert.equal output[field], 'email [REDACTED] failed'
assert.equal err[field], orig_val
assert.notEqual output, err # Expect a copy, not the original object itself
assert.deepEqual _.omit(output, field), _.omit(err, field)
assert.equal output.stack, Scrubbers.key_value_pairs(['email']) output.stack
assert output instanceof Error
assert output instanceof ErrorClass
_.each [
input: {a: new Error('email <EMAIL> failed')}
expected: {a: new Error('email [REDACTED] failed')}
,
input: ['email xyz', new Error('email <EMAIL> failed')]
expected: ['email [REDACTED]', new Error('email [REDACTED] failed')]
], ({input, expected}) ->
it 'correctly deals with error objects embedded in other objects', ->
assert.deepEqual (Scrubbers.key_value_pairs(['email']) input), expected
describe 'composition and extension', ->
_.each [
[{user:'name'}, {user:'[REDACTED]'}]
[{id:'number'}, {id:'number'}]
[{a:'user'}, {a:'user'}]
[{b:'id 1234'}, {b:'id [REDACTED]'}]
[{c:'someurl?id=12345&user=name'}, {c:'someurl?id=[REDACTED]&user=name'}]
], ([input, output]) ->
it 'allows different illegal words for different functions', ->
scrub = _.compose(Scrubbers.key_value_pairs(['id']), Scrubbers.object_keys(['user']), Scrubbers.url_query_params(['id']),)
assert.deepEqual scrub(input), output
_.each [
[Scrubbers.object_keys(), {password: '<PASSWORD>', a: 'password'}, {password: '[REDACTED]', a: 'password'}]
[Scrubbers.key_value_pairs(), 'user NAME is taken', 'user [REDACTED] is taken']
[Scrubbers.url_query_params(), 'www.example.com/?client_id=abc&client_secret=123'
,'www.example.com/?client_id=[REDACTED]&client_secret=[REDACTED]']
], ([func, input, output]) ->
it 'has default args when none are given', ->
assert.deepEqual func(input), output
_.each [
[[{password: '<PASSWORD>'}, {secret: 'sth'}], [{password: '[<PASSWORD>]'}, {secret: '[REDACTED]'}]]
[
{url: 'refresh_token=<PASSWORD>&client_id=someid&client_secret=somethingelse'}
{url: 'refresh_token=[REDACTED]&client_id=[REDACTED]&client_secret=[REDACTED]'}
]
[{string: 'username = <EMAIL>'}, {string: 'username = [REDACTED]'}]
], ([input, output]) ->
it 'allows default composition', ->
assert.deepEqual (Scrubbers.default() input), output
_.each [
[{password: '<PASSWORD>'}, {password: <PASSWORD>]'}]
[
{url: 'refresh_token=<PASSWORD>&client_id=someid&client_secret=somethingelse'}
{url: 'refresh_token=[REDACTED]&client_id=[REDACTED]&client_secret=[REDACTED]'}
]
[{string: 'username = <EMAIL>'}, {string: 'username = [REDACTED]'}]
[{omit_this_key: 'val'}, {}]
], ([input, output]) ->
it 'allows user defined functions to be composed with default ones', ->
scrub = _.compose(Scrubbers.default(), user_scrub(['some', 'keywords']))
assert.deepEqual (scrub input), output
| true | _ = require 'underscore'
assert = require 'assert'
os = require 'os'
Scrubbers = require ("#{__dirname}/../lib/loofah")
user_scrub = (keywords) ->
return (object) ->
_.omit object, 'omit_this_key'
describe 'Loofah', ->
describe 'object_keys', ->
_.each [
[{a: 'non sensitive'}, {a: 'non sensitive'}]
[
{b: {secret:'shhh', c: 'non sensitive'}, big_secret: 'SHHH'}
{b: {secret:'[REDACTED]', c: 'non sensitive'}, big_secret: 'SHHH'}
]
[{password: 'PI:PASSWORD:<PASSWORD>END_PI'}, {password: '[PI:PASSWORD:<PASSWORD>END_PI]'}]
[
{b: [{secret:['shhh'], c: ['non sensitive']}], big_secret: 'SHHH'}
{b: [{secret:['[REDACTED]'], c: ['non sensitive']}], big_secret: 'SHHH'}
]
[
{secret:[{b: [{a:[['shhh']]}]}]}
{secret:[{b: [{a:[['[REDACTED]']]}]}]}
]
], ([input, output]) ->
it 'scrubs keys with banned names', ->
assert.deepEqual (Scrubbers.object_keys(['secret', 'password']) input), output
_.each ['string', 2, undefined, null], (value) ->
it 'if not given an object, returns what it was given', ->
assert.equal (Scrubbers.object_keys(['secret', 'password']) value), value
describe 'substrings', ->
_.each [
[{a: 'a string of text contains thisIsOurApiKey'}, {a: 'a string of text contains [REDACTED]'}]
[{b: 'a string of text contains thisisourapikey'}, {b: 'a string of text contains thisisourapikey'}]
[{c: 'thisIsOurApiKeythisIsOurApiKeythisIsOurApiKey'}, {c: '[REDACTED][REDACTED][REDACTED]'}]
['thisIsOurApiKeythisIsOurApiKeythisIsOurApiKey', '[REDACTED][REDACTED][REDACTED]']
], ([input, output]) ->
it 'scrubs banned values in strings and objects', ->
assert.deepEqual (Scrubbers.substrings(['thisIsOurApiKey']) input), output
_.each [2, undefined, null], (value) ->
it 'if not given an object or string, returns what it was given', ->
assert.equal (Scrubbers.substrings(['some', 'kwargs']) value), value
describe 'url_query_params', ->
_.each [
[
{url: 'refresh_token=PI:KEY:<KEY>END_PI&CliENT_Id=123456789.apps.googleusercontent.com&client_secret=PI:KEY:<KEY>END_PI&grant_type=refresh_token'}
{url: 'refresh_token=[REDACTED]&CliENT_Id=[REDACTED].apps.googleusercontent.com&client_secret=[REDACTED]&grant_type=refresh_token'}
]
[
'refresh_token=PI:KEY:<KEY>END_PI&CliENT_Id=123456789.apps.googleusercontent.com&client_secret=PI:KEY:<KEY>END_PI&grant_type=refresh_token'
'refresh_token=[REDACTED]&CliENT_Id=[REDACTED].apps.googleusercontent.com&client_secret=[REDACTED]&grant_type=refresh_token'
]
], ([input, output]) ->
it 'replaces sensitive url encoded info in strings and objects with [REDACTED]', ->
assert.deepEqual (Scrubbers.url_query_params([/client_*/i, 'refresh_token']) input), output
_.each ['this username NAME is in a string', 2, undefined, null], (value) ->
it 'if not given a url, returns what it was given', ->
assert.deepEqual (Scrubbers.url_query_params(['username']) value), value
describe 'key_value_pairs', ->
_.each [
['Error: something went wrong', 'Error: something went wrong']
['Error: Username PI:EMAIL:<EMAIL>END_PI was taken', 'Error: Username [REDACTED] was taken']
['Error: thisUsernames PI:EMAIL:<EMAIL>END_PI was taken', 'Error: thisUsernames PI:EMAIL:<EMAIL>END_PI was taken']
['username PI:EMAIL:<EMAIL>END_PI was taken', 'username [REDACTED] was taken']
['Error: Username PI:EMAIL:<EMAIL>END_PI', 'Error: Username [REDACTED]']
['Error: Username = PI:EMAIL:<EMAIL>END_PI', 'Error: Username = [REDACTED]']
['Error: Username', 'Error: Username']
[{a:'Error: Username PI:EMAIL:<EMAIL>END_PI'}, {a:'Error: Username [REDACTED]'}]
], ([input, output]) ->
it 'replaces sensitive data in plain text with [REDACTED]', ->
assert.deepEqual (Scrubbers.key_value_pairs(['username']) input), output
_.each [2, undefined, null], (value) ->
it 'if not given an object or string, returns what it was given', ->
assert.equal (Scrubbers.key_value_pairs(['username']) value), value
it 'allows you to specify delimiters', ->
assert.equal (Scrubbers.key_value_pairs(['username'], ['_']) 'username_NAME'), 'username_[REDACTED]'
describe 'error objects', ->
class CustomError extends Error
constructor: (@message, @custom = 'nada') ->
class StackError extends Error
constructor: (@message) -> Error.captureStackTrace @, arguments.callee
_.each [Error, CustomError, StackError], (ErrorClass) ->
_.each ['message', 'new_field'], (field) ->
it "correctly scrubs the #{field} in instances of #{ErrorClass.name}", ->
err = new ErrorClass 'test error'
orig_val = 'email PI:EMAIL:<EMAIL>END_PI failed'
err[field] = orig_val
output = (Scrubbers.key_value_pairs(['email']) err)
assert.equal output[field], 'email [REDACTED] failed'
assert.equal err[field], orig_val
assert.notEqual output, err # Expect a copy, not the original object itself
assert.deepEqual _.omit(output, field), _.omit(err, field)
assert.equal output.stack, Scrubbers.key_value_pairs(['email']) output.stack
assert output instanceof Error
assert output instanceof ErrorClass
_.each [
input: {a: new Error('email PI:EMAIL:<EMAIL>END_PI failed')}
expected: {a: new Error('email [REDACTED] failed')}
,
input: ['email xyz', new Error('email PI:EMAIL:<EMAIL>END_PI failed')]
expected: ['email [REDACTED]', new Error('email [REDACTED] failed')]
], ({input, expected}) ->
it 'correctly deals with error objects embedded in other objects', ->
assert.deepEqual (Scrubbers.key_value_pairs(['email']) input), expected
describe 'composition and extension', ->
_.each [
[{user:'name'}, {user:'[REDACTED]'}]
[{id:'number'}, {id:'number'}]
[{a:'user'}, {a:'user'}]
[{b:'id 1234'}, {b:'id [REDACTED]'}]
[{c:'someurl?id=12345&user=name'}, {c:'someurl?id=[REDACTED]&user=name'}]
], ([input, output]) ->
it 'allows different illegal words for different functions', ->
scrub = _.compose(Scrubbers.key_value_pairs(['id']), Scrubbers.object_keys(['user']), Scrubbers.url_query_params(['id']),)
assert.deepEqual scrub(input), output
_.each [
[Scrubbers.object_keys(), {password: 'PI:PASSWORD:<PASSWORD>END_PI', a: 'password'}, {password: '[REDACTED]', a: 'password'}]
[Scrubbers.key_value_pairs(), 'user NAME is taken', 'user [REDACTED] is taken']
[Scrubbers.url_query_params(), 'www.example.com/?client_id=abc&client_secret=123'
,'www.example.com/?client_id=[REDACTED]&client_secret=[REDACTED]']
], ([func, input, output]) ->
it 'has default args when none are given', ->
assert.deepEqual func(input), output
_.each [
[[{password: 'PI:PASSWORD:<PASSWORD>END_PI'}, {secret: 'sth'}], [{password: '[PI:PASSWORD:<PASSWORD>END_PI]'}, {secret: '[REDACTED]'}]]
[
{url: 'refresh_token=PI:PASSWORD:<PASSWORD>END_PI&client_id=someid&client_secret=somethingelse'}
{url: 'refresh_token=[REDACTED]&client_id=[REDACTED]&client_secret=[REDACTED]'}
]
[{string: 'username = PI:EMAIL:<EMAIL>END_PI'}, {string: 'username = [REDACTED]'}]
], ([input, output]) ->
it 'allows default composition', ->
assert.deepEqual (Scrubbers.default() input), output
_.each [
[{password: 'PI:PASSWORD:<PASSWORD>END_PI'}, {password: PI:PASSWORD:<PASSWORD>END_PI]'}]
[
{url: 'refresh_token=PI:PASSWORD:<PASSWORD>END_PI&client_id=someid&client_secret=somethingelse'}
{url: 'refresh_token=[REDACTED]&client_id=[REDACTED]&client_secret=[REDACTED]'}
]
[{string: 'username = PI:EMAIL:<EMAIL>END_PI'}, {string: 'username = [REDACTED]'}]
[{omit_this_key: 'val'}, {}]
], ([input, output]) ->
it 'allows user defined functions to be composed with default ones', ->
scrub = _.compose(Scrubbers.default(), user_scrub(['some', 'keywords']))
assert.deepEqual (scrub input), output
|
[
{
"context": "verview Tests for no-empty-pattern rule.\n# @author Alberto Rodríguez\n###\n'use strict'\n\n#------------------------------",
"end": 81,
"score": 0.9998541474342346,
"start": 64,
"tag": "NAME",
"value": "Alberto Rodríguez"
}
] | src/tests/rules/no-empty-pattern.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-empty-pattern rule.
# @author Alberto Rodríguez
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-empty-pattern'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-empty-pattern', rule,
# Examples of code that should not trigger the rule
valid: [
'{a = {}} = foo'
'{a, b = {}} = foo'
'{a = []} = foo'
'({a = {}}) ->'
'({a = []}) ->'
'[a] = foo'
]
# Examples of code that should trigger the rule
invalid: [
code: '{} = foo'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '[] = foo'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
,
code: '{a: {}} = foo'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '{a, b: {}} = foo'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '{a: []} = foo'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
,
code: '({}) ->'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '([]) ->'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
,
code: 'foo = ({a: {}}) ->'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '({a: []}) ->'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
]
| 195363 | ###*
# @fileoverview Tests for no-empty-pattern rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-empty-pattern'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-empty-pattern', rule,
# Examples of code that should not trigger the rule
valid: [
'{a = {}} = foo'
'{a, b = {}} = foo'
'{a = []} = foo'
'({a = {}}) ->'
'({a = []}) ->'
'[a] = foo'
]
# Examples of code that should trigger the rule
invalid: [
code: '{} = foo'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '[] = foo'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
,
code: '{a: {}} = foo'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '{a, b: {}} = foo'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '{a: []} = foo'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
,
code: '({}) ->'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '([]) ->'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
,
code: 'foo = ({a: {}}) ->'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '({a: []}) ->'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
]
| true | ###*
# @fileoverview Tests for no-empty-pattern rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-empty-pattern'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-empty-pattern', rule,
# Examples of code that should not trigger the rule
valid: [
'{a = {}} = foo'
'{a, b = {}} = foo'
'{a = []} = foo'
'({a = {}}) ->'
'({a = []}) ->'
'[a] = foo'
]
# Examples of code that should trigger the rule
invalid: [
code: '{} = foo'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '[] = foo'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
,
code: '{a: {}} = foo'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '{a, b: {}} = foo'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '{a: []} = foo'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
,
code: '({}) ->'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '([]) ->'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
,
code: 'foo = ({a: {}}) ->'
errors: [
messageId: 'unexpected'
data: type: 'object'
type: 'ObjectPattern'
]
,
code: '({a: []}) ->'
errors: [
messageId: 'unexpected'
data: type: 'array'
type: 'ArrayPattern'
]
]
|
[
{
"context": "\n # root key used in settings \n @settingsKey = 'au-cmsinn'\n @plugins = plugins\n # currently loaded plugin",
"end": 1374,
"score": 0.9950805902481079,
"start": 1365,
"tag": "KEY",
"value": "au-cmsinn"
}
] | lib/service.coffee | arillo/au-cmsinn | 0 | if Meteor.isServer
jQuery = {}
# var subs = new SubsManager();
###*
# Storage public interface used by AuCmsInn internally
#
# @param adapter specialized implementation
###
Storage = (adapter) ->
@adapter = adapter
@collection = @adapter.collection
@hooks =
'beforeInsert': []
'beforeUpdate': []
'beforePublish': []
return
Storage::constructor = Storage
Storage::update = (selector, modifier, options, callback) ->
# Run pre-update hooks
_.each @hooks.beforeUpdate, (hook) ->
hook selector, modifier, options
return
@adapter.update selector, modifier, options, callback
return
Storage::insert = (doc, callback) ->
# Run pre-insert hooks
_.each @hooks.beforeInsert, (hook) ->
hook doc
return
@adapter.insert doc, callback
return
Storage::remove = (selector, options, callback) ->
@adapter.remove selector, options, callback
return
Storage::beforeInsert = (callback) ->
@hooks.beforeInsert.push callback
return
Storage::beforeUpdate = (callback) ->
@hooks.beforeUpdate.push callback
return
Storage::beforePublish = (callback) ->
@hooks.beforePublish.push callback
return
###*
# Main package
#
# @param plugins what plugins should be loaded
###
AuCmsInn = (plugins, jQuery) ->
@subsciptionName = 'au-cmsinn-content'
@jquery = jQuery
# root key used in settings
@settingsKey = 'au-cmsinn'
@plugins = plugins
# currently loaded plugin
@currentPlugin = null
@options =
storageAdapter: new RemoteCollectionStorageAdapter
plugins: {}
# on init subscribe to data
# if (Meteor.isClient) {
# this.subscribe();
# }
return
AuCmsInn::constructor = AuCmsInn
###*
# Configuration is loaded on client and server
# difference is that on server we also publish data
#
# We init plugins here, set storage, configure router
# and set settings
###
AuCmsInn::configure = (options) ->
self = this
options = options or {}
@options = @options or {}
_.extend @options, options
@storage = new Storage(@options.storageAdapter)
Log.debug 'storage collection count:', @storage.collection.find().count()
# Each plugin can define hooks and those will be loaded here
_.each self.plugins, (options, item) ->
if typeof self.plugins[item].hooks == 'object'
if self.plugins[item].hooks.beforeInsert
self.storage.beforeInsert self.plugins[item].hooks['beforeInsert']
if self.plugins[item].hooks.beforeUpdate
self.storage.beforeUpdate self.plugins[item].hooks['beforeUpdate']
if self.plugins[item].hooks.beforePublish
self.storage.beforePublish self.plugins[item].hooks['beforePublish']
return
# Log.debug('Router.configure', this.options);
# Router.configure(this.options);
_.each self.plugins, (options, item) ->
self.plugins[item].storage = self.storage
return
# // Set different template to be shown while data is being loaded
# if (this.options.loadingTemplate) {
# Router.configure({
# loadingTemplate: this.options.loadingTemplate
# });
# }
# // Set not found template
# if (this.options.notFoundTemplate) {
# Router.configure({
# notFoundTemplate: this.options.notFoundTemplate
# });
# }
# We got dependency here for router
# Settings defined in settings.json will be loaded here
# and passed to corresponding plugin
_.each @plugins, (plugin, item) ->
# REMARK: check if intended to access via public on client?
if Meteor.isClient
if _.isObject(Meteor.settings) and _.isObject(Meteor.settings.public) and _.isObject(Meteor.settings.public[self.settingsKey]) and _.has(Meteor.settings.public[self.settingsKey], item)
if !_.has(self.options.plugins, item)
self.options.plugins[item] = {}
_.extend self.options.plugins[item], Meteor.settings.public[self.settingsKey][item]
else
if _.isObject(Meteor.settings) and _.isObject(Meteor.settings[self.settingsKey]) and _.has(Meteor.settings[self.settingsKey], item)
if !_.has(self.options.plugins, item)
self.options.plugins[item] = {}
_.extend self.options.plugins[item], Meteor.settings[self.settingsKey][item]
if _.isUndefined(self.options.plugins[item])
self.options.plugins[item] = {}
Log.debug plugin.name, self.options.plugins[item]
plugin.config self.options.plugins[item]
return
if Meteor.isClient
@subscribe()
# publish after configuration is done, because we are waitting for roles
# that will define who can see what
if Meteor.isServer
Log.debug 'server publish'
@publish()
return
# When we subscribe to data change layout to main one
AuCmsInn::onStarted = ->
if @options and @options.layoutTemplate
Router.configure layoutTemplate: @options.layoutTemplate
return
# We init plugins when we got data
# for example navigation plugin needs to load routes into router
# that comes from db
AuCmsInn::subscribe = ->
self = this
Router.configure autoStart: false
init = ->
_.each self.plugins, (options, item) ->
if self.plugins[item].init != undefined
self.plugins[item].init()
return
self.onStarted()
# When everything is loaded start router
Router.start()
return
# we start Router manually because we have to load routes first
# subs.subscribe(this.subsciptionName, init);
Log.debug 'subscribe', @subsciptionName
Meteor.subscribe @subsciptionName, init
return
# Execute hooks before publishing
AuCmsInn::publish = ->
self = this
Meteor.publish @subsciptionName, ->
that = this
query = {}
options = {}
_.each self.storage.hooks.beforePublish, (hook) ->
hook query, options, that.userId
return
Log.info 'publish', self.subsciptionName, @connection.id
# Log.debug(query, options);
self.storage.collection.find query, options
return
# Toggle plugins and execute enable() method on plugin
AuCmsInn::enable = (plugin) ->
@currentPlugin = @plugins[plugin]
@currentPlugin.enable @jquery
return
# Disable
AuCmsInn::disable = ->
if @currentPlugin
@currentPlugin.disable @jquery
@currentPlugin = null
return
AuCmsInn::save = ->
if @currentPlugin and _.isFunction(@currentPlugin.save)
@currentPlugin.save()
return
###*
# Initialiaze
###
CmsInn = new AuCmsInn({
label: CmsInnLabel
navigation: CmsInnNavigation
image: CmsInnImage
record: CmsInnRecord
locale: CmsInnLocale
sortable: CmsInnSortable
deletable: CmsInnDeletable
versioning: CmsInnVersioning
rolesmanager: CmsInnRolesManager
settings: CmsInnSettings
}, jQuery)
Log.debug CmsInn | 140535 | if Meteor.isServer
jQuery = {}
# var subs = new SubsManager();
###*
# Storage public interface used by AuCmsInn internally
#
# @param adapter specialized implementation
###
Storage = (adapter) ->
@adapter = adapter
@collection = @adapter.collection
@hooks =
'beforeInsert': []
'beforeUpdate': []
'beforePublish': []
return
Storage::constructor = Storage
Storage::update = (selector, modifier, options, callback) ->
# Run pre-update hooks
_.each @hooks.beforeUpdate, (hook) ->
hook selector, modifier, options
return
@adapter.update selector, modifier, options, callback
return
Storage::insert = (doc, callback) ->
# Run pre-insert hooks
_.each @hooks.beforeInsert, (hook) ->
hook doc
return
@adapter.insert doc, callback
return
Storage::remove = (selector, options, callback) ->
@adapter.remove selector, options, callback
return
Storage::beforeInsert = (callback) ->
@hooks.beforeInsert.push callback
return
Storage::beforeUpdate = (callback) ->
@hooks.beforeUpdate.push callback
return
Storage::beforePublish = (callback) ->
@hooks.beforePublish.push callback
return
###*
# Main package
#
# @param plugins what plugins should be loaded
###
AuCmsInn = (plugins, jQuery) ->
@subsciptionName = 'au-cmsinn-content'
@jquery = jQuery
# root key used in settings
@settingsKey = '<KEY>'
@plugins = plugins
# currently loaded plugin
@currentPlugin = null
@options =
storageAdapter: new RemoteCollectionStorageAdapter
plugins: {}
# on init subscribe to data
# if (Meteor.isClient) {
# this.subscribe();
# }
return
AuCmsInn::constructor = AuCmsInn
###*
# Configuration is loaded on client and server
# difference is that on server we also publish data
#
# We init plugins here, set storage, configure router
# and set settings
###
AuCmsInn::configure = (options) ->
self = this
options = options or {}
@options = @options or {}
_.extend @options, options
@storage = new Storage(@options.storageAdapter)
Log.debug 'storage collection count:', @storage.collection.find().count()
# Each plugin can define hooks and those will be loaded here
_.each self.plugins, (options, item) ->
if typeof self.plugins[item].hooks == 'object'
if self.plugins[item].hooks.beforeInsert
self.storage.beforeInsert self.plugins[item].hooks['beforeInsert']
if self.plugins[item].hooks.beforeUpdate
self.storage.beforeUpdate self.plugins[item].hooks['beforeUpdate']
if self.plugins[item].hooks.beforePublish
self.storage.beforePublish self.plugins[item].hooks['beforePublish']
return
# Log.debug('Router.configure', this.options);
# Router.configure(this.options);
_.each self.plugins, (options, item) ->
self.plugins[item].storage = self.storage
return
# // Set different template to be shown while data is being loaded
# if (this.options.loadingTemplate) {
# Router.configure({
# loadingTemplate: this.options.loadingTemplate
# });
# }
# // Set not found template
# if (this.options.notFoundTemplate) {
# Router.configure({
# notFoundTemplate: this.options.notFoundTemplate
# });
# }
# We got dependency here for router
# Settings defined in settings.json will be loaded here
# and passed to corresponding plugin
_.each @plugins, (plugin, item) ->
# REMARK: check if intended to access via public on client?
if Meteor.isClient
if _.isObject(Meteor.settings) and _.isObject(Meteor.settings.public) and _.isObject(Meteor.settings.public[self.settingsKey]) and _.has(Meteor.settings.public[self.settingsKey], item)
if !_.has(self.options.plugins, item)
self.options.plugins[item] = {}
_.extend self.options.plugins[item], Meteor.settings.public[self.settingsKey][item]
else
if _.isObject(Meteor.settings) and _.isObject(Meteor.settings[self.settingsKey]) and _.has(Meteor.settings[self.settingsKey], item)
if !_.has(self.options.plugins, item)
self.options.plugins[item] = {}
_.extend self.options.plugins[item], Meteor.settings[self.settingsKey][item]
if _.isUndefined(self.options.plugins[item])
self.options.plugins[item] = {}
Log.debug plugin.name, self.options.plugins[item]
plugin.config self.options.plugins[item]
return
if Meteor.isClient
@subscribe()
# publish after configuration is done, because we are waitting for roles
# that will define who can see what
if Meteor.isServer
Log.debug 'server publish'
@publish()
return
# When we subscribe to data change layout to main one
AuCmsInn::onStarted = ->
if @options and @options.layoutTemplate
Router.configure layoutTemplate: @options.layoutTemplate
return
# We init plugins when we got data
# for example navigation plugin needs to load routes into router
# that comes from db
AuCmsInn::subscribe = ->
self = this
Router.configure autoStart: false
init = ->
_.each self.plugins, (options, item) ->
if self.plugins[item].init != undefined
self.plugins[item].init()
return
self.onStarted()
# When everything is loaded start router
Router.start()
return
# we start Router manually because we have to load routes first
# subs.subscribe(this.subsciptionName, init);
Log.debug 'subscribe', @subsciptionName
Meteor.subscribe @subsciptionName, init
return
# Execute hooks before publishing
AuCmsInn::publish = ->
self = this
Meteor.publish @subsciptionName, ->
that = this
query = {}
options = {}
_.each self.storage.hooks.beforePublish, (hook) ->
hook query, options, that.userId
return
Log.info 'publish', self.subsciptionName, @connection.id
# Log.debug(query, options);
self.storage.collection.find query, options
return
# Toggle plugins and execute enable() method on plugin
AuCmsInn::enable = (plugin) ->
@currentPlugin = @plugins[plugin]
@currentPlugin.enable @jquery
return
# Disable
AuCmsInn::disable = ->
if @currentPlugin
@currentPlugin.disable @jquery
@currentPlugin = null
return
AuCmsInn::save = ->
if @currentPlugin and _.isFunction(@currentPlugin.save)
@currentPlugin.save()
return
###*
# Initialiaze
###
CmsInn = new AuCmsInn({
label: CmsInnLabel
navigation: CmsInnNavigation
image: CmsInnImage
record: CmsInnRecord
locale: CmsInnLocale
sortable: CmsInnSortable
deletable: CmsInnDeletable
versioning: CmsInnVersioning
rolesmanager: CmsInnRolesManager
settings: CmsInnSettings
}, jQuery)
Log.debug CmsInn | true | if Meteor.isServer
jQuery = {}
# var subs = new SubsManager();
###*
# Storage public interface used by AuCmsInn internally
#
# @param adapter specialized implementation
###
Storage = (adapter) ->
@adapter = adapter
@collection = @adapter.collection
@hooks =
'beforeInsert': []
'beforeUpdate': []
'beforePublish': []
return
Storage::constructor = Storage
Storage::update = (selector, modifier, options, callback) ->
# Run pre-update hooks
_.each @hooks.beforeUpdate, (hook) ->
hook selector, modifier, options
return
@adapter.update selector, modifier, options, callback
return
Storage::insert = (doc, callback) ->
# Run pre-insert hooks
_.each @hooks.beforeInsert, (hook) ->
hook doc
return
@adapter.insert doc, callback
return
Storage::remove = (selector, options, callback) ->
@adapter.remove selector, options, callback
return
Storage::beforeInsert = (callback) ->
@hooks.beforeInsert.push callback
return
Storage::beforeUpdate = (callback) ->
@hooks.beforeUpdate.push callback
return
Storage::beforePublish = (callback) ->
@hooks.beforePublish.push callback
return
###*
# Main package
#
# @param plugins what plugins should be loaded
###
AuCmsInn = (plugins, jQuery) ->
@subsciptionName = 'au-cmsinn-content'
@jquery = jQuery
# root key used in settings
@settingsKey = 'PI:KEY:<KEY>END_PI'
@plugins = plugins
# currently loaded plugin
@currentPlugin = null
@options =
storageAdapter: new RemoteCollectionStorageAdapter
plugins: {}
# on init subscribe to data
# if (Meteor.isClient) {
# this.subscribe();
# }
return
AuCmsInn::constructor = AuCmsInn
###*
# Configuration is loaded on client and server
# difference is that on server we also publish data
#
# We init plugins here, set storage, configure router
# and set settings
###
AuCmsInn::configure = (options) ->
self = this
options = options or {}
@options = @options or {}
_.extend @options, options
@storage = new Storage(@options.storageAdapter)
Log.debug 'storage collection count:', @storage.collection.find().count()
# Each plugin can define hooks and those will be loaded here
_.each self.plugins, (options, item) ->
if typeof self.plugins[item].hooks == 'object'
if self.plugins[item].hooks.beforeInsert
self.storage.beforeInsert self.plugins[item].hooks['beforeInsert']
if self.plugins[item].hooks.beforeUpdate
self.storage.beforeUpdate self.plugins[item].hooks['beforeUpdate']
if self.plugins[item].hooks.beforePublish
self.storage.beforePublish self.plugins[item].hooks['beforePublish']
return
# Log.debug('Router.configure', this.options);
# Router.configure(this.options);
_.each self.plugins, (options, item) ->
self.plugins[item].storage = self.storage
return
# // Set different template to be shown while data is being loaded
# if (this.options.loadingTemplate) {
# Router.configure({
# loadingTemplate: this.options.loadingTemplate
# });
# }
# // Set not found template
# if (this.options.notFoundTemplate) {
# Router.configure({
# notFoundTemplate: this.options.notFoundTemplate
# });
# }
# We got dependency here for router
# Settings defined in settings.json will be loaded here
# and passed to corresponding plugin
_.each @plugins, (plugin, item) ->
# REMARK: check if intended to access via public on client?
if Meteor.isClient
if _.isObject(Meteor.settings) and _.isObject(Meteor.settings.public) and _.isObject(Meteor.settings.public[self.settingsKey]) and _.has(Meteor.settings.public[self.settingsKey], item)
if !_.has(self.options.plugins, item)
self.options.plugins[item] = {}
_.extend self.options.plugins[item], Meteor.settings.public[self.settingsKey][item]
else
if _.isObject(Meteor.settings) and _.isObject(Meteor.settings[self.settingsKey]) and _.has(Meteor.settings[self.settingsKey], item)
if !_.has(self.options.plugins, item)
self.options.plugins[item] = {}
_.extend self.options.plugins[item], Meteor.settings[self.settingsKey][item]
if _.isUndefined(self.options.plugins[item])
self.options.plugins[item] = {}
Log.debug plugin.name, self.options.plugins[item]
plugin.config self.options.plugins[item]
return
if Meteor.isClient
@subscribe()
# publish after configuration is done, because we are waitting for roles
# that will define who can see what
if Meteor.isServer
Log.debug 'server publish'
@publish()
return
# When we subscribe to data change layout to main one
AuCmsInn::onStarted = ->
if @options and @options.layoutTemplate
Router.configure layoutTemplate: @options.layoutTemplate
return
# We init plugins when we got data
# for example navigation plugin needs to load routes into router
# that comes from db
AuCmsInn::subscribe = ->
self = this
Router.configure autoStart: false
init = ->
_.each self.plugins, (options, item) ->
if self.plugins[item].init != undefined
self.plugins[item].init()
return
self.onStarted()
# When everything is loaded start router
Router.start()
return
# we start Router manually because we have to load routes first
# subs.subscribe(this.subsciptionName, init);
Log.debug 'subscribe', @subsciptionName
Meteor.subscribe @subsciptionName, init
return
# Execute hooks before publishing
AuCmsInn::publish = ->
self = this
Meteor.publish @subsciptionName, ->
that = this
query = {}
options = {}
_.each self.storage.hooks.beforePublish, (hook) ->
hook query, options, that.userId
return
Log.info 'publish', self.subsciptionName, @connection.id
# Log.debug(query, options);
self.storage.collection.find query, options
return
# Toggle plugins and execute enable() method on plugin
AuCmsInn::enable = (plugin) ->
@currentPlugin = @plugins[plugin]
@currentPlugin.enable @jquery
return
# Disable
AuCmsInn::disable = ->
if @currentPlugin
@currentPlugin.disable @jquery
@currentPlugin = null
return
AuCmsInn::save = ->
if @currentPlugin and _.isFunction(@currentPlugin.save)
@currentPlugin.save()
return
###*
# Initialiaze
###
CmsInn = new AuCmsInn({
label: CmsInnLabel
navigation: CmsInnNavigation
image: CmsInnImage
record: CmsInnRecord
locale: CmsInnLocale
sortable: CmsInnSortable
deletable: CmsInnDeletable
versioning: CmsInnVersioning
rolesmanager: CmsInnRolesManager
settings: CmsInnSettings
}, jQuery)
Log.debug CmsInn |
[
{
"context": "ext'/>)\n\n key = if globals.os is 'mac' then '⌘ + C' else 'Ctrl + C'\n\n expect(key).toEqual modal",
"end": 773,
"score": 0.9708335995674133,
"start": 768,
"tag": "KEY",
"value": "⌘ + C"
},
{
"context": " key = if globals.os is 'mac' then '⌘ + C' else 'Ctrl ... | client/app/lib/components/codeblock/test.coffee | ezgikaysi/koding | 1 | React = require 'kd-react'
expect = require 'expect'
globals = require 'globals'
CodeBlock = require './index'
TestUtils = require 'react-addons-test-utils'
describe 'CodeBlock', ->
{ Simulate, renderIntoDocument } = TestUtils
describe '::render', ->
it 'checks rendered modal prop type', ->
modal = renderIntoDocument(<CodeBlock cmd='copy this text'/>)
expect(modal.props.cmd).toBeA 'string'
it 'should render correct code block and key', ->
modal = renderIntoDocument(<CodeBlock cmd='copy this text'/>)
expect(modal.refs.codeblock.innerHTML).toEqual 'copy this text'
it 'should render correct key', ->
modal = renderIntoDocument(<CodeBlock cmd='copy this text'/>)
key = if globals.os is 'mac' then '⌘ + C' else 'Ctrl + C'
expect(key).toEqual modal.state.key
| 143311 | React = require 'kd-react'
expect = require 'expect'
globals = require 'globals'
CodeBlock = require './index'
TestUtils = require 'react-addons-test-utils'
describe 'CodeBlock', ->
{ Simulate, renderIntoDocument } = TestUtils
describe '::render', ->
it 'checks rendered modal prop type', ->
modal = renderIntoDocument(<CodeBlock cmd='copy this text'/>)
expect(modal.props.cmd).toBeA 'string'
it 'should render correct code block and key', ->
modal = renderIntoDocument(<CodeBlock cmd='copy this text'/>)
expect(modal.refs.codeblock.innerHTML).toEqual 'copy this text'
it 'should render correct key', ->
modal = renderIntoDocument(<CodeBlock cmd='copy this text'/>)
key = if globals.os is 'mac' then '<KEY>' else '<KEY>'
expect(key).toEqual modal.state.key
| true | React = require 'kd-react'
expect = require 'expect'
globals = require 'globals'
CodeBlock = require './index'
TestUtils = require 'react-addons-test-utils'
describe 'CodeBlock', ->
{ Simulate, renderIntoDocument } = TestUtils
describe '::render', ->
it 'checks rendered modal prop type', ->
modal = renderIntoDocument(<CodeBlock cmd='copy this text'/>)
expect(modal.props.cmd).toBeA 'string'
it 'should render correct code block and key', ->
modal = renderIntoDocument(<CodeBlock cmd='copy this text'/>)
expect(modal.refs.codeblock.innerHTML).toEqual 'copy this text'
it 'should render correct key', ->
modal = renderIntoDocument(<CodeBlock cmd='copy this text'/>)
key = if globals.os is 'mac' then 'PI:KEY:<KEY>END_PI' else 'PI:KEY:<KEY>END_PI'
expect(key).toEqual modal.state.key
|
[
{
"context": "// noise functions.\n// Author : Ian McEwan, Ashima Arts.\n// Maintainer : ijm\n// Lastmod",
"end": 163,
"score": 0.9998944997787476,
"start": 153,
"tag": "NAME",
"value": "Ian McEwan"
},
{
"context": " noise functions.\n// Author : Ian ... | shaders/NoiseShader.coffee | anandprabhakar0507/Kosmos | 46 | _common = """precision highp float;
//
// Description : Array and textureless GLSL 2D/3D/4D simplex
// noise functions.
// Author : Ian McEwan, Ashima Arts.
// Maintainer : ijm
// Lastmod : 20110822 (ijm)
// License : Copyright (C) 2011 Ashima Arts. All rights reserved.
// Distributed under the MIT License. See LICENSE file.
// https://github.com/ashima/webgl-noise
//
vec2 mod289(vec2 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec3 mod289(vec3 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec4 mod289(vec4 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec3 permute(vec3 x) {
return mod289(((x*34.0)+1.0)*x);
}
vec4 permute(vec4 x) {
return mod289(((x*34.0)+1.0)*x);
}
vec4 taylorInvSqrt(vec4 r)
{
return 1.79284291400159 - 0.85373472095314 * r;
}
"""
xgl.commonNoiseShaderSource3 = _common + """
float snoise(vec3 v)
{
const vec2 C = vec2(1.0/6.0, 1.0/3.0) ;
const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
// First corner
vec3 i = floor(v + dot(v, C.yyy) );
vec3 x0 = v - i + dot(i, C.xxx) ;
// Other corners
vec3 g = step(x0.yzx, x0.xyz);
vec3 l = 1.0 - g;
vec3 i1 = min( g.xyz, l.zxy );
vec3 i2 = max( g.xyz, l.zxy );
// x0 = x0 - 0.0 + 0.0 * C.xxx;
// x1 = x0 - i1 + 1.0 * C.xxx;
// x2 = x0 - i2 + 2.0 * C.xxx;
// x3 = x0 - 1.0 + 3.0 * C.xxx;
vec3 x1 = x0 - i1 + C.xxx;
vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y
vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y
// Permutations
i = mod289(i);
vec4 p = permute( permute( permute(
i.z + vec4(0.0, i1.z, i2.z, 1.0 ))
+ i.y + vec4(0.0, i1.y, i2.y, 1.0 ))
+ i.x + vec4(0.0, i1.x, i2.x, 1.0 ));
// Gradients: 7x7 points over a square, mapped onto an octahedron.
// The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
float n_ = 0.142857142857; // 1.0/7.0
vec3 ns = n_ * D.wyz - D.xzx;
vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)
vec4 x_ = floor(j * ns.z);
vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)
vec4 x = x_ *ns.x + ns.yyyy;
vec4 y = y_ *ns.x + ns.yyyy;
vec4 h = 1.0 - abs(x) - abs(y);
vec4 b0 = vec4( x.xy, y.xy );
vec4 b1 = vec4( x.zw, y.zw );
//vec4 s0 = vec4(lessThan(b0,0.0))*2.0 - 1.0;
//vec4 s1 = vec4(lessThan(b1,0.0))*2.0 - 1.0;
vec4 s0 = floor(b0)*2.0 + 1.0;
vec4 s1 = floor(b1)*2.0 + 1.0;
vec4 sh = -step(h, vec4(0.0));
vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;
vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;
vec3 p0 = vec3(a0.xy,h.x);
vec3 p1 = vec3(a0.zw,h.y);
vec3 p2 = vec3(a1.xy,h.z);
vec3 p3 = vec3(a1.zw,h.w);
//Normalise gradients
vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
// Mix final noise value
vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
m = m * m;
return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),
dot(p2,x2), dot(p3,x3) ) );
}
"""
xgl.commonNoiseShaderSource2 = _common + """
float snoise(vec2 v)
{
const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0
0.366025403784439, // 0.5*(sqrt(3.0)-1.0)
-0.577350269189626, // -1.0 + 2.0 * C.x
0.024390243902439); // 1.0 / 41.0
// First corner
vec2 i = floor(v + dot(v, C.yy) );
vec2 x0 = v - i + dot(i, C.xx);
// Other corners
vec2 i1;
//i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0
//i1.y = 1.0 - i1.x;
i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
// x0 = x0 - 0.0 + 0.0 * C.xx ;
// x1 = x0 - i1 + 1.0 * C.xx ;
// x2 = x0 - 1.0 + 2.0 * C.xx ;
vec4 x12 = x0.xyxy + C.xxzz;
x12.xy -= i1;
// Permutations
i = mod289(i); // Avoid truncation effects in permutation
vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 ))
+ i.x + vec3(0.0, i1.x, 1.0 ));
vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0);
m = m*m ;
m = m*m ;
// Gradients: 41 points uniformly over a line, mapped onto a diamond.
// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)
vec3 x = 2.0 * fract(p * C.www) - 1.0;
vec3 h = abs(x) - 0.5;
vec3 ox = floor(x + 0.5);
vec3 a0 = x - ox;
// Normalise gradients implicitly by scaling m
// Approximation of: m *= inversesqrt( a0*a0 + h*h );
m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h );
// Compute final noise value at P
vec3 g;
g.x = a0.x * x0.x + h.x * x0.y;
g.yz = a0.yz * x12.xz + h.yz * x12.yw;
return 130.0 * dot(m, g);
}
"""
| 167178 | _common = """precision highp float;
//
// Description : Array and textureless GLSL 2D/3D/4D simplex
// noise functions.
// Author : <NAME>, <NAME>.
// Maintainer : ijm
// Lastmod : 20110822 (ijm)
// License : Copyright (C) 2011 <NAME>ima Arts. All rights reserved.
// Distributed under the MIT License. See LICENSE file.
// https://github.com/ashima/webgl-noise
//
vec2 mod289(vec2 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec3 mod289(vec3 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec4 mod289(vec4 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec3 permute(vec3 x) {
return mod289(((x*34.0)+1.0)*x);
}
vec4 permute(vec4 x) {
return mod289(((x*34.0)+1.0)*x);
}
vec4 taylorInvSqrt(vec4 r)
{
return 1.79284291400159 - 0.85373472095314 * r;
}
"""
xgl.commonNoiseShaderSource3 = _common + """
float snoise(vec3 v)
{
const vec2 C = vec2(1.0/6.0, 1.0/3.0) ;
const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
// First corner
vec3 i = floor(v + dot(v, C.yyy) );
vec3 x0 = v - i + dot(i, C.xxx) ;
// Other corners
vec3 g = step(x0.yzx, x0.xyz);
vec3 l = 1.0 - g;
vec3 i1 = min( g.xyz, l.zxy );
vec3 i2 = max( g.xyz, l.zxy );
// x0 = x0 - 0.0 + 0.0 * C.xxx;
// x1 = x0 - i1 + 1.0 * C.xxx;
// x2 = x0 - i2 + 2.0 * C.xxx;
// x3 = x0 - 1.0 + 3.0 * C.xxx;
vec3 x1 = x0 - i1 + C.xxx;
vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y
vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y
// Permutations
i = mod289(i);
vec4 p = permute( permute( permute(
i.z + vec4(0.0, i1.z, i2.z, 1.0 ))
+ i.y + vec4(0.0, i1.y, i2.y, 1.0 ))
+ i.x + vec4(0.0, i1.x, i2.x, 1.0 ));
// Gradients: 7x7 points over a square, mapped onto an octahedron.
// The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
float n_ = 0.142857142857; // 1.0/7.0
vec3 ns = n_ * D.wyz - D.xzx;
vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)
vec4 x_ = floor(j * ns.z);
vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)
vec4 x = x_ *ns.x + ns.yyyy;
vec4 y = y_ *ns.x + ns.yyyy;
vec4 h = 1.0 - abs(x) - abs(y);
vec4 b0 = vec4( x.xy, y.xy );
vec4 b1 = vec4( x.zw, y.zw );
//vec4 s0 = vec4(lessThan(b0,0.0))*2.0 - 1.0;
//vec4 s1 = vec4(lessThan(b1,0.0))*2.0 - 1.0;
vec4 s0 = floor(b0)*2.0 + 1.0;
vec4 s1 = floor(b1)*2.0 + 1.0;
vec4 sh = -step(h, vec4(0.0));
vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;
vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;
vec3 p0 = vec3(a0.xy,h.x);
vec3 p1 = vec3(a0.zw,h.y);
vec3 p2 = vec3(a1.xy,h.z);
vec3 p3 = vec3(a1.zw,h.w);
//Normalise gradients
vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
// Mix final noise value
vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
m = m * m;
return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),
dot(p2,x2), dot(p3,x3) ) );
}
"""
xgl.commonNoiseShaderSource2 = _common + """
float snoise(vec2 v)
{
const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0
0.366025403784439, // 0.5*(sqrt(3.0)-1.0)
-0.577350269189626, // -1.0 + 2.0 * C.x
0.024390243902439); // 1.0 / 41.0
// First corner
vec2 i = floor(v + dot(v, C.yy) );
vec2 x0 = v - i + dot(i, C.xx);
// Other corners
vec2 i1;
//i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0
//i1.y = 1.0 - i1.x;
i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
// x0 = x0 - 0.0 + 0.0 * C.xx ;
// x1 = x0 - i1 + 1.0 * C.xx ;
// x2 = x0 - 1.0 + 2.0 * C.xx ;
vec4 x12 = x0.xyxy + C.xxzz;
x12.xy -= i1;
// Permutations
i = mod289(i); // Avoid truncation effects in permutation
vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 ))
+ i.x + vec3(0.0, i1.x, 1.0 ));
vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0);
m = m*m ;
m = m*m ;
// Gradients: 41 points uniformly over a line, mapped onto a diamond.
// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)
vec3 x = 2.0 * fract(p * C.www) - 1.0;
vec3 h = abs(x) - 0.5;
vec3 ox = floor(x + 0.5);
vec3 a0 = x - ox;
// Normalise gradients implicitly by scaling m
// Approximation of: m *= inversesqrt( a0*a0 + h*h );
m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h );
// Compute final noise value at P
vec3 g;
g.x = a0.x * x0.x + h.x * x0.y;
g.yz = a0.yz * x12.xz + h.yz * x12.yw;
return 130.0 * dot(m, g);
}
"""
| true | _common = """precision highp float;
//
// Description : Array and textureless GLSL 2D/3D/4D simplex
// noise functions.
// Author : PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI.
// Maintainer : ijm
// Lastmod : 20110822 (ijm)
// License : Copyright (C) 2011 PI:NAME:<NAME>END_PIima Arts. All rights reserved.
// Distributed under the MIT License. See LICENSE file.
// https://github.com/ashima/webgl-noise
//
vec2 mod289(vec2 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec3 mod289(vec3 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec4 mod289(vec4 x) {
return x - floor(x * (1.0 / 289.0)) * 289.0;
}
vec3 permute(vec3 x) {
return mod289(((x*34.0)+1.0)*x);
}
vec4 permute(vec4 x) {
return mod289(((x*34.0)+1.0)*x);
}
vec4 taylorInvSqrt(vec4 r)
{
return 1.79284291400159 - 0.85373472095314 * r;
}
"""
xgl.commonNoiseShaderSource3 = _common + """
float snoise(vec3 v)
{
const vec2 C = vec2(1.0/6.0, 1.0/3.0) ;
const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
// First corner
vec3 i = floor(v + dot(v, C.yyy) );
vec3 x0 = v - i + dot(i, C.xxx) ;
// Other corners
vec3 g = step(x0.yzx, x0.xyz);
vec3 l = 1.0 - g;
vec3 i1 = min( g.xyz, l.zxy );
vec3 i2 = max( g.xyz, l.zxy );
// x0 = x0 - 0.0 + 0.0 * C.xxx;
// x1 = x0 - i1 + 1.0 * C.xxx;
// x2 = x0 - i2 + 2.0 * C.xxx;
// x3 = x0 - 1.0 + 3.0 * C.xxx;
vec3 x1 = x0 - i1 + C.xxx;
vec3 x2 = x0 - i2 + C.yyy; // 2.0*C.x = 1/3 = C.y
vec3 x3 = x0 - D.yyy; // -1.0+3.0*C.x = -0.5 = -D.y
// Permutations
i = mod289(i);
vec4 p = permute( permute( permute(
i.z + vec4(0.0, i1.z, i2.z, 1.0 ))
+ i.y + vec4(0.0, i1.y, i2.y, 1.0 ))
+ i.x + vec4(0.0, i1.x, i2.x, 1.0 ));
// Gradients: 7x7 points over a square, mapped onto an octahedron.
// The ring size 17*17 = 289 is close to a multiple of 49 (49*6 = 294)
float n_ = 0.142857142857; // 1.0/7.0
vec3 ns = n_ * D.wyz - D.xzx;
vec4 j = p - 49.0 * floor(p * ns.z * ns.z); // mod(p,7*7)
vec4 x_ = floor(j * ns.z);
vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)
vec4 x = x_ *ns.x + ns.yyyy;
vec4 y = y_ *ns.x + ns.yyyy;
vec4 h = 1.0 - abs(x) - abs(y);
vec4 b0 = vec4( x.xy, y.xy );
vec4 b1 = vec4( x.zw, y.zw );
//vec4 s0 = vec4(lessThan(b0,0.0))*2.0 - 1.0;
//vec4 s1 = vec4(lessThan(b1,0.0))*2.0 - 1.0;
vec4 s0 = floor(b0)*2.0 + 1.0;
vec4 s1 = floor(b1)*2.0 + 1.0;
vec4 sh = -step(h, vec4(0.0));
vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;
vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;
vec3 p0 = vec3(a0.xy,h.x);
vec3 p1 = vec3(a0.zw,h.y);
vec3 p2 = vec3(a1.xy,h.z);
vec3 p3 = vec3(a1.zw,h.w);
//Normalise gradients
vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));
p0 *= norm.x;
p1 *= norm.y;
p2 *= norm.z;
p3 *= norm.w;
// Mix final noise value
vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
m = m * m;
return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),
dot(p2,x2), dot(p3,x3) ) );
}
"""
xgl.commonNoiseShaderSource2 = _common + """
float snoise(vec2 v)
{
const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0
0.366025403784439, // 0.5*(sqrt(3.0)-1.0)
-0.577350269189626, // -1.0 + 2.0 * C.x
0.024390243902439); // 1.0 / 41.0
// First corner
vec2 i = floor(v + dot(v, C.yy) );
vec2 x0 = v - i + dot(i, C.xx);
// Other corners
vec2 i1;
//i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0
//i1.y = 1.0 - i1.x;
i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
// x0 = x0 - 0.0 + 0.0 * C.xx ;
// x1 = x0 - i1 + 1.0 * C.xx ;
// x2 = x0 - 1.0 + 2.0 * C.xx ;
vec4 x12 = x0.xyxy + C.xxzz;
x12.xy -= i1;
// Permutations
i = mod289(i); // Avoid truncation effects in permutation
vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 ))
+ i.x + vec3(0.0, i1.x, 1.0 ));
vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0);
m = m*m ;
m = m*m ;
// Gradients: 41 points uniformly over a line, mapped onto a diamond.
// The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)
vec3 x = 2.0 * fract(p * C.www) - 1.0;
vec3 h = abs(x) - 0.5;
vec3 ox = floor(x + 0.5);
vec3 a0 = x - ox;
// Normalise gradients implicitly by scaling m
// Approximation of: m *= inversesqrt( a0*a0 + h*h );
m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h );
// Compute final noise value at P
vec3 g;
g.x = a0.x * x0.x + h.x * x0.y;
g.yz = a0.yz * x12.xz + h.yz * x12.yw;
return 130.0 * dot(m, g);
}
"""
|
[
{
"context": "# Description:\n# Applause from Orson Welles and others\n#\n# Dependencies:\n# None\n#\n# Configu",
"end": 45,
"score": 0.9966522455215454,
"start": 33,
"tag": "NAME",
"value": "Orson Welles"
},
{
"context": "ud|bravo|slow clap) - Get applause\n#\n# Author:\n# jos... | src/scripts/applause.coffee | Reelhouse/hubot-scripts | 2 | # Description:
# Applause from Orson Welles and others
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# (applause|applaud|bravo|slow clap) - Get applause
#
# Author:
# joshfrench
images = [
"http://assets0.ordienetworks.com/images/GifGuide/clapping/Kurtclapping.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/riker.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/hp3.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/dwight.gif",
"http://i.imgur.com/t8zvc.gif",
"http://i.imgur.com/5zKXz.gif",
"http://www.animateit.net/data/media/july2012/clap-animated-animation-clap-000340-large.gif",
"http://i.imgur.com/9Zv4V.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/1292223254212-dumpfm-mario-Obamaclap.gif",
"http://sunglasses.name/gif/joker-clap.gif",
"http://www.reactiongifs.com/wp-content/uploads/2013/01/applause.gif"
]
module.exports = (robot) ->
robot.hear /applau(d|se)|bravo|slow clap/i, (msg) ->
msg.send msg.random images
| 101771 | # Description:
# Applause from <NAME> and others
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# (applause|applaud|bravo|slow clap) - Get applause
#
# Author:
# joshfrench
images = [
"http://assets0.ordienetworks.com/images/GifGuide/clapping/Kurtclapping.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/riker.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/hp3.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/dwight.gif",
"http://i.imgur.com/t8zvc.gif",
"http://i.imgur.com/5zKXz.gif",
"http://www.animateit.net/data/media/july2012/clap-animated-animation-clap-000340-large.gif",
"http://i.imgur.com/9Zv4V.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/1292223254212-dumpfm-mario-Obamaclap.gif",
"http://sunglasses.name/gif/joker-clap.gif",
"http://www.reactiongifs.com/wp-content/uploads/2013/01/applause.gif"
]
module.exports = (robot) ->
robot.hear /applau(d|se)|bravo|slow clap/i, (msg) ->
msg.send msg.random images
| true | # Description:
# Applause from PI:NAME:<NAME>END_PI and others
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# (applause|applaud|bravo|slow clap) - Get applause
#
# Author:
# joshfrench
images = [
"http://assets0.ordienetworks.com/images/GifGuide/clapping/Kurtclapping.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/riker.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/hp3.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/dwight.gif",
"http://i.imgur.com/t8zvc.gif",
"http://i.imgur.com/5zKXz.gif",
"http://www.animateit.net/data/media/july2012/clap-animated-animation-clap-000340-large.gif",
"http://i.imgur.com/9Zv4V.gif",
"http://assets0.ordienetworks.com/images/GifGuide/clapping/1292223254212-dumpfm-mario-Obamaclap.gif",
"http://sunglasses.name/gif/joker-clap.gif",
"http://www.reactiongifs.com/wp-content/uploads/2013/01/applause.gif"
]
module.exports = (robot) ->
robot.hear /applau(d|se)|bravo|slow clap/i, (msg) ->
msg.send msg.random images
|
[
{
"context": "', 'Cleric', 'Barbarian', 'Fighter']}\n {name: \"wraith\", statMult: 1.1, slotCost: 1, restrictL",
"end": 601,
"score": 0.8401570320129395,
"start": 595,
"tag": "NAME",
"value": "wraith"
},
{
"context": "1.1, slotCost: 1, restrictLevel: 55}\n {name: \"v... | src/character/spells/misc/Summon.coffee | jawsome/IdleLands | 3 |
Spell = require "../../base/Spell"
Event = require "../../../event/Event"
Equipment = require "../../../item/Equipment"
_ = require "lodash"
requireDir = require "require-dir"
classProtos = requireDir "../../classes"
baseStats = ['Str', 'Dex', 'Con', 'Agi', 'Int', 'Wis', 'Luck']
monsters =
Necromancer: [
{name: "zombie", statMult: 0.5, slotCost: 1, restrictLevel: 5, restrictClasses: ['Monster']}
{name: "skeleton", statMult: 0.8, slotCost: 1, restrictLevel: 25, restrictClasses: ['Generalist', 'Rogue', 'Mage', 'Cleric', 'Barbarian', 'Fighter']}
{name: "wraith", statMult: 1.1, slotCost: 1, restrictLevel: 55}
{name: "vampire", statMult: 1.0, slotCost: 2, restrictLevel: 70, baseStats: {vampire: 10}}
{name: "plaguebringer", statMult: 1.0, slotCost: 2, restrictLevel: 70, baseStats: {venom: 10}}
{name: "ghoul", statMult: 1.0, slotCost: 2, restrictLevel: 70, baseStats: {poison: 10}}
{name: "dracolich", statMult: 1.35, slotCost: 2, restrictLevel: 85, baseStats: {mirror: 1}, requireCollectibles: ["Undead Draygon Scale"]}
{name: "demogorgon", statMult: 1.75, slotCost: 4, restrictLevel: 150, requireCollectibles: ["Gorgon Snake"]}
]
class Summon extends Spell
name: "summon"
@element = Summon::element = Spell::Element.none
@tiers = Summon::tiers = [
`/**
* This spell summons a variety of monsters under the command of the caster.
*
* @name summon
* @requirement {class} Necromancer
* @requirement {mp} 0.15*maxMp
* @requirement {level} 85
* @category Necromancer
* @package Spells
*/`
{name: "summon", spellPower: 1, cost: ((caster) -> Math.round caster.mp.maximum * 0.15), class: "Necromancer", level: 5}
]
@canChoose = (caster) ->
not caster.isMonster and not caster.special.atMax()
getPossibleMonstersForCaster: ->
_(monsters[@caster.professionName])
.reject (monster) => monster.restrictLevel > @caster.level.getValue()
.reject (monster) => monster.requireCollectibles?.length > 0 and not @hasCollectibles @caster, monster.requireCollectibles
.reject (monster) => monster.slotCost > @caster.special.maximum - @caster.special.getValue()
.value()
determineTargets: -> @caster
cast: ->
chosenBaseMonster = _.clone _.sample @getPossibleMonstersForCaster()
chosenBaseMonster.class = _.sample chosenBaseMonster.restrictClasses if chosenBaseMonster.restrictClasses
chosenBaseMonster.level = @caster.level.getValue()
isFail = @chance.bool {likelihood: 5}
otherParty = _.sample _.without @caster.party.currentBattle.parties, @caster.party
joinParty = if isFail then otherParty else @caster.party
monster = @game.monsterGenerator.experimentalMonsterGeneration chosenBaseMonster, @caster.calc.totalItemScore(), if isFail then @caster.party else otherParty
monster.name = "#{@caster.name}'s #{monster.name}"
monster.hp.toMaximum()
monster.mp.toMaximum()
monster.isPet = yes
monster.needsToRecalcCombat = yes
basePhylact = (_.clone chosenBaseMonster.baseStats) or {}
[basePhylact.type, basePhylact.class, basePhylact.name] = ["monster", "newbie", "phylactic essence"]
currentProto = classProtos[monster.professionName].prototype
applicableStats = _.reject baseStats, (stat) -> currentProto["base#{stat}PerLevel"] is 0
_.each applicableStats, (stat) =>
basePhylact[stat.toLowerCase()] = currentProto["base#{stat}PerLevel"] * @caster.level.getValue() * chosenBaseMonster.statMult
specialBuffs = Math.floor @caster.level.getValue() / 40
basePhylact[_.sample Event::specialStats] = 1 for i in [0..specialBuffs]
monster.equipment.push new Equipment basePhylact
message = "%casterName summoned <player.name>#{monster.getName()}</player.name> to the battlefield#{if isFail then ', but failed, and it ended up as a foe' else ''}!"
@broadcast @caster, message
joinParty.recruit [monster]
monster.party.currentBattle.turnOrder.push monster
@caster.special.add chosenBaseMonster.slotCost if not isFail
monster.on "combat.self.killed", ->
monster.canFade = yes
monster.on "combat.round.end", =>
if monster.needsToRecalcCombat
monster.party.currentBattle.calculateTurnOrder()
monster.needsToRecalcCombat = no
return
return if not monster.canFade
@caster.special.sub chosenBaseMonster.slotCost if not isFail
monster.party.playerLeave monster, yes
@caster.party?.currentBattle.calculateTurnOrder()
constructor: (@game, @caster) ->
super @game, @caster
@bindings =
doSpellCast: @cast
module.exports = exports = Summon
| 91977 |
Spell = require "../../base/Spell"
Event = require "../../../event/Event"
Equipment = require "../../../item/Equipment"
_ = require "lodash"
requireDir = require "require-dir"
classProtos = requireDir "../../classes"
baseStats = ['Str', 'Dex', 'Con', 'Agi', 'Int', 'Wis', 'Luck']
monsters =
Necromancer: [
{name: "zombie", statMult: 0.5, slotCost: 1, restrictLevel: 5, restrictClasses: ['Monster']}
{name: "skeleton", statMult: 0.8, slotCost: 1, restrictLevel: 25, restrictClasses: ['Generalist', 'Rogue', 'Mage', 'Cleric', 'Barbarian', 'Fighter']}
{name: "<NAME>", statMult: 1.1, slotCost: 1, restrictLevel: 55}
{name: "<NAME>", statMult: 1.0, slotCost: 2, restrictLevel: 70, baseStats: {vampire: 10}}
{name: "<NAME>aguebr<NAME>", statMult: 1.0, slotCost: 2, restrictLevel: 70, baseStats: {venom: 10}}
{name: "<NAME>", statMult: 1.0, slotCost: 2, restrictLevel: 70, baseStats: {poison: 10}}
{name: "<NAME>", statMult: 1.35, slotCost: 2, restrictLevel: 85, baseStats: {mirror: 1}, requireCollectibles: ["Undead Draygon Scale"]}
{name: "demogorgon", statMult: 1.75, slotCost: 4, restrictLevel: 150, requireCollectibles: ["Gorgon Snake"]}
]
class Summon extends Spell
name: "summon"
@element = Summon::element = Spell::Element.none
@tiers = Summon::tiers = [
`/**
* This spell summons a variety of monsters under the command of the caster.
*
* @name <NAME>mon
* @requirement {class} Necromancer
* @requirement {mp} 0.15*maxMp
* @requirement {level} 85
* @category Necromancer
* @package Spells
*/`
{name: "<NAME>", spellPower: 1, cost: ((caster) -> Math.round caster.mp.maximum * 0.15), class: "Necromancer", level: 5}
]
@canChoose = (caster) ->
not caster.isMonster and not caster.special.atMax()
getPossibleMonstersForCaster: ->
_(monsters[@caster.professionName])
.reject (monster) => monster.restrictLevel > @caster.level.getValue()
.reject (monster) => monster.requireCollectibles?.length > 0 and not @hasCollectibles @caster, monster.requireCollectibles
.reject (monster) => monster.slotCost > @caster.special.maximum - @caster.special.getValue()
.value()
determineTargets: -> @caster
cast: ->
chosenBaseMonster = _.clone _.sample @getPossibleMonstersForCaster()
chosenBaseMonster.class = _.sample chosenBaseMonster.restrictClasses if chosenBaseMonster.restrictClasses
chosenBaseMonster.level = @caster.level.getValue()
isFail = @chance.bool {likelihood: 5}
otherParty = _.sample _.without @caster.party.currentBattle.parties, @caster.party
joinParty = if isFail then otherParty else @caster.party
monster = @game.monsterGenerator.experimentalMonsterGeneration chosenBaseMonster, @caster.calc.totalItemScore(), if isFail then @caster.party else otherParty
monster.name = "#{@caster.name}'s #{monster.name}"
monster.hp.toMaximum()
monster.mp.toMaximum()
monster.isPet = yes
monster.needsToRecalcCombat = yes
basePhylact = (_.clone chosenBaseMonster.baseStats) or {}
[basePhylact.type, basePhylact.class, basePhylact.name] = ["monster", "newbie", "phylactic essence"]
currentProto = classProtos[monster.professionName].prototype
applicableStats = _.reject baseStats, (stat) -> currentProto["base#{stat}PerLevel"] is 0
_.each applicableStats, (stat) =>
basePhylact[stat.toLowerCase()] = currentProto["base#{stat}PerLevel"] * @caster.level.getValue() * chosenBaseMonster.statMult
specialBuffs = Math.floor @caster.level.getValue() / 40
basePhylact[_.sample Event::specialStats] = 1 for i in [0..specialBuffs]
monster.equipment.push new Equipment basePhylact
message = "%casterName summoned <player.name>#{monster.getName()}</player.name> to the battlefield#{if isFail then ', but failed, and it ended up as a foe' else ''}!"
@broadcast @caster, message
joinParty.recruit [monster]
monster.party.currentBattle.turnOrder.push monster
@caster.special.add chosenBaseMonster.slotCost if not isFail
monster.on "combat.self.killed", ->
monster.canFade = yes
monster.on "combat.round.end", =>
if monster.needsToRecalcCombat
monster.party.currentBattle.calculateTurnOrder()
monster.needsToRecalcCombat = no
return
return if not monster.canFade
@caster.special.sub chosenBaseMonster.slotCost if not isFail
monster.party.playerLeave monster, yes
@caster.party?.currentBattle.calculateTurnOrder()
constructor: (@game, @caster) ->
super @game, @caster
@bindings =
doSpellCast: @cast
module.exports = exports = Summon
| true |
Spell = require "../../base/Spell"
Event = require "../../../event/Event"
Equipment = require "../../../item/Equipment"
_ = require "lodash"
requireDir = require "require-dir"
classProtos = requireDir "../../classes"
baseStats = ['Str', 'Dex', 'Con', 'Agi', 'Int', 'Wis', 'Luck']
monsters =
Necromancer: [
{name: "zombie", statMult: 0.5, slotCost: 1, restrictLevel: 5, restrictClasses: ['Monster']}
{name: "skeleton", statMult: 0.8, slotCost: 1, restrictLevel: 25, restrictClasses: ['Generalist', 'Rogue', 'Mage', 'Cleric', 'Barbarian', 'Fighter']}
{name: "PI:NAME:<NAME>END_PI", statMult: 1.1, slotCost: 1, restrictLevel: 55}
{name: "PI:NAME:<NAME>END_PI", statMult: 1.0, slotCost: 2, restrictLevel: 70, baseStats: {vampire: 10}}
{name: "PI:NAME:<NAME>END_PIaguebrPI:NAME:<NAME>END_PI", statMult: 1.0, slotCost: 2, restrictLevel: 70, baseStats: {venom: 10}}
{name: "PI:NAME:<NAME>END_PI", statMult: 1.0, slotCost: 2, restrictLevel: 70, baseStats: {poison: 10}}
{name: "PI:NAME:<NAME>END_PI", statMult: 1.35, slotCost: 2, restrictLevel: 85, baseStats: {mirror: 1}, requireCollectibles: ["Undead Draygon Scale"]}
{name: "demogorgon", statMult: 1.75, slotCost: 4, restrictLevel: 150, requireCollectibles: ["Gorgon Snake"]}
]
class Summon extends Spell
name: "summon"
@element = Summon::element = Spell::Element.none
@tiers = Summon::tiers = [
`/**
* This spell summons a variety of monsters under the command of the caster.
*
* @name PI:NAME:<NAME>END_PImon
* @requirement {class} Necromancer
* @requirement {mp} 0.15*maxMp
* @requirement {level} 85
* @category Necromancer
* @package Spells
*/`
{name: "PI:NAME:<NAME>END_PI", spellPower: 1, cost: ((caster) -> Math.round caster.mp.maximum * 0.15), class: "Necromancer", level: 5}
]
@canChoose = (caster) ->
not caster.isMonster and not caster.special.atMax()
getPossibleMonstersForCaster: ->
_(monsters[@caster.professionName])
.reject (monster) => monster.restrictLevel > @caster.level.getValue()
.reject (monster) => monster.requireCollectibles?.length > 0 and not @hasCollectibles @caster, monster.requireCollectibles
.reject (monster) => monster.slotCost > @caster.special.maximum - @caster.special.getValue()
.value()
determineTargets: -> @caster
cast: ->
chosenBaseMonster = _.clone _.sample @getPossibleMonstersForCaster()
chosenBaseMonster.class = _.sample chosenBaseMonster.restrictClasses if chosenBaseMonster.restrictClasses
chosenBaseMonster.level = @caster.level.getValue()
isFail = @chance.bool {likelihood: 5}
otherParty = _.sample _.without @caster.party.currentBattle.parties, @caster.party
joinParty = if isFail then otherParty else @caster.party
monster = @game.monsterGenerator.experimentalMonsterGeneration chosenBaseMonster, @caster.calc.totalItemScore(), if isFail then @caster.party else otherParty
monster.name = "#{@caster.name}'s #{monster.name}"
monster.hp.toMaximum()
monster.mp.toMaximum()
monster.isPet = yes
monster.needsToRecalcCombat = yes
basePhylact = (_.clone chosenBaseMonster.baseStats) or {}
[basePhylact.type, basePhylact.class, basePhylact.name] = ["monster", "newbie", "phylactic essence"]
currentProto = classProtos[monster.professionName].prototype
applicableStats = _.reject baseStats, (stat) -> currentProto["base#{stat}PerLevel"] is 0
_.each applicableStats, (stat) =>
basePhylact[stat.toLowerCase()] = currentProto["base#{stat}PerLevel"] * @caster.level.getValue() * chosenBaseMonster.statMult
specialBuffs = Math.floor @caster.level.getValue() / 40
basePhylact[_.sample Event::specialStats] = 1 for i in [0..specialBuffs]
monster.equipment.push new Equipment basePhylact
message = "%casterName summoned <player.name>#{monster.getName()}</player.name> to the battlefield#{if isFail then ', but failed, and it ended up as a foe' else ''}!"
@broadcast @caster, message
joinParty.recruit [monster]
monster.party.currentBattle.turnOrder.push monster
@caster.special.add chosenBaseMonster.slotCost if not isFail
monster.on "combat.self.killed", ->
monster.canFade = yes
monster.on "combat.round.end", =>
if monster.needsToRecalcCombat
monster.party.currentBattle.calculateTurnOrder()
monster.needsToRecalcCombat = no
return
return if not monster.canFade
@caster.special.sub chosenBaseMonster.slotCost if not isFail
monster.party.playerLeave monster, yes
@caster.party?.currentBattle.calculateTurnOrder()
constructor: (@game, @caster) ->
super @game, @caster
@bindings =
doSpellCast: @cast
module.exports = exports = Summon
|
[
{
"context": " </pre>\n \"\"\"\n\n\n tokens: ['CALL_START']\n\n lintToken: (token, tokenApi) ->\n [p",
"end": 785,
"score": 0.7953498959541321,
"start": 775,
"tag": "KEY",
"value": "CALL_START"
}
] | src/rules/missing_parseint_radix.coffee | UziTech/coffeelint | 13 | module.exports = class ParseintRadix
rule:
type: 'problem'
name: 'missing_parseint_radix'
level: 'warn'
message: 'parseInt is missing the radix argument'
description: """
This rule warns about using parseInt without a radix. From the MDN
developers reference: <q>Always specify this parameter to eliminate
reader confusion and to guarantee predictable behavior.</q>
<pre>
<code># You would expect this to result in 8, but
# it might result in 0 (parsed as octal).
parseInt '08'
# To be safe, specify the radix argument:
parseInt '08', 10
</code>
</pre>
"""
tokens: ['CALL_START']
lintToken: (token, tokenApi) ->
[prevToken, functionName] = tokenApi.peek(-1)
if functionName is 'parseInt'
[callEnd] = tokenApi.peek(2)
return { token } if callEnd is 'CALL_END'
| 47493 | module.exports = class ParseintRadix
rule:
type: 'problem'
name: 'missing_parseint_radix'
level: 'warn'
message: 'parseInt is missing the radix argument'
description: """
This rule warns about using parseInt without a radix. From the MDN
developers reference: <q>Always specify this parameter to eliminate
reader confusion and to guarantee predictable behavior.</q>
<pre>
<code># You would expect this to result in 8, but
# it might result in 0 (parsed as octal).
parseInt '08'
# To be safe, specify the radix argument:
parseInt '08', 10
</code>
</pre>
"""
tokens: ['<KEY>']
lintToken: (token, tokenApi) ->
[prevToken, functionName] = tokenApi.peek(-1)
if functionName is 'parseInt'
[callEnd] = tokenApi.peek(2)
return { token } if callEnd is 'CALL_END'
| true | module.exports = class ParseintRadix
rule:
type: 'problem'
name: 'missing_parseint_radix'
level: 'warn'
message: 'parseInt is missing the radix argument'
description: """
This rule warns about using parseInt without a radix. From the MDN
developers reference: <q>Always specify this parameter to eliminate
reader confusion and to guarantee predictable behavior.</q>
<pre>
<code># You would expect this to result in 8, but
# it might result in 0 (parsed as octal).
parseInt '08'
# To be safe, specify the radix argument:
parseInt '08', 10
</code>
</pre>
"""
tokens: ['PI:KEY:<KEY>END_PI']
lintToken: (token, tokenApi) ->
[prevToken, functionName] = tokenApi.peek(-1)
if functionName is 'parseInt'
[callEnd] = tokenApi.peek(2)
return { token } if callEnd is 'CALL_END'
|
[
{
"context": " localStorage.removeItem key\n\n keys = [\n 'flowhub-avatar'\n 'flowhub-debug'\n 'flowhub-plan'\n ",
"end": 913,
"score": 0.7973220348358154,
"start": 899,
"tag": "KEY",
"value": "flowhub-avatar"
},
{
"context": "m key\n\n keys = [\n 'flowh... | components/LoadUserData.coffee | rishi229225111/noflo-ui | 0 | noflo = require 'noflo'
validate = (items, callback) ->
return callback null, items unless items['flowhub-user']
try
items['flowhub-user'] = JSON.parse items['flowhub-user']
catch e
return callback e
callback null, items
exports.getComponent = ->
c = new noflo.Component
c.inPorts.add 'start',
datatype: 'bang'
c.outPorts.add 'user', ->
datatype: 'object'
c.outPorts.add 'error', ->
datatype: 'object'
noflo.helpers.WirePattern c,
in: 'start'
out: 'user'
async: true
, (ins, groups, out, callback) ->
# Handle obsolete keys
deprecated =
'grid-avatar': 'flowhub-avatar'
'grid-token': 'flowhub-token'
'grid-user': 'flowhub-user'
for key, newKey of deprecated
val = localStorage.getItem key
continue unless val
localStorage.setItem newKey, val
localStorage.removeItem key
keys = [
'flowhub-avatar'
'flowhub-debug'
'flowhub-plan'
'flowhub-theme'
'flowhub-token'
'flowhub-user'
'github-token'
'github-username'
]
items = {}
for key in keys
items[key] = localStorage.getItem key
validate items, (err, valid) ->
return callback err if err
out.send valid
do callback
| 73241 | noflo = require 'noflo'
validate = (items, callback) ->
return callback null, items unless items['flowhub-user']
try
items['flowhub-user'] = JSON.parse items['flowhub-user']
catch e
return callback e
callback null, items
exports.getComponent = ->
c = new noflo.Component
c.inPorts.add 'start',
datatype: 'bang'
c.outPorts.add 'user', ->
datatype: 'object'
c.outPorts.add 'error', ->
datatype: 'object'
noflo.helpers.WirePattern c,
in: 'start'
out: 'user'
async: true
, (ins, groups, out, callback) ->
# Handle obsolete keys
deprecated =
'grid-avatar': 'flowhub-avatar'
'grid-token': 'flowhub-token'
'grid-user': 'flowhub-user'
for key, newKey of deprecated
val = localStorage.getItem key
continue unless val
localStorage.setItem newKey, val
localStorage.removeItem key
keys = [
'<KEY>'
'<KEY>'
'flow<KEY>plan'
'flowhub-theme'
'flowhub-token'
'flowhub-user'
'github-token'
'github-username'
]
items = {}
for key in keys
items[key] = localStorage.getItem key
validate items, (err, valid) ->
return callback err if err
out.send valid
do callback
| true | noflo = require 'noflo'
validate = (items, callback) ->
return callback null, items unless items['flowhub-user']
try
items['flowhub-user'] = JSON.parse items['flowhub-user']
catch e
return callback e
callback null, items
exports.getComponent = ->
c = new noflo.Component
c.inPorts.add 'start',
datatype: 'bang'
c.outPorts.add 'user', ->
datatype: 'object'
c.outPorts.add 'error', ->
datatype: 'object'
noflo.helpers.WirePattern c,
in: 'start'
out: 'user'
async: true
, (ins, groups, out, callback) ->
# Handle obsolete keys
deprecated =
'grid-avatar': 'flowhub-avatar'
'grid-token': 'flowhub-token'
'grid-user': 'flowhub-user'
for key, newKey of deprecated
val = localStorage.getItem key
continue unless val
localStorage.setItem newKey, val
localStorage.removeItem key
keys = [
'PI:KEY:<KEY>END_PI'
'PI:KEY:<KEY>END_PI'
'flowPI:KEY:<KEY>END_PIplan'
'flowhub-theme'
'flowhub-token'
'flowhub-user'
'github-token'
'github-username'
]
items = {}
for key in keys
items[key] = localStorage.getItem key
validate items, (err, valid) ->
return callback err if err
out.send valid
do callback
|
[
{
"context": "*\n# JSMapView - GoogleMaps manage class\n# Coded by kouichi.sakazaki 2013.10.03\n#*************************************",
"end": 108,
"score": 0.9983095526695251,
"start": 92,
"tag": "NAME",
"value": "kouichi.sakazaki"
}
] | JSKit/frameworks/JSMapKit.framework/JSMapView.coffee | digitarhythm/codeJS | 0 | #*****************************************
# JSMapView - GoogleMaps manage class
# Coded by kouichi.sakazaki 2013.10.03
#*****************************************
class JSMapView extends JSView
constructor: (frame)->
super(frame)
@delegate = @_self
@_map = undefined
@mapOptions =
center: new google.maps.LatLng(0.0, 0.0)
zoom: 8
mapTypeId: google.maps.MapTypeId.ROADMAP
panControl: false
zoomControl: false
mapTypeControl: false
scaleControl: false
streetViewControl: false
# create map object
createMap:->
tag = "<div id='"+@_objectID+"_mapcanvas' style='width:"+@_frame.size.width+"px;height:"+@_frame.size.height+"px;'></div>"
if ($(@_viewSelector+"_mapcanvas").length)
$(@_viewSelector+"_mapcanvas").remove()
$(@_viewSelector).append(tag)
@_map = new google.maps.Map(document.getElementById(@_objectID+"_mapcanvas"), @mapOptions)
# set/get zoom(region)
setRegion:(zoom)->
if ($(@_viewSelector+"_mapcanvas").length)
@_map.setZoom(zoom)
getRegion:->
if ($(@_viewSelector+"_mapcanvas").length)
return @_map.getZoom()
else
return 0
# set map center coordinate
setCenterCoordinate:(coord)->
if ($(@_viewSelector+"_mapcanvas").length)
latitude = coord._latitude
longitude = coord._longitude
@_center = new google.maps.LatLng(latitude, longitude)
@_map.setCenter(@_center)
# MapType
setMapType:(maptype)->
if ($(@_viewSelector+"_mapcanvas").length)
switch (maptype)
when "MKMapTypeHybrid"
maptypeid = google.maps.MapTypeId.HYBRID
when "MKMapTypeStandard"
maptypeid = google.maps.MapTypeId.ROADMAP
when "MKMapTypeSatellite"
maptypeid = google.maps.MapTypeId.SATELLITE
when "MKMapTypeTerrain"
maptypeid = google.maps.MapTypeId.TERRAIN
@_map.setMapTypeId(maptypeid)
# set map options
mapOptionReflection:->
center = @_map.getCenter()
zoom = @_map.getZoom()
maptypeid = @_map.getMapTypeId()
@mapOptions.center = center
@mapOptions.zoom = zoom
@mapOptions.mapTypeId = maptypeid
@_map.setOptions(@mapOptions)
# view did appear
viewDidAppear:->
super()
if (!$(@_viewSelector+"_mapcanvas").length)
@createMap()
| 5472 | #*****************************************
# JSMapView - GoogleMaps manage class
# Coded by <NAME> 2013.10.03
#*****************************************
class JSMapView extends JSView
constructor: (frame)->
super(frame)
@delegate = @_self
@_map = undefined
@mapOptions =
center: new google.maps.LatLng(0.0, 0.0)
zoom: 8
mapTypeId: google.maps.MapTypeId.ROADMAP
panControl: false
zoomControl: false
mapTypeControl: false
scaleControl: false
streetViewControl: false
# create map object
createMap:->
tag = "<div id='"+@_objectID+"_mapcanvas' style='width:"+@_frame.size.width+"px;height:"+@_frame.size.height+"px;'></div>"
if ($(@_viewSelector+"_mapcanvas").length)
$(@_viewSelector+"_mapcanvas").remove()
$(@_viewSelector).append(tag)
@_map = new google.maps.Map(document.getElementById(@_objectID+"_mapcanvas"), @mapOptions)
# set/get zoom(region)
setRegion:(zoom)->
if ($(@_viewSelector+"_mapcanvas").length)
@_map.setZoom(zoom)
getRegion:->
if ($(@_viewSelector+"_mapcanvas").length)
return @_map.getZoom()
else
return 0
# set map center coordinate
setCenterCoordinate:(coord)->
if ($(@_viewSelector+"_mapcanvas").length)
latitude = coord._latitude
longitude = coord._longitude
@_center = new google.maps.LatLng(latitude, longitude)
@_map.setCenter(@_center)
# MapType
setMapType:(maptype)->
if ($(@_viewSelector+"_mapcanvas").length)
switch (maptype)
when "MKMapTypeHybrid"
maptypeid = google.maps.MapTypeId.HYBRID
when "MKMapTypeStandard"
maptypeid = google.maps.MapTypeId.ROADMAP
when "MKMapTypeSatellite"
maptypeid = google.maps.MapTypeId.SATELLITE
when "MKMapTypeTerrain"
maptypeid = google.maps.MapTypeId.TERRAIN
@_map.setMapTypeId(maptypeid)
# set map options
mapOptionReflection:->
center = @_map.getCenter()
zoom = @_map.getZoom()
maptypeid = @_map.getMapTypeId()
@mapOptions.center = center
@mapOptions.zoom = zoom
@mapOptions.mapTypeId = maptypeid
@_map.setOptions(@mapOptions)
# view did appear
viewDidAppear:->
super()
if (!$(@_viewSelector+"_mapcanvas").length)
@createMap()
| true | #*****************************************
# JSMapView - GoogleMaps manage class
# Coded by PI:NAME:<NAME>END_PI 2013.10.03
#*****************************************
class JSMapView extends JSView
constructor: (frame)->
super(frame)
@delegate = @_self
@_map = undefined
@mapOptions =
center: new google.maps.LatLng(0.0, 0.0)
zoom: 8
mapTypeId: google.maps.MapTypeId.ROADMAP
panControl: false
zoomControl: false
mapTypeControl: false
scaleControl: false
streetViewControl: false
# create map object
createMap:->
tag = "<div id='"+@_objectID+"_mapcanvas' style='width:"+@_frame.size.width+"px;height:"+@_frame.size.height+"px;'></div>"
if ($(@_viewSelector+"_mapcanvas").length)
$(@_viewSelector+"_mapcanvas").remove()
$(@_viewSelector).append(tag)
@_map = new google.maps.Map(document.getElementById(@_objectID+"_mapcanvas"), @mapOptions)
# set/get zoom(region)
setRegion:(zoom)->
if ($(@_viewSelector+"_mapcanvas").length)
@_map.setZoom(zoom)
getRegion:->
if ($(@_viewSelector+"_mapcanvas").length)
return @_map.getZoom()
else
return 0
# set map center coordinate
setCenterCoordinate:(coord)->
if ($(@_viewSelector+"_mapcanvas").length)
latitude = coord._latitude
longitude = coord._longitude
@_center = new google.maps.LatLng(latitude, longitude)
@_map.setCenter(@_center)
# MapType
setMapType:(maptype)->
if ($(@_viewSelector+"_mapcanvas").length)
switch (maptype)
when "MKMapTypeHybrid"
maptypeid = google.maps.MapTypeId.HYBRID
when "MKMapTypeStandard"
maptypeid = google.maps.MapTypeId.ROADMAP
when "MKMapTypeSatellite"
maptypeid = google.maps.MapTypeId.SATELLITE
when "MKMapTypeTerrain"
maptypeid = google.maps.MapTypeId.TERRAIN
@_map.setMapTypeId(maptypeid)
# set map options
mapOptionReflection:->
center = @_map.getCenter()
zoom = @_map.getZoom()
maptypeid = @_map.getMapTypeId()
@mapOptions.center = center
@mapOptions.zoom = zoom
@mapOptions.mapTypeId = maptypeid
@_map.setOptions(@mapOptions)
# view did appear
viewDidAppear:->
super()
if (!$(@_viewSelector+"_mapcanvas").length)
@createMap()
|
[
{
"context": "r the iTunes link to Single Ladies\n#\n# Author:\n# Jon Rohan <yes@jonrohan.codes>\n\nmodule.exports = (robot) ->",
"end": 183,
"score": 0.9998666048049927,
"start": 174,
"tag": "NAME",
"value": "Jon Rohan"
},
{
"context": " link to Single Ladies\n#\n# Author:\n# Jo... | src/itunes-search.coffee | swipswaps/hubot-itunes-search | 0 | # Description
# Search iTunes for music, and return previews
#
# Commands:
# hubot music single ladies - will search for the iTunes link to Single Ladies
#
# Author:
# Jon Rohan <yes@jonrohan.codes>
module.exports = (robot) ->
robot.respond /music( me)? (.+)/i, (msg) ->
query = msg.match[2]
country = process.env.HUBOT_ITUNES_SEARCH_COUNTRY || 'US'
robot.http("http://itunes.apple.com/search")
.query({
entity: "song",
limit: "1",
term: query,
country: country
})
.get() (err, res, body) ->
return msg.send "Error :: #{err}" if err
try
songs = JSON.parse(body)
catch error
return msg.send "Error :: iTunes api error."
return msg.send "No tracks found." if songs.resultCount == 0
track = songs.results[0]
msg.send track.trackViewUrl
msg.send track.artworkUrl100 unless robot.adapterName == "slack"
msg.send "*#{track.trackName}*\n#{track.artistName} — #{track.collectionName}"
msg.send track.previewUrl
| 50402 | # Description
# Search iTunes for music, and return previews
#
# Commands:
# hubot music single ladies - will search for the iTunes link to Single Ladies
#
# Author:
# <NAME> <<EMAIL>>
module.exports = (robot) ->
robot.respond /music( me)? (.+)/i, (msg) ->
query = msg.match[2]
country = process.env.HUBOT_ITUNES_SEARCH_COUNTRY || 'US'
robot.http("http://itunes.apple.com/search")
.query({
entity: "song",
limit: "1",
term: query,
country: country
})
.get() (err, res, body) ->
return msg.send "Error :: #{err}" if err
try
songs = JSON.parse(body)
catch error
return msg.send "Error :: iTunes api error."
return msg.send "No tracks found." if songs.resultCount == 0
track = songs.results[0]
msg.send track.trackViewUrl
msg.send track.artworkUrl100 unless robot.adapterName == "slack"
msg.send "*#{track.trackName}*\n#{track.artistName} — #{track.collectionName}"
msg.send track.previewUrl
| true | # Description
# Search iTunes for music, and return previews
#
# Commands:
# hubot music single ladies - will search for the iTunes link to Single Ladies
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
module.exports = (robot) ->
robot.respond /music( me)? (.+)/i, (msg) ->
query = msg.match[2]
country = process.env.HUBOT_ITUNES_SEARCH_COUNTRY || 'US'
robot.http("http://itunes.apple.com/search")
.query({
entity: "song",
limit: "1",
term: query,
country: country
})
.get() (err, res, body) ->
return msg.send "Error :: #{err}" if err
try
songs = JSON.parse(body)
catch error
return msg.send "Error :: iTunes api error."
return msg.send "No tracks found." if songs.resultCount == 0
track = songs.results[0]
msg.send track.trackViewUrl
msg.send track.artworkUrl100 unless robot.adapterName == "slack"
msg.send "*#{track.trackName}*\n#{track.artistName} — #{track.collectionName}"
msg.send track.previewUrl
|
[
{
"context": "#\n# Project's main unit\n#\n# Copyright (C) 2013 Nikolay Nemshilov\n#\n\nshow = ->\n element = document.creat",
"end": 64,
"score": 0.9998774528503418,
"start": 47,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | E002/hello-ie/src/hello_ie.coffee | lovely-io/lovely.io-show | 1 | #
# Project's main unit
#
# Copyright (C) 2013 Nikolay Nemshilov
#
show = ->
element = document.createElement('div')
element.id = 'hello-ie'
element.innerHTML = """
<div class="locker"></div>
<div class="dialog">
<h1>Warning!</h1>
<a href="#" onclick="Lovely.module('hello-ie').hide(); return false" class="close">×</a>
<p>
You're using an utterly obsolete browser,
therefore some features might not be available
</p>
<p class="buttons">
<a href="http://www.whatbrowser.org/">What's Browser?</a>
<a href="" onclick="Lovely.module('hello-ie').hide(); return false">Continue</a>
</p>
</div>
"""
document.body.appendChild(element)
hide = ->
element = document.getElementById('hello-ie')
document.body.removeChild(element)
| 70700 | #
# Project's main unit
#
# Copyright (C) 2013 <NAME>
#
show = ->
element = document.createElement('div')
element.id = 'hello-ie'
element.innerHTML = """
<div class="locker"></div>
<div class="dialog">
<h1>Warning!</h1>
<a href="#" onclick="Lovely.module('hello-ie').hide(); return false" class="close">×</a>
<p>
You're using an utterly obsolete browser,
therefore some features might not be available
</p>
<p class="buttons">
<a href="http://www.whatbrowser.org/">What's Browser?</a>
<a href="" onclick="Lovely.module('hello-ie').hide(); return false">Continue</a>
</p>
</div>
"""
document.body.appendChild(element)
hide = ->
element = document.getElementById('hello-ie')
document.body.removeChild(element)
| true | #
# Project's main unit
#
# Copyright (C) 2013 PI:NAME:<NAME>END_PI
#
show = ->
element = document.createElement('div')
element.id = 'hello-ie'
element.innerHTML = """
<div class="locker"></div>
<div class="dialog">
<h1>Warning!</h1>
<a href="#" onclick="Lovely.module('hello-ie').hide(); return false" class="close">×</a>
<p>
You're using an utterly obsolete browser,
therefore some features might not be available
</p>
<p class="buttons">
<a href="http://www.whatbrowser.org/">What's Browser?</a>
<a href="" onclick="Lovely.module('hello-ie').hide(); return false">Continue</a>
</p>
</div>
"""
document.body.appendChild(element)
hide = ->
element = document.getElementById('hello-ie')
document.body.removeChild(element)
|
[
{
"context": "### ^\nBSD 3-Clause License\n\nCopyright (c) 2017, Stephan Jorek\nAll rights reserved.\n\nRedistribution and use in s",
"end": 61,
"score": 0.9998389482498169,
"start": 48,
"tag": "NAME",
"value": "Stephan Jorek"
}
] | src/Repl.coffee | sjorek/goatee-script.js | 0 | ### ^
BSD 3-Clause License
Copyright (c) 2017, Stephan Jorek
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
fs = require 'fs'
path = require 'path'
#vm = require 'vm'
NodeRepl = require 'repl'
{
compile,
evaluate,
render,
stringify
} = require './GoateeScript'
Expression = require './Expression'
{
isArray
} = require './Utility'
###
# # REPL …
# -------------
#
# … **R**ead → **E**xecute → **P**rint → **L**oop !
#
####
###*
# -------------
# @class Repl
# @namespace GoateeScript
###
class Repl
###*
# -------------
# Creates a nice error message like, following the "standard" format
# <filename>:<line>:<col>: <message> plus the line with the error and a marker
# showing where the error is.
#
# @function _prettyErrorMessage
# @param {Boolean|Array|Error} [error]
# @param {String} [filename]
# @param {Number} [code]
# @param {Boolean|Function} [colorize]
# @private
###
_prettyErrorMessage = (error, filename, code, colorize) ->
if not error? or error is false or ( isArray(error) and error.length is 0 )
return null
if isArray error
message = []
for e in error
message.push _prettyErrorMessage(e, filename, code, colorize)
return message.join("\n——\n")
# Prefer original source file information stored in the error if present.
filename = error.filename or filename
code = error.code or code
message = error.message
if colorize?
if colorize is yes
colorize = (str) -> "\x1B[1;31m#{str}\x1B[0m"
message = colorize message
"""
#{filename}: #{message}
"""
###*
# -------------
# @function _addMultilineHandler
# @param {Repl} [repl]
# @private
###
_addMultilineHandler = (repl) ->
{rli, inputStream, outputStream} = repl
# Node 0.11.12 changed API, prompt is now _prompt.
origPrompt = repl._prompt ? repl.prompt
multiline =
enabled: off
initialPrompt: origPrompt.replace(/^[^> ]*/, (x) -> x.replace(/./g, '-'))
prompt: origPrompt.replace(/^[^> ]*>?/, (x) -> x.replace(/./g, '.'))
buffer: ''
# Proxy node's line listener
nodeLineListener = rli.listeners('line')[0]
rli.removeListener 'line', nodeLineListener
rli.on 'line', (cmd) ->
if multiline.enabled
multiline.buffer += "#{cmd}\n"
rli.setPrompt multiline.prompt
rli.prompt true
else
nodeLineListener cmd
return
# Handle Ctrl-v
inputStream.on 'keypress', (char, key) ->
return unless key and key.ctrl and not key.meta and not key.shift and key.name is 'v'
if multiline.enabled
# allow arbitrarily switching between modes
# any time before multiple lines are entered
unless multiline.buffer.match /\n/
multiline.enabled = not multiline.enabled
rli.setPrompt origPrompt
rli.prompt true
return
# no-op unless the current line is empty
return if rli.line? and not rli.line.match /^\s*$/
# eval, print, loop
multiline.enabled = not multiline.enabled
rli.line = ''
rli.cursor = 0
rli.output.cursorTo 0
rli.output.clearLine 1
# XXX: multiline hack
multiline.buffer = multiline.buffer.replace /\n/g, '\uFF00'
rli.emit 'line', multiline.buffer
multiline.buffer = ''
else
multiline.enabled = not multiline.enabled
rli.setPrompt multiline.initialPrompt
rli.prompt true
return
###*
# -------------
# Store and load command history from a file
#
# @function _addHistory
# @param {Repl} [repl]
# @param {String} [filename]
# @param {Number} [maxSize]
# @private
###
_addHistory = (repl, filename, maxSize) ->
lastLine = null
try
# Get file info and at most maxSize of command history
stat = fs.statSync filename
size = Math.min maxSize, stat.size
# Read last `size` bytes from the file
readFd = fs.openSync filename, 'r'
buffer = new Buffer(size)
fs.readSync readFd, buffer, 0, size, stat.size - size
# Set the history on the interpreter
repl.rli.history = buffer.toString().split('\n').reverse()
# If the history file was truncated we
# should pop off a potential partial line
repl.rli.history.pop() if stat.size > maxSize
# Shift off the final blank newline
repl.rli.history.shift() if repl.rli.history[0] is ''
repl.rli.historyIndex = -1
lastLine = repl.rli.history[0]
fd = fs.openSync filename, 'a'
repl.rli.addListener 'line', (code) ->
if code and code.length and code isnt '.history' and lastLine isnt code
# Save the latest command in the file
fs.write fd, "#{code}\n"
lastLine = code
repl.rli.on 'exit', -> fs.close fd
# Add a command to show the history stack
repl.commands['.history'] =
help: 'Show command history'
action: ->
repl.outputStream.write "#{repl.rli.history[..].reverse().join '\n'}\n"
repl.displayPrompt()
###*
# -------------
# @property defaults
# @type {Object}
###
Repl.defaults = _options =
command: {}
context: {}
variables: {}
###*
# -------------
# @function defaults.eval
# @param {String} input
# @param {Object} [context]
# @param {Number} [code]
# @param {Function} [callback]
###
eval: (input, context, filename, callback) ->
# XXX: multiline hack.
input = input.replace /\uFF00/g, '\n'
# Node's REPL sends the input ending with a newline and then wrapped in
# parens. Unwrap all that.
input = input.replace /^\(([\s\S]*)\n\)$/m, '$1'
context = _options.context || context
variables = _options.variables || _options.variables={}
error = []
{
compile,
evaluate,
parse,
render,
stringify
} = _options.command
{
mode,
compress
} = _options.flags
Expression.callback (expression, result, stack, errors) ->
context['_'] = result
for own key, value of stack.local
variables[key] = value
error = error.concat(errors) if errors?
return
try
output =
switch mode
when 'c' then compile input, null, compress
when 'p' then stringify input, null, compress
when 'r' then render input, null, compress
when 's' then parse input
else evaluate input, context, variables
callback _prettyErrorMessage(error, filename, input, yes), output
#callback null, vm.runInContext(js, context, filename)
catch error
callback _prettyErrorMessage(error, filename, input, yes)
return
###*
# -------------
# @method start
# @param {Object} command
# @param {Object} [flags={}]
# @param {Object} [options=defaults.options]
# @param {Boolean|Function} [colorize]
# @static
###
Repl.start = (command, flags = {}, options = _options) ->
[
major, minor #, build
] = process.versions.node.split('.').map (n) -> parseInt(n)
if major is 0 and minor < 10
console.warn "Node 0.10.0+ required for #{command.NAME} REPL"
process.exit 1
_options = options
_options.command = command
_options.flags = flags
_options.prompt = "#{command.NAME}> "
if process.env.HOME
_options.historyFile = path.join process.env.HOME, ".#{command.NAME}_history"
_options.historyMaxInputSize = 10240
repl = NodeRepl.start options
repl.on 'exit', -> repl.outputStream.write '\n'
_addMultilineHandler repl
if _options.historyFile?
_addHistory repl, _options.historyFile, _options.historyMaxInputSize
repl
module.exports = Repl
| 94319 | ### ^
BSD 3-Clause License
Copyright (c) 2017, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
fs = require 'fs'
path = require 'path'
#vm = require 'vm'
NodeRepl = require 'repl'
{
compile,
evaluate,
render,
stringify
} = require './GoateeScript'
Expression = require './Expression'
{
isArray
} = require './Utility'
###
# # REPL …
# -------------
#
# … **R**ead → **E**xecute → **P**rint → **L**oop !
#
####
###*
# -------------
# @class Repl
# @namespace GoateeScript
###
class Repl
###*
# -------------
# Creates a nice error message like, following the "standard" format
# <filename>:<line>:<col>: <message> plus the line with the error and a marker
# showing where the error is.
#
# @function _prettyErrorMessage
# @param {Boolean|Array|Error} [error]
# @param {String} [filename]
# @param {Number} [code]
# @param {Boolean|Function} [colorize]
# @private
###
_prettyErrorMessage = (error, filename, code, colorize) ->
if not error? or error is false or ( isArray(error) and error.length is 0 )
return null
if isArray error
message = []
for e in error
message.push _prettyErrorMessage(e, filename, code, colorize)
return message.join("\n——\n")
# Prefer original source file information stored in the error if present.
filename = error.filename or filename
code = error.code or code
message = error.message
if colorize?
if colorize is yes
colorize = (str) -> "\x1B[1;31m#{str}\x1B[0m"
message = colorize message
"""
#{filename}: #{message}
"""
###*
# -------------
# @function _addMultilineHandler
# @param {Repl} [repl]
# @private
###
_addMultilineHandler = (repl) ->
{rli, inputStream, outputStream} = repl
# Node 0.11.12 changed API, prompt is now _prompt.
origPrompt = repl._prompt ? repl.prompt
multiline =
enabled: off
initialPrompt: origPrompt.replace(/^[^> ]*/, (x) -> x.replace(/./g, '-'))
prompt: origPrompt.replace(/^[^> ]*>?/, (x) -> x.replace(/./g, '.'))
buffer: ''
# Proxy node's line listener
nodeLineListener = rli.listeners('line')[0]
rli.removeListener 'line', nodeLineListener
rli.on 'line', (cmd) ->
if multiline.enabled
multiline.buffer += "#{cmd}\n"
rli.setPrompt multiline.prompt
rli.prompt true
else
nodeLineListener cmd
return
# Handle Ctrl-v
inputStream.on 'keypress', (char, key) ->
return unless key and key.ctrl and not key.meta and not key.shift and key.name is 'v'
if multiline.enabled
# allow arbitrarily switching between modes
# any time before multiple lines are entered
unless multiline.buffer.match /\n/
multiline.enabled = not multiline.enabled
rli.setPrompt origPrompt
rli.prompt true
return
# no-op unless the current line is empty
return if rli.line? and not rli.line.match /^\s*$/
# eval, print, loop
multiline.enabled = not multiline.enabled
rli.line = ''
rli.cursor = 0
rli.output.cursorTo 0
rli.output.clearLine 1
# XXX: multiline hack
multiline.buffer = multiline.buffer.replace /\n/g, '\uFF00'
rli.emit 'line', multiline.buffer
multiline.buffer = ''
else
multiline.enabled = not multiline.enabled
rli.setPrompt multiline.initialPrompt
rli.prompt true
return
###*
# -------------
# Store and load command history from a file
#
# @function _addHistory
# @param {Repl} [repl]
# @param {String} [filename]
# @param {Number} [maxSize]
# @private
###
_addHistory = (repl, filename, maxSize) ->
lastLine = null
try
# Get file info and at most maxSize of command history
stat = fs.statSync filename
size = Math.min maxSize, stat.size
# Read last `size` bytes from the file
readFd = fs.openSync filename, 'r'
buffer = new Buffer(size)
fs.readSync readFd, buffer, 0, size, stat.size - size
# Set the history on the interpreter
repl.rli.history = buffer.toString().split('\n').reverse()
# If the history file was truncated we
# should pop off a potential partial line
repl.rli.history.pop() if stat.size > maxSize
# Shift off the final blank newline
repl.rli.history.shift() if repl.rli.history[0] is ''
repl.rli.historyIndex = -1
lastLine = repl.rli.history[0]
fd = fs.openSync filename, 'a'
repl.rli.addListener 'line', (code) ->
if code and code.length and code isnt '.history' and lastLine isnt code
# Save the latest command in the file
fs.write fd, "#{code}\n"
lastLine = code
repl.rli.on 'exit', -> fs.close fd
# Add a command to show the history stack
repl.commands['.history'] =
help: 'Show command history'
action: ->
repl.outputStream.write "#{repl.rli.history[..].reverse().join '\n'}\n"
repl.displayPrompt()
###*
# -------------
# @property defaults
# @type {Object}
###
Repl.defaults = _options =
command: {}
context: {}
variables: {}
###*
# -------------
# @function defaults.eval
# @param {String} input
# @param {Object} [context]
# @param {Number} [code]
# @param {Function} [callback]
###
eval: (input, context, filename, callback) ->
# XXX: multiline hack.
input = input.replace /\uFF00/g, '\n'
# Node's REPL sends the input ending with a newline and then wrapped in
# parens. Unwrap all that.
input = input.replace /^\(([\s\S]*)\n\)$/m, '$1'
context = _options.context || context
variables = _options.variables || _options.variables={}
error = []
{
compile,
evaluate,
parse,
render,
stringify
} = _options.command
{
mode,
compress
} = _options.flags
Expression.callback (expression, result, stack, errors) ->
context['_'] = result
for own key, value of stack.local
variables[key] = value
error = error.concat(errors) if errors?
return
try
output =
switch mode
when 'c' then compile input, null, compress
when 'p' then stringify input, null, compress
when 'r' then render input, null, compress
when 's' then parse input
else evaluate input, context, variables
callback _prettyErrorMessage(error, filename, input, yes), output
#callback null, vm.runInContext(js, context, filename)
catch error
callback _prettyErrorMessage(error, filename, input, yes)
return
###*
# -------------
# @method start
# @param {Object} command
# @param {Object} [flags={}]
# @param {Object} [options=defaults.options]
# @param {Boolean|Function} [colorize]
# @static
###
Repl.start = (command, flags = {}, options = _options) ->
[
major, minor #, build
] = process.versions.node.split('.').map (n) -> parseInt(n)
if major is 0 and minor < 10
console.warn "Node 0.10.0+ required for #{command.NAME} REPL"
process.exit 1
_options = options
_options.command = command
_options.flags = flags
_options.prompt = "#{command.NAME}> "
if process.env.HOME
_options.historyFile = path.join process.env.HOME, ".#{command.NAME}_history"
_options.historyMaxInputSize = 10240
repl = NodeRepl.start options
repl.on 'exit', -> repl.outputStream.write '\n'
_addMultilineHandler repl
if _options.historyFile?
_addHistory repl, _options.historyFile, _options.historyMaxInputSize
repl
module.exports = Repl
| true | ### ^
BSD 3-Clause License
Copyright (c) 2017, PI:NAME:<NAME>END_PI
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
fs = require 'fs'
path = require 'path'
#vm = require 'vm'
NodeRepl = require 'repl'
{
compile,
evaluate,
render,
stringify
} = require './GoateeScript'
Expression = require './Expression'
{
isArray
} = require './Utility'
###
# # REPL …
# -------------
#
# … **R**ead → **E**xecute → **P**rint → **L**oop !
#
####
###*
# -------------
# @class Repl
# @namespace GoateeScript
###
class Repl
###*
# -------------
# Creates a nice error message like, following the "standard" format
# <filename>:<line>:<col>: <message> plus the line with the error and a marker
# showing where the error is.
#
# @function _prettyErrorMessage
# @param {Boolean|Array|Error} [error]
# @param {String} [filename]
# @param {Number} [code]
# @param {Boolean|Function} [colorize]
# @private
###
_prettyErrorMessage = (error, filename, code, colorize) ->
if not error? or error is false or ( isArray(error) and error.length is 0 )
return null
if isArray error
message = []
for e in error
message.push _prettyErrorMessage(e, filename, code, colorize)
return message.join("\n——\n")
# Prefer original source file information stored in the error if present.
filename = error.filename or filename
code = error.code or code
message = error.message
if colorize?
if colorize is yes
colorize = (str) -> "\x1B[1;31m#{str}\x1B[0m"
message = colorize message
"""
#{filename}: #{message}
"""
###*
# -------------
# @function _addMultilineHandler
# @param {Repl} [repl]
# @private
###
_addMultilineHandler = (repl) ->
{rli, inputStream, outputStream} = repl
# Node 0.11.12 changed API, prompt is now _prompt.
origPrompt = repl._prompt ? repl.prompt
multiline =
enabled: off
initialPrompt: origPrompt.replace(/^[^> ]*/, (x) -> x.replace(/./g, '-'))
prompt: origPrompt.replace(/^[^> ]*>?/, (x) -> x.replace(/./g, '.'))
buffer: ''
# Proxy node's line listener
nodeLineListener = rli.listeners('line')[0]
rli.removeListener 'line', nodeLineListener
rli.on 'line', (cmd) ->
if multiline.enabled
multiline.buffer += "#{cmd}\n"
rli.setPrompt multiline.prompt
rli.prompt true
else
nodeLineListener cmd
return
# Handle Ctrl-v
inputStream.on 'keypress', (char, key) ->
return unless key and key.ctrl and not key.meta and not key.shift and key.name is 'v'
if multiline.enabled
# allow arbitrarily switching between modes
# any time before multiple lines are entered
unless multiline.buffer.match /\n/
multiline.enabled = not multiline.enabled
rli.setPrompt origPrompt
rli.prompt true
return
# no-op unless the current line is empty
return if rli.line? and not rli.line.match /^\s*$/
# eval, print, loop
multiline.enabled = not multiline.enabled
rli.line = ''
rli.cursor = 0
rli.output.cursorTo 0
rli.output.clearLine 1
# XXX: multiline hack
multiline.buffer = multiline.buffer.replace /\n/g, '\uFF00'
rli.emit 'line', multiline.buffer
multiline.buffer = ''
else
multiline.enabled = not multiline.enabled
rli.setPrompt multiline.initialPrompt
rli.prompt true
return
###*
# -------------
# Store and load command history from a file
#
# @function _addHistory
# @param {Repl} [repl]
# @param {String} [filename]
# @param {Number} [maxSize]
# @private
###
_addHistory = (repl, filename, maxSize) ->
lastLine = null
try
# Get file info and at most maxSize of command history
stat = fs.statSync filename
size = Math.min maxSize, stat.size
# Read last `size` bytes from the file
readFd = fs.openSync filename, 'r'
buffer = new Buffer(size)
fs.readSync readFd, buffer, 0, size, stat.size - size
# Set the history on the interpreter
repl.rli.history = buffer.toString().split('\n').reverse()
# If the history file was truncated we
# should pop off a potential partial line
repl.rli.history.pop() if stat.size > maxSize
# Shift off the final blank newline
repl.rli.history.shift() if repl.rli.history[0] is ''
repl.rli.historyIndex = -1
lastLine = repl.rli.history[0]
fd = fs.openSync filename, 'a'
repl.rli.addListener 'line', (code) ->
if code and code.length and code isnt '.history' and lastLine isnt code
# Save the latest command in the file
fs.write fd, "#{code}\n"
lastLine = code
repl.rli.on 'exit', -> fs.close fd
# Add a command to show the history stack
repl.commands['.history'] =
help: 'Show command history'
action: ->
repl.outputStream.write "#{repl.rli.history[..].reverse().join '\n'}\n"
repl.displayPrompt()
###*
# -------------
# @property defaults
# @type {Object}
###
Repl.defaults = _options =
command: {}
context: {}
variables: {}
###*
# -------------
# @function defaults.eval
# @param {String} input
# @param {Object} [context]
# @param {Number} [code]
# @param {Function} [callback]
###
eval: (input, context, filename, callback) ->
# XXX: multiline hack.
input = input.replace /\uFF00/g, '\n'
# Node's REPL sends the input ending with a newline and then wrapped in
# parens. Unwrap all that.
input = input.replace /^\(([\s\S]*)\n\)$/m, '$1'
context = _options.context || context
variables = _options.variables || _options.variables={}
error = []
{
compile,
evaluate,
parse,
render,
stringify
} = _options.command
{
mode,
compress
} = _options.flags
Expression.callback (expression, result, stack, errors) ->
context['_'] = result
for own key, value of stack.local
variables[key] = value
error = error.concat(errors) if errors?
return
try
output =
switch mode
when 'c' then compile input, null, compress
when 'p' then stringify input, null, compress
when 'r' then render input, null, compress
when 's' then parse input
else evaluate input, context, variables
callback _prettyErrorMessage(error, filename, input, yes), output
#callback null, vm.runInContext(js, context, filename)
catch error
callback _prettyErrorMessage(error, filename, input, yes)
return
###*
# -------------
# @method start
# @param {Object} command
# @param {Object} [flags={}]
# @param {Object} [options=defaults.options]
# @param {Boolean|Function} [colorize]
# @static
###
Repl.start = (command, flags = {}, options = _options) ->
[
major, minor #, build
] = process.versions.node.split('.').map (n) -> parseInt(n)
if major is 0 and minor < 10
console.warn "Node 0.10.0+ required for #{command.NAME} REPL"
process.exit 1
_options = options
_options.command = command
_options.flags = flags
_options.prompt = "#{command.NAME}> "
if process.env.HOME
_options.historyFile = path.join process.env.HOME, ".#{command.NAME}_history"
_options.historyMaxInputSize = 10240
repl = NodeRepl.start options
repl.on 'exit', -> repl.outputStream.write '\n'
_addMultilineHandler repl
if _options.historyFile?
_addHistory repl, _options.historyFile, _options.historyMaxInputSize
repl
module.exports = Repl
|
[
{
"context": "# times - times loop for your coffee.\n#\n# Author: Veselin Todorov <hi@vesln.com>\n# Licensed under the MIT License.\n",
"end": 65,
"score": 0.9998748302459717,
"start": 50,
"tag": "NAME",
"value": "Veselin Todorov"
},
{
"context": "oop for your coffee.\n#\n# Author: V... | src/times.coffee | vesln/times | 1 | # times - times loop for your coffee.
#
# Author: Veselin Todorov <hi@vesln.com>
# Licensed under the MIT License.
# Dependencies.
package = require('package')(module)
# Simple forEach proxy
times = (number, cb) ->
collection = []
[1..number].forEach (el, index, array) ->
if 'function' != typeof cb
collection.push cb
else
collection.push cb(el, index, array)
collection
# Extending the Number object.
Number::times = (cb) ->
times @, cb
# Exporting the lib.
module.exports = times
# Version
module.exports.version = package.version | 130570 | # times - times loop for your coffee.
#
# Author: <NAME> <<EMAIL>>
# Licensed under the MIT License.
# Dependencies.
package = require('package')(module)
# Simple forEach proxy
times = (number, cb) ->
collection = []
[1..number].forEach (el, index, array) ->
if 'function' != typeof cb
collection.push cb
else
collection.push cb(el, index, array)
collection
# Extending the Number object.
Number::times = (cb) ->
times @, cb
# Exporting the lib.
module.exports = times
# Version
module.exports.version = package.version | true | # times - times loop for your coffee.
#
# Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Licensed under the MIT License.
# Dependencies.
package = require('package')(module)
# Simple forEach proxy
times = (number, cb) ->
collection = []
[1..number].forEach (el, index, array) ->
if 'function' != typeof cb
collection.push cb
else
collection.push cb(el, index, array)
collection
# Extending the Number object.
Number::times = (cb) ->
times @, cb
# Exporting the lib.
module.exports = times
# Version
module.exports.version = package.version |
[
{
"context": "##\n##\n## Forked from Jeff Mott's CryptoJS\n##\n## https://code.google.com/p/cryp",
"end": 30,
"score": 0.9998688697814941,
"start": 21,
"tag": "NAME",
"value": "Jeff Mott"
},
{
"context": " update : (lo,hi) =>\n for i in [lo...hi] by @bsiw\n @encrypt... | src/algbase.iced | CyberFlameGO/triplesec | 274 | ##
##
## Forked from Jeff Mott's CryptoJS
##
## https://code.google.com/p/crypto-js/
##
{WordArray} = require './wordarray'
util = require './util'
#=======================================================================
#
# Abstract buffered block algorithm template.
#
# The property blockSize must be implemented in a concrete subtype.
#
# @property {Number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
#
class BufferedBlockAlgorithm
_minBufferSize : 0
# Does little other than eset/initialize internal state.
constructor : () ->
@reset()
# Resets this block algorithm's data buffer to its initial state.
reset : () ->
@_data = new WordArray()
@_nDataBytes = 0
# Adds new data to this block algorithm's buffer.
#
# @param {WordArray} data The data to append. Strings are converted to a WordArray using UTF-8.
#
# @example
# bufferedBlockAlgorithm._append(wordArray);
_append : (data) ->
@_data.concat data
@_nDataBytes += data.sigBytes
#
# Processes available data blocks.
#
# This method invokes _doProcessBlock(offset), which must be implemented
# by a concrete subtype.
#
# @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
# @return {WordArray} The processed data.
#
# @example
# processedData = bufferedBlockAlgorithm._process();
# processedData = bufferedBlockAlgorithm._process(!!'flush');
#
_process : (doFlush) ->
data = @_data
dataWords = data.words
dataSigBytes = data.sigBytes
blockSizeBytes = @blockSize * 4
# Count blocks ready
nBlocksReady = dataSigBytes / blockSizeBytes
if doFlush
# Round up to include partial blocks
nBlocksReady = Math.ceil nBlocksReady
else
# Round down to include only full blocks,
# less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
# Count words ready
nWordsReady = nBlocksReady * @blockSize
#Count bytes ready
nBytesReady = Math.min(nWordsReady * 4, dataSigBytes)
# Process blocks
if nWordsReady
for offset in [0...nWordsReady] by @blockSize
# Perform concrete-algorithm logic
@_doProcessBlock dataWords, offset
# Remove processed words
processedWords = dataWords.splice 0, nWordsReady
data.sigBytes -= nBytesReady
# Return processed words
new WordArray processedWords, nBytesReady
# Copy the contents of the algorithm base to the given target
# object (of the same class). Used in cloning.
#
# @param {BufferedBlockAlgorithm} out The object to copy to.
copy_to : (out) ->
out._data = @_data.clone()
out._nDataBytes = @_nDataBytes
#
# Creates a copy of this object.
#
# @return {Object} The clone.
#
clone : ->
obj = new BufferedBlockAlgorithm()
@copy_to obj
obj
#=======================================================================
#
# Abstract hasher template.
#
# @property {Number} blockSize The number of 32-bit words this hasher
# operates on. Default: 16 (512 bits)
#
class Hasher extends BufferedBlockAlgorithm
constructor : () ->
super()
#
# Resets this hasher to its initial state.
#
# @return {Hasher} Return `this` object for chaining
reset : () ->
super()
# Perform concrete-hasher logic
@_doReset()
@
#
# Updates this hasher with a message.
#
# @param {WordArray} messageUpdate The message to append.
#
# @return {Hasher} This hasher for chaining.
#
update : (messageUpdate) ->
@_append(messageUpdate)
@_process()
@
#
# Finalizes the hash computation.
# Note that the finalize operation is effectively a destructive,
# read-once operation.
#
# @param {WordArray} messageUpdate (Optional) A final message update.
# @return {WordArray} The output hash message digest.
#
# @example
# hash = hasher.finalize()
# hash = hasher.finalize(wordArray)
#
finalize : (messageUpdate) ->
@_append messageUpdate if messageUpdate
@_doFinalize()
#
# Hashes from a buffer to a buffer
#
# @param {Buffer} input
# @return {Buffer} output
#
bufhash : (input) ->
wa_in = WordArray.from_buffer input
wa_out = @finalize wa_in
out = wa_out.to_buffer()
wa_in.scrub()
wa_out.scrub()
out
#=======================================================================
exports.BlockCipher = class BlockCipher
constructor : (key) ->
encryptBlock : (M, offset) ->
#=======================================================================
# A base class for a stream cipher. This will be used for bonafide stream ciphers
# like {Salsa20} but also for {BlockCipher}s running in CTR mode.
class StreamCipher
constructor : () ->
# Encrypt one block's worth of data. Use the next block
# in the keystream (order matters here!). Call into the
# virtual @get_pad() function to get the pad from the underlying
# block cipher for this block.
#
# @param {WordArray} word_array The WordArray to operator on
# @param {Number} dst_offset The offset to operate on, in wordGs
# @return {Number} the number of blocks encrypted
encryptBlock : (word_array, dst_offset = 0) ->
pad = @get_pad()
#console.log "pad -> #{pad.to_hex()}"
n_words = Math.min(word_array.words.length - dst_offset, @bsiw)
word_array.xor pad, { dst_offset, n_words }
pad.scrub()
@bsiw
#---------------------
# Encrypt an entire word array in place, overwriting the original
# plaintext with the cipher text.
#
# @param {WordArray} word_array The plaintext and also the ciphertext location.
# @return {WordArray} Return `word_array` too just for convenient chaining.
encrypt : (word_array) ->
for i in [0...word_array.words.length] by @bsiw
@encryptBlock word_array, i
word_array
#---------------------
# Like `encrypt` but with an asynchronous preemptable interface. Good
# for encrypting big payloads without blocking up the process. As above,
# encrypt in place, so the output ciphertext will be where the input
# plaintext was.
#
# @param {WordArray} input The input cipher text
# @param {Function} progress_hook A standard progress hook
# @param {String} what What the progress hook should say we are doing.
# @param {callback} cb Callback with the completed ciphertext after completion.
bulk_encrypt : ({input, progress_hook, what}, cb) ->
slice_args =
update : (lo,hi) =>
for i in [lo...hi] by @bsiw
@encryptBlock input, i
finalize : () -> input
default_n : @bsiw * 1024
async_args = {progress_hook, cb, what }
util.bulk input.sigBytes, slice_args, async_args
#=======================================================================
exports.BlockCipher = BlockCipher
exports.Hasher = Hasher
exports.BufferedBlockAlgorithm = BufferedBlockAlgorithm
exports.StreamCipher = StreamCipher
| 195234 | ##
##
## Forked from <NAME>'s CryptoJS
##
## https://code.google.com/p/crypto-js/
##
{WordArray} = require './wordarray'
util = require './util'
#=======================================================================
#
# Abstract buffered block algorithm template.
#
# The property blockSize must be implemented in a concrete subtype.
#
# @property {Number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
#
class BufferedBlockAlgorithm
_minBufferSize : 0
# Does little other than eset/initialize internal state.
constructor : () ->
@reset()
# Resets this block algorithm's data buffer to its initial state.
reset : () ->
@_data = new WordArray()
@_nDataBytes = 0
# Adds new data to this block algorithm's buffer.
#
# @param {WordArray} data The data to append. Strings are converted to a WordArray using UTF-8.
#
# @example
# bufferedBlockAlgorithm._append(wordArray);
_append : (data) ->
@_data.concat data
@_nDataBytes += data.sigBytes
#
# Processes available data blocks.
#
# This method invokes _doProcessBlock(offset), which must be implemented
# by a concrete subtype.
#
# @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
# @return {WordArray} The processed data.
#
# @example
# processedData = bufferedBlockAlgorithm._process();
# processedData = bufferedBlockAlgorithm._process(!!'flush');
#
_process : (doFlush) ->
data = @_data
dataWords = data.words
dataSigBytes = data.sigBytes
blockSizeBytes = @blockSize * 4
# Count blocks ready
nBlocksReady = dataSigBytes / blockSizeBytes
if doFlush
# Round up to include partial blocks
nBlocksReady = Math.ceil nBlocksReady
else
# Round down to include only full blocks,
# less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
# Count words ready
nWordsReady = nBlocksReady * @blockSize
#Count bytes ready
nBytesReady = Math.min(nWordsReady * 4, dataSigBytes)
# Process blocks
if nWordsReady
for offset in [0...nWordsReady] by @blockSize
# Perform concrete-algorithm logic
@_doProcessBlock dataWords, offset
# Remove processed words
processedWords = dataWords.splice 0, nWordsReady
data.sigBytes -= nBytesReady
# Return processed words
new WordArray processedWords, nBytesReady
# Copy the contents of the algorithm base to the given target
# object (of the same class). Used in cloning.
#
# @param {BufferedBlockAlgorithm} out The object to copy to.
copy_to : (out) ->
out._data = @_data.clone()
out._nDataBytes = @_nDataBytes
#
# Creates a copy of this object.
#
# @return {Object} The clone.
#
clone : ->
obj = new BufferedBlockAlgorithm()
@copy_to obj
obj
#=======================================================================
#
# Abstract hasher template.
#
# @property {Number} blockSize The number of 32-bit words this hasher
# operates on. Default: 16 (512 bits)
#
class Hasher extends BufferedBlockAlgorithm
constructor : () ->
super()
#
# Resets this hasher to its initial state.
#
# @return {Hasher} Return `this` object for chaining
reset : () ->
super()
# Perform concrete-hasher logic
@_doReset()
@
#
# Updates this hasher with a message.
#
# @param {WordArray} messageUpdate The message to append.
#
# @return {Hasher} This hasher for chaining.
#
update : (messageUpdate) ->
@_append(messageUpdate)
@_process()
@
#
# Finalizes the hash computation.
# Note that the finalize operation is effectively a destructive,
# read-once operation.
#
# @param {WordArray} messageUpdate (Optional) A final message update.
# @return {WordArray} The output hash message digest.
#
# @example
# hash = hasher.finalize()
# hash = hasher.finalize(wordArray)
#
finalize : (messageUpdate) ->
@_append messageUpdate if messageUpdate
@_doFinalize()
#
# Hashes from a buffer to a buffer
#
# @param {Buffer} input
# @return {Buffer} output
#
bufhash : (input) ->
wa_in = WordArray.from_buffer input
wa_out = @finalize wa_in
out = wa_out.to_buffer()
wa_in.scrub()
wa_out.scrub()
out
#=======================================================================
exports.BlockCipher = class BlockCipher
constructor : (key) ->
encryptBlock : (M, offset) ->
#=======================================================================
# A base class for a stream cipher. This will be used for bonafide stream ciphers
# like {Salsa20} but also for {BlockCipher}s running in CTR mode.
class StreamCipher
constructor : () ->
# Encrypt one block's worth of data. Use the next block
# in the keystream (order matters here!). Call into the
# virtual @get_pad() function to get the pad from the underlying
# block cipher for this block.
#
# @param {WordArray} word_array The WordArray to operator on
# @param {Number} dst_offset The offset to operate on, in wordGs
# @return {Number} the number of blocks encrypted
encryptBlock : (word_array, dst_offset = 0) ->
pad = @get_pad()
#console.log "pad -> #{pad.to_hex()}"
n_words = Math.min(word_array.words.length - dst_offset, @bsiw)
word_array.xor pad, { dst_offset, n_words }
pad.scrub()
@bsiw
#---------------------
# Encrypt an entire word array in place, overwriting the original
# plaintext with the cipher text.
#
# @param {WordArray} word_array The plaintext and also the ciphertext location.
# @return {WordArray} Return `word_array` too just for convenient chaining.
encrypt : (word_array) ->
for i in [0...word_array.words.length] by @bsiw
@encryptBlock word_array, i
word_array
#---------------------
# Like `encrypt` but with an asynchronous preemptable interface. Good
# for encrypting big payloads without blocking up the process. As above,
# encrypt in place, so the output ciphertext will be where the input
# plaintext was.
#
# @param {WordArray} input The input cipher text
# @param {Function} progress_hook A standard progress hook
# @param {String} what What the progress hook should say we are doing.
# @param {callback} cb Callback with the completed ciphertext after completion.
bulk_encrypt : ({input, progress_hook, what}, cb) ->
slice_args =
update : (lo,hi) =>
for i in [lo...hi] by @bsiw
@encryptBlock input, i
finalize : () -> input
default_n : @bsiw * 1024
async_args = {progress_hook, cb, what }
util.bulk input.sigBytes, slice_args, async_args
#=======================================================================
exports.BlockCipher = BlockCipher
exports.Hasher = Hasher
exports.BufferedBlockAlgorithm = BufferedBlockAlgorithm
exports.StreamCipher = StreamCipher
| true | ##
##
## Forked from PI:NAME:<NAME>END_PI's CryptoJS
##
## https://code.google.com/p/crypto-js/
##
{WordArray} = require './wordarray'
util = require './util'
#=======================================================================
#
# Abstract buffered block algorithm template.
#
# The property blockSize must be implemented in a concrete subtype.
#
# @property {Number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
#
class BufferedBlockAlgorithm
_minBufferSize : 0
# Does little other than eset/initialize internal state.
constructor : () ->
@reset()
# Resets this block algorithm's data buffer to its initial state.
reset : () ->
@_data = new WordArray()
@_nDataBytes = 0
# Adds new data to this block algorithm's buffer.
#
# @param {WordArray} data The data to append. Strings are converted to a WordArray using UTF-8.
#
# @example
# bufferedBlockAlgorithm._append(wordArray);
_append : (data) ->
@_data.concat data
@_nDataBytes += data.sigBytes
#
# Processes available data blocks.
#
# This method invokes _doProcessBlock(offset), which must be implemented
# by a concrete subtype.
#
# @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
# @return {WordArray} The processed data.
#
# @example
# processedData = bufferedBlockAlgorithm._process();
# processedData = bufferedBlockAlgorithm._process(!!'flush');
#
_process : (doFlush) ->
data = @_data
dataWords = data.words
dataSigBytes = data.sigBytes
blockSizeBytes = @blockSize * 4
# Count blocks ready
nBlocksReady = dataSigBytes / blockSizeBytes
if doFlush
# Round up to include partial blocks
nBlocksReady = Math.ceil nBlocksReady
else
# Round down to include only full blocks,
# less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
# Count words ready
nWordsReady = nBlocksReady * @blockSize
#Count bytes ready
nBytesReady = Math.min(nWordsReady * 4, dataSigBytes)
# Process blocks
if nWordsReady
for offset in [0...nWordsReady] by @blockSize
# Perform concrete-algorithm logic
@_doProcessBlock dataWords, offset
# Remove processed words
processedWords = dataWords.splice 0, nWordsReady
data.sigBytes -= nBytesReady
# Return processed words
new WordArray processedWords, nBytesReady
# Copy the contents of the algorithm base to the given target
# object (of the same class). Used in cloning.
#
# @param {BufferedBlockAlgorithm} out The object to copy to.
copy_to : (out) ->
out._data = @_data.clone()
out._nDataBytes = @_nDataBytes
#
# Creates a copy of this object.
#
# @return {Object} The clone.
#
clone : ->
obj = new BufferedBlockAlgorithm()
@copy_to obj
obj
#=======================================================================
#
# Abstract hasher template.
#
# @property {Number} blockSize The number of 32-bit words this hasher
# operates on. Default: 16 (512 bits)
#
class Hasher extends BufferedBlockAlgorithm
constructor : () ->
super()
#
# Resets this hasher to its initial state.
#
# @return {Hasher} Return `this` object for chaining
reset : () ->
super()
# Perform concrete-hasher logic
@_doReset()
@
#
# Updates this hasher with a message.
#
# @param {WordArray} messageUpdate The message to append.
#
# @return {Hasher} This hasher for chaining.
#
update : (messageUpdate) ->
@_append(messageUpdate)
@_process()
@
#
# Finalizes the hash computation.
# Note that the finalize operation is effectively a destructive,
# read-once operation.
#
# @param {WordArray} messageUpdate (Optional) A final message update.
# @return {WordArray} The output hash message digest.
#
# @example
# hash = hasher.finalize()
# hash = hasher.finalize(wordArray)
#
finalize : (messageUpdate) ->
@_append messageUpdate if messageUpdate
@_doFinalize()
#
# Hashes from a buffer to a buffer
#
# @param {Buffer} input
# @return {Buffer} output
#
bufhash : (input) ->
wa_in = WordArray.from_buffer input
wa_out = @finalize wa_in
out = wa_out.to_buffer()
wa_in.scrub()
wa_out.scrub()
out
#=======================================================================
exports.BlockCipher = class BlockCipher
constructor : (key) ->
encryptBlock : (M, offset) ->
#=======================================================================
# A base class for a stream cipher. This will be used for bonafide stream ciphers
# like {Salsa20} but also for {BlockCipher}s running in CTR mode.
class StreamCipher
constructor : () ->
# Encrypt one block's worth of data. Use the next block
# in the keystream (order matters here!). Call into the
# virtual @get_pad() function to get the pad from the underlying
# block cipher for this block.
#
# @param {WordArray} word_array The WordArray to operator on
# @param {Number} dst_offset The offset to operate on, in wordGs
# @return {Number} the number of blocks encrypted
encryptBlock : (word_array, dst_offset = 0) ->
pad = @get_pad()
#console.log "pad -> #{pad.to_hex()}"
n_words = Math.min(word_array.words.length - dst_offset, @bsiw)
word_array.xor pad, { dst_offset, n_words }
pad.scrub()
@bsiw
#---------------------
# Encrypt an entire word array in place, overwriting the original
# plaintext with the cipher text.
#
# @param {WordArray} word_array The plaintext and also the ciphertext location.
# @return {WordArray} Return `word_array` too just for convenient chaining.
encrypt : (word_array) ->
for i in [0...word_array.words.length] by @bsiw
@encryptBlock word_array, i
word_array
#---------------------
# Like `encrypt` but with an asynchronous preemptable interface. Good
# for encrypting big payloads without blocking up the process. As above,
# encrypt in place, so the output ciphertext will be where the input
# plaintext was.
#
# @param {WordArray} input The input cipher text
# @param {Function} progress_hook A standard progress hook
# @param {String} what What the progress hook should say we are doing.
# @param {callback} cb Callback with the completed ciphertext after completion.
bulk_encrypt : ({input, progress_hook, what}, cb) ->
slice_args =
update : (lo,hi) =>
for i in [lo...hi] by @bsiw
@encryptBlock input, i
finalize : () -> input
default_n : @bsiw * 1024
async_args = {progress_hook, cb, what }
util.bulk input.sigBytes, slice_args, async_args
#=======================================================================
exports.BlockCipher = BlockCipher
exports.Hasher = Hasher
exports.BufferedBlockAlgorithm = BufferedBlockAlgorithm
exports.StreamCipher = StreamCipher
|
[
{
"context": "###\nCopyright (c) 2014 Ramesh Nair (hiddentao.com)\n\nPermission is hereby granted, fr",
"end": 34,
"score": 0.9998819231987,
"start": 23,
"tag": "NAME",
"value": "Ramesh Nair"
},
{
"context": "es: [2014, '\"feb\"'] }, @inst.toParam()\n\n 'fix for hiddentao/squel#63':... | test/update.test.coffee | nlang/squel-hdb | 0 | ###
Copyright (c) 2014 Ramesh Nair (hiddentao.com)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
###
squel = require "../squel-basic"
{_, testCreator, assert, expect, should} = require './testbase'
test = testCreator()
test['UPDATE builder'] =
beforeEach: ->
@func = squel.update
@inst = @func()
'instanceof QueryBuilder': ->
assert.instanceOf @inst, squel.cls.QueryBuilder
'constructor':
'override options': ->
@inst = squel.update
usingValuePlaceholders: true
dummy: true
expectedOptions = _.extend {}, squel.cls.DefaultQueryBuilderOptions,
usingValuePlaceholders: true
dummy: true
for block in @inst.blocks
if (block instanceof squel.cls.WhereBlock)
assert.same _.extend({}, expectedOptions, { verb: 'WHERE'}), block.options
else
assert.same expectedOptions, block.options
'override blocks': ->
block = new squel.cls.StringBlock('SELECT')
@inst = @func {}, [block]
assert.same [block], @inst.blocks
'build query':
'need to call set() first': ->
@inst.table('table')
assert.throws (=> @inst.toString()), 'set() needs to be called'
'>> table(table, t1).set(field, 1)':
beforeEach: -> @inst.table('table', 't1').set('field', 1)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1'
'>> set(field2, 1.2)':
beforeEach: -> @inst.set('field2', 1.2)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = 1.2'
'>> set(field2, true)':
beforeEach: -> @inst.set('field2', true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = TRUE'
'>> set(field2, null)':
beforeEach: -> @inst.set('field2', null)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = NULL'
toParam: ->
assert.same @inst.toParam(), { text: 'UPDATE table `t1` SET field = 1, field2 = ?', values: [null] }
'>> set(field2, "str")':
beforeEach: -> @inst.set('field2', 'str')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = \'str\''
toParam: ->
assert.same @inst.toParam(), {
text: 'UPDATE table `t1` SET field = ?, field2 = ?'
values: [1, 'str']
}
'>> set(field2, "str", { dontQuote: true })':
beforeEach: -> @inst.set('field2', 'str', dontQuote: true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = str'
toParam: ->
assert.same @inst.toParam(), {
text: 'UPDATE table `t1` SET field = ?, field2 = ?'
values: [1, 'str']
}
'>> set(field, query builder)':
beforeEach: ->
@subQuery = squel.select().field('MAX(score)').from('scores')
@inst.set( 'field', @subQuery )
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = (SELECT MAX(score) FROM scores)'
toParam: ->
parameterized = @inst.toParam()
assert.same parameterized.text, 'UPDATE table `t1` SET field = (SELECT MAX(score) FROM scores)'
assert.same parameterized.values, []
'>> set(custom value type)':
beforeEach: ->
class MyClass
@inst.registerValueHandler MyClass, (a) -> 'abcd'
@inst.set( 'field', new MyClass() )
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = (abcd)'
toParam: ->
parameterized = @inst.toParam()
assert.same parameterized.text, 'UPDATE table `t1` SET field = ?'
assert.same parameterized.values, ['abcd']
'>> setFields({field2: \'value2\', field3: true })':
beforeEach: -> @inst.setFields({field2: 'value2', field3: true })
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = \'value2\', field3 = TRUE'
toParam: ->
parameterized = @inst.toParam()
assert.same parameterized.text, 'UPDATE table `t1` SET field = ?, field2 = ?, field3 = ?'
assert.same parameterized.values, [1, 'value2', true]
'>> setFields({field2: \'value2\', field: true })':
beforeEach: -> @inst.setFields({field2: 'value2', field: true })
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = TRUE, field2 = \'value2\''
'>> set(field2, null)':
beforeEach: -> @inst.set('field2', null)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = NULL'
'>> table(table2)':
beforeEach: -> @inst.table('table2')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL'
'>> where(a = 1)':
beforeEach: -> @inst.where('a = 1')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL WHERE (a = 1)'
'>> order(a, true)':
beforeEach: -> @inst.order('a', true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL WHERE (a = 1) ORDER BY a ASC'
'>> limit(2)':
beforeEach: -> @inst.limit(2)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL WHERE (a = 1) ORDER BY a ASC LIMIT 2'
'>> table(table, t1).setFields({field1: 1, field2: \'value2\'})':
beforeEach: -> @inst.table('table', 't1').setFields({field1: 1, field2: 'value2' })
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = 1, field2 = \'value2\''
'>> set(field1, 1.2)':
beforeEach: -> @inst.set('field1', 1.2)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = 1.2, field2 = \'value2\''
'>> setFields({field3: true, field4: \'value4\'})':
beforeEach: -> @inst.setFields({field3: true, field4: 'value4'})
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = 1, field2 = \'value2\', field3 = TRUE, field4 = \'value4\''
'>> setFields({field1: true, field3: \'value3\'})':
beforeEach: -> @inst.setFields({field1: true, field3: 'value3'})
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = TRUE, field2 = \'value2\', field3 = \'value3\''
'>> table(table, t1).set("count = count + 1")':
beforeEach: -> @inst.table('table', 't1').set('count = count + 1')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET count = count + 1'
'str()':
beforeEach: -> @inst.table('students').set('field', squel.str('GETDATE(?, ?)', 2014, '"feb"'))
toString: ->
assert.same 'UPDATE students SET field = (GETDATE(2014, \'"feb"\'))', @inst.toString()
toParam: ->
assert.same { text: 'UPDATE students SET field = (GETDATE(?, ?))', values: [2014, '"feb"'] }, @inst.toParam()
'fix for hiddentao/squel#63': ->
newinst = @inst.table('students').set('field = field + 1')
newinst.set('field2', 2).set('field3', true)
assert.same { text: 'UPDATE students SET field = field + 1, field2 = ?, field3 = ?', values: [2, true] }, @inst.toParam()
'dontQuote and replaceSingleQuotes set(field2, "ISNULL(\'str\', str)", { dontQuote: true })':
beforeEach: ->
@inst = squel.update replaceSingleQuotes: true
@inst.table('table', 't1').set('field', 1)
@inst.set('field2', "ISNULL('str', str)", dontQuote: true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = ISNULL(\'str\', str)'
toParam: ->
assert.same @inst.toParam(), {
text: 'UPDATE table `t1` SET field = ?, field2 = ?'
values: [1, "ISNULL('str', str)"]
}
'cloning': ->
newinst = @inst.table('students').set('field', 1).clone()
newinst.set('field', 2).set('field2', true)
assert.same 'UPDATE students SET field = 1', @inst.toString()
assert.same 'UPDATE students SET field = 2, field2 = TRUE', newinst.toString()
module?.exports[require('path').basename(__filename)] = test
| 94895 | ###
Copyright (c) 2014 <NAME> (hiddentao.com)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
###
squel = require "../squel-basic"
{_, testCreator, assert, expect, should} = require './testbase'
test = testCreator()
test['UPDATE builder'] =
beforeEach: ->
@func = squel.update
@inst = @func()
'instanceof QueryBuilder': ->
assert.instanceOf @inst, squel.cls.QueryBuilder
'constructor':
'override options': ->
@inst = squel.update
usingValuePlaceholders: true
dummy: true
expectedOptions = _.extend {}, squel.cls.DefaultQueryBuilderOptions,
usingValuePlaceholders: true
dummy: true
for block in @inst.blocks
if (block instanceof squel.cls.WhereBlock)
assert.same _.extend({}, expectedOptions, { verb: 'WHERE'}), block.options
else
assert.same expectedOptions, block.options
'override blocks': ->
block = new squel.cls.StringBlock('SELECT')
@inst = @func {}, [block]
assert.same [block], @inst.blocks
'build query':
'need to call set() first': ->
@inst.table('table')
assert.throws (=> @inst.toString()), 'set() needs to be called'
'>> table(table, t1).set(field, 1)':
beforeEach: -> @inst.table('table', 't1').set('field', 1)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1'
'>> set(field2, 1.2)':
beforeEach: -> @inst.set('field2', 1.2)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = 1.2'
'>> set(field2, true)':
beforeEach: -> @inst.set('field2', true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = TRUE'
'>> set(field2, null)':
beforeEach: -> @inst.set('field2', null)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = NULL'
toParam: ->
assert.same @inst.toParam(), { text: 'UPDATE table `t1` SET field = 1, field2 = ?', values: [null] }
'>> set(field2, "str")':
beforeEach: -> @inst.set('field2', 'str')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = \'str\''
toParam: ->
assert.same @inst.toParam(), {
text: 'UPDATE table `t1` SET field = ?, field2 = ?'
values: [1, 'str']
}
'>> set(field2, "str", { dontQuote: true })':
beforeEach: -> @inst.set('field2', 'str', dontQuote: true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = str'
toParam: ->
assert.same @inst.toParam(), {
text: 'UPDATE table `t1` SET field = ?, field2 = ?'
values: [1, 'str']
}
'>> set(field, query builder)':
beforeEach: ->
@subQuery = squel.select().field('MAX(score)').from('scores')
@inst.set( 'field', @subQuery )
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = (SELECT MAX(score) FROM scores)'
toParam: ->
parameterized = @inst.toParam()
assert.same parameterized.text, 'UPDATE table `t1` SET field = (SELECT MAX(score) FROM scores)'
assert.same parameterized.values, []
'>> set(custom value type)':
beforeEach: ->
class MyClass
@inst.registerValueHandler MyClass, (a) -> 'abcd'
@inst.set( 'field', new MyClass() )
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = (abcd)'
toParam: ->
parameterized = @inst.toParam()
assert.same parameterized.text, 'UPDATE table `t1` SET field = ?'
assert.same parameterized.values, ['abcd']
'>> setFields({field2: \'value2\', field3: true })':
beforeEach: -> @inst.setFields({field2: 'value2', field3: true })
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = \'value2\', field3 = TRUE'
toParam: ->
parameterized = @inst.toParam()
assert.same parameterized.text, 'UPDATE table `t1` SET field = ?, field2 = ?, field3 = ?'
assert.same parameterized.values, [1, 'value2', true]
'>> setFields({field2: \'value2\', field: true })':
beforeEach: -> @inst.setFields({field2: 'value2', field: true })
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = TRUE, field2 = \'value2\''
'>> set(field2, null)':
beforeEach: -> @inst.set('field2', null)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = NULL'
'>> table(table2)':
beforeEach: -> @inst.table('table2')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL'
'>> where(a = 1)':
beforeEach: -> @inst.where('a = 1')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL WHERE (a = 1)'
'>> order(a, true)':
beforeEach: -> @inst.order('a', true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL WHERE (a = 1) ORDER BY a ASC'
'>> limit(2)':
beforeEach: -> @inst.limit(2)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL WHERE (a = 1) ORDER BY a ASC LIMIT 2'
'>> table(table, t1).setFields({field1: 1, field2: \'value2\'})':
beforeEach: -> @inst.table('table', 't1').setFields({field1: 1, field2: 'value2' })
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = 1, field2 = \'value2\''
'>> set(field1, 1.2)':
beforeEach: -> @inst.set('field1', 1.2)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = 1.2, field2 = \'value2\''
'>> setFields({field3: true, field4: \'value4\'})':
beforeEach: -> @inst.setFields({field3: true, field4: 'value4'})
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = 1, field2 = \'value2\', field3 = TRUE, field4 = \'value4\''
'>> setFields({field1: true, field3: \'value3\'})':
beforeEach: -> @inst.setFields({field1: true, field3: 'value3'})
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = TRUE, field2 = \'value2\', field3 = \'value3\''
'>> table(table, t1).set("count = count + 1")':
beforeEach: -> @inst.table('table', 't1').set('count = count + 1')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET count = count + 1'
'str()':
beforeEach: -> @inst.table('students').set('field', squel.str('GETDATE(?, ?)', 2014, '"feb"'))
toString: ->
assert.same 'UPDATE students SET field = (GETDATE(2014, \'"feb"\'))', @inst.toString()
toParam: ->
assert.same { text: 'UPDATE students SET field = (GETDATE(?, ?))', values: [2014, '"feb"'] }, @inst.toParam()
'fix for hiddentao/squel#63': ->
newinst = @inst.table('students').set('field = field + 1')
newinst.set('field2', 2).set('field3', true)
assert.same { text: 'UPDATE students SET field = field + 1, field2 = ?, field3 = ?', values: [2, true] }, @inst.toParam()
'dontQuote and replaceSingleQuotes set(field2, "ISNULL(\'str\', str)", { dontQuote: true })':
beforeEach: ->
@inst = squel.update replaceSingleQuotes: true
@inst.table('table', 't1').set('field', 1)
@inst.set('field2', "ISNULL('str', str)", dontQuote: true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = ISNULL(\'str\', str)'
toParam: ->
assert.same @inst.toParam(), {
text: 'UPDATE table `t1` SET field = ?, field2 = ?'
values: [1, "ISNULL('str', str)"]
}
'cloning': ->
newinst = @inst.table('students').set('field', 1).clone()
newinst.set('field', 2).set('field2', true)
assert.same 'UPDATE students SET field = 1', @inst.toString()
assert.same 'UPDATE students SET field = 2, field2 = TRUE', newinst.toString()
module?.exports[require('path').basename(__filename)] = test
| true | ###
Copyright (c) 2014 PI:NAME:<NAME>END_PI (hiddentao.com)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
###
squel = require "../squel-basic"
{_, testCreator, assert, expect, should} = require './testbase'
test = testCreator()
test['UPDATE builder'] =
beforeEach: ->
@func = squel.update
@inst = @func()
'instanceof QueryBuilder': ->
assert.instanceOf @inst, squel.cls.QueryBuilder
'constructor':
'override options': ->
@inst = squel.update
usingValuePlaceholders: true
dummy: true
expectedOptions = _.extend {}, squel.cls.DefaultQueryBuilderOptions,
usingValuePlaceholders: true
dummy: true
for block in @inst.blocks
if (block instanceof squel.cls.WhereBlock)
assert.same _.extend({}, expectedOptions, { verb: 'WHERE'}), block.options
else
assert.same expectedOptions, block.options
'override blocks': ->
block = new squel.cls.StringBlock('SELECT')
@inst = @func {}, [block]
assert.same [block], @inst.blocks
'build query':
'need to call set() first': ->
@inst.table('table')
assert.throws (=> @inst.toString()), 'set() needs to be called'
'>> table(table, t1).set(field, 1)':
beforeEach: -> @inst.table('table', 't1').set('field', 1)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1'
'>> set(field2, 1.2)':
beforeEach: -> @inst.set('field2', 1.2)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = 1.2'
'>> set(field2, true)':
beforeEach: -> @inst.set('field2', true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = TRUE'
'>> set(field2, null)':
beforeEach: -> @inst.set('field2', null)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = NULL'
toParam: ->
assert.same @inst.toParam(), { text: 'UPDATE table `t1` SET field = 1, field2 = ?', values: [null] }
'>> set(field2, "str")':
beforeEach: -> @inst.set('field2', 'str')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = \'str\''
toParam: ->
assert.same @inst.toParam(), {
text: 'UPDATE table `t1` SET field = ?, field2 = ?'
values: [1, 'str']
}
'>> set(field2, "str", { dontQuote: true })':
beforeEach: -> @inst.set('field2', 'str', dontQuote: true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = str'
toParam: ->
assert.same @inst.toParam(), {
text: 'UPDATE table `t1` SET field = ?, field2 = ?'
values: [1, 'str']
}
'>> set(field, query builder)':
beforeEach: ->
@subQuery = squel.select().field('MAX(score)').from('scores')
@inst.set( 'field', @subQuery )
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = (SELECT MAX(score) FROM scores)'
toParam: ->
parameterized = @inst.toParam()
assert.same parameterized.text, 'UPDATE table `t1` SET field = (SELECT MAX(score) FROM scores)'
assert.same parameterized.values, []
'>> set(custom value type)':
beforeEach: ->
class MyClass
@inst.registerValueHandler MyClass, (a) -> 'abcd'
@inst.set( 'field', new MyClass() )
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = (abcd)'
toParam: ->
parameterized = @inst.toParam()
assert.same parameterized.text, 'UPDATE table `t1` SET field = ?'
assert.same parameterized.values, ['abcd']
'>> setFields({field2: \'value2\', field3: true })':
beforeEach: -> @inst.setFields({field2: 'value2', field3: true })
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = \'value2\', field3 = TRUE'
toParam: ->
parameterized = @inst.toParam()
assert.same parameterized.text, 'UPDATE table `t1` SET field = ?, field2 = ?, field3 = ?'
assert.same parameterized.values, [1, 'value2', true]
'>> setFields({field2: \'value2\', field: true })':
beforeEach: -> @inst.setFields({field2: 'value2', field: true })
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = TRUE, field2 = \'value2\''
'>> set(field2, null)':
beforeEach: -> @inst.set('field2', null)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = NULL'
'>> table(table2)':
beforeEach: -> @inst.table('table2')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL'
'>> where(a = 1)':
beforeEach: -> @inst.where('a = 1')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL WHERE (a = 1)'
'>> order(a, true)':
beforeEach: -> @inst.order('a', true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL WHERE (a = 1) ORDER BY a ASC'
'>> limit(2)':
beforeEach: -> @inst.limit(2)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1`, table2 SET field = 1, field2 = NULL WHERE (a = 1) ORDER BY a ASC LIMIT 2'
'>> table(table, t1).setFields({field1: 1, field2: \'value2\'})':
beforeEach: -> @inst.table('table', 't1').setFields({field1: 1, field2: 'value2' })
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = 1, field2 = \'value2\''
'>> set(field1, 1.2)':
beforeEach: -> @inst.set('field1', 1.2)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = 1.2, field2 = \'value2\''
'>> setFields({field3: true, field4: \'value4\'})':
beforeEach: -> @inst.setFields({field3: true, field4: 'value4'})
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = 1, field2 = \'value2\', field3 = TRUE, field4 = \'value4\''
'>> setFields({field1: true, field3: \'value3\'})':
beforeEach: -> @inst.setFields({field1: true, field3: 'value3'})
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field1 = TRUE, field2 = \'value2\', field3 = \'value3\''
'>> table(table, t1).set("count = count + 1")':
beforeEach: -> @inst.table('table', 't1').set('count = count + 1')
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET count = count + 1'
'str()':
beforeEach: -> @inst.table('students').set('field', squel.str('GETDATE(?, ?)', 2014, '"feb"'))
toString: ->
assert.same 'UPDATE students SET field = (GETDATE(2014, \'"feb"\'))', @inst.toString()
toParam: ->
assert.same { text: 'UPDATE students SET field = (GETDATE(?, ?))', values: [2014, '"feb"'] }, @inst.toParam()
'fix for hiddentao/squel#63': ->
newinst = @inst.table('students').set('field = field + 1')
newinst.set('field2', 2).set('field3', true)
assert.same { text: 'UPDATE students SET field = field + 1, field2 = ?, field3 = ?', values: [2, true] }, @inst.toParam()
'dontQuote and replaceSingleQuotes set(field2, "ISNULL(\'str\', str)", { dontQuote: true })':
beforeEach: ->
@inst = squel.update replaceSingleQuotes: true
@inst.table('table', 't1').set('field', 1)
@inst.set('field2', "ISNULL('str', str)", dontQuote: true)
toString: ->
assert.same @inst.toString(), 'UPDATE table `t1` SET field = 1, field2 = ISNULL(\'str\', str)'
toParam: ->
assert.same @inst.toParam(), {
text: 'UPDATE table `t1` SET field = ?, field2 = ?'
values: [1, "ISNULL('str', str)"]
}
'cloning': ->
newinst = @inst.table('students').set('field', 1).clone()
newinst.set('field', 2).set('field2', true)
assert.same 'UPDATE students SET field = 1', @inst.toString()
assert.same 'UPDATE students SET field = 2, field2 = TRUE', newinst.toString()
module?.exports[require('path').basename(__filename)] = test
|
[
{
"context": "f422-62db-42dc-b1ce-37ca3393710f',\n 'name': 'Magus Repository',\n 'label': 'live',\n 'uri': 'http://arc",
"end": 1730,
"score": 0.8048432469367981,
"start": 1714,
"tag": "NAME",
"value": "Magus Repository"
},
{
"context": "f422-62db-42dc-b1ce-37ca3393710... | test/spec/controllers/main.coffee | TelekomCloud/postrider | 0 | 'use strict'
describe 'Controller: MainCtrl', ()->
# load the required module
beforeEach(angular.mock.module('restangular'))
# load the controller's module
beforeEach(module('postriderApp'))
# Initialize the controller and a mock scope
beforeEach( inject( ($injector, $controller, $rootScope) ->
scope = $rootScope.$new()
@Restangular = $injector.get('Restangular')
@httpBackend = $injector.get('$httpBackend')
# reliably determine object types
# http://stackoverflow.com/questions/7390426/better-way-to-get-type-of-a-javascript-variable
@typeOf = (obj) ->
({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
MainCtrl = $controller('MainCtrl', {
$scope: scope,
Restangular: @Restangular
})
))
afterEach () ->
@httpBackend.verifyNoOutstandingExpectation()
@httpBackend.verifyNoOutstandingRequest()
# Some Mockup data:
#------------------
allNodes1 = nodes = [
{ 'id': 'my1.full.fqdn' },
{ 'id': 'my2.full.fqdn' }
]
allPackages1 = [
{ 'name': 'xx', 'versions': [
{'version':'1.0','id':'xx10'}
], 'upstream': {}
},
{ 'name': 'yy', 'versions': [
{'version':'1.1','id':'yy11'},
{'version':'1.2','id':'yy12'}
], 'upstream': {}
}
]
allPackages2 = [
{ 'name': 'xx', 'versions': [
{'version':'1.0','id':'xx10'}
], 'upstream': {
'latest': '1.0'
}
},
{ 'name': 'yy', 'versions': [
{'version':'1.1','id':'yy11'},
{'version':'1.2','id':'yy12'}
], 'upstream': {
'latest': '2.0'
}
}
]
allRepos1 = [
{
'id': '44e5f422-62db-42dc-b1ce-37ca3393710f',
'name': 'Magus Repository',
'label': 'live',
'uri': 'http://archive.canonical.com/ubuntu/dists/precise/partner/binary-amd64/Packages.gz',
'provider': 'apt'
}
]
allRepos2 = allRepos1.concat [
{
'id': '44e5f422-62db-42dc-b1ce-37ca3393710e',
'name': 'Minas Thorun',
'label': 'ref',
'uri': 'http://archive2.canonical.com/ubuntu/dists/precise/partner/binary-amd64/Packages.gz',
'provider': 'apt'
}
]
package1 = {
'name': 'accountsservice',
'uri': 'http://us.archive.ubuntu.com/ubuntu/pool/main/a/accountsservice/accountsservice_0.6.15-2ubuntu9_amd64.deb',
'summary': 'query and manipulate user account information',
'version': '0.6.15-2ubuntu9',
'architecture': 'amd64',
'provider': 'apt',
'archive': 'precise',
'nodes': [
'my1.full.fqdn'
]
}
package2 = {
'name': 'otherservice',
'uri': 'http://us.archive.ubuntu.com/ubuntu/pool/main/o/otherservice/otherservice_0.6.15-2ubuntu9_amd64.deb',
'summary': 'some other service',
'version': '0.2-2ubuntu9',
'architecture': 'amd64',
'provider': 'apt',
'archive': 'precise',
'nodes': [
'my2.full.fqdn'
]
}
## Helpers:
##---------
build_request = (site, params = [])->
# remove all undefined
p = params.filter (x) -> x?
q = ( p.map (x) -> x.join('=') ).sort().join('&')
if q.length == 0
site
else
"#{site}?#{q}"
paginateResponse = (httpBackend, baseUrl, response, action, opts = {})->
limit = opts.limit || 50
query = [['limit', limit]].concat opts.query
# 1. working pagination
# it will request page 1, get it,
# and request page 2 and finish
url = build_request baseUrl, query.concat [['page', 1]]
httpBackend.whenGET(url).respond(response)
httpBackend.expectGET(url)
url = build_request baseUrl, query.concat [['page', 2]]
httpBackend.whenGET(url).respond(410,'Gone')
httpBackend.expectGET(url)
# take the action and flush the backend
action()
httpBackend.flush()
dontPaginateResponse = (httpBackend, baseUrl, response, action, opts = {})->
limit = opts.limit || 50
query = [['limit', limit]].concat opts.query
# 2. no pagination
# it will request page 1, won't get it
# and try without pagination
url = build_request baseUrl, query.concat [['page', 1]]
httpBackend.whenGET(url).respond(410,'Gone')
httpBackend.expectGET(url)
url = build_request baseUrl, opts.query || []
httpBackend.whenGET(url).respond(response)
httpBackend.expectGET(url)
# take the action and flush the backend
action()
httpBackend.flush()
callResponse = (httpBackend, baseUrl, requestType, responseCode, response, action)->
httpBackend["when#{requestType}"](baseUrl).respond(responseCode,response)
httpBackend["expect#{requestType}"](baseUrl)
# take the action
action()
httpBackend.flush()
# The tests:
#-----------
## Configuration
it 'should have the default host pointing to <HOST>/api', () ->
expect(scope.ponyExpressHost).toBe( window.location.host + "/api" )
it 'should check the endpoint health to be ok', ()->
callResponse @httpBackend, '/v1/status', 'GET',
200, {'version': '0.6.0', 'name': 'pony-express'},
() -> scope.isEndpointOk()
expect(scope.ponyExpressHostOk).toBe(true)
it 'should check the endpoint health to be not ok (non-responsive)', ()->
callResponse @httpBackend, '/v1/status', 'GET',
404, {},
() -> scope.isEndpointOk()
expect(scope.ponyExpressHostOk).toBe(false)
it 'should check the endpoint health to be not ok (invalid)', ()->
callResponse @httpBackend, '/v1/status', 'GET',
200, {'version': '0.6.0'},
() -> scope.isEndpointOk()
expect(scope.ponyExpressHostOk).toBe(false)
## Querying Nodes and Package
it 'should paginate /nodes if it supports pagination', ()->
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
expect(scope.nodes.length).toBe(allNodes1.length)
it 'should not paginate /nodes if it doesnt supports pagination', ()->
dontPaginateResponse @httpBackend, '/v1/nodes', allNodes1, ()-> scope.fetchNodes()
expect(scope.nodes.length).toBe(allNodes1.length)
it 'should paginate /packages if it supports pagination', ()->
paginateResponse @httpBackend, '/v1/packages', allPackages1, ()-> scope.fetchPackages()
expect(scope.packages.length).toBe(allPackages1.length)
it 'should not paginate /packages if it doesnt supports pagination', ()->
dontPaginateResponse @httpBackend, '/v1/packages', allPackages1, ()-> scope.fetchPackages()
expect(scope.packages.length).toBe(allPackages1.length)
it 'should be able to list /nodes', () ->
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
expect(scope.nodes.length).toBe(2)
# test both nodes
for idx in [0,1]
expect(@typeOf(scope.nodes[idx])).toBe('object')
expect(scope.nodes[idx]['id']).toBe(allNodes1[idx]['id'])
it 'should not containe duplicate nodes when fetching mutliple times', () ->
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
expect(scope.nodes.length).toBe(2)
it 'should be able to access /node/xyz info (empty node)', () ->
id = 'test'
@httpBackend.whenGET('/v1/node/'+id).respond({
'packages':[]
})
@httpBackend.expectGET('/v1/node/'+id)
# issue the call
scope.ensureNode(id)
@httpBackend.flush()
n = scope.node[id]
# check if the first node has properties
expect(@typeOf(n)).toBe('object')
expect(n.id).toBe(id)
expect(@typeOf(n.packages)).toBe('array')
expect(n.packages.length).toBe( 0 )
it 'should be able to access /node/xzy info (filled one)', () ->
id = 'test'
@httpBackend.whenGET('/v1/node/'+id).respond({
'packages':[
{
'id': 'poiu',
'name': 'accountsservice',
'summary': 'query and manipulate user account information'
}
]
})
@httpBackend.expectGET('/v1/node/'+id)
# issue the call
scope.ensureNode(id)
@httpBackend.flush()
n = scope.node[id]
# check if the first node has properties
expect(@typeOf(n)).toBe('object')
expect(n.id).toBe(id)
expect(@typeOf(n.packages)).toBe('array')
expect(n.packages.length).toBe( 1 )
expect(n.packages[0].id).toBe( 'poiu' )
expect(n.packages[0].name).toBe( 'accountsservice' )
expect(n.packages[0].summary).toBe( 'query and manipulate user account information' )
it 'should be a able to fetch /packages', () ->
ps = allPackages1
paginateResponse @httpBackend, '/v1/packages', ps, () -> scope.fetchPackages()
expect(scope.packages.length).toBe(ps.length)
# test both packages
for idx in [0,1]
res_p = scope.packages[idx]
expect(@typeOf(res_p)).toBe('object')
expect(res_p.name).toBe(ps[idx].name)
expect(res_p.versions.length).toBe(ps[idx].versions.length)
# every package we load creates an entry in the package map
for v in res_p.versions
p = scope.package[v.id]
expect(@typeOf(p)).toBe('object')
expect(p.name).toBe(ps[idx].name)
expect(p.version).toBe(v.version)
expect(p.versions).toBe(undefined)
it 'should not contain duplicate packages when fetching multiple times', () ->
paginateResponse @httpBackend, '/v1/packages', allPackages1, () -> scope.fetchPackages()
paginateResponse @httpBackend, '/v1/packages', allPackages1, () -> scope.fetchPackages()
expect(scope.packages.length).toBe(allPackages1.length)
query_packages_with_upstream_repo_id = (httpBackend)->
# get repos
paginateResponse httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
# set packages list when selecting a repository
ps = allPackages2
scope.selectRepo(allRepos1[0])
opts = {'query': [['repo',allRepos1[0].id],['outdated','true']]}
dontPaginateResponse httpBackend, '/v1/packages', ps, (() -> scope.fetchPackages()), opts
# results
expect(scope.allPackages.length).toBe(ps.length)
expect(scope.packages.length).toBe(ps.length)
# return the packages we returned from the query
return ps
it 'should list /packages compared to upstream repositories (by ID)', () ->
ps = query_packages_with_upstream_repo_id(@httpBackend)
# test both packages
for idx in [0,1]
res_p = scope.packages[idx]
expect(@typeOf(res_p)).toBe('object')
expect(res_p.name).toBe(ps[idx].name)
expect(res_p.versions.length).toBe(ps[idx].versions.length)
expect(res_p.upstream).toEqual(ps[idx].upstream)
# test if it is outdated
expect( scope.isPackageOutdated( scope.packages[0]) ).toBe(false)
expect( scope.isPackageOutdated( scope.packages[1]) ).toBe(true)
it 'should list /packages compared to upstream repositories (by label)', () ->
# get repos
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
# set packages list when selecting a repository
ps = allPackages2
scope.selectRepoLabel(allRepos1[0].label)
opts = {'query': [['repolabel',allRepos1[0].label],['outdated','true']]}
dontPaginateResponse @httpBackend, '/v1/packages', ps, (() -> scope.fetchPackages()), opts
# results
expect(scope.allPackages.length).toBe(ps.length)
expect(scope.packages.length).toBe(ps.length)
# test both packages
for idx in [0,1]
res_p = scope.packages[idx]
expect(@typeOf(res_p)).toBe('object')
expect(res_p.name).toBe(ps[idx].name)
expect(res_p.versions.length).toBe(ps[idx].versions.length)
expect(res_p.upstream).toEqual(ps[idx].upstream)
# test if it is outdated
expect( scope.isPackageOutdated( scope.packages[0]) ).toBe(false)
expect( scope.isPackageOutdated( scope.packages[1]) ).toBe(true)
it 'should add the outdated info to a package', ()->
ps = query_packages_with_upstream_repo_id(@httpBackend)
# test if non-outdated don't get an outdated_info
scope.addOutdatedInfo( scope.packages[0] )
expect( scope.packages[0].outdated_info ).toBe( undefined )
# outdated packages should have the info field
scope.addOutdatedInfo( scope.packages[1] )
expect( scope.packages[1].outdated_info ).toBe( 'latest: '+scope.packages[1].upstream.latest )
it 'should not containd upstream version infos in packages without an upstream repo query', ()->
ps = allPackages1
paginateResponse @httpBackend, '/v1/packages', ps, () -> scope.fetchPackages()
for idx in [0,1]
expect( scope.packages[idx].upstream ).toBe( undefined )
it 'should only allow selecting either repo label or ID', () ->
# get repos
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
# for now...
expect(scope.repoSelected).toEqual({})
expect(scope.repoSelectedLabel).toBe(null)
opts = {'query': [['repolabel',allRepos1[0].label],['outdated','true']]}
select_by_label = () -> scope.selectRepoLabel(allRepos1[0].label)
paginateResponse @httpBackend, '/v1/packages', allPackages1, select_by_label, opts
expect(scope.repoSelected).toEqual({})
expect(scope.repoSelectedLabel).toBe(allRepos1[0].label)
opts = {'query': [['repo',allRepos1[0].id],['outdated','true']]}
select_by_id = () -> scope.selectRepo(allRepos1[0])
paginateResponse @httpBackend, '/v1/packages', allPackages1, select_by_id, opts
expect(scope.repoSelected[allRepos1[0].id]).toBe(allRepos1[0])
expect(scope.repoSelectedLabel).toBe(null)
opts = {'query': [['repolabel',allRepos1[0].label],['outdated','true']]}
select_by_label = () -> scope.selectRepoLabel(allRepos1[0].label)
paginateResponse @httpBackend, '/v1/packages', allPackages1, select_by_label, opts
expect(scope.repoSelected).toEqual({})
expect(scope.repoSelectedLabel).toBe(allRepos1[0].label)
it 'provides all repository labels (uniq)', () ->
scope.repos = [
{'label': 'a'}, {'label': 'a'},
{'label': 'b'}
]
labels = scope.repoLabels()
expect( labels ).toContain('a')
expect( labels ).toContain('b')
expect( labels.length ).toBe(2)
it 'should be able to access /package/xyz info (empty one)', () ->
id = 'xyz'
@httpBackend.whenGET('/v1/package/'+id).respond({})
@httpBackend.expectGET('/v1/package/'+id)
scope.fetchPackage(id)
@httpBackend.flush()
p = scope.package[id]
expect(@typeOf(p)).toBe('object')
expect(p.id).toBe(id)
it 'should be able to access /package/xyz info (filled one)', () ->
id = 'xyz'
r = package1
@httpBackend.whenGET('/v1/package/'+id).respond(r)
@httpBackend.expectGET('/v1/package/'+id)
scope.fetchPackage(id)
@httpBackend.flush()
p = scope.package[id]
expect(@typeOf(p)).toBe('object')
expect(p.id).toBe(id)
expect(p.name).toBe(r.name)
expect(p.uri).toBe(r.uri)
expect(p.summary).toBe(r.summary)
expect(p.version).toBe(r.version)
expect(p.architecture).toBe(r.architecture)
expect(p.provider).toBe(r.provider)
expect(p.archive).toBe(r.archive)
expect(@typeOf(p.nodes)).toBe('array')
expect(p.nodes.length).toBe(r.nodes.length)
it 'should provide all nodes if no package is selected', () ->
scope.allNodes = allNodes1
scope.updateNodeSelection()
expect( scope.nodes ).toBe( scope.allNodes )
it 'should provide only the node which has the selected package (all versions)', () ->
scope.allNodes = allNodes1
scope.packageByName['p'] =
'versions': [
{ 'id': 'version_xyz_id1' },
{ 'id': 'version_xyz_id2' }
]
scope.package['version_xyz_id1'] = {}
scope.package['version_xyz_id1'].nodes = [ { 'id': allNodes1[0].id } ]
scope.package['version_xyz_id2'] = {}
scope.package['version_xyz_id2'].nodes = [ { 'id': allNodes1[1].id } ]
scope.packageSelected['p'] = true
scope.updateNodeSelection()
expect( scope.nodes.length ).toBe( 2 )
expect( scope.nodes[0].id ).toBe( allNodes1[0].id )
expect( scope.nodes[1].id ).toBe( allNodes1[1].id )
it 'should provide only the node which has the selected a specific package version', () ->
scope.allNodes = allNodes1
scope.package['version_xyz_id'] = {}
scope.package['version_xyz_id'].nodes = [ { 'id': allNodes1[0].id } ]
scope.packageSelectedVersions['p'] = {}
scope.packageSelectedVersions['p']['version_xyz_id'] = true
scope.updateNodeSelection()
expect( scope.nodes.length ).toBe( 1 )
expect( scope.nodes[0].id ).toBe( allNodes1[0].id )
it 'should provide all packages if no node is selected', () ->
scope.allPackages = allPackages1
scope.updatePackageSelection()
expect( scope.packages ).toBe( scope.allPackages )
it 'should provide only the packages assigned to a selected node', () ->
scope.allPackages = allPackages1
scope.node['n'] = {}
scope.node['n'].packages = [ { 'id': allPackages1[0].versions[0].id } ]
scope.nodeSelected['n'] = true
scope.updatePackageSelection()
expect( scope.packages.length ).toBe( 1 )
expect( scope.packages[0].name ).toBe( allPackages1[0].name )
## Querying Repositories
it 'should be able to [C]reate a new repository', () ->
# when you create a new repository it should add a new position to the list to the front
expect( scope.newRepos.length ).toBe(0)
scope.newRepo()
expect( scope.newRepos.length ).toBe(1)
expect( scope.newRepos[0].id ).toBe(undefined)
# when you click on save, it should issue an post request to the server to indicate a new element
callResponse @httpBackend, '/v1/repositories', 'POST', 201, allRepos1[0], () -> scope.saveRepo(scope.newRepos[0])
# make sure nothing is changed if the call was successful
expect( scope.newRepos.length ).toBe(0)
expect( scope.repos[0].id ).not.toBe(undefined)
it 'should [R]ead all repositories the server has available', () ->
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
it 'should have the expected list of repositories when reading multiple times', () ->
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toEqual(allRepos1.length)
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toEqual(allRepos1.length)
it 'should be able to [U]pdate an existing repository', () ->
# TODO: maybe remove the creation and expect it to exist already
scope.newRepo()
callResponse @httpBackend, '/v1/repositories', 'POST', 201, allRepos1[0], () -> scope.saveRepo(scope.newRepos[0])
# initiate editing of a repository
obj = scope.repos[0]
expect(scope.editingRepo[obj.id]).toBe(undefined)
scope.editRepo(obj)
expect(scope.editingRepo[obj.id]).not.toBe(undefined)
# change some property of this repository
scope.editingRepo[obj.id].name = 'Minus Monor'
# save the result
res = allRepos1[0]
res.name = 'Minus Monor'
callResponse @httpBackend, '/v1/repositories/'+obj.id, 'PATCH', 200, res, () -> scope.saveRepo(scope.editingRepo[obj.id])
# check if the results are correct
expect(scope.editingRepo[obj.id]).toBe(undefined)
obj = scope.repos[0]
expect(obj.name).toBe('Minus Monor')
it 'should be able to [D]elete an existing repository', () ->
# TODO: maybe remove the creation and expect it to exist already
scope.newRepo()
callResponse @httpBackend, '/v1/repositories', 'POST', 201, allRepos1[0], () -> scope.saveRepo(scope.newRepos[0])
# update the name of an existing repository
callResponse @httpBackend, '/v1/repositories/'+scope.repos[0].id, 'DELETE', 204, null, () -> scope.deleteRepo(scope.repos[0])
expect(scope.repos.length).toBe(0) | 156765 | 'use strict'
describe 'Controller: MainCtrl', ()->
# load the required module
beforeEach(angular.mock.module('restangular'))
# load the controller's module
beforeEach(module('postriderApp'))
# Initialize the controller and a mock scope
beforeEach( inject( ($injector, $controller, $rootScope) ->
scope = $rootScope.$new()
@Restangular = $injector.get('Restangular')
@httpBackend = $injector.get('$httpBackend')
# reliably determine object types
# http://stackoverflow.com/questions/7390426/better-way-to-get-type-of-a-javascript-variable
@typeOf = (obj) ->
({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
MainCtrl = $controller('MainCtrl', {
$scope: scope,
Restangular: @Restangular
})
))
afterEach () ->
@httpBackend.verifyNoOutstandingExpectation()
@httpBackend.verifyNoOutstandingRequest()
# Some Mockup data:
#------------------
allNodes1 = nodes = [
{ 'id': 'my1.full.fqdn' },
{ 'id': 'my2.full.fqdn' }
]
allPackages1 = [
{ 'name': 'xx', 'versions': [
{'version':'1.0','id':'xx10'}
], 'upstream': {}
},
{ 'name': 'yy', 'versions': [
{'version':'1.1','id':'yy11'},
{'version':'1.2','id':'yy12'}
], 'upstream': {}
}
]
allPackages2 = [
{ 'name': 'xx', 'versions': [
{'version':'1.0','id':'xx10'}
], 'upstream': {
'latest': '1.0'
}
},
{ 'name': 'yy', 'versions': [
{'version':'1.1','id':'yy11'},
{'version':'1.2','id':'yy12'}
], 'upstream': {
'latest': '2.0'
}
}
]
allRepos1 = [
{
'id': '44e5f422-62db-42dc-b1ce-37ca3393710f',
'name': '<NAME>',
'label': 'live',
'uri': 'http://archive.canonical.com/ubuntu/dists/precise/partner/binary-amd64/Packages.gz',
'provider': 'apt'
}
]
allRepos2 = allRepos1.concat [
{
'id': '44e5f422-62db-42dc-b1ce-37ca3393710e',
'name': '<NAME>',
'label': 'ref',
'uri': 'http://archive2.canonical.com/ubuntu/dists/precise/partner/binary-amd64/Packages.gz',
'provider': 'apt'
}
]
package1 = {
'name': 'accountsservice',
'uri': 'http://us.archive.ubuntu.com/ubuntu/pool/main/a/accountsservice/accountsservice_0.6.15-2ubuntu9_amd64.deb',
'summary': 'query and manipulate user account information',
'version': '0.6.15-2ubuntu9',
'architecture': 'amd64',
'provider': 'apt',
'archive': 'precise',
'nodes': [
'my1.full.fqdn'
]
}
package2 = {
'name': 'otherservice',
'uri': 'http://us.archive.ubuntu.com/ubuntu/pool/main/o/otherservice/otherservice_0.6.15-2ubuntu9_amd64.deb',
'summary': 'some other service',
'version': '0.2-2ubuntu9',
'architecture': 'amd64',
'provider': 'apt',
'archive': 'precise',
'nodes': [
'my2.full.fqdn'
]
}
## Helpers:
##---------
build_request = (site, params = [])->
# remove all undefined
p = params.filter (x) -> x?
q = ( p.map (x) -> x.join('=') ).sort().join('&')
if q.length == 0
site
else
"#{site}?#{q}"
paginateResponse = (httpBackend, baseUrl, response, action, opts = {})->
limit = opts.limit || 50
query = [['limit', limit]].concat opts.query
# 1. working pagination
# it will request page 1, get it,
# and request page 2 and finish
url = build_request baseUrl, query.concat [['page', 1]]
httpBackend.whenGET(url).respond(response)
httpBackend.expectGET(url)
url = build_request baseUrl, query.concat [['page', 2]]
httpBackend.whenGET(url).respond(410,'Gone')
httpBackend.expectGET(url)
# take the action and flush the backend
action()
httpBackend.flush()
dontPaginateResponse = (httpBackend, baseUrl, response, action, opts = {})->
limit = opts.limit || 50
query = [['limit', limit]].concat opts.query
# 2. no pagination
# it will request page 1, won't get it
# and try without pagination
url = build_request baseUrl, query.concat [['page', 1]]
httpBackend.whenGET(url).respond(410,'Gone')
httpBackend.expectGET(url)
url = build_request baseUrl, opts.query || []
httpBackend.whenGET(url).respond(response)
httpBackend.expectGET(url)
# take the action and flush the backend
action()
httpBackend.flush()
callResponse = (httpBackend, baseUrl, requestType, responseCode, response, action)->
httpBackend["when#{requestType}"](baseUrl).respond(responseCode,response)
httpBackend["expect#{requestType}"](baseUrl)
# take the action
action()
httpBackend.flush()
# The tests:
#-----------
## Configuration
it 'should have the default host pointing to <HOST>/api', () ->
expect(scope.ponyExpressHost).toBe( window.location.host + "/api" )
it 'should check the endpoint health to be ok', ()->
callResponse @httpBackend, '/v1/status', 'GET',
200, {'version': '0.6.0', 'name': 'pony-express'},
() -> scope.isEndpointOk()
expect(scope.ponyExpressHostOk).toBe(true)
it 'should check the endpoint health to be not ok (non-responsive)', ()->
callResponse @httpBackend, '/v1/status', 'GET',
404, {},
() -> scope.isEndpointOk()
expect(scope.ponyExpressHostOk).toBe(false)
it 'should check the endpoint health to be not ok (invalid)', ()->
callResponse @httpBackend, '/v1/status', 'GET',
200, {'version': '0.6.0'},
() -> scope.isEndpointOk()
expect(scope.ponyExpressHostOk).toBe(false)
## Querying Nodes and Package
it 'should paginate /nodes if it supports pagination', ()->
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
expect(scope.nodes.length).toBe(allNodes1.length)
it 'should not paginate /nodes if it doesnt supports pagination', ()->
dontPaginateResponse @httpBackend, '/v1/nodes', allNodes1, ()-> scope.fetchNodes()
expect(scope.nodes.length).toBe(allNodes1.length)
it 'should paginate /packages if it supports pagination', ()->
paginateResponse @httpBackend, '/v1/packages', allPackages1, ()-> scope.fetchPackages()
expect(scope.packages.length).toBe(allPackages1.length)
it 'should not paginate /packages if it doesnt supports pagination', ()->
dontPaginateResponse @httpBackend, '/v1/packages', allPackages1, ()-> scope.fetchPackages()
expect(scope.packages.length).toBe(allPackages1.length)
it 'should be able to list /nodes', () ->
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
expect(scope.nodes.length).toBe(2)
# test both nodes
for idx in [0,1]
expect(@typeOf(scope.nodes[idx])).toBe('object')
expect(scope.nodes[idx]['id']).toBe(allNodes1[idx]['id'])
it 'should not containe duplicate nodes when fetching mutliple times', () ->
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
expect(scope.nodes.length).toBe(2)
it 'should be able to access /node/xyz info (empty node)', () ->
id = 'test'
@httpBackend.whenGET('/v1/node/'+id).respond({
'packages':[]
})
@httpBackend.expectGET('/v1/node/'+id)
# issue the call
scope.ensureNode(id)
@httpBackend.flush()
n = scope.node[id]
# check if the first node has properties
expect(@typeOf(n)).toBe('object')
expect(n.id).toBe(id)
expect(@typeOf(n.packages)).toBe('array')
expect(n.packages.length).toBe( 0 )
it 'should be able to access /node/xzy info (filled one)', () ->
id = 'test'
@httpBackend.whenGET('/v1/node/'+id).respond({
'packages':[
{
'id': 'poiu',
'name': 'accountsservice',
'summary': 'query and manipulate user account information'
}
]
})
@httpBackend.expectGET('/v1/node/'+id)
# issue the call
scope.ensureNode(id)
@httpBackend.flush()
n = scope.node[id]
# check if the first node has properties
expect(@typeOf(n)).toBe('object')
expect(n.id).toBe(id)
expect(@typeOf(n.packages)).toBe('array')
expect(n.packages.length).toBe( 1 )
expect(n.packages[0].id).toBe( 'poiu' )
expect(n.packages[0].name).toBe( 'accountsservice' )
expect(n.packages[0].summary).toBe( 'query and manipulate user account information' )
it 'should be a able to fetch /packages', () ->
ps = allPackages1
paginateResponse @httpBackend, '/v1/packages', ps, () -> scope.fetchPackages()
expect(scope.packages.length).toBe(ps.length)
# test both packages
for idx in [0,1]
res_p = scope.packages[idx]
expect(@typeOf(res_p)).toBe('object')
expect(res_p.name).toBe(ps[idx].name)
expect(res_p.versions.length).toBe(ps[idx].versions.length)
# every package we load creates an entry in the package map
for v in res_p.versions
p = scope.package[v.id]
expect(@typeOf(p)).toBe('object')
expect(p.name).toBe(ps[idx].name)
expect(p.version).toBe(v.version)
expect(p.versions).toBe(undefined)
it 'should not contain duplicate packages when fetching multiple times', () ->
paginateResponse @httpBackend, '/v1/packages', allPackages1, () -> scope.fetchPackages()
paginateResponse @httpBackend, '/v1/packages', allPackages1, () -> scope.fetchPackages()
expect(scope.packages.length).toBe(allPackages1.length)
query_packages_with_upstream_repo_id = (httpBackend)->
# get repos
paginateResponse httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
# set packages list when selecting a repository
ps = allPackages2
scope.selectRepo(allRepos1[0])
opts = {'query': [['repo',allRepos1[0].id],['outdated','true']]}
dontPaginateResponse httpBackend, '/v1/packages', ps, (() -> scope.fetchPackages()), opts
# results
expect(scope.allPackages.length).toBe(ps.length)
expect(scope.packages.length).toBe(ps.length)
# return the packages we returned from the query
return ps
it 'should list /packages compared to upstream repositories (by ID)', () ->
ps = query_packages_with_upstream_repo_id(@httpBackend)
# test both packages
for idx in [0,1]
res_p = scope.packages[idx]
expect(@typeOf(res_p)).toBe('object')
expect(res_p.name).toBe(ps[idx].name)
expect(res_p.versions.length).toBe(ps[idx].versions.length)
expect(res_p.upstream).toEqual(ps[idx].upstream)
# test if it is outdated
expect( scope.isPackageOutdated( scope.packages[0]) ).toBe(false)
expect( scope.isPackageOutdated( scope.packages[1]) ).toBe(true)
it 'should list /packages compared to upstream repositories (by label)', () ->
# get repos
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
# set packages list when selecting a repository
ps = allPackages2
scope.selectRepoLabel(allRepos1[0].label)
opts = {'query': [['repolabel',allRepos1[0].label],['outdated','true']]}
dontPaginateResponse @httpBackend, '/v1/packages', ps, (() -> scope.fetchPackages()), opts
# results
expect(scope.allPackages.length).toBe(ps.length)
expect(scope.packages.length).toBe(ps.length)
# test both packages
for idx in [0,1]
res_p = scope.packages[idx]
expect(@typeOf(res_p)).toBe('object')
expect(res_p.name).toBe(ps[idx].name)
expect(res_p.versions.length).toBe(ps[idx].versions.length)
expect(res_p.upstream).toEqual(ps[idx].upstream)
# test if it is outdated
expect( scope.isPackageOutdated( scope.packages[0]) ).toBe(false)
expect( scope.isPackageOutdated( scope.packages[1]) ).toBe(true)
it 'should add the outdated info to a package', ()->
ps = query_packages_with_upstream_repo_id(@httpBackend)
# test if non-outdated don't get an outdated_info
scope.addOutdatedInfo( scope.packages[0] )
expect( scope.packages[0].outdated_info ).toBe( undefined )
# outdated packages should have the info field
scope.addOutdatedInfo( scope.packages[1] )
expect( scope.packages[1].outdated_info ).toBe( 'latest: '+scope.packages[1].upstream.latest )
it 'should not containd upstream version infos in packages without an upstream repo query', ()->
ps = allPackages1
paginateResponse @httpBackend, '/v1/packages', ps, () -> scope.fetchPackages()
for idx in [0,1]
expect( scope.packages[idx].upstream ).toBe( undefined )
it 'should only allow selecting either repo label or ID', () ->
# get repos
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
# for now...
expect(scope.repoSelected).toEqual({})
expect(scope.repoSelectedLabel).toBe(null)
opts = {'query': [['repolabel',allRepos1[0].label],['outdated','true']]}
select_by_label = () -> scope.selectRepoLabel(allRepos1[0].label)
paginateResponse @httpBackend, '/v1/packages', allPackages1, select_by_label, opts
expect(scope.repoSelected).toEqual({})
expect(scope.repoSelectedLabel).toBe(allRepos1[0].label)
opts = {'query': [['repo',allRepos1[0].id],['outdated','true']]}
select_by_id = () -> scope.selectRepo(allRepos1[0])
paginateResponse @httpBackend, '/v1/packages', allPackages1, select_by_id, opts
expect(scope.repoSelected[allRepos1[0].id]).toBe(allRepos1[0])
expect(scope.repoSelectedLabel).toBe(null)
opts = {'query': [['repolabel',allRepos1[0].label],['outdated','true']]}
select_by_label = () -> scope.selectRepoLabel(allRepos1[0].label)
paginateResponse @httpBackend, '/v1/packages', allPackages1, select_by_label, opts
expect(scope.repoSelected).toEqual({})
expect(scope.repoSelectedLabel).toBe(allRepos1[0].label)
it 'provides all repository labels (uniq)', () ->
scope.repos = [
{'label': 'a'}, {'label': 'a'},
{'label': 'b'}
]
labels = scope.repoLabels()
expect( labels ).toContain('a')
expect( labels ).toContain('b')
expect( labels.length ).toBe(2)
it 'should be able to access /package/xyz info (empty one)', () ->
id = 'xyz'
@httpBackend.whenGET('/v1/package/'+id).respond({})
@httpBackend.expectGET('/v1/package/'+id)
scope.fetchPackage(id)
@httpBackend.flush()
p = scope.package[id]
expect(@typeOf(p)).toBe('object')
expect(p.id).toBe(id)
it 'should be able to access /package/xyz info (filled one)', () ->
id = 'xyz'
r = package1
@httpBackend.whenGET('/v1/package/'+id).respond(r)
@httpBackend.expectGET('/v1/package/'+id)
scope.fetchPackage(id)
@httpBackend.flush()
p = scope.package[id]
expect(@typeOf(p)).toBe('object')
expect(p.id).toBe(id)
expect(p.name).toBe(r.name)
expect(p.uri).toBe(r.uri)
expect(p.summary).toBe(r.summary)
expect(p.version).toBe(r.version)
expect(p.architecture).toBe(r.architecture)
expect(p.provider).toBe(r.provider)
expect(p.archive).toBe(r.archive)
expect(@typeOf(p.nodes)).toBe('array')
expect(p.nodes.length).toBe(r.nodes.length)
it 'should provide all nodes if no package is selected', () ->
scope.allNodes = allNodes1
scope.updateNodeSelection()
expect( scope.nodes ).toBe( scope.allNodes )
it 'should provide only the node which has the selected package (all versions)', () ->
scope.allNodes = allNodes1
scope.packageByName['p'] =
'versions': [
{ 'id': 'version_xyz_id1' },
{ 'id': 'version_xyz_id2' }
]
scope.package['version_xyz_id1'] = {}
scope.package['version_xyz_id1'].nodes = [ { 'id': allNodes1[0].id } ]
scope.package['version_xyz_id2'] = {}
scope.package['version_xyz_id2'].nodes = [ { 'id': allNodes1[1].id } ]
scope.packageSelected['p'] = true
scope.updateNodeSelection()
expect( scope.nodes.length ).toBe( 2 )
expect( scope.nodes[0].id ).toBe( allNodes1[0].id )
expect( scope.nodes[1].id ).toBe( allNodes1[1].id )
it 'should provide only the node which has the selected a specific package version', () ->
scope.allNodes = allNodes1
scope.package['version_xyz_id'] = {}
scope.package['version_xyz_id'].nodes = [ { 'id': allNodes1[0].id } ]
scope.packageSelectedVersions['p'] = {}
scope.packageSelectedVersions['p']['version_xyz_id'] = true
scope.updateNodeSelection()
expect( scope.nodes.length ).toBe( 1 )
expect( scope.nodes[0].id ).toBe( allNodes1[0].id )
it 'should provide all packages if no node is selected', () ->
scope.allPackages = allPackages1
scope.updatePackageSelection()
expect( scope.packages ).toBe( scope.allPackages )
it 'should provide only the packages assigned to a selected node', () ->
scope.allPackages = allPackages1
scope.node['n'] = {}
scope.node['n'].packages = [ { 'id': allPackages1[0].versions[0].id } ]
scope.nodeSelected['n'] = true
scope.updatePackageSelection()
expect( scope.packages.length ).toBe( 1 )
expect( scope.packages[0].name ).toBe( allPackages1[0].name )
## Querying Repositories
it 'should be able to [C]reate a new repository', () ->
# when you create a new repository it should add a new position to the list to the front
expect( scope.newRepos.length ).toBe(0)
scope.newRepo()
expect( scope.newRepos.length ).toBe(1)
expect( scope.newRepos[0].id ).toBe(undefined)
# when you click on save, it should issue an post request to the server to indicate a new element
callResponse @httpBackend, '/v1/repositories', 'POST', 201, allRepos1[0], () -> scope.saveRepo(scope.newRepos[0])
# make sure nothing is changed if the call was successful
expect( scope.newRepos.length ).toBe(0)
expect( scope.repos[0].id ).not.toBe(undefined)
it 'should [R]ead all repositories the server has available', () ->
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
it 'should have the expected list of repositories when reading multiple times', () ->
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toEqual(allRepos1.length)
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toEqual(allRepos1.length)
it 'should be able to [U]pdate an existing repository', () ->
# TODO: maybe remove the creation and expect it to exist already
scope.newRepo()
callResponse @httpBackend, '/v1/repositories', 'POST', 201, allRepos1[0], () -> scope.saveRepo(scope.newRepos[0])
# initiate editing of a repository
obj = scope.repos[0]
expect(scope.editingRepo[obj.id]).toBe(undefined)
scope.editRepo(obj)
expect(scope.editingRepo[obj.id]).not.toBe(undefined)
# change some property of this repository
scope.editingRepo[obj.id].name = 'Minus Monor'
# save the result
res = allRepos1[0]
res.name = '<NAME> Monor'
callResponse @httpBackend, '/v1/repositories/'+obj.id, 'PATCH', 200, res, () -> scope.saveRepo(scope.editingRepo[obj.id])
# check if the results are correct
expect(scope.editingRepo[obj.id]).toBe(undefined)
obj = scope.repos[0]
expect(obj.name).toBe('<NAME> Monor')
it 'should be able to [D]elete an existing repository', () ->
# TODO: maybe remove the creation and expect it to exist already
scope.newRepo()
callResponse @httpBackend, '/v1/repositories', 'POST', 201, allRepos1[0], () -> scope.saveRepo(scope.newRepos[0])
# update the name of an existing repository
callResponse @httpBackend, '/v1/repositories/'+scope.repos[0].id, 'DELETE', 204, null, () -> scope.deleteRepo(scope.repos[0])
expect(scope.repos.length).toBe(0) | true | 'use strict'
describe 'Controller: MainCtrl', ()->
# load the required module
beforeEach(angular.mock.module('restangular'))
# load the controller's module
beforeEach(module('postriderApp'))
# Initialize the controller and a mock scope
beforeEach( inject( ($injector, $controller, $rootScope) ->
scope = $rootScope.$new()
@Restangular = $injector.get('Restangular')
@httpBackend = $injector.get('$httpBackend')
# reliably determine object types
# http://stackoverflow.com/questions/7390426/better-way-to-get-type-of-a-javascript-variable
@typeOf = (obj) ->
({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
MainCtrl = $controller('MainCtrl', {
$scope: scope,
Restangular: @Restangular
})
))
afterEach () ->
@httpBackend.verifyNoOutstandingExpectation()
@httpBackend.verifyNoOutstandingRequest()
# Some Mockup data:
#------------------
allNodes1 = nodes = [
{ 'id': 'my1.full.fqdn' },
{ 'id': 'my2.full.fqdn' }
]
allPackages1 = [
{ 'name': 'xx', 'versions': [
{'version':'1.0','id':'xx10'}
], 'upstream': {}
},
{ 'name': 'yy', 'versions': [
{'version':'1.1','id':'yy11'},
{'version':'1.2','id':'yy12'}
], 'upstream': {}
}
]
allPackages2 = [
{ 'name': 'xx', 'versions': [
{'version':'1.0','id':'xx10'}
], 'upstream': {
'latest': '1.0'
}
},
{ 'name': 'yy', 'versions': [
{'version':'1.1','id':'yy11'},
{'version':'1.2','id':'yy12'}
], 'upstream': {
'latest': '2.0'
}
}
]
allRepos1 = [
{
'id': '44e5f422-62db-42dc-b1ce-37ca3393710f',
'name': 'PI:NAME:<NAME>END_PI',
'label': 'live',
'uri': 'http://archive.canonical.com/ubuntu/dists/precise/partner/binary-amd64/Packages.gz',
'provider': 'apt'
}
]
allRepos2 = allRepos1.concat [
{
'id': '44e5f422-62db-42dc-b1ce-37ca3393710e',
'name': 'PI:NAME:<NAME>END_PI',
'label': 'ref',
'uri': 'http://archive2.canonical.com/ubuntu/dists/precise/partner/binary-amd64/Packages.gz',
'provider': 'apt'
}
]
package1 = {
'name': 'accountsservice',
'uri': 'http://us.archive.ubuntu.com/ubuntu/pool/main/a/accountsservice/accountsservice_0.6.15-2ubuntu9_amd64.deb',
'summary': 'query and manipulate user account information',
'version': '0.6.15-2ubuntu9',
'architecture': 'amd64',
'provider': 'apt',
'archive': 'precise',
'nodes': [
'my1.full.fqdn'
]
}
package2 = {
'name': 'otherservice',
'uri': 'http://us.archive.ubuntu.com/ubuntu/pool/main/o/otherservice/otherservice_0.6.15-2ubuntu9_amd64.deb',
'summary': 'some other service',
'version': '0.2-2ubuntu9',
'architecture': 'amd64',
'provider': 'apt',
'archive': 'precise',
'nodes': [
'my2.full.fqdn'
]
}
## Helpers:
##---------
build_request = (site, params = [])->
# remove all undefined
p = params.filter (x) -> x?
q = ( p.map (x) -> x.join('=') ).sort().join('&')
if q.length == 0
site
else
"#{site}?#{q}"
paginateResponse = (httpBackend, baseUrl, response, action, opts = {})->
limit = opts.limit || 50
query = [['limit', limit]].concat opts.query
# 1. working pagination
# it will request page 1, get it,
# and request page 2 and finish
url = build_request baseUrl, query.concat [['page', 1]]
httpBackend.whenGET(url).respond(response)
httpBackend.expectGET(url)
url = build_request baseUrl, query.concat [['page', 2]]
httpBackend.whenGET(url).respond(410,'Gone')
httpBackend.expectGET(url)
# take the action and flush the backend
action()
httpBackend.flush()
dontPaginateResponse = (httpBackend, baseUrl, response, action, opts = {})->
limit = opts.limit || 50
query = [['limit', limit]].concat opts.query
# 2. no pagination
# it will request page 1, won't get it
# and try without pagination
url = build_request baseUrl, query.concat [['page', 1]]
httpBackend.whenGET(url).respond(410,'Gone')
httpBackend.expectGET(url)
url = build_request baseUrl, opts.query || []
httpBackend.whenGET(url).respond(response)
httpBackend.expectGET(url)
# take the action and flush the backend
action()
httpBackend.flush()
callResponse = (httpBackend, baseUrl, requestType, responseCode, response, action)->
httpBackend["when#{requestType}"](baseUrl).respond(responseCode,response)
httpBackend["expect#{requestType}"](baseUrl)
# take the action
action()
httpBackend.flush()
# The tests:
#-----------
## Configuration
it 'should have the default host pointing to <HOST>/api', () ->
expect(scope.ponyExpressHost).toBe( window.location.host + "/api" )
it 'should check the endpoint health to be ok', ()->
callResponse @httpBackend, '/v1/status', 'GET',
200, {'version': '0.6.0', 'name': 'pony-express'},
() -> scope.isEndpointOk()
expect(scope.ponyExpressHostOk).toBe(true)
it 'should check the endpoint health to be not ok (non-responsive)', ()->
callResponse @httpBackend, '/v1/status', 'GET',
404, {},
() -> scope.isEndpointOk()
expect(scope.ponyExpressHostOk).toBe(false)
it 'should check the endpoint health to be not ok (invalid)', ()->
callResponse @httpBackend, '/v1/status', 'GET',
200, {'version': '0.6.0'},
() -> scope.isEndpointOk()
expect(scope.ponyExpressHostOk).toBe(false)
## Querying Nodes and Package
it 'should paginate /nodes if it supports pagination', ()->
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
expect(scope.nodes.length).toBe(allNodes1.length)
it 'should not paginate /nodes if it doesnt supports pagination', ()->
dontPaginateResponse @httpBackend, '/v1/nodes', allNodes1, ()-> scope.fetchNodes()
expect(scope.nodes.length).toBe(allNodes1.length)
it 'should paginate /packages if it supports pagination', ()->
paginateResponse @httpBackend, '/v1/packages', allPackages1, ()-> scope.fetchPackages()
expect(scope.packages.length).toBe(allPackages1.length)
it 'should not paginate /packages if it doesnt supports pagination', ()->
dontPaginateResponse @httpBackend, '/v1/packages', allPackages1, ()-> scope.fetchPackages()
expect(scope.packages.length).toBe(allPackages1.length)
it 'should be able to list /nodes', () ->
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
expect(scope.nodes.length).toBe(2)
# test both nodes
for idx in [0,1]
expect(@typeOf(scope.nodes[idx])).toBe('object')
expect(scope.nodes[idx]['id']).toBe(allNodes1[idx]['id'])
it 'should not containe duplicate nodes when fetching mutliple times', () ->
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
paginateResponse @httpBackend, '/v1/nodes', allNodes1, () -> scope.fetchNodes()
expect(scope.nodes.length).toBe(2)
it 'should be able to access /node/xyz info (empty node)', () ->
id = 'test'
@httpBackend.whenGET('/v1/node/'+id).respond({
'packages':[]
})
@httpBackend.expectGET('/v1/node/'+id)
# issue the call
scope.ensureNode(id)
@httpBackend.flush()
n = scope.node[id]
# check if the first node has properties
expect(@typeOf(n)).toBe('object')
expect(n.id).toBe(id)
expect(@typeOf(n.packages)).toBe('array')
expect(n.packages.length).toBe( 0 )
it 'should be able to access /node/xzy info (filled one)', () ->
id = 'test'
@httpBackend.whenGET('/v1/node/'+id).respond({
'packages':[
{
'id': 'poiu',
'name': 'accountsservice',
'summary': 'query and manipulate user account information'
}
]
})
@httpBackend.expectGET('/v1/node/'+id)
# issue the call
scope.ensureNode(id)
@httpBackend.flush()
n = scope.node[id]
# check if the first node has properties
expect(@typeOf(n)).toBe('object')
expect(n.id).toBe(id)
expect(@typeOf(n.packages)).toBe('array')
expect(n.packages.length).toBe( 1 )
expect(n.packages[0].id).toBe( 'poiu' )
expect(n.packages[0].name).toBe( 'accountsservice' )
expect(n.packages[0].summary).toBe( 'query and manipulate user account information' )
it 'should be a able to fetch /packages', () ->
ps = allPackages1
paginateResponse @httpBackend, '/v1/packages', ps, () -> scope.fetchPackages()
expect(scope.packages.length).toBe(ps.length)
# test both packages
for idx in [0,1]
res_p = scope.packages[idx]
expect(@typeOf(res_p)).toBe('object')
expect(res_p.name).toBe(ps[idx].name)
expect(res_p.versions.length).toBe(ps[idx].versions.length)
# every package we load creates an entry in the package map
for v in res_p.versions
p = scope.package[v.id]
expect(@typeOf(p)).toBe('object')
expect(p.name).toBe(ps[idx].name)
expect(p.version).toBe(v.version)
expect(p.versions).toBe(undefined)
it 'should not contain duplicate packages when fetching multiple times', () ->
paginateResponse @httpBackend, '/v1/packages', allPackages1, () -> scope.fetchPackages()
paginateResponse @httpBackend, '/v1/packages', allPackages1, () -> scope.fetchPackages()
expect(scope.packages.length).toBe(allPackages1.length)
query_packages_with_upstream_repo_id = (httpBackend)->
# get repos
paginateResponse httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
# set packages list when selecting a repository
ps = allPackages2
scope.selectRepo(allRepos1[0])
opts = {'query': [['repo',allRepos1[0].id],['outdated','true']]}
dontPaginateResponse httpBackend, '/v1/packages', ps, (() -> scope.fetchPackages()), opts
# results
expect(scope.allPackages.length).toBe(ps.length)
expect(scope.packages.length).toBe(ps.length)
# return the packages we returned from the query
return ps
it 'should list /packages compared to upstream repositories (by ID)', () ->
ps = query_packages_with_upstream_repo_id(@httpBackend)
# test both packages
for idx in [0,1]
res_p = scope.packages[idx]
expect(@typeOf(res_p)).toBe('object')
expect(res_p.name).toBe(ps[idx].name)
expect(res_p.versions.length).toBe(ps[idx].versions.length)
expect(res_p.upstream).toEqual(ps[idx].upstream)
# test if it is outdated
expect( scope.isPackageOutdated( scope.packages[0]) ).toBe(false)
expect( scope.isPackageOutdated( scope.packages[1]) ).toBe(true)
it 'should list /packages compared to upstream repositories (by label)', () ->
# get repos
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
# set packages list when selecting a repository
ps = allPackages2
scope.selectRepoLabel(allRepos1[0].label)
opts = {'query': [['repolabel',allRepos1[0].label],['outdated','true']]}
dontPaginateResponse @httpBackend, '/v1/packages', ps, (() -> scope.fetchPackages()), opts
# results
expect(scope.allPackages.length).toBe(ps.length)
expect(scope.packages.length).toBe(ps.length)
# test both packages
for idx in [0,1]
res_p = scope.packages[idx]
expect(@typeOf(res_p)).toBe('object')
expect(res_p.name).toBe(ps[idx].name)
expect(res_p.versions.length).toBe(ps[idx].versions.length)
expect(res_p.upstream).toEqual(ps[idx].upstream)
# test if it is outdated
expect( scope.isPackageOutdated( scope.packages[0]) ).toBe(false)
expect( scope.isPackageOutdated( scope.packages[1]) ).toBe(true)
it 'should add the outdated info to a package', ()->
ps = query_packages_with_upstream_repo_id(@httpBackend)
# test if non-outdated don't get an outdated_info
scope.addOutdatedInfo( scope.packages[0] )
expect( scope.packages[0].outdated_info ).toBe( undefined )
# outdated packages should have the info field
scope.addOutdatedInfo( scope.packages[1] )
expect( scope.packages[1].outdated_info ).toBe( 'latest: '+scope.packages[1].upstream.latest )
it 'should not containd upstream version infos in packages without an upstream repo query', ()->
ps = allPackages1
paginateResponse @httpBackend, '/v1/packages', ps, () -> scope.fetchPackages()
for idx in [0,1]
expect( scope.packages[idx].upstream ).toBe( undefined )
it 'should only allow selecting either repo label or ID', () ->
# get repos
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
# for now...
expect(scope.repoSelected).toEqual({})
expect(scope.repoSelectedLabel).toBe(null)
opts = {'query': [['repolabel',allRepos1[0].label],['outdated','true']]}
select_by_label = () -> scope.selectRepoLabel(allRepos1[0].label)
paginateResponse @httpBackend, '/v1/packages', allPackages1, select_by_label, opts
expect(scope.repoSelected).toEqual({})
expect(scope.repoSelectedLabel).toBe(allRepos1[0].label)
opts = {'query': [['repo',allRepos1[0].id],['outdated','true']]}
select_by_id = () -> scope.selectRepo(allRepos1[0])
paginateResponse @httpBackend, '/v1/packages', allPackages1, select_by_id, opts
expect(scope.repoSelected[allRepos1[0].id]).toBe(allRepos1[0])
expect(scope.repoSelectedLabel).toBe(null)
opts = {'query': [['repolabel',allRepos1[0].label],['outdated','true']]}
select_by_label = () -> scope.selectRepoLabel(allRepos1[0].label)
paginateResponse @httpBackend, '/v1/packages', allPackages1, select_by_label, opts
expect(scope.repoSelected).toEqual({})
expect(scope.repoSelectedLabel).toBe(allRepos1[0].label)
it 'provides all repository labels (uniq)', () ->
scope.repos = [
{'label': 'a'}, {'label': 'a'},
{'label': 'b'}
]
labels = scope.repoLabels()
expect( labels ).toContain('a')
expect( labels ).toContain('b')
expect( labels.length ).toBe(2)
it 'should be able to access /package/xyz info (empty one)', () ->
id = 'xyz'
@httpBackend.whenGET('/v1/package/'+id).respond({})
@httpBackend.expectGET('/v1/package/'+id)
scope.fetchPackage(id)
@httpBackend.flush()
p = scope.package[id]
expect(@typeOf(p)).toBe('object')
expect(p.id).toBe(id)
it 'should be able to access /package/xyz info (filled one)', () ->
id = 'xyz'
r = package1
@httpBackend.whenGET('/v1/package/'+id).respond(r)
@httpBackend.expectGET('/v1/package/'+id)
scope.fetchPackage(id)
@httpBackend.flush()
p = scope.package[id]
expect(@typeOf(p)).toBe('object')
expect(p.id).toBe(id)
expect(p.name).toBe(r.name)
expect(p.uri).toBe(r.uri)
expect(p.summary).toBe(r.summary)
expect(p.version).toBe(r.version)
expect(p.architecture).toBe(r.architecture)
expect(p.provider).toBe(r.provider)
expect(p.archive).toBe(r.archive)
expect(@typeOf(p.nodes)).toBe('array')
expect(p.nodes.length).toBe(r.nodes.length)
it 'should provide all nodes if no package is selected', () ->
scope.allNodes = allNodes1
scope.updateNodeSelection()
expect( scope.nodes ).toBe( scope.allNodes )
it 'should provide only the node which has the selected package (all versions)', () ->
scope.allNodes = allNodes1
scope.packageByName['p'] =
'versions': [
{ 'id': 'version_xyz_id1' },
{ 'id': 'version_xyz_id2' }
]
scope.package['version_xyz_id1'] = {}
scope.package['version_xyz_id1'].nodes = [ { 'id': allNodes1[0].id } ]
scope.package['version_xyz_id2'] = {}
scope.package['version_xyz_id2'].nodes = [ { 'id': allNodes1[1].id } ]
scope.packageSelected['p'] = true
scope.updateNodeSelection()
expect( scope.nodes.length ).toBe( 2 )
expect( scope.nodes[0].id ).toBe( allNodes1[0].id )
expect( scope.nodes[1].id ).toBe( allNodes1[1].id )
it 'should provide only the node which has the selected a specific package version', () ->
scope.allNodes = allNodes1
scope.package['version_xyz_id'] = {}
scope.package['version_xyz_id'].nodes = [ { 'id': allNodes1[0].id } ]
scope.packageSelectedVersions['p'] = {}
scope.packageSelectedVersions['p']['version_xyz_id'] = true
scope.updateNodeSelection()
expect( scope.nodes.length ).toBe( 1 )
expect( scope.nodes[0].id ).toBe( allNodes1[0].id )
it 'should provide all packages if no node is selected', () ->
scope.allPackages = allPackages1
scope.updatePackageSelection()
expect( scope.packages ).toBe( scope.allPackages )
it 'should provide only the packages assigned to a selected node', () ->
scope.allPackages = allPackages1
scope.node['n'] = {}
scope.node['n'].packages = [ { 'id': allPackages1[0].versions[0].id } ]
scope.nodeSelected['n'] = true
scope.updatePackageSelection()
expect( scope.packages.length ).toBe( 1 )
expect( scope.packages[0].name ).toBe( allPackages1[0].name )
## Querying Repositories
it 'should be able to [C]reate a new repository', () ->
# when you create a new repository it should add a new position to the list to the front
expect( scope.newRepos.length ).toBe(0)
scope.newRepo()
expect( scope.newRepos.length ).toBe(1)
expect( scope.newRepos[0].id ).toBe(undefined)
# when you click on save, it should issue an post request to the server to indicate a new element
callResponse @httpBackend, '/v1/repositories', 'POST', 201, allRepos1[0], () -> scope.saveRepo(scope.newRepos[0])
# make sure nothing is changed if the call was successful
expect( scope.newRepos.length ).toBe(0)
expect( scope.repos[0].id ).not.toBe(undefined)
it 'should [R]ead all repositories the server has available', () ->
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toBe(allRepos1.length)
it 'should have the expected list of repositories when reading multiple times', () ->
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toEqual(allRepos1.length)
paginateResponse @httpBackend, '/v1/repositories', allRepos1, () -> scope.fetchRepos()
expect(scope.repos.length).toEqual(allRepos1.length)
it 'should be able to [U]pdate an existing repository', () ->
# TODO: maybe remove the creation and expect it to exist already
scope.newRepo()
callResponse @httpBackend, '/v1/repositories', 'POST', 201, allRepos1[0], () -> scope.saveRepo(scope.newRepos[0])
# initiate editing of a repository
obj = scope.repos[0]
expect(scope.editingRepo[obj.id]).toBe(undefined)
scope.editRepo(obj)
expect(scope.editingRepo[obj.id]).not.toBe(undefined)
# change some property of this repository
scope.editingRepo[obj.id].name = 'Minus Monor'
# save the result
res = allRepos1[0]
res.name = 'PI:NAME:<NAME>END_PI Monor'
callResponse @httpBackend, '/v1/repositories/'+obj.id, 'PATCH', 200, res, () -> scope.saveRepo(scope.editingRepo[obj.id])
# check if the results are correct
expect(scope.editingRepo[obj.id]).toBe(undefined)
obj = scope.repos[0]
expect(obj.name).toBe('PI:NAME:<NAME>END_PI Monor')
it 'should be able to [D]elete an existing repository', () ->
# TODO: maybe remove the creation and expect it to exist already
scope.newRepo()
callResponse @httpBackend, '/v1/repositories', 'POST', 201, allRepos1[0], () -> scope.saveRepo(scope.newRepos[0])
# update the name of an existing repository
callResponse @httpBackend, '/v1/repositories/'+scope.repos[0].id, 'DELETE', 204, null, () -> scope.deleteRepo(scope.repos[0])
expect(scope.repos.length).toBe(0) |
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9985572695732117,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-http-expect-continue.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
handler = (req, res) ->
assert.equal sent_continue, true, "Full response sent before 100 Continue"
common.debug "Server sending full response..."
res.writeHead 200,
"Content-Type": "text/plain"
ABCD: "1"
res.end test_res_body
return
common = require("../common")
assert = require("assert")
http = require("http")
outstanding_reqs = 0
test_req_body = "some stuff...\n"
test_res_body = "other stuff!\n"
sent_continue = false
got_continue = false
server = http.createServer(handler)
server.on "checkContinue", (req, res) ->
common.debug "Server got Expect: 100-continue..."
res.writeContinue()
sent_continue = true
setTimeout (->
handler req, res
return
), 100
return
server.listen common.PORT
server.on "listening", ->
req = http.request(
port: common.PORT
method: "POST"
path: "/world"
headers:
Expect: "100-continue"
)
common.debug "Client sending request..."
outstanding_reqs++
body = ""
req.on "continue", ->
common.debug "Client got 100 Continue..."
got_continue = true
req.end test_req_body
return
req.on "response", (res) ->
assert.equal got_continue, true, "Full response received before 100 Continue"
assert.equal 200, res.statusCode, "Final status code was " + res.statusCode + ", not 200."
res.setEncoding "utf8"
res.on "data", (chunk) ->
body += chunk
return
res.on "end", ->
common.debug "Got full response."
assert.equal body, test_res_body, "Response body doesn't match."
assert.ok "abcd" of res.headers, "Response headers missing."
outstanding_reqs--
if outstanding_reqs is 0
server.close()
process.exit()
return
return
return
| 57481 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
handler = (req, res) ->
assert.equal sent_continue, true, "Full response sent before 100 Continue"
common.debug "Server sending full response..."
res.writeHead 200,
"Content-Type": "text/plain"
ABCD: "1"
res.end test_res_body
return
common = require("../common")
assert = require("assert")
http = require("http")
outstanding_reqs = 0
test_req_body = "some stuff...\n"
test_res_body = "other stuff!\n"
sent_continue = false
got_continue = false
server = http.createServer(handler)
server.on "checkContinue", (req, res) ->
common.debug "Server got Expect: 100-continue..."
res.writeContinue()
sent_continue = true
setTimeout (->
handler req, res
return
), 100
return
server.listen common.PORT
server.on "listening", ->
req = http.request(
port: common.PORT
method: "POST"
path: "/world"
headers:
Expect: "100-continue"
)
common.debug "Client sending request..."
outstanding_reqs++
body = ""
req.on "continue", ->
common.debug "Client got 100 Continue..."
got_continue = true
req.end test_req_body
return
req.on "response", (res) ->
assert.equal got_continue, true, "Full response received before 100 Continue"
assert.equal 200, res.statusCode, "Final status code was " + res.statusCode + ", not 200."
res.setEncoding "utf8"
res.on "data", (chunk) ->
body += chunk
return
res.on "end", ->
common.debug "Got full response."
assert.equal body, test_res_body, "Response body doesn't match."
assert.ok "abcd" of res.headers, "Response headers missing."
outstanding_reqs--
if outstanding_reqs is 0
server.close()
process.exit()
return
return
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
handler = (req, res) ->
assert.equal sent_continue, true, "Full response sent before 100 Continue"
common.debug "Server sending full response..."
res.writeHead 200,
"Content-Type": "text/plain"
ABCD: "1"
res.end test_res_body
return
common = require("../common")
assert = require("assert")
http = require("http")
outstanding_reqs = 0
test_req_body = "some stuff...\n"
test_res_body = "other stuff!\n"
sent_continue = false
got_continue = false
server = http.createServer(handler)
server.on "checkContinue", (req, res) ->
common.debug "Server got Expect: 100-continue..."
res.writeContinue()
sent_continue = true
setTimeout (->
handler req, res
return
), 100
return
server.listen common.PORT
server.on "listening", ->
req = http.request(
port: common.PORT
method: "POST"
path: "/world"
headers:
Expect: "100-continue"
)
common.debug "Client sending request..."
outstanding_reqs++
body = ""
req.on "continue", ->
common.debug "Client got 100 Continue..."
got_continue = true
req.end test_req_body
return
req.on "response", (res) ->
assert.equal got_continue, true, "Full response received before 100 Continue"
assert.equal 200, res.statusCode, "Final status code was " + res.statusCode + ", not 200."
res.setEncoding "utf8"
res.on "data", (chunk) ->
body += chunk
return
res.on "end", ->
common.debug "Got full response."
assert.equal body, test_res_body, "Response body doesn't match."
assert.ok "abcd" of res.headers, "Response headers missing."
outstanding_reqs--
if outstanding_reqs is 0
server.close()
process.exit()
return
return
return
|
[
{
"context": "s.ProductHunt extends Columns.FeedColumn\n name: \"ProductHunt\"\n thumb: \"img/column-producthunt.png\"\n element:",
"end": 73,
"score": 0.6513082385063171,
"start": 62,
"tag": "NAME",
"value": "ProductHunt"
},
{
"context": "9480c4eefbeb981d56f310d\",\n clien... | src/columns/producthunt/ProductHunt.coffee | jariz/hackertab | 548 | class Columns.ProductHunt extends Columns.FeedColumn
name: "ProductHunt"
thumb: "img/column-producthunt.png"
element: "ph-item"
dataPath: "posts"
link: "https://www.producthunt.com"
dialog: "ph-dialog"
width: 1
attemptAdd: (successCallback) ->
chrome.permissions.request
origins: ['https://api.producthunt.com/']
, (granted) =>
if granted and typeof successCallback is 'function' then successCallback()
draw: (data, holderElement) ->
if not @config.type then @config.type = "list"
@element = if @config.type == "list" then "ph-item" else "ph-thumb"
@flex = @element == "ph-thumb"
data.posts = data.posts.map (item, index) -> item.index = index + 1; item
super data, holderElement
refresh: (columnElement, holderElement) =>
#producthunt api requires a request for a access token
#when we've got access token, we can go on as usual
fetch "https://api.producthunt.com/v1/oauth/token",
method: "post",
headers:
"Accept": "application/json"
"Content-Type": "application/json"
body: JSON.stringify
client_id: "6c7ae468245e828676be999f5a42e6e50e0101ca99480c4eefbeb981d56f310d",
client_secret: "00825be2da634a7d80bc4dc8d3cbdd54bcaa46d4273101227c27dbd68accdb77",
grant_type: "client_credentials"
.then (response) ->
if response.status is 200 then Promise.resolve response
else Promise.reject new Error response.statusText
.then (response) ->
return response.json()
.then (json) =>
@url = "https://api.producthunt.com/v1/posts?access_token="+json.access_token
super columnElement, holderElement
.catch (error) =>
console.error error
@refreshing = false
@loading = false
if not @cache or @cache.length is 0 then @error holderElement
tabbie.register "ProductHunt" | 110109 | class Columns.ProductHunt extends Columns.FeedColumn
name: "<NAME>"
thumb: "img/column-producthunt.png"
element: "ph-item"
dataPath: "posts"
link: "https://www.producthunt.com"
dialog: "ph-dialog"
width: 1
attemptAdd: (successCallback) ->
chrome.permissions.request
origins: ['https://api.producthunt.com/']
, (granted) =>
if granted and typeof successCallback is 'function' then successCallback()
draw: (data, holderElement) ->
if not @config.type then @config.type = "list"
@element = if @config.type == "list" then "ph-item" else "ph-thumb"
@flex = @element == "ph-thumb"
data.posts = data.posts.map (item, index) -> item.index = index + 1; item
super data, holderElement
refresh: (columnElement, holderElement) =>
#producthunt api requires a request for a access token
#when we've got access token, we can go on as usual
fetch "https://api.producthunt.com/v1/oauth/token",
method: "post",
headers:
"Accept": "application/json"
"Content-Type": "application/json"
body: JSON.stringify
client_id: "6c7ae468245e828676be999f5a42e6e50e0101ca99480c4eefbeb981d56f310d",
client_secret: "<KEY>",
grant_type: "client_credentials"
.then (response) ->
if response.status is 200 then Promise.resolve response
else Promise.reject new Error response.statusText
.then (response) ->
return response.json()
.then (json) =>
@url = "https://api.producthunt.com/v1/posts?access_token="+json.access_token
super columnElement, holderElement
.catch (error) =>
console.error error
@refreshing = false
@loading = false
if not @cache or @cache.length is 0 then @error holderElement
tabbie.register "ProductHunt" | true | class Columns.ProductHunt extends Columns.FeedColumn
name: "PI:NAME:<NAME>END_PI"
thumb: "img/column-producthunt.png"
element: "ph-item"
dataPath: "posts"
link: "https://www.producthunt.com"
dialog: "ph-dialog"
width: 1
attemptAdd: (successCallback) ->
chrome.permissions.request
origins: ['https://api.producthunt.com/']
, (granted) =>
if granted and typeof successCallback is 'function' then successCallback()
draw: (data, holderElement) ->
if not @config.type then @config.type = "list"
@element = if @config.type == "list" then "ph-item" else "ph-thumb"
@flex = @element == "ph-thumb"
data.posts = data.posts.map (item, index) -> item.index = index + 1; item
super data, holderElement
refresh: (columnElement, holderElement) =>
#producthunt api requires a request for a access token
#when we've got access token, we can go on as usual
fetch "https://api.producthunt.com/v1/oauth/token",
method: "post",
headers:
"Accept": "application/json"
"Content-Type": "application/json"
body: JSON.stringify
client_id: "6c7ae468245e828676be999f5a42e6e50e0101ca99480c4eefbeb981d56f310d",
client_secret: "PI:KEY:<KEY>END_PI",
grant_type: "client_credentials"
.then (response) ->
if response.status is 200 then Promise.resolve response
else Promise.reject new Error response.statusText
.then (response) ->
return response.json()
.then (json) =>
@url = "https://api.producthunt.com/v1/posts?access_token="+json.access_token
super columnElement, holderElement
.catch (error) =>
console.error error
@refreshing = false
@loading = false
if not @cache or @cache.length is 0 then @error holderElement
tabbie.register "ProductHunt" |
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998459815979004,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai... | library/nucleus/ktools.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
moment = require "moment"
pkginfo = require "pkginfo"
socketio = require "socket.io"
uuid = require "node-uuid"
colors = require "colors"
assert = require "assert"
redisio = require "redis"
async = require "async"
nconf = require "nconf"
https = require "https"
paths = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{format} = require "util"
{RedisStore} = require "socket.io"
{Archetype} = require "./arche"
# This is an abstract base class component that contains a set of
# essential kernel tools and utilities, basically - the toolchain.
# This component should be used in the actual kernel implementation
# to segregate the core functionality of the kernel from utilities
# that are common for nearly every kernel. These tools are meant to
# lift the routine that is usually involved in the kernel classes.
module.exports.KernelTools = class KernelTools extends Archetype
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# This static property should contain the loaded NPM package
# module which is used by the kernel to draw different kinds
# of the information and data. This could be overridden by the
# modified kernels that are custom to arbitrary applications.
# This definition (package.json) should corellate to framework.
assert @FRAMEWORK = pkginfo.read(module).package
# This static property should contain the loaded NPM package
# module which is used by the kernel to draw different kinds
# of the information and data. This could be overridden by the
# modified kernels that are custom to arbitrary applications.
# This definition (package.json) should corellate to application.
assert @APPLICATION = pkginfo.read(0, process.cwd()).package
# Create a new instance of the kernel, run all the prerequisites
# that are necessary, do the configuration on the kernel, then
# boot it up, using the hostname and port parameters from config.
# Please use this static method instead of manually launching up.
# Refer to the static method `makeKernelSetup` for information.
@bootstrap: (options={}) -> new this @makeKernelSetup options
# The kernel preemption routine is called once the kernel has
# passed the initial launching and configuration phase, but is
# yet to start up the router, connect services and instantiate
# an actual application. This method gets passes continuation
# that does that. The method can either invoke it or omit it.
kernelPreemption: (continuation) -> continuation.apply this
# Either get or set an identica token. This token is application
# identification string of a free form, but usually formed by a
# app name plus a verion after the at sign. If no arguments are
# supplied, the method will get identica, otherwise - attempt to
# set one. If there is no identica - it asks the configuration.
@identica: (identica) ->
assert comp = "identica:compiled" # config key
automatic = => f(@$identica or nconf.get comp)
functional = _.isFunction identica or false
i = (fn) => return fn.apply this, arguments
f = (x) => if _.isFunction x then i(x) else x
return automatic() if arguments.length is 0
return @$identica = identica if functional
noIdentica = "this identica is not a string"
m = "Setting up identica to %s within the %s"
assert _.isString idc = try this.identify()
assert _.isString(identica or 0), noIdentica
logger?.silly? m.red, identica.red.bold, idc
assert @$identica = identica.toString()
return @emit? "identica", arguments...
# This is a little kernel registry broker that when asked to,
# goes to the router registry and attempts to find there the
# instance of the specified kind (class). If it succeeds then
# it returns an instance to the invoker. If not, however, it
# throws an assertion error about being unable to accquire.
accquire: (kinded, silent=no) ->
usage = "method has been used incrorrectly"
sign = "should be called with the class arg"
assert (arguments.length or NaN) >= 1, usage
assert _.isObject(kinded or undefined), sign
assert ident = try kinded.identify() or null
error = "could not find a %s in the registry"
noKinded = "the supplied arg has to be class"
success = "Successfully accquired %s service"
formatted = try format error, ident.toString()
assert _.isArray registry = @router?.registry
assert _.isObject(kinded.__super__), noKinded
look = (fxc) -> try fxc.objectOf kinded, yes
spoted = _.find(registry, look) or undefined
assert _.isObject(spoted) or silent, formatted
logger.debug success.grey, try ident.underline
try spoted.accquired? kinded, silent; spoted
# This routine takes care of resolving all the necessary details
# for successfully creating and running an HTTPS (SSL) server.
# The details are typically at least the key and the certficiate.
# This implementation draws data from the config file and then
# used it to obtain the necessary content and whater else needs.
resolveSslDetails: ->
options = new Object() # container for SSL
missingKey = "the secure.key setting missing"
missingCert = "the secure.cert setting missing"
assert _.isObject secure = nconf.get "secure"
assert _.isString(try secure.key), missingKey
assert _.isString(try secure.cert), missingCert
key = paths.relative process.cwd(), secure.key
cert = paths.relative process.cwd(), secure.cert
template = "Reading SSL %s file at %s".toString()
logger.warn template.grey, "key".bold, key.underline
logger.warn template.grey, "cert".bold, cert.underline
logger.debug "Assembling the SSL/HTTPS options".green
do -> options.key = fs.readFileSync paths.resolve key
do -> options.cert = fs.readFileSync paths.resolve cert
assert options.cert.length >= 64, "invalid SSL cert"
assert options.key.length >= 64, "invalid SSL key"
options.secure = secure; return options # SSL
# The utilitary method that is being called by either the kernel
# or scope implementation to establish the desirable facade for
# logging. The options from the config may be used to configure
# various options of the logger, such as output format, etc.
# Please see the methods source and the `Winston` library docs.
setupLoggingFacade: ->
assert _.isObject @logging = logger
assert format = "DD/MM/YYYY @ HH:mm:ss"
stamp = -> return moment().format format
options = timestamp: stamp, colorize: yes
options.level = nconf.get "log:level" or 0
noLevel = "No logging level is specified"
throw new Error noLevel unless options.level
assert console = logger.transports.Console
try do -> logger.remove console catch error
m = "Installed kernel logging facade of %s"
assert identify = this.constructor.identify()
logger.add console, options # re-assemble it
logger.silly m.yellow, identify.yellow.bold
return this # return self-ref for chaining
# Create and wire in an appropriate Connext middleware that will
# serve the specified directory as the directory with a static
# content. That is, it will expose it to the world (not list it).
# The serving aspects can be configured via a passed in options.
# Please see the method source code for more information on it.
serveStaticDirectory: (directory, options={}) ->
sdir = "no directory string is supplied"
usage = "method has been used a wrong way"
assert (arguments.length or 0) >= 1, usage
assert _.isString(directory or null), sdir
assert cwd = try process.cwd().toString()
solved = try paths.relative cwd, directory
serving = "Serving %s as static assets dir"
notExist = "The assets dir %s does not exist"
fail = -> logger.warn notExist, solved.underline
return fail() unless fs.existsSync directory
middleware = connect.static directory, options
logger.info serving.cyan, solved.underline
try @connect.use middleware; return this
| 39764 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
moment = require "moment"
pkginfo = require "pkginfo"
socketio = require "socket.io"
uuid = require "node-uuid"
colors = require "colors"
assert = require "assert"
redisio = require "redis"
async = require "async"
nconf = require "nconf"
https = require "https"
paths = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{format} = require "util"
{RedisStore} = require "socket.io"
{Archetype} = require "./arche"
# This is an abstract base class component that contains a set of
# essential kernel tools and utilities, basically - the toolchain.
# This component should be used in the actual kernel implementation
# to segregate the core functionality of the kernel from utilities
# that are common for nearly every kernel. These tools are meant to
# lift the routine that is usually involved in the kernel classes.
module.exports.KernelTools = class KernelTools extends Archetype
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# This static property should contain the loaded NPM package
# module which is used by the kernel to draw different kinds
# of the information and data. This could be overridden by the
# modified kernels that are custom to arbitrary applications.
# This definition (package.json) should corellate to framework.
assert @FRAMEWORK = pkginfo.read(module).package
# This static property should contain the loaded NPM package
# module which is used by the kernel to draw different kinds
# of the information and data. This could be overridden by the
# modified kernels that are custom to arbitrary applications.
# This definition (package.json) should corellate to application.
assert @APPLICATION = pkginfo.read(0, process.cwd()).package
# Create a new instance of the kernel, run all the prerequisites
# that are necessary, do the configuration on the kernel, then
# boot it up, using the hostname and port parameters from config.
# Please use this static method instead of manually launching up.
# Refer to the static method `makeKernelSetup` for information.
@bootstrap: (options={}) -> new this @makeKernelSetup options
# The kernel preemption routine is called once the kernel has
# passed the initial launching and configuration phase, but is
# yet to start up the router, connect services and instantiate
# an actual application. This method gets passes continuation
# that does that. The method can either invoke it or omit it.
kernelPreemption: (continuation) -> continuation.apply this
# Either get or set an identica token. This token is application
# identification string of a free form, but usually formed by a
# app name plus a verion after the at sign. If no arguments are
# supplied, the method will get identica, otherwise - attempt to
# set one. If there is no identica - it asks the configuration.
@identica: (identica) ->
assert comp = "identica:compiled" # config key
automatic = => f(@$identica or nconf.get comp)
functional = _.isFunction identica or false
i = (fn) => return fn.apply this, arguments
f = (x) => if _.isFunction x then i(x) else x
return automatic() if arguments.length is 0
return @$identica = identica if functional
noIdentica = "this identica is not a string"
m = "Setting up identica to %s within the %s"
assert _.isString idc = try this.identify()
assert _.isString(identica or 0), noIdentica
logger?.silly? m.red, identica.red.bold, idc
assert @$identica = identica.toString()
return @emit? "identica", arguments...
# This is a little kernel registry broker that when asked to,
# goes to the router registry and attempts to find there the
# instance of the specified kind (class). If it succeeds then
# it returns an instance to the invoker. If not, however, it
# throws an assertion error about being unable to accquire.
accquire: (kinded, silent=no) ->
usage = "method has been used incrorrectly"
sign = "should be called with the class arg"
assert (arguments.length or NaN) >= 1, usage
assert _.isObject(kinded or undefined), sign
assert ident = try kinded.identify() or null
error = "could not find a %s in the registry"
noKinded = "the supplied arg has to be class"
success = "Successfully accquired %s service"
formatted = try format error, ident.toString()
assert _.isArray registry = @router?.registry
assert _.isObject(kinded.__super__), noKinded
look = (fxc) -> try fxc.objectOf kinded, yes
spoted = _.find(registry, look) or undefined
assert _.isObject(spoted) or silent, formatted
logger.debug success.grey, try ident.underline
try spoted.accquired? kinded, silent; spoted
# This routine takes care of resolving all the necessary details
# for successfully creating and running an HTTPS (SSL) server.
# The details are typically at least the key and the certficiate.
# This implementation draws data from the config file and then
# used it to obtain the necessary content and whater else needs.
resolveSslDetails: ->
options = new Object() # container for SSL
missingKey = "the secure.key setting missing"
missingCert = "the secure.cert setting missing"
assert _.isObject secure = nconf.get "secure"
assert _.isString(try secure.key), missingKey
assert _.isString(try secure.cert), missingCert
key = paths.relative process.cwd(), secure.key
cert = paths.relative process.cwd(), secure.cert
template = "Reading SSL %s file at %s".toString()
logger.warn template.grey, "key".bold, key.underline
logger.warn template.grey, "cert".bold, cert.underline
logger.debug "Assembling the SSL/HTTPS options".green
do -> options.key = fs.readFileSync paths.resolve key
do -> options.cert = fs.readFileSync paths.resolve cert
assert options.cert.length >= 64, "invalid SSL cert"
assert options.key.length >= 64, "invalid SSL key"
options.secure = secure; return options # SSL
# The utilitary method that is being called by either the kernel
# or scope implementation to establish the desirable facade for
# logging. The options from the config may be used to configure
# various options of the logger, such as output format, etc.
# Please see the methods source and the `Winston` library docs.
setupLoggingFacade: ->
assert _.isObject @logging = logger
assert format = "DD/MM/YYYY @ HH:mm:ss"
stamp = -> return moment().format format
options = timestamp: stamp, colorize: yes
options.level = nconf.get "log:level" or 0
noLevel = "No logging level is specified"
throw new Error noLevel unless options.level
assert console = logger.transports.Console
try do -> logger.remove console catch error
m = "Installed kernel logging facade of %s"
assert identify = this.constructor.identify()
logger.add console, options # re-assemble it
logger.silly m.yellow, identify.yellow.bold
return this # return self-ref for chaining
# Create and wire in an appropriate Connext middleware that will
# serve the specified directory as the directory with a static
# content. That is, it will expose it to the world (not list it).
# The serving aspects can be configured via a passed in options.
# Please see the method source code for more information on it.
serveStaticDirectory: (directory, options={}) ->
sdir = "no directory string is supplied"
usage = "method has been used a wrong way"
assert (arguments.length or 0) >= 1, usage
assert _.isString(directory or null), sdir
assert cwd = try process.cwd().toString()
solved = try paths.relative cwd, directory
serving = "Serving %s as static assets dir"
notExist = "The assets dir %s does not exist"
fail = -> logger.warn notExist, solved.underline
return fail() unless fs.existsSync directory
middleware = connect.static directory, options
logger.info serving.cyan, solved.underline
try @connect.use middleware; return this
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
asciify = require "asciify"
connect = require "connect"
logger = require "winston"
moment = require "moment"
pkginfo = require "pkginfo"
socketio = require "socket.io"
uuid = require "node-uuid"
colors = require "colors"
assert = require "assert"
redisio = require "redis"
async = require "async"
nconf = require "nconf"
https = require "https"
paths = require "path"
http = require "http"
util = require "util"
fs = require "fs"
{format} = require "util"
{RedisStore} = require "socket.io"
{Archetype} = require "./arche"
# This is an abstract base class component that contains a set of
# essential kernel tools and utilities, basically - the toolchain.
# This component should be used in the actual kernel implementation
# to segregate the core functionality of the kernel from utilities
# that are common for nearly every kernel. These tools are meant to
# lift the routine that is usually involved in the kernel classes.
module.exports.KernelTools = class KernelTools extends Archetype
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# This static property should contain the loaded NPM package
# module which is used by the kernel to draw different kinds
# of the information and data. This could be overridden by the
# modified kernels that are custom to arbitrary applications.
# This definition (package.json) should corellate to framework.
assert @FRAMEWORK = pkginfo.read(module).package
# This static property should contain the loaded NPM package
# module which is used by the kernel to draw different kinds
# of the information and data. This could be overridden by the
# modified kernels that are custom to arbitrary applications.
# This definition (package.json) should corellate to application.
assert @APPLICATION = pkginfo.read(0, process.cwd()).package
# Create a new instance of the kernel, run all the prerequisites
# that are necessary, do the configuration on the kernel, then
# boot it up, using the hostname and port parameters from config.
# Please use this static method instead of manually launching up.
# Refer to the static method `makeKernelSetup` for information.
@bootstrap: (options={}) -> new this @makeKernelSetup options
# The kernel preemption routine is called once the kernel has
# passed the initial launching and configuration phase, but is
# yet to start up the router, connect services and instantiate
# an actual application. This method gets passes continuation
# that does that. The method can either invoke it or omit it.
kernelPreemption: (continuation) -> continuation.apply this
# Either get or set an identica token. This token is application
# identification string of a free form, but usually formed by a
# app name plus a verion after the at sign. If no arguments are
# supplied, the method will get identica, otherwise - attempt to
# set one. If there is no identica - it asks the configuration.
@identica: (identica) ->
assert comp = "identica:compiled" # config key
automatic = => f(@$identica or nconf.get comp)
functional = _.isFunction identica or false
i = (fn) => return fn.apply this, arguments
f = (x) => if _.isFunction x then i(x) else x
return automatic() if arguments.length is 0
return @$identica = identica if functional
noIdentica = "this identica is not a string"
m = "Setting up identica to %s within the %s"
assert _.isString idc = try this.identify()
assert _.isString(identica or 0), noIdentica
logger?.silly? m.red, identica.red.bold, idc
assert @$identica = identica.toString()
return @emit? "identica", arguments...
# This is a little kernel registry broker that when asked to,
# goes to the router registry and attempts to find there the
# instance of the specified kind (class). If it succeeds then
# it returns an instance to the invoker. If not, however, it
# throws an assertion error about being unable to accquire.
accquire: (kinded, silent=no) ->
usage = "method has been used incrorrectly"
sign = "should be called with the class arg"
assert (arguments.length or NaN) >= 1, usage
assert _.isObject(kinded or undefined), sign
assert ident = try kinded.identify() or null
error = "could not find a %s in the registry"
noKinded = "the supplied arg has to be class"
success = "Successfully accquired %s service"
formatted = try format error, ident.toString()
assert _.isArray registry = @router?.registry
assert _.isObject(kinded.__super__), noKinded
look = (fxc) -> try fxc.objectOf kinded, yes
spoted = _.find(registry, look) or undefined
assert _.isObject(spoted) or silent, formatted
logger.debug success.grey, try ident.underline
try spoted.accquired? kinded, silent; spoted
# This routine takes care of resolving all the necessary details
# for successfully creating and running an HTTPS (SSL) server.
# The details are typically at least the key and the certficiate.
# This implementation draws data from the config file and then
# used it to obtain the necessary content and whater else needs.
resolveSslDetails: ->
options = new Object() # container for SSL
missingKey = "the secure.key setting missing"
missingCert = "the secure.cert setting missing"
assert _.isObject secure = nconf.get "secure"
assert _.isString(try secure.key), missingKey
assert _.isString(try secure.cert), missingCert
key = paths.relative process.cwd(), secure.key
cert = paths.relative process.cwd(), secure.cert
template = "Reading SSL %s file at %s".toString()
logger.warn template.grey, "key".bold, key.underline
logger.warn template.grey, "cert".bold, cert.underline
logger.debug "Assembling the SSL/HTTPS options".green
do -> options.key = fs.readFileSync paths.resolve key
do -> options.cert = fs.readFileSync paths.resolve cert
assert options.cert.length >= 64, "invalid SSL cert"
assert options.key.length >= 64, "invalid SSL key"
options.secure = secure; return options # SSL
# The utilitary method that is being called by either the kernel
# or scope implementation to establish the desirable facade for
# logging. The options from the config may be used to configure
# various options of the logger, such as output format, etc.
# Please see the methods source and the `Winston` library docs.
setupLoggingFacade: ->
assert _.isObject @logging = logger
assert format = "DD/MM/YYYY @ HH:mm:ss"
stamp = -> return moment().format format
options = timestamp: stamp, colorize: yes
options.level = nconf.get "log:level" or 0
noLevel = "No logging level is specified"
throw new Error noLevel unless options.level
assert console = logger.transports.Console
try do -> logger.remove console catch error
m = "Installed kernel logging facade of %s"
assert identify = this.constructor.identify()
logger.add console, options # re-assemble it
logger.silly m.yellow, identify.yellow.bold
return this # return self-ref for chaining
# Create and wire in an appropriate Connext middleware that will
# serve the specified directory as the directory with a static
# content. That is, it will expose it to the world (not list it).
# The serving aspects can be configured via a passed in options.
# Please see the method source code for more information on it.
serveStaticDirectory: (directory, options={}) ->
sdir = "no directory string is supplied"
usage = "method has been used a wrong way"
assert (arguments.length or 0) >= 1, usage
assert _.isString(directory or null), sdir
assert cwd = try process.cwd().toString()
solved = try paths.relative cwd, directory
serving = "Serving %s as static assets dir"
notExist = "The assets dir %s does not exist"
fail = -> logger.warn notExist, solved.underline
return fail() unless fs.existsSync directory
middleware = connect.static directory, options
logger.info serving.cyan, solved.underline
try @connect.use middleware; return this
|
[
{
"context": "exports.certs = \n \"api.keybase.io\" : \"\"\"-----BEGIN CERTIFICATE-----\nMIIGmzCCBIOgAwIBAgIJAPzhpcIBaOeNMA0GCSqGSIb3DQEBBQUAMIGPMQswCQYD\nVQQGEwJVUzELMAkGA1UECBMCTlkxETAPBgNVBAcTCE5ldyBZb3JrMRQwEgYDVQQK\nEwtLZXliYXNlIExMQzEXMBUGA1UECxMOQ2VydCBBdXRob3JpdHkxEzARBgNVBAMT\nCmtleWJhc2UuaW8xHDAaBgkq... | src/ca.iced | AngelKey/Angelkey.nodeclient | 151 | exports.certs =
"api.keybase.io" : """-----BEGIN CERTIFICATE-----
MIIGmzCCBIOgAwIBAgIJAPzhpcIBaOeNMA0GCSqGSIb3DQEBBQUAMIGPMQswCQYD
VQQGEwJVUzELMAkGA1UECBMCTlkxETAPBgNVBAcTCE5ldyBZb3JrMRQwEgYDVQQK
EwtLZXliYXNlIExMQzEXMBUGA1UECxMOQ2VydCBBdXRob3JpdHkxEzARBgNVBAMT
CmtleWJhc2UuaW8xHDAaBgkqhkiG9w0BCQEWDWNhQGtleWJhc2UuaW8wHhcNMTQw
MTAyMTY0MjMzWhcNMjMxMjMxMTY0MjMzWjCBjzELMAkGA1UEBhMCVVMxCzAJBgNV
BAgTAk5ZMREwDwYDVQQHEwhOZXcgWW9yazEUMBIGA1UEChMLS2V5YmFzZSBMTEMx
FzAVBgNVBAsTDkNlcnQgQXV0aG9yaXR5MRMwEQYDVQQDEwprZXliYXNlLmlvMRww
GgYJKoZIhvcNAQkBFg1jYUBrZXliYXNlLmlvMIICIjANBgkqhkiG9w0BAQEFAAOC
Ag8AMIICCgKCAgEA3sLA6ZG8uOvmlFvFLVIOURmcQrZyMFKbVu9/TeDiemls3w3/
JzVTduD+7KiUi9R7QcCW/V1ZpReTfunm7rfACiJ1fpIkjSQrgsvKDLghIzxIS5FM
I8utet5p6QtuJhaAwmmXn8xX05FvqWNbrcXRdpL4goFdigPsFK2xhTUiWatLMste
oShI7+zmrgkx75LeLMD0bL2uOf87JjOzbY8x2sUIZLGwPoATyG8WS38ey6KkJxRj
AhG3p+OTYEjYSrsAtQA6ImbeDpfSHKOB8HF3nVp//Eb4HEiEsWwBRbQXvAWh3DYL
GukFW0wiO0HVCoWY+bHL/Mqa0NdRGOlLsbL4Z4pLrhqKgSDU8umX9YuNRRaB0P5n
TkzyU6axHqzq990Gep/I62bjsBdYYp+DjSPK43mXRrfWJl2NTcl8xKAyfsOW+9hQ
9vwK0tpSicNxfYuUZs0BhfjSZ/Tc6Z1ERdgUYRiXTtohl+SRA2IgZMloHCllVMNj
EjXhguvHgLAOrcuyhVBupiUQGUHQvkMsr1Uz8VPNDFOJedwucRU2AaR881bknnSb
ds9+zNLsvUFV+BK7Qdnt/WkFpYL78rGwY47msi9Ooddx6fPyeg3qkJGM6cwn/boy
w9lQeleYDq8kyJdixIAxtAskNzRPJ4nDu2izTfByQoM8epwAWboc/gNFObMCAwEA
AaOB9zCB9DAdBgNVHQ4EFgQURqpATOw1gVVrzlqqFKbkfaKXvwowgcQGA1UdIwSB
vDCBuYAURqpATOw1gVVrzlqqFKbkfaKXvwqhgZWkgZIwgY8xCzAJBgNVBAYTAlVT
MQswCQYDVQQIEwJOWTERMA8GA1UEBxMITmV3IFlvcmsxFDASBgNVBAoTC0tleWJh
c2UgTExDMRcwFQYDVQQLEw5DZXJ0IEF1dGhvcml0eTETMBEGA1UEAxMKa2V5YmFz
ZS5pbzEcMBoGCSqGSIb3DQEJARYNY2FAa2V5YmFzZS5pb4IJAPzhpcIBaOeNMAwG
A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggIBAA3Z5FIhulYghMuHdcHYTYWc
7xT5WD4hXQ0WALZs4p5Y+b2Af54o6v1wUE1Au97FORq5CsFXX/kGl/JzzTimeucn
YJwGuXMpilrlHCBAL5/lSQjA7qbYIolQ3SB9ON+LYuF1jKB9k8SqNp7qzucxT3tO
b8ZMDEPNsseC7NE2uwNtcW3yrTh6WZnSqg/jwswiWjHYDdG7U8FjMYlRol3wPux2
PizGbSgiR+ztI2OthxtxNWMrT9XKxNQTpcxOXnLuhiSwqH8PoY17ecP8VPpaa0K6
zym0zSkbroqydazaxcXRk3eSlc02Ktk7HzRzuqQQXhRMkxVnHbFHgGsz03L533pm
mlIEgBMggZkHwNvs1LR7f3v2McdKulDH7Mv8yyfguuQ5Jxxt7RJhUuqSudbEhoaM
6jAJwBkMFxsV2YnyFEd3eZ/qBYPf7TYHhyzmHW6WkSypGqSnXd4gYpJ8o7LxSf4F
inLjxRD+H9Xn1UVXWLM0gaBB7zZcXd2zjMpRsWgezf5IR5vyakJsc7fxzgor3Qeq
Ri6LvdEkhhFVl5rHMQBwNOPngySrq8cs/ikTLTfQVTYXXA4Ba1YyiMOlfaR1LhKw
If1AkUV0tfCTNRZ01EotKSK77+o+k214n+BAu+7mO+9B5Kb7lMFQcuWCHXKYB2Md
cT7Yh09F0QpFUd0ymEfv
-----END CERTIFICATE-----
"""
| 163208 | exports.certs =
"api.keybase.io" : """-----<KEY>
<KEY>
-----END CERTIFICATE-----
"""
| true | exports.certs =
"api.keybase.io" : """-----PI:KEY:<KEY>END_PI
PI:KEY:<KEY>END_PI
-----END CERTIFICATE-----
"""
|
[
{
"context": ".user =\n username : null\n password : null\n\n # ========================================",
"end": 757,
"score": 0.996767520904541,
"start": 753,
"tag": "PASSWORD",
"value": "null"
}
] | Projects/Mobile/Ionic Project/src/coffee/controllers/general/login/login-controller.coffee | carloshpds/MyOmakase | 0 | 'use strict'
# =============================================
# Module
# =============================================
angular.module 'IonicProjectModelApp'
# =============================================
# LoginController
# =============================================
.controller 'LoginController', ['$scope', '$window', 'LoginService', '$state', 'NotificationsFactory', 'MessagesEnumsFactory', '$cordovaToast', '$ionicLoading',
($scope, $window, LoginService, $state, NotificationsFactory, MessagesEnumsFactory, $cordovaToast, $ionicLoading) ->
# =============================================
# Attributes
# =============================================
$scope.user =
username : null
password : null
# =============================================
# Handlers
# =============================================
$scope.clickLoginButtonHandler = () ->
$ionicLoading.show()
promise = LoginService.login($scope.user)
promise.success (data, status, headers, config) -> alert 'Connected'
promise.error (data, status, headers, config, statusText) ->
message = MessagesEnumsFactory.get "user.does.not.exist"
if $window.cordova
$cordovaToast.showLongBottom message
else
NotificationsFactory.add message
promise.finally ->
$ionicLoading.hide()
# =============================================
# Methods
# =============================================
$scope.goState = (state) -> $state.go state
] | 191870 | 'use strict'
# =============================================
# Module
# =============================================
angular.module 'IonicProjectModelApp'
# =============================================
# LoginController
# =============================================
.controller 'LoginController', ['$scope', '$window', 'LoginService', '$state', 'NotificationsFactory', 'MessagesEnumsFactory', '$cordovaToast', '$ionicLoading',
($scope, $window, LoginService, $state, NotificationsFactory, MessagesEnumsFactory, $cordovaToast, $ionicLoading) ->
# =============================================
# Attributes
# =============================================
$scope.user =
username : null
password : <PASSWORD>
# =============================================
# Handlers
# =============================================
$scope.clickLoginButtonHandler = () ->
$ionicLoading.show()
promise = LoginService.login($scope.user)
promise.success (data, status, headers, config) -> alert 'Connected'
promise.error (data, status, headers, config, statusText) ->
message = MessagesEnumsFactory.get "user.does.not.exist"
if $window.cordova
$cordovaToast.showLongBottom message
else
NotificationsFactory.add message
promise.finally ->
$ionicLoading.hide()
# =============================================
# Methods
# =============================================
$scope.goState = (state) -> $state.go state
] | true | 'use strict'
# =============================================
# Module
# =============================================
angular.module 'IonicProjectModelApp'
# =============================================
# LoginController
# =============================================
.controller 'LoginController', ['$scope', '$window', 'LoginService', '$state', 'NotificationsFactory', 'MessagesEnumsFactory', '$cordovaToast', '$ionicLoading',
($scope, $window, LoginService, $state, NotificationsFactory, MessagesEnumsFactory, $cordovaToast, $ionicLoading) ->
# =============================================
# Attributes
# =============================================
$scope.user =
username : null
password : PI:PASSWORD:<PASSWORD>END_PI
# =============================================
# Handlers
# =============================================
$scope.clickLoginButtonHandler = () ->
$ionicLoading.show()
promise = LoginService.login($scope.user)
promise.success (data, status, headers, config) -> alert 'Connected'
promise.error (data, status, headers, config, statusText) ->
message = MessagesEnumsFactory.get "user.does.not.exist"
if $window.cordova
$cordovaToast.showLongBottom message
else
NotificationsFactory.add message
promise.finally ->
$ionicLoading.hide()
# =============================================
# Methods
# =============================================
$scope.goState = (state) -> $state.go state
] |
[
{
"context": "watchers = {\n \"besu\": {\n channel: \"besu-contributors\"\n regexes:",
"end": 20,
"score": 0.6946786642074585,
"start": 16,
"tag": "USERNAME",
"value": "besu"
},
{
"context": "No channels care about this build'\n\n brainKey = \"#{CIRCLE_NOTIFICATION_PREFIX}-... | scripts/circle-ci-notifications.coffee | shemnon/hyperledger-rocket-chat-hubot | 0 | watchers = {
"besu": {
channel: "besu-contributors"
regexes: [
/master/
/release-.*/
]
}
}
CIRCLE_NOTIFICATION_PREFIX = 'circle-ci-notify'
module.exports = (robot) ->
robot.router.post '/hubot/circleci', (req, res) ->
payload = req.body.payload
branch = payload.branch.toLowerCase()
repo = payload.reponame.toLowerCase()
jobName = payload.workflows.job_name
currentResult = payload.outcome.toUpperCase()
robot.logger.debug "Starting checks of #{repo}/#{branch}-#{jobName} with status #{currentResult}"
if ! watchers[repo].regexes.some((rx) -> rx.test(branch))
robot.logger.debug "No channels care about #{repo}/#{branch}"
return res.send 'No channels care about this build'
brainKey = "#{CIRCLE_NOTIFICATION_PREFIX}-#{repo}-#{branch}-#{jobName}"
lastResult = robot.brain.get(brainKey)
robot.logger.debug "Last result was #{lastResult}, current result is #{currentResult}"
robot.brain.set(brainKey, currentResult)
if currentResult != "SUCCESS"
message = "#{jobName} for #{repo} - #{branch} : #{currentResult}. See more at `#{payload.build_url}`"
robot.send {room: watchers[repo].channel}, message
res.send 'Users alerted of build status.'
else if lastResult? and lastResult != currentResult and currentResult == "SUCESS"
message = "#{jobName} for #{repo} - #{branch} has recovered"
robot.send {room: watchers[repo].channel}, message
res.send 'Users alerted of build status.'
| 179542 | watchers = {
"besu": {
channel: "besu-contributors"
regexes: [
/master/
/release-.*/
]
}
}
CIRCLE_NOTIFICATION_PREFIX = 'circle-ci-notify'
module.exports = (robot) ->
robot.router.post '/hubot/circleci', (req, res) ->
payload = req.body.payload
branch = payload.branch.toLowerCase()
repo = payload.reponame.toLowerCase()
jobName = payload.workflows.job_name
currentResult = payload.outcome.toUpperCase()
robot.logger.debug "Starting checks of #{repo}/#{branch}-#{jobName} with status #{currentResult}"
if ! watchers[repo].regexes.some((rx) -> rx.test(branch))
robot.logger.debug "No channels care about #{repo}/#{branch}"
return res.send 'No channels care about this build'
brainKey = <KEY>
lastResult = robot.brain.get(brainKey)
robot.logger.debug "Last result was #{lastResult}, current result is #{currentResult}"
robot.brain.set(brainKey, currentResult)
if currentResult != "SUCCESS"
message = "#{jobName} for #{repo} - #{branch} : #{currentResult}. See more at `#{payload.build_url}`"
robot.send {room: watchers[repo].channel}, message
res.send 'Users alerted of build status.'
else if lastResult? and lastResult != currentResult and currentResult == "SUCESS"
message = "#{jobName} for #{repo} - #{branch} has recovered"
robot.send {room: watchers[repo].channel}, message
res.send 'Users alerted of build status.'
| true | watchers = {
"besu": {
channel: "besu-contributors"
regexes: [
/master/
/release-.*/
]
}
}
CIRCLE_NOTIFICATION_PREFIX = 'circle-ci-notify'
module.exports = (robot) ->
robot.router.post '/hubot/circleci', (req, res) ->
payload = req.body.payload
branch = payload.branch.toLowerCase()
repo = payload.reponame.toLowerCase()
jobName = payload.workflows.job_name
currentResult = payload.outcome.toUpperCase()
robot.logger.debug "Starting checks of #{repo}/#{branch}-#{jobName} with status #{currentResult}"
if ! watchers[repo].regexes.some((rx) -> rx.test(branch))
robot.logger.debug "No channels care about #{repo}/#{branch}"
return res.send 'No channels care about this build'
brainKey = PI:KEY:<KEY>END_PI
lastResult = robot.brain.get(brainKey)
robot.logger.debug "Last result was #{lastResult}, current result is #{currentResult}"
robot.brain.set(brainKey, currentResult)
if currentResult != "SUCCESS"
message = "#{jobName} for #{repo} - #{branch} : #{currentResult}. See more at `#{payload.build_url}`"
robot.send {room: watchers[repo].channel}, message
res.send 'Users alerted of build status.'
else if lastResult? and lastResult != currentResult and currentResult == "SUCESS"
message = "#{jobName} for #{repo} - #{branch} has recovered"
robot.send {room: watchers[repo].channel}, message
res.send 'Users alerted of build status.'
|
[
{
"context": "lly installed packages\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\n\n#\n# Reads a file content in the current direct",
"end": 92,
"score": 0.9998883008956909,
"start": 75,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | cli/commands/publish.coffee | lovely-io/lovely.io-stl | 2 | #
# Updates all the locally installed packages
#
# Copyright (C) 2011-2012 Nikolay Nemshilov
#
#
# Reads a file content in the current directory
#
# @param {String} filename
# @return {String} file content
#
read = (filename)->
fs = require('fs')
filename = process.cwd() + "/" + filename
if fs.existsSync(filename)
fs.readFileSync(filename).toString()
else
''
#
# Reading the images list
#
# @return {Object} images
#
read_images = (build)->
fs = require('fs')
folder = "#{process.cwd()}/images/"
images = {}
if match = build.match(/('|"|\()\/?images\/.+?\1/g)
for file in match
file = file.substr(1, file.length - 2)
file = file.substr(0, file.length - 1) if file[file.length-1] is "\\"
if file = file.split('images/')[1]
if fs.existsSync(folder + file)
images[file] = fs.readFileSync(folder + file).toString('base64')
return images
#
# Collects the documentation from the current directory
#
# @return {Object} documentation index
#
collect_documentation = ->
fs = require('fs')
cwd = process.cwd()
docs =
index: read('README.md')
demo: read("demo.html") || read("index.html")
changelog: read('CHANGELOG')
loop_recursively = (dirname)->
for filename in fs.readdirSync("#{cwd}/#{dirname}")
if fs.statSync("#{cwd}/#{dirname}/#{filename}").isDirectory()
loop_recursively("#{dirname}/#{filename}")
else
docs["#{dirname}/#{filename}"] = read("#{dirname}/#{filename}")
loop_recursively('docs') if fs.existsSync("#{cwd}/docs")
return docs
#
# Kicks in the command
#
exports.init = (args) ->
pack = require('../package')
hosting = require('../hosting')
lovelyrc = require('../lovelyrc')
sout "» Compiling the project".ljust(61)
system "#{__dirname}/../../bin/lovely build", ->
sout "Done\n".green
build = read("build/#{pack.name}.js")
sout "» Publishing #{lovelyrc.host}/packages/#{pack.name} ".ljust(61)
hosting.send_package
manifest: read('package.json')
build: build
images: read_images(build)
documents: collect_documentation()
sout "Done\n".green
#
# Prints out the command help
#
exports.help = (args) ->
"""
Publishes the package on the lovely.io host
Usage:
lovely publish
""" | 22050 | #
# Updates all the locally installed packages
#
# Copyright (C) 2011-2012 <NAME>
#
#
# Reads a file content in the current directory
#
# @param {String} filename
# @return {String} file content
#
read = (filename)->
fs = require('fs')
filename = process.cwd() + "/" + filename
if fs.existsSync(filename)
fs.readFileSync(filename).toString()
else
''
#
# Reading the images list
#
# @return {Object} images
#
read_images = (build)->
fs = require('fs')
folder = "#{process.cwd()}/images/"
images = {}
if match = build.match(/('|"|\()\/?images\/.+?\1/g)
for file in match
file = file.substr(1, file.length - 2)
file = file.substr(0, file.length - 1) if file[file.length-1] is "\\"
if file = file.split('images/')[1]
if fs.existsSync(folder + file)
images[file] = fs.readFileSync(folder + file).toString('base64')
return images
#
# Collects the documentation from the current directory
#
# @return {Object} documentation index
#
collect_documentation = ->
fs = require('fs')
cwd = process.cwd()
docs =
index: read('README.md')
demo: read("demo.html") || read("index.html")
changelog: read('CHANGELOG')
loop_recursively = (dirname)->
for filename in fs.readdirSync("#{cwd}/#{dirname}")
if fs.statSync("#{cwd}/#{dirname}/#{filename}").isDirectory()
loop_recursively("#{dirname}/#{filename}")
else
docs["#{dirname}/#{filename}"] = read("#{dirname}/#{filename}")
loop_recursively('docs') if fs.existsSync("#{cwd}/docs")
return docs
#
# Kicks in the command
#
exports.init = (args) ->
pack = require('../package')
hosting = require('../hosting')
lovelyrc = require('../lovelyrc')
sout "» Compiling the project".ljust(61)
system "#{__dirname}/../../bin/lovely build", ->
sout "Done\n".green
build = read("build/#{pack.name}.js")
sout "» Publishing #{lovelyrc.host}/packages/#{pack.name} ".ljust(61)
hosting.send_package
manifest: read('package.json')
build: build
images: read_images(build)
documents: collect_documentation()
sout "Done\n".green
#
# Prints out the command help
#
exports.help = (args) ->
"""
Publishes the package on the lovely.io host
Usage:
lovely publish
""" | true | #
# Updates all the locally installed packages
#
# Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI
#
#
# Reads a file content in the current directory
#
# @param {String} filename
# @return {String} file content
#
read = (filename)->
fs = require('fs')
filename = process.cwd() + "/" + filename
if fs.existsSync(filename)
fs.readFileSync(filename).toString()
else
''
#
# Reading the images list
#
# @return {Object} images
#
read_images = (build)->
fs = require('fs')
folder = "#{process.cwd()}/images/"
images = {}
if match = build.match(/('|"|\()\/?images\/.+?\1/g)
for file in match
file = file.substr(1, file.length - 2)
file = file.substr(0, file.length - 1) if file[file.length-1] is "\\"
if file = file.split('images/')[1]
if fs.existsSync(folder + file)
images[file] = fs.readFileSync(folder + file).toString('base64')
return images
#
# Collects the documentation from the current directory
#
# @return {Object} documentation index
#
collect_documentation = ->
fs = require('fs')
cwd = process.cwd()
docs =
index: read('README.md')
demo: read("demo.html") || read("index.html")
changelog: read('CHANGELOG')
loop_recursively = (dirname)->
for filename in fs.readdirSync("#{cwd}/#{dirname}")
if fs.statSync("#{cwd}/#{dirname}/#{filename}").isDirectory()
loop_recursively("#{dirname}/#{filename}")
else
docs["#{dirname}/#{filename}"] = read("#{dirname}/#{filename}")
loop_recursively('docs') if fs.existsSync("#{cwd}/docs")
return docs
#
# Kicks in the command
#
exports.init = (args) ->
pack = require('../package')
hosting = require('../hosting')
lovelyrc = require('../lovelyrc')
sout "» Compiling the project".ljust(61)
system "#{__dirname}/../../bin/lovely build", ->
sout "Done\n".green
build = read("build/#{pack.name}.js")
sout "» Publishing #{lovelyrc.host}/packages/#{pack.name} ".ljust(61)
hosting.send_package
manifest: read('package.json')
build: build
images: read_images(build)
documents: collect_documentation()
sout "Done\n".green
#
# Prints out the command help
#
exports.help = (args) ->
"""
Publishes the package on the lovely.io host
Usage:
lovely publish
""" |
[
{
"context": "#{@get('id')}\")\n .set('X-Xapp-Token': artsyXapp)\n .end (err, res) ->\n if err\n",
"end": 2127,
"score": 0.6451995372772217,
"start": 2121,
"tag": "PASSWORD",
"value": "syXapp"
},
{
"context": "#{@get('id')}\")\n .set('X-Xapp-Toke... | src/client/models/channel.coffee | craigspaeth/positron | 0 | _ = require 'underscore'
Backbone = require 'backbone'
sd = require('sharify').data
async = require 'async'
request = require 'superagent'
artsyXapp = require('artsy-xapp').token or ''
module.exports = class Channel extends Backbone.Model
urlRoot: "#{sd.API_URL}/channels"
isTeam: ->
@get('type') is 'team'
isEditorial: ->
@get('type') is 'editorial'
isArtsyChannel: ->
@get('type') in ['editorial', 'support', 'team']
hasFeature: (feature) ->
type = @get('type')
if type is 'editorial'
_.contains [
'header'
'superArticle'
'text'
'artworks'
'images'
'image_set'
'video'
'embed'
'callout'
'follow'
'layout'
'postscript'
'sponsor'
], feature
else if type is 'team'
_.contains [
'text'
'artworks'
'images'
'image_set'
'video'
'embed'
'callout'
'follow'
'hero'
], feature
else if type is 'support'
_.contains [
'text'
'artworks'
'images'
'video'
'callout'
'follow'
'hero'
], feature
else if type is 'partner'
_.contains [
'text'
'artworks'
'images'
'video'
], feature
hasAssociation: (association) ->
type = @get('type')
if type is 'editorial'
_.contains [
'artworks'
'artists'
'shows'
'fairs'
'partners'
'auctions'
], association
else if type is 'team'
false
else if type is 'support'
_.contains [
'artworks'
'artists'
'shows'
'fairs'
'partners'
'auctions'
], association
else if type is 'partner'
_.contains [
'artworks'
'artists'
'shows'
'fairs'
'partners'
'auctions'
], association
fetchChannelOrPartner: (options) ->
async.parallel [
(cb) =>
request.get("#{sd.API_URL}/channels/#{@get('id')}")
.set('X-Xapp-Token': artsyXapp)
.end (err, res) ->
if err
cb null, {}
else
cb null, res
(cb) =>
request.get("#{sd.ARTSY_URL}/api/v1/partner/#{@get('id')}")
.set('X-Xapp-Token': artsyXapp)
.end (err, res) ->
if err
cb null, {}
else
cb null, res
], (err, results) ->
if results[0]?.ok
options.success new Channel results[0].body
else if results[1]?.ok
channel = new Channel(
name: results[1].body.name
id: results[1].body._id
type: 'partner'
)
options.success channel
else
options.error err
denormalized: ->
{
id: @get('id')
name: @get('name')
type: if _.contains ['editorial', 'support', 'team'], @get('type') then @get('type') else 'partner'
}
| 32097 | _ = require 'underscore'
Backbone = require 'backbone'
sd = require('sharify').data
async = require 'async'
request = require 'superagent'
artsyXapp = require('artsy-xapp').token or ''
module.exports = class Channel extends Backbone.Model
urlRoot: "#{sd.API_URL}/channels"
isTeam: ->
@get('type') is 'team'
isEditorial: ->
@get('type') is 'editorial'
isArtsyChannel: ->
@get('type') in ['editorial', 'support', 'team']
hasFeature: (feature) ->
type = @get('type')
if type is 'editorial'
_.contains [
'header'
'superArticle'
'text'
'artworks'
'images'
'image_set'
'video'
'embed'
'callout'
'follow'
'layout'
'postscript'
'sponsor'
], feature
else if type is 'team'
_.contains [
'text'
'artworks'
'images'
'image_set'
'video'
'embed'
'callout'
'follow'
'hero'
], feature
else if type is 'support'
_.contains [
'text'
'artworks'
'images'
'video'
'callout'
'follow'
'hero'
], feature
else if type is 'partner'
_.contains [
'text'
'artworks'
'images'
'video'
], feature
hasAssociation: (association) ->
type = @get('type')
if type is 'editorial'
_.contains [
'artworks'
'artists'
'shows'
'fairs'
'partners'
'auctions'
], association
else if type is 'team'
false
else if type is 'support'
_.contains [
'artworks'
'artists'
'shows'
'fairs'
'partners'
'auctions'
], association
else if type is 'partner'
_.contains [
'artworks'
'artists'
'shows'
'fairs'
'partners'
'auctions'
], association
fetchChannelOrPartner: (options) ->
async.parallel [
(cb) =>
request.get("#{sd.API_URL}/channels/#{@get('id')}")
.set('X-Xapp-Token': art<PASSWORD>)
.end (err, res) ->
if err
cb null, {}
else
cb null, res
(cb) =>
request.get("#{sd.ARTSY_URL}/api/v1/partner/#{@get('id')}")
.set('X-Xapp-Token': art<PASSWORD>)
.end (err, res) ->
if err
cb null, {}
else
cb null, res
], (err, results) ->
if results[0]?.ok
options.success new Channel results[0].body
else if results[1]?.ok
channel = new Channel(
name: results[1].body.name
id: results[1].body._id
type: 'partner'
)
options.success channel
else
options.error err
denormalized: ->
{
id: @get('id')
name: @get('name')
type: if _.contains ['editorial', 'support', 'team'], @get('type') then @get('type') else 'partner'
}
| true | _ = require 'underscore'
Backbone = require 'backbone'
sd = require('sharify').data
async = require 'async'
request = require 'superagent'
artsyXapp = require('artsy-xapp').token or ''
module.exports = class Channel extends Backbone.Model
urlRoot: "#{sd.API_URL}/channels"
isTeam: ->
@get('type') is 'team'
isEditorial: ->
@get('type') is 'editorial'
isArtsyChannel: ->
@get('type') in ['editorial', 'support', 'team']
hasFeature: (feature) ->
type = @get('type')
if type is 'editorial'
_.contains [
'header'
'superArticle'
'text'
'artworks'
'images'
'image_set'
'video'
'embed'
'callout'
'follow'
'layout'
'postscript'
'sponsor'
], feature
else if type is 'team'
_.contains [
'text'
'artworks'
'images'
'image_set'
'video'
'embed'
'callout'
'follow'
'hero'
], feature
else if type is 'support'
_.contains [
'text'
'artworks'
'images'
'video'
'callout'
'follow'
'hero'
], feature
else if type is 'partner'
_.contains [
'text'
'artworks'
'images'
'video'
], feature
hasAssociation: (association) ->
type = @get('type')
if type is 'editorial'
_.contains [
'artworks'
'artists'
'shows'
'fairs'
'partners'
'auctions'
], association
else if type is 'team'
false
else if type is 'support'
_.contains [
'artworks'
'artists'
'shows'
'fairs'
'partners'
'auctions'
], association
else if type is 'partner'
_.contains [
'artworks'
'artists'
'shows'
'fairs'
'partners'
'auctions'
], association
fetchChannelOrPartner: (options) ->
async.parallel [
(cb) =>
request.get("#{sd.API_URL}/channels/#{@get('id')}")
.set('X-Xapp-Token': artPI:PASSWORD:<PASSWORD>END_PI)
.end (err, res) ->
if err
cb null, {}
else
cb null, res
(cb) =>
request.get("#{sd.ARTSY_URL}/api/v1/partner/#{@get('id')}")
.set('X-Xapp-Token': artPI:PASSWORD:<PASSWORD>END_PI)
.end (err, res) ->
if err
cb null, {}
else
cb null, res
], (err, results) ->
if results[0]?.ok
options.success new Channel results[0].body
else if results[1]?.ok
channel = new Channel(
name: results[1].body.name
id: results[1].body._id
type: 'partner'
)
options.success channel
else
options.error err
denormalized: ->
{
id: @get('id')
name: @get('name')
type: if _.contains ['editorial', 'support', 'team'], @get('type') then @get('type') else 'partner'
}
|
[
{
"context": "gin()\n data =\n email:form.email\n pwd:form.pwd\n console.debug 'making request', data\n axio",
"end": 580,
"score": 0.8235343098640442,
"start": 572,
"tag": "PASSWORD",
"value": "form.pwd"
}
] | v2/goalnet/front/browser_ext/src/popup/login/login.coffee | DaniloZZZ/GoalNet | 0 | import React, { Component } from 'react'
import L from 'react-dom-factories'
#import {Label} from '@smooth-ui/core-sc'
import { Form, Field } from 'react-final-form'
import axios from 'axios'
#import {debug_login} from '../../Utils/sessions.coffee'
L_ = React.createElement
import './login.less'
host = 'lykov.tech:8080'
GNET_LOGIN= 'http://'+host+'/auth/login'
export default class LoginPage extends Component
constructor: (props)->
super(props)
@state =
counter: 0
log_in:(form)=>
#debug_login()
data =
email:form.email
pwd:form.pwd
console.debug 'making request', data
axios.post GNET_LOGIN, data
.then (response)=>
console.log 'got response', response
token = response.data.token
@props.onLogin token
window.location.reload()
render: ->
L.div className:'login page',
L_ Form,
onSubmit:@log_in
render: ({handleSubmit})->
L.div className:'form',
L.form onSubmit:handleSubmit,
L.div 0,
L.label 0, 'Email'
L_ Field, name:'email',component:'input'
L.div 0,
L.label 0, 'Password'
L_ Field, name:'pwd',type:'password',component:'input'
L.button type:'submit','Login'
| 131914 | import React, { Component } from 'react'
import L from 'react-dom-factories'
#import {Label} from '@smooth-ui/core-sc'
import { Form, Field } from 'react-final-form'
import axios from 'axios'
#import {debug_login} from '../../Utils/sessions.coffee'
L_ = React.createElement
import './login.less'
host = 'lykov.tech:8080'
GNET_LOGIN= 'http://'+host+'/auth/login'
export default class LoginPage extends Component
constructor: (props)->
super(props)
@state =
counter: 0
log_in:(form)=>
#debug_login()
data =
email:form.email
pwd:<PASSWORD>
console.debug 'making request', data
axios.post GNET_LOGIN, data
.then (response)=>
console.log 'got response', response
token = response.data.token
@props.onLogin token
window.location.reload()
render: ->
L.div className:'login page',
L_ Form,
onSubmit:@log_in
render: ({handleSubmit})->
L.div className:'form',
L.form onSubmit:handleSubmit,
L.div 0,
L.label 0, 'Email'
L_ Field, name:'email',component:'input'
L.div 0,
L.label 0, 'Password'
L_ Field, name:'pwd',type:'password',component:'input'
L.button type:'submit','Login'
| true | import React, { Component } from 'react'
import L from 'react-dom-factories'
#import {Label} from '@smooth-ui/core-sc'
import { Form, Field } from 'react-final-form'
import axios from 'axios'
#import {debug_login} from '../../Utils/sessions.coffee'
L_ = React.createElement
import './login.less'
host = 'lykov.tech:8080'
GNET_LOGIN= 'http://'+host+'/auth/login'
export default class LoginPage extends Component
constructor: (props)->
super(props)
@state =
counter: 0
log_in:(form)=>
#debug_login()
data =
email:form.email
pwd:PI:PASSWORD:<PASSWORD>END_PI
console.debug 'making request', data
axios.post GNET_LOGIN, data
.then (response)=>
console.log 'got response', response
token = response.data.token
@props.onLogin token
window.location.reload()
render: ->
L.div className:'login page',
L_ Form,
onSubmit:@log_in
render: ({handleSubmit})->
L.div className:'form',
L.form onSubmit:handleSubmit,
L.div 0,
L.label 0, 'Email'
L_ Field, name:'email',component:'input'
L.div 0,
L.label 0, 'Password'
L_ Field, name:'pwd',type:'password',component:'input'
L.button type:'submit','Login'
|
[
{
"context": "equest Body example:\n {\n 'users':[ {'email': 'user1@user1.com',\n 'name': 'user1',\n ",
"end": 2492,
"score": 0.9998387694358826,
"start": 2477,
"tag": "EMAIL",
"value": "user1@user1.com"
},
{
"context": "mail': 'user1@user1.com',\n ... | server/restapi/restapi.coffee | sunboy/rchat | 0 | Api = new Restivus
useDefaultAuth: true
prettyJson: true
Api.addRoute 'version', authRequired: false,
get: ->
version = {api: '0.1', rocketchat: '0.5'}
status: 'success', versions: version
Api.addRoute 'publicRooms', authRequired: true,
get: ->
rooms = ChatRoom.find({ t: 'c' }, { sort: { msgs:-1 } }).fetch()
status: 'success', rooms: rooms
# join a room
Api.addRoute 'rooms/:id/join', authRequired: true,
post: ->
Meteor.runAsUser this.userId, () =>
Meteor.call('joinRoom', @urlParams.id)
status: 'success' # need to handle error
# leave a room
Api.addRoute 'rooms/:id/leave', authRequired: true,
post: ->
Meteor.runAsUser this.userId, () =>
Meteor.call('leaveRoom', @urlParams.id)
status: 'success' # need to handle error
# get messages in a room
Api.addRoute 'rooms/:id/messages', authRequired: true,
get: ->
try
if Meteor.call('canAccessRoom', @urlParams.id, this.userId)
msgs = ChatMessage.find({rid: @urlParams.id, _hidden: {$ne: true}}, {sort: {ts: -1}}, {limit: 50}).fetch()
status: 'success', messages: msgs
else
statusCode: 403 # forbidden
body: status: 'fail', message: 'Cannot access room.'
catch e
statusCode: 400 # bad request or other errors
body: status: 'fail', message: e.name + ' :: ' + e.message
# send a message in a room - POST body should be { "msg" : "this is my message"}
Api.addRoute 'rooms/:id/send', authRequired: true,
post: ->
Meteor.runAsUser this.userId, () =>
console.log @bodyParams.msg
Meteor.call('sendMessage', {msg: this.bodyParams.msg, rid: @urlParams.id} )
status: 'success' #need to handle error
# validate an array of users
Api.testapiValidateUsers = (users) ->
for user, i in users
if user.name?
if user.email?
if user.pass?
if /^[0-9a-z-_]+$/i.test user.name
if /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]+\b/i.test user.email
continue
throw new Meteor.Error 'invalid-user-record', "[restapi] bulk/register -> record #" + i + " is invalid"
return
###
@api {post} /bulk/register Register multiple users based on an input array.
@apiName register
@apiGroup TestAndAdminAutomation
@apiVersion 0.0.1
@apiDescription Caller must have 'testagent' or 'adminautomation' role.
NOTE: remove room is NOT recommended; use Meteor.reset() to clear db and re-seed instead
@apiParam {json} rooms An array of users in the body of the POST.
@apiParamExample {json} POST Request Body example:
{
'users':[ {'email': 'user1@user1.com',
'name': 'user1',
'pass': 'abc123' },
{'email': 'user2@user2.com',
'name': 'user2',
'pass': 'abc123'},
...
]
}
@apiSuccess {json} ids An array of IDs of the registered users.
@apiSuccessExample {json} Success-Response:
HTTP/1.1 200 OK
{
'ids':[ {'uid': 'uid_1'},
{'uid': 'uid_2'},
...
]
}
###
Api.addRoute 'bulk/register', authRequired: true,
post:
roleRequired: ['testagent', 'adminautomation']
action: ->
try
Api.testapiValidateUsers @bodyParams.users
this.response.setTimeout (500 * @bodyParams.users.length)
ids = []
endCount = @bodyParams.users.length - 1
for incoming, i in @bodyParams.users
ids[i] = Meteor.call 'registerUser', incoming
Meteor.runAsUser ids[i].uid, () =>
Meteor.call 'setUsername', incoming.name
status: 'success', ids: ids
catch e
statusCode: 400 # bad request or other errors
body: status: 'fail', message: e.name + ' :: ' + e.message
# validate an array of rooms
Api.testapiValidateRooms = (rooms) ->
for room, i in rooms
if room.name?
if room.members?
if room.members.length > 1
if /^[0-9a-z-_]+$/i.test room.name
continue
throw new Meteor.Error 'invalid-room-record', "[restapi] bulk/createRoom -> record #" + i + " is invalid"
return
###
@api {post} /bulk/createRoom Create multiple rooms based on an input array.
@apiName createRoom
@apiGroup TestAndAdminAutomation
@apiVersion 0.0.1
@apiParam {json} rooms An array of rooms in the body of the POST.
@apiParamExample {json} POST Request Body example:
{
'rooms':[ {'name': 'room1',
'members': ['user1', 'user2']
},
{'name': 'room2',
'members': ['user1', 'user2', 'user3']
}
...
]
}
@apiDescription Caller must have 'testagent' or 'adminautomation' role.
NOTE: remove room is NOT recommended; use Meteor.reset() to clear db and re-seed instead
@apiSuccess {json} ids An array of ids of the rooms created.
@apiSuccessExample {json} Success-Response:
HTTP/1.1 200 OK
{
'ids':[ {'rid': 'rid_1'},
{'rid': 'rid_2'},
...
]
}
###
Api.addRoute 'bulk/createRoom', authRequired: true,
post:
roleRequired: ['testagent', 'adminautomation']
action: ->
try
this.response.setTimeout (1000 * @bodyParams.rooms.length)
Api.testapiValidateRooms @bodyParams.rooms
ids = []
Meteor.runAsUser this.userId, () =>
(ids[i] = Meteor.call 'createChannel', incoming.name, incoming.members) for incoming,i in @bodyParams.rooms
status: 'success', ids: ids # need to handle error
catch e
statusCode: 400 # bad request or other errors
body: status: 'fail', message: e.name + ' :: ' + e.message
| 121895 | Api = new Restivus
useDefaultAuth: true
prettyJson: true
Api.addRoute 'version', authRequired: false,
get: ->
version = {api: '0.1', rocketchat: '0.5'}
status: 'success', versions: version
Api.addRoute 'publicRooms', authRequired: true,
get: ->
rooms = ChatRoom.find({ t: 'c' }, { sort: { msgs:-1 } }).fetch()
status: 'success', rooms: rooms
# join a room
Api.addRoute 'rooms/:id/join', authRequired: true,
post: ->
Meteor.runAsUser this.userId, () =>
Meteor.call('joinRoom', @urlParams.id)
status: 'success' # need to handle error
# leave a room
Api.addRoute 'rooms/:id/leave', authRequired: true,
post: ->
Meteor.runAsUser this.userId, () =>
Meteor.call('leaveRoom', @urlParams.id)
status: 'success' # need to handle error
# get messages in a room
Api.addRoute 'rooms/:id/messages', authRequired: true,
get: ->
try
if Meteor.call('canAccessRoom', @urlParams.id, this.userId)
msgs = ChatMessage.find({rid: @urlParams.id, _hidden: {$ne: true}}, {sort: {ts: -1}}, {limit: 50}).fetch()
status: 'success', messages: msgs
else
statusCode: 403 # forbidden
body: status: 'fail', message: 'Cannot access room.'
catch e
statusCode: 400 # bad request or other errors
body: status: 'fail', message: e.name + ' :: ' + e.message
# send a message in a room - POST body should be { "msg" : "this is my message"}
Api.addRoute 'rooms/:id/send', authRequired: true,
post: ->
Meteor.runAsUser this.userId, () =>
console.log @bodyParams.msg
Meteor.call('sendMessage', {msg: this.bodyParams.msg, rid: @urlParams.id} )
status: 'success' #need to handle error
# validate an array of users
Api.testapiValidateUsers = (users) ->
for user, i in users
if user.name?
if user.email?
if user.pass?
if /^[0-9a-z-_]+$/i.test user.name
if /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]+\b/i.test user.email
continue
throw new Meteor.Error 'invalid-user-record', "[restapi] bulk/register -> record #" + i + " is invalid"
return
###
@api {post} /bulk/register Register multiple users based on an input array.
@apiName register
@apiGroup TestAndAdminAutomation
@apiVersion 0.0.1
@apiDescription Caller must have 'testagent' or 'adminautomation' role.
NOTE: remove room is NOT recommended; use Meteor.reset() to clear db and re-seed instead
@apiParam {json} rooms An array of users in the body of the POST.
@apiParamExample {json} POST Request Body example:
{
'users':[ {'email': '<EMAIL>',
'name': 'user1',
'pass': '<PASSWORD>' },
{'email': '<EMAIL>',
'name': 'user2',
'pass': '<PASSWORD>'},
...
]
}
@apiSuccess {json} ids An array of IDs of the registered users.
@apiSuccessExample {json} Success-Response:
HTTP/1.1 200 OK
{
'ids':[ {'uid': 'uid_1'},
{'uid': 'uid_2'},
...
]
}
###
Api.addRoute 'bulk/register', authRequired: true,
post:
roleRequired: ['testagent', 'adminautomation']
action: ->
try
Api.testapiValidateUsers @bodyParams.users
this.response.setTimeout (500 * @bodyParams.users.length)
ids = []
endCount = @bodyParams.users.length - 1
for incoming, i in @bodyParams.users
ids[i] = Meteor.call 'registerUser', incoming
Meteor.runAsUser ids[i].uid, () =>
Meteor.call 'setUsername', incoming.name
status: 'success', ids: ids
catch e
statusCode: 400 # bad request or other errors
body: status: 'fail', message: e.name + ' :: ' + e.message
# validate an array of rooms
Api.testapiValidateRooms = (rooms) ->
for room, i in rooms
if room.name?
if room.members?
if room.members.length > 1
if /^[0-9a-z-_]+$/i.test room.name
continue
throw new Meteor.Error 'invalid-room-record', "[restapi] bulk/createRoom -> record #" + i + " is invalid"
return
###
@api {post} /bulk/createRoom Create multiple rooms based on an input array.
@apiName createRoom
@apiGroup TestAndAdminAutomation
@apiVersion 0.0.1
@apiParam {json} rooms An array of rooms in the body of the POST.
@apiParamExample {json} POST Request Body example:
{
'rooms':[ {'name': 'room1',
'members': ['user1', 'user2']
},
{'name': 'room2',
'members': ['user1', 'user2', 'user3']
}
...
]
}
@apiDescription Caller must have 'testagent' or 'adminautomation' role.
NOTE: remove room is NOT recommended; use Meteor.reset() to clear db and re-seed instead
@apiSuccess {json} ids An array of ids of the rooms created.
@apiSuccessExample {json} Success-Response:
HTTP/1.1 200 OK
{
'ids':[ {'rid': 'rid_1'},
{'rid': 'rid_2'},
...
]
}
###
Api.addRoute 'bulk/createRoom', authRequired: true,
post:
roleRequired: ['testagent', 'adminautomation']
action: ->
try
this.response.setTimeout (1000 * @bodyParams.rooms.length)
Api.testapiValidateRooms @bodyParams.rooms
ids = []
Meteor.runAsUser this.userId, () =>
(ids[i] = Meteor.call 'createChannel', incoming.name, incoming.members) for incoming,i in @bodyParams.rooms
status: 'success', ids: ids # need to handle error
catch e
statusCode: 400 # bad request or other errors
body: status: 'fail', message: e.name + ' :: ' + e.message
| true | Api = new Restivus
useDefaultAuth: true
prettyJson: true
Api.addRoute 'version', authRequired: false,
get: ->
version = {api: '0.1', rocketchat: '0.5'}
status: 'success', versions: version
Api.addRoute 'publicRooms', authRequired: true,
get: ->
rooms = ChatRoom.find({ t: 'c' }, { sort: { msgs:-1 } }).fetch()
status: 'success', rooms: rooms
# join a room
Api.addRoute 'rooms/:id/join', authRequired: true,
post: ->
Meteor.runAsUser this.userId, () =>
Meteor.call('joinRoom', @urlParams.id)
status: 'success' # need to handle error
# leave a room
Api.addRoute 'rooms/:id/leave', authRequired: true,
post: ->
Meteor.runAsUser this.userId, () =>
Meteor.call('leaveRoom', @urlParams.id)
status: 'success' # need to handle error
# get messages in a room
Api.addRoute 'rooms/:id/messages', authRequired: true,
get: ->
try
if Meteor.call('canAccessRoom', @urlParams.id, this.userId)
msgs = ChatMessage.find({rid: @urlParams.id, _hidden: {$ne: true}}, {sort: {ts: -1}}, {limit: 50}).fetch()
status: 'success', messages: msgs
else
statusCode: 403 # forbidden
body: status: 'fail', message: 'Cannot access room.'
catch e
statusCode: 400 # bad request or other errors
body: status: 'fail', message: e.name + ' :: ' + e.message
# send a message in a room - POST body should be { "msg" : "this is my message"}
Api.addRoute 'rooms/:id/send', authRequired: true,
post: ->
Meteor.runAsUser this.userId, () =>
console.log @bodyParams.msg
Meteor.call('sendMessage', {msg: this.bodyParams.msg, rid: @urlParams.id} )
status: 'success' #need to handle error
# validate an array of users
Api.testapiValidateUsers = (users) ->
for user, i in users
if user.name?
if user.email?
if user.pass?
if /^[0-9a-z-_]+$/i.test user.name
if /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]+\b/i.test user.email
continue
throw new Meteor.Error 'invalid-user-record', "[restapi] bulk/register -> record #" + i + " is invalid"
return
###
@api {post} /bulk/register Register multiple users based on an input array.
@apiName register
@apiGroup TestAndAdminAutomation
@apiVersion 0.0.1
@apiDescription Caller must have 'testagent' or 'adminautomation' role.
NOTE: remove room is NOT recommended; use Meteor.reset() to clear db and re-seed instead
@apiParam {json} rooms An array of users in the body of the POST.
@apiParamExample {json} POST Request Body example:
{
'users':[ {'email': 'PI:EMAIL:<EMAIL>END_PI',
'name': 'user1',
'pass': 'PI:PASSWORD:<PASSWORD>END_PI' },
{'email': 'PI:EMAIL:<EMAIL>END_PI',
'name': 'user2',
'pass': 'PI:PASSWORD:<PASSWORD>END_PI'},
...
]
}
@apiSuccess {json} ids An array of IDs of the registered users.
@apiSuccessExample {json} Success-Response:
HTTP/1.1 200 OK
{
'ids':[ {'uid': 'uid_1'},
{'uid': 'uid_2'},
...
]
}
###
Api.addRoute 'bulk/register', authRequired: true,
post:
roleRequired: ['testagent', 'adminautomation']
action: ->
try
Api.testapiValidateUsers @bodyParams.users
this.response.setTimeout (500 * @bodyParams.users.length)
ids = []
endCount = @bodyParams.users.length - 1
for incoming, i in @bodyParams.users
ids[i] = Meteor.call 'registerUser', incoming
Meteor.runAsUser ids[i].uid, () =>
Meteor.call 'setUsername', incoming.name
status: 'success', ids: ids
catch e
statusCode: 400 # bad request or other errors
body: status: 'fail', message: e.name + ' :: ' + e.message
# validate an array of rooms
Api.testapiValidateRooms = (rooms) ->
for room, i in rooms
if room.name?
if room.members?
if room.members.length > 1
if /^[0-9a-z-_]+$/i.test room.name
continue
throw new Meteor.Error 'invalid-room-record', "[restapi] bulk/createRoom -> record #" + i + " is invalid"
return
###
@api {post} /bulk/createRoom Create multiple rooms based on an input array.
@apiName createRoom
@apiGroup TestAndAdminAutomation
@apiVersion 0.0.1
@apiParam {json} rooms An array of rooms in the body of the POST.
@apiParamExample {json} POST Request Body example:
{
'rooms':[ {'name': 'room1',
'members': ['user1', 'user2']
},
{'name': 'room2',
'members': ['user1', 'user2', 'user3']
}
...
]
}
@apiDescription Caller must have 'testagent' or 'adminautomation' role.
NOTE: remove room is NOT recommended; use Meteor.reset() to clear db and re-seed instead
@apiSuccess {json} ids An array of ids of the rooms created.
@apiSuccessExample {json} Success-Response:
HTTP/1.1 200 OK
{
'ids':[ {'rid': 'rid_1'},
{'rid': 'rid_2'},
...
]
}
###
Api.addRoute 'bulk/createRoom', authRequired: true,
post:
roleRequired: ['testagent', 'adminautomation']
action: ->
try
this.response.setTimeout (1000 * @bodyParams.rooms.length)
Api.testapiValidateRooms @bodyParams.rooms
ids = []
Meteor.runAsUser this.userId, () =>
(ids[i] = Meteor.call 'createChannel', incoming.name, incoming.members) for incoming,i in @bodyParams.rooms
status: 'success', ids: ids # need to handle error
catch e
statusCode: 400 # bad request or other errors
body: status: 'fail', message: e.name + ' :: ' + e.message
|
[
{
"context": "eCode] = {\n githubURL: \"https://github.com/codecombat/codecombat/blob/master/app/locale/#{languageCode}",
"end": 595,
"score": 0.9808774590492249,
"start": 585,
"tag": "USERNAME",
"value": "codecombat"
},
{
"context": "UK)\n ru: ['EagleTA', 'ImmortalJoker', ... | app/views/contribute/DiplomatView.coffee | michaelrn/codecombat | 5 | ContributeClassView = require './ContributeClassView'
template = require 'templates/contribute/diplomat'
{me} = require 'core/auth'
locale = require 'locale/locale'
module.exports = class DiplomatView extends ContributeClassView
id: 'diplomat-view'
template: template
initialize: ->
@contributorClassName = 'diplomat'
promises = []
@languageStats = {}
Object.keys(locale).forEach (languageCode) =>
console.log "processing #{languageCode}"
language = locale[languageCode]
@languageStats[languageCode] = {
githubURL: "https://github.com/codecombat/codecombat/blob/master/app/locale/#{languageCode}.coffee"
nativeDescription: language.nativeDescription
englishDescription: language.englishDescription
diplomats: @diplomats[languageCode] ? []
nativeDescription: language.nativeDescription
englishDescription: language.englishDescription
languageCode: languageCode
loading: true
}
promises.push locale.load(languageCode).then =>
_.assign @languageStats[languageCode], @calculateSpokenLanguageStats(languageCode, locale[languageCode])
@languageStats[languageCode].loading = false
@render()
console.log "Loaded #{languageCode}"
calculateSpokenLanguageStats: (languageCode, language) ->
totalStrings = @countStrings locale.en
return {
completion: @countStrings(language) / totalStrings
}
countStrings: (language) ->
translated = 0
for section, strings of language.translation
translated += _.size strings
translated
diplomats:
en: [] # English - English
'en-US': [] # English (US), English (US)
'en-GB': [] # English (UK), English (UK)
ru: ['EagleTA', 'ImmortalJoker', 'Mr A', 'Shpionus', 'a1ip', 'fess89', 'iulianR', 'kerradus', 'kisik21', 'nixel', 'ser-storchak', 'CatSkald'] # русский язык, Russian
'de-DE': ['Anon', 'Dirk', 'HiroP0', 'bahuma20', 'bkimminich', 'djsmith85', 'dkundel', 'domenukk', 'faabsen', 'Zeldaretter', 'joca16'] # Deutsch (Deutschland), German (Germany)
'de-AT': ['djsmith85'] # Deutsch (Österreich), German (Austria)
'de-CH': ['greyhusky'] # Deutsch (Schweiz), German (Switzerland)
'es-419': ['2xG', 'Federico Tomas', 'Jesús Ruppel', 'Mariano Luzza', 'Matthew Burt'] # español (América Latina), Spanish (Latin America)
'es-ES': ['3rr3s3v3n', 'Anon', 'DanielRodriguezRivero', 'Matthew Burt', 'OviiiOne', 'Pouyio', 'Vindurrin'] # español (ES), Spanish (Spain)
'zh-HANS': ['1c7', 'Adam23', 'BonnieBBS', 'Cheng Zheng', 'Vic020', 'ZephyrSails', 'julycoolwind', 'onion7878', 'spacepope', 'yangxuan8282', 'yfdyh000'] # 简体中文, Chinese (Simplified)
'zh-HANT': ['Adam23', 'gintau', 'shuwn'] # 繁體中文, Chinese (Traditional)
'zh-WUU-HANS': [] # 吴语, Wuu (Simplified)
'zh-WUU-HANT': ['benojan'] # 吳語, Wuu (Traditional)
fr: ['AminSai', 'Anon', 'Armaldio', 'ChrisLightman', 'Elfisen', 'Feugy', 'MartinDelille', 'Oaugereau', 'Xeonarno', 'dc55028', 'jaybi', 'pstweb', 'veritable', 'xavismeh', 'CatSkald'] # français, French
ja: ['Coderaulic', 'g1itch', 'kengos', 'treby'] # 日本語, Japanese
ar: ['5y', 'ahmed80dz'] # العربية, Arabic
'pt-BR': ['Bia41', 'Gutenberg Barros', 'Kieizroe', 'Matthew Burt', 'brunoporto', 'cassiocardoso', 'jklemm', 'Arkhad'] # português do Brasil, Portuguese (Brazil)
'pt-PT': ['Imperadeiro98', 'Matthew Burt', 'ProgramadorLucas', 'ReiDuKuduro', 'batista', 'gutierri'] # Português (Portugal), Portuguese (Portugal)
pl: ['Anon', 'Kacper Ciepielewski', 'TigroTigro', 'kvasnyk', 'CatSkald'] # język polski, Polish
it: ['flauta', 'Atomk', 'Lionhear7'] # italiano, Italian
tr: ['Nazım Gediz Aydındoğmuş', 'cobaimelan', 'gediz', 'ilisyus', 'wakeup'] # Türkçe, Turkish
nl: [] # Nederlands, Dutch
'nl-BE': ['Glen De Cauwsemaecker', 'Ruben Vereecken'] # Nederlands (België), Dutch (Belgium)
'nl-NL': ['Guido Zuidhof', "Jasper D\'haene"] # Nederlands (Nederland), Dutch (Netherlands)
fa: ['Reza Habibi (Rehb)'] # فارسی, Persian
cs: ['Martin005', 'Gygram', 'vanous'] # čeština, Czech
sv: ['iamhj', 'Galaky'] # Svenska, Swedish
id: ['mlewisno-oberlin'] # Bahasa Indonesia, Indonesian
el: ['Stergios', 'micman', 'zsdregas'] # ελληνικά, Greek
ro: [] # limba română, Romanian
vi: ['An Nguyen Hoang Thien'] # Tiếng Việt, Vietnamese
hu: ['Anon', 'atlantisguru', 'bbeasmile', 'csuvsaregal', 'divaDseidnA', 'ferpeter', 'kinez', 'adamcsillag', 'LogMeIn', 'espell.com'] # magyar, Hungarian
th: ['Kamolchanok Jittrepit'] # ไทย, Thai
da: ['Anon', 'Einar Rasmussen', 'Rahazan', 'Randi Hillerøe', 'Silwing', 'marc-portier', 'sorsjen', 'Zleep-Dogg'] # dansk, Danish
ko: ['Melondonut'] # 한국어, Korean
sk: ['Anon', 'Juraj Pecháč'] # slovenčina, Slovak
sl: [] # slovenščina, Slovene
fi: [] # suomi, Finnish
bg: [] # български език, Bulgarian
nb: ['bardeh', 'ebirkenes', 'matifol', 'mcclane654', 'mogsie', 'torehaug', 'AnitaOlsen'] # Norsk Bokmål, Norwegian (Bokmål)
nn: ['Ayexa'] # Norsk Nynorsk, Norwegian (Nynorsk)
he: ['OverProgram', 'monetita'] # עברית, Hebrew
lt: [] # lietuvių kalba, Lithuanian
sr: ['Vitalije'] # српски, Serbian
uk: ['ImmortalJoker', 'OlenaGapak', 'Rarst', 'endrilian', 'fess89', 'gorodsb', 'probil', 'CatSkald'] # українська, Ukrainian
hi: [] # मानक हिन्दी, Hindi
ur: [] # اُردُو, Urdu
ms: [] # Bahasa Melayu, Bahasa Malaysia
ca: ['ArniMcFrag', 'Nainufar'] # Català, Catalan
gl: ['mcaeiror'] # Galego, Galician
'mk-MK': ['SuperPranx'] # Македонски, Macedonian
eo: [] # Esperanto, Esperanto
uz: [] # O'zbekcha, Uzbek
my: [] # မြန်မာစကား, Myanmar language
et: [] # Eesti, Estonian
hr: [] # hrvatski jezik, Croatian
mi: [] # te reo Māori, Māori
haw: [] # ʻŌlelo Hawaiʻi, Hawaiian
kk: [] # қазақ тілі, Kazakh
az: [] # azərbaycan dili, Azerbaijani
fil: ['Celestz'] #Like This?
| 198146 | ContributeClassView = require './ContributeClassView'
template = require 'templates/contribute/diplomat'
{me} = require 'core/auth'
locale = require 'locale/locale'
module.exports = class DiplomatView extends ContributeClassView
id: 'diplomat-view'
template: template
initialize: ->
@contributorClassName = 'diplomat'
promises = []
@languageStats = {}
Object.keys(locale).forEach (languageCode) =>
console.log "processing #{languageCode}"
language = locale[languageCode]
@languageStats[languageCode] = {
githubURL: "https://github.com/codecombat/codecombat/blob/master/app/locale/#{languageCode}.coffee"
nativeDescription: language.nativeDescription
englishDescription: language.englishDescription
diplomats: @diplomats[languageCode] ? []
nativeDescription: language.nativeDescription
englishDescription: language.englishDescription
languageCode: languageCode
loading: true
}
promises.push locale.load(languageCode).then =>
_.assign @languageStats[languageCode], @calculateSpokenLanguageStats(languageCode, locale[languageCode])
@languageStats[languageCode].loading = false
@render()
console.log "Loaded #{languageCode}"
calculateSpokenLanguageStats: (languageCode, language) ->
totalStrings = @countStrings locale.en
return {
completion: @countStrings(language) / totalStrings
}
countStrings: (language) ->
translated = 0
for section, strings of language.translation
translated += _.size strings
translated
diplomats:
en: [] # English - English
'en-US': [] # English (US), English (US)
'en-GB': [] # English (UK), English (UK)
ru: ['EagleTA', 'ImmortalJoker', 'Mr A', 'Shpionus', 'a1ip', 'fess89', 'iulianR', 'kerradus', 'kisik21', 'nixel', 'ser-storchak', 'CatSkald'] # русский язык, Russian
'de-DE': ['<NAME>', '<NAME>', '<NAME>', 'bahuma20', 'bkimminich', 'djsmith85', 'dkundel', 'domenukk', 'faabsen', 'Zeldaretter', 'joca16'] # Deutsch (Deutschland), German (Germany)
'de-AT': ['djsmith85'] # Deutsch (Österreich), German (Austria)
'de-CH': ['greyhusky'] # Deutsch (Schweiz), German (Switzerland)
'es-419': ['2xG', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] # español (América Latina), Spanish (Latin America)
'es-ES': ['3rr3s3v3n', '<NAME>', '<NAME>', '<NAME>', 'OviiiOne', '<NAME>', '<NAME>'] # español (ES), Spanish (Spain)
'zh-HANS': ['1c7', '<NAME>', 'BonnieBBS', '<NAME>', 'Vic020', 'ZephyrSails', 'julycoolwind', 'onion7878', 'spacepope', 'yangxuan8282', 'yfdyh000'] # 简体中文, Chinese (Simplified)
'zh-HANT': ['<NAME>', 'gintau', 'shuwn'] # 繁體中文, Chinese (Traditional)
'zh-WUU-HANS': [] # 吴语, Wuu (Simplified)
'zh-WUU-HANT': ['benojan'] # 吳語, Wuu (Traditional)
fr: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'dc55028', 'jaybi', 'pstweb', 'veritable', 'xavismeh', 'CatSkald'] # français, French
ja: ['Coderaulic', 'g1itch', 'kengos', 'treby'] # 日本語, Japanese
ar: ['5y', 'ahmed80dz'] # العربية, Arabic
'pt-BR': ['Bia41', '<NAME>', '<NAME>', '<NAME>', 'brunoporto', 'cassiocardoso', 'jklemm', 'Arkhad'] # português do Brasil, Portuguese (Brazil)
'pt-PT': ['Imper<NAME>iro98', '<NAME>', 'Programador<NAME>', '<NAME>', 'batista', 'gutierri'] # Português (Portugal), Portuguese (Portugal)
pl: ['<NAME>', '<NAME>', '<NAME>', 'k<NAME>', 'CatSk<NAME>'] # język polski, Polish
it: ['flauta', 'Atomk', 'Lionhear7'] # italiano, Italian
tr: ['<NAME>', 'cobaimelan', 'gediz', 'ilisyus', 'wakeup'] # Türkçe, Turkish
nl: [] # Nederlands, Dutch
'nl-BE': ['<NAME>', '<NAME>'] # Nederlands (België), Dutch (Belgium)
'nl-NL': ['<NAME>', "<NAME>"] # Nederlands (Nederland), Dutch (Netherlands)
fa: ['<NAME> (Rehb)'] # فارسی, Persian
cs: ['<NAME>', '<NAME>', 'vanous'] # čeština, Czech
sv: ['iamhj', 'Galaky'] # Svenska, Swedish
id: ['mlewisno-oberlin'] # Bahasa Indonesia, Indonesian
el: ['<NAME>', '<NAME>', 'zsdregas'] # ελληνικά, Greek
ro: [] # limba română, Romanian
vi: ['<NAME>'] # Tiếng Việt, Vietnamese
hu: ['<NAME>', 'atlantisguru', '<NAME>', 'csuvsaregal', 'divaDseidnA', '<NAME>', '<NAME>', 'adamcsillag', 'LogMeIn', 'espell.com'] # magyar, Hungarian
th: ['<NAME>'] # ไทย, Thai
da: ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] # dansk, Danish
ko: ['<NAME>'] # 한국어, Korean
sk: ['<NAME>', '<NAME>'] # slovenčina, Slovak
sl: [] # slovenščina, Slovene
fi: [] # suomi, Finnish
bg: [] # български език, Bulgarian
nb: ['<NAME>', 'eb<NAME>', 'matifol', 'mcclane654', '<NAME>', '<NAME>', '<NAME>'] # Norsk Bokmål, Norwegian (Bokmål)
nn: ['<NAME>a'] # Norsk Nynorsk, Norwegian (Nynorsk)
he: ['<NAME>', '<NAME>'] # עברית, Hebrew
lt: [] # lietuvių kalba, Lithuanian
sr: ['<NAME>'] # српски, Serbian
uk: ['ImmortalJoker', '<NAME>', '<NAME>', 'endrilian', 'fess89', 'gorodsb', 'probil', 'CatSkald'] # українська, Ukrainian
hi: [] # मानक हिन्दी, Hindi
ur: [] # اُردُو, Urdu
ms: [] # Bahasa Melayu, Bahasa Malaysia
ca: ['ArniMcFrag', 'Nainufar'] # Català, Catalan
gl: ['mcaeiror'] # Galego, Galician
'mk-MK': ['SuperPranx'] # Македонски, Macedonian
eo: [] # Esperanto, Esperanto
uz: [] # O'zbekcha, Uzbek
my: [] # မြန်မာစကား, Myanmar language
et: [] # Eesti, Estonian
hr: [] # hrvatski jezik, Croatian
mi: [] # te reo Māori, Māori
haw: [] # ʻŌlelo Hawaiʻi, Hawaiian
kk: [] # қазақ тілі, Kazakh
az: [] # azərbaycan dili, Azerbaijani
fil: ['Celestz'] #Like This?
| true | ContributeClassView = require './ContributeClassView'
template = require 'templates/contribute/diplomat'
{me} = require 'core/auth'
locale = require 'locale/locale'
module.exports = class DiplomatView extends ContributeClassView
id: 'diplomat-view'
template: template
initialize: ->
@contributorClassName = 'diplomat'
promises = []
@languageStats = {}
Object.keys(locale).forEach (languageCode) =>
console.log "processing #{languageCode}"
language = locale[languageCode]
@languageStats[languageCode] = {
githubURL: "https://github.com/codecombat/codecombat/blob/master/app/locale/#{languageCode}.coffee"
nativeDescription: language.nativeDescription
englishDescription: language.englishDescription
diplomats: @diplomats[languageCode] ? []
nativeDescription: language.nativeDescription
englishDescription: language.englishDescription
languageCode: languageCode
loading: true
}
promises.push locale.load(languageCode).then =>
_.assign @languageStats[languageCode], @calculateSpokenLanguageStats(languageCode, locale[languageCode])
@languageStats[languageCode].loading = false
@render()
console.log "Loaded #{languageCode}"
calculateSpokenLanguageStats: (languageCode, language) ->
totalStrings = @countStrings locale.en
return {
completion: @countStrings(language) / totalStrings
}
countStrings: (language) ->
translated = 0
for section, strings of language.translation
translated += _.size strings
translated
diplomats:
en: [] # English - English
'en-US': [] # English (US), English (US)
'en-GB': [] # English (UK), English (UK)
ru: ['EagleTA', 'ImmortalJoker', 'Mr A', 'Shpionus', 'a1ip', 'fess89', 'iulianR', 'kerradus', 'kisik21', 'nixel', 'ser-storchak', 'CatSkald'] # русский язык, Russian
'de-DE': ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'bahuma20', 'bkimminich', 'djsmith85', 'dkundel', 'domenukk', 'faabsen', 'Zeldaretter', 'joca16'] # Deutsch (Deutschland), German (Germany)
'de-AT': ['djsmith85'] # Deutsch (Österreich), German (Austria)
'de-CH': ['greyhusky'] # Deutsch (Schweiz), German (Switzerland)
'es-419': ['2xG', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] # español (América Latina), Spanish (Latin America)
'es-ES': ['3rr3s3v3n', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'OviiiOne', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] # español (ES), Spanish (Spain)
'zh-HANS': ['1c7', 'PI:NAME:<NAME>END_PI', 'BonnieBBS', 'PI:NAME:<NAME>END_PI', 'Vic020', 'ZephyrSails', 'julycoolwind', 'onion7878', 'spacepope', 'yangxuan8282', 'yfdyh000'] # 简体中文, Chinese (Simplified)
'zh-HANT': ['PI:NAME:<NAME>END_PI', 'gintau', 'shuwn'] # 繁體中文, Chinese (Traditional)
'zh-WUU-HANS': [] # 吴语, Wuu (Simplified)
'zh-WUU-HANT': ['benojan'] # 吳語, Wuu (Traditional)
fr: ['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', 'dc55028', 'jaybi', 'pstweb', 'veritable', 'xavismeh', 'CatSkald'] # français, French
ja: ['Coderaulic', 'g1itch', 'kengos', 'treby'] # 日本語, Japanese
ar: ['5y', 'ahmed80dz'] # العربية, Arabic
'pt-BR': ['Bia41', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'brunoporto', 'cassiocardoso', 'jklemm', 'Arkhad'] # português do Brasil, Portuguese (Brazil)
'pt-PT': ['ImperPI:NAME:<NAME>END_PIiro98', 'PI:NAME:<NAME>END_PI', 'ProgramadorPI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'batista', 'gutierri'] # Português (Portugal), Portuguese (Portugal)
pl: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'kPI:NAME:<NAME>END_PI', 'CatSkPI:NAME:<NAME>END_PI'] # język polski, Polish
it: ['flauta', 'Atomk', 'Lionhear7'] # italiano, Italian
tr: ['PI:NAME:<NAME>END_PI', 'cobaimelan', 'gediz', 'ilisyus', 'wakeup'] # Türkçe, Turkish
nl: [] # Nederlands, Dutch
'nl-BE': ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] # Nederlands (België), Dutch (Belgium)
'nl-NL': ['PI:NAME:<NAME>END_PI', "PI:NAME:<NAME>END_PI"] # Nederlands (Nederland), Dutch (Netherlands)
fa: ['PI:NAME:<NAME>END_PI (Rehb)'] # فارسی, Persian
cs: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'vanous'] # čeština, Czech
sv: ['iamhj', 'Galaky'] # Svenska, Swedish
id: ['mlewisno-oberlin'] # Bahasa Indonesia, Indonesian
el: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'zsdregas'] # ελληνικά, Greek
ro: [] # limba română, Romanian
vi: ['PI:NAME:<NAME>END_PI'] # Tiếng Việt, Vietnamese
hu: ['PI:NAME:<NAME>END_PI', 'atlantisguru', 'PI:NAME:<NAME>END_PI', 'csuvsaregal', 'divaDseidnA', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'adamcsillag', 'LogMeIn', 'espell.com'] # magyar, Hungarian
th: ['PI:NAME:<NAME>END_PI'] # ไทย, Thai
da: ['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'] # dansk, Danish
ko: ['PI:NAME:<NAME>END_PI'] # 한국어, Korean
sk: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] # slovenčina, Slovak
sl: [] # slovenščina, Slovene
fi: [] # suomi, Finnish
bg: [] # български език, Bulgarian
nb: ['PI:NAME:<NAME>END_PI', 'ebPI:NAME:<NAME>END_PI', 'matifol', 'mcclane654', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] # Norsk Bokmål, Norwegian (Bokmål)
nn: ['PI:NAME:<NAME>END_PIa'] # Norsk Nynorsk, Norwegian (Nynorsk)
he: ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI'] # עברית, Hebrew
lt: [] # lietuvių kalba, Lithuanian
sr: ['PI:NAME:<NAME>END_PI'] # српски, Serbian
uk: ['ImmortalJoker', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'endrilian', 'fess89', 'gorodsb', 'probil', 'CatSkald'] # українська, Ukrainian
hi: [] # मानक हिन्दी, Hindi
ur: [] # اُردُو, Urdu
ms: [] # Bahasa Melayu, Bahasa Malaysia
ca: ['ArniMcFrag', 'Nainufar'] # Català, Catalan
gl: ['mcaeiror'] # Galego, Galician
'mk-MK': ['SuperPranx'] # Македонски, Macedonian
eo: [] # Esperanto, Esperanto
uz: [] # O'zbekcha, Uzbek
my: [] # မြန်မာစကား, Myanmar language
et: [] # Eesti, Estonian
hr: [] # hrvatski jezik, Croatian
mi: [] # te reo Māori, Māori
haw: [] # ʻŌlelo Hawaiʻi, Hawaiian
kk: [] # қазақ тілі, Kazakh
az: [] # azərbaycan dili, Azerbaijani
fil: ['Celestz'] #Like This?
|
[
{
"context": "b, \"main\"\n username=process.argv[1]\n passphrase=process.argv[2]\n await login { username, email, passphrase },",
"end": 348,
"score": 0.725903332233429,
"start": 336,
"tag": "PASSWORD",
"value": "process.argv"
}
] | src/cmd.iced | pchara20/keybase-login_arg | 0 | read = require 'read'
{login} = require '../'
{make_esc} = require 'iced-error'
parse_email_or_username = (email_or_username) ->
if email_or_username.indexOf('@') > 0 then { email : email_or_username }
else { username : email_or_username }
exports.cmd = (cb) ->
esc = make_esc cb, "main"
username=process.argv[1]
passphrase=process.argv[2]
await login { username, email, passphrase }, defer err, res
cb err, res
| 42949 | read = require 'read'
{login} = require '../'
{make_esc} = require 'iced-error'
parse_email_or_username = (email_or_username) ->
if email_or_username.indexOf('@') > 0 then { email : email_or_username }
else { username : email_or_username }
exports.cmd = (cb) ->
esc = make_esc cb, "main"
username=process.argv[1]
passphrase=<PASSWORD>[2]
await login { username, email, passphrase }, defer err, res
cb err, res
| true | read = require 'read'
{login} = require '../'
{make_esc} = require 'iced-error'
parse_email_or_username = (email_or_username) ->
if email_or_username.indexOf('@') > 0 then { email : email_or_username }
else { username : email_or_username }
exports.cmd = (cb) ->
esc = make_esc cb, "main"
username=process.argv[1]
passphrase=PI:PASSWORD:<PASSWORD>END_PI[2]
await login { username, email, passphrase }, defer err, res
cb err, res
|
[
{
"context": "age that captures that emotion.\n# \n# Author:\n# missu \n\nmodule.exports = (robot) ->\n robot.hear /(.*) ",
"end": 283,
"score": 0.9843725562095642,
"start": 278,
"tag": "NAME",
"value": "missu"
}
] | scripts/panda-panda.coffee | missu/hubot-pandapanda | 3 | # Description
# listens for panda related trigger words and responds
#
# Dependencies:
# none
#
# Commands:
# sad panda, angry panda, frustrated panda, happy panda, hungry panda, kungfu panda - hubot will reply with an image that captures that emotion.
#
# Author:
# missu
module.exports = (robot) ->
robot.hear /(.*) panda/i, (msg) ->
pandaType = msg.match[1].toLowerCase()
angry = [
'http://fc08.deviantart.net/fs70/f/2010/010/6/1/CROSS_ID_Panda_Version_by_xxcrossmaniac.jpg'
'http://www.electricdialogue.com/2012dev/wp-content/uploads/2012/04/angry-panda.png'
'http://2.bp.blogspot.com/-QCQupZ13FtA/TeV0Z8DmQzI/AAAAAAAAAGs/axFV7-ADzZw/s400/angry-panda.jpg'
'http://memecrunch.com/image/51c27308afa96f3383000052.jpg?w=269'
'https://farm1.staticflickr.com/57/211758568_8eb74e506e.jpg'
]
sad = [
'https://farm5.staticflickr.com/4083/4966109357_eb24f7b6a1.jpg'
'http://legendaryarchive.files.wordpress.com/2014/03/sad-panda.jpg'
'http://fc05.deviantart.net/fs70/f/2011/029/a/a/sad_panda_by_garnwraly-d38cf9k.jpg'
'https://farm4.staticflickr.com/3139/2829615734_a14e14c9e1.jpg'
]
frustrated = [
'http://media-cache-ak0.pinimg.com/736x/26/84/a2/2684a227bbace77222b9f8b6393c6419.jpg'
'http://news.bbcimg.co.uk/media/images/69193000/jpg/_69193264_69193263.jpg'
'https://farm4.staticflickr.com/3701/12329543123_60fdfed002.jpg'
]
happy = [
'http://media.tumblr.com/tumblr_lu71bnOkdD1qdljoj.jpg'
'http://www.asianstyle.cz/upload/files/3/7d469/7d4699bdd4c28588e837326cf825c2b5.jpg'
'http://2.bp.blogspot.com/--wvunLxIz0s/UHEJS8vqcnI/AAAAAAAAHZI/khje3PTQQxk/s1600/Happy%20Pandas%20Photo.jpg'
]
surprised = [
'https://farm1.staticflickr.com/165/438577300_eeb3c46b6f.jpg'
'https://farm4.staticflickr.com/3354/3406887187_ae7d802c85.jpg'
]
hungry = [
'https://farm3.staticflickr.com/2650/3851900028_fa765fd0df.jpg'
'https://farm4.staticflickr.com/3042/5872444975_6ed0abe1d1.jpg'
'https://farm4.staticflickr.com/3681/9195957186_3fb961ddc3.jpg'
]
kungfu = [
'https://farm4.staticflickr.com/3173/2759317285_253b40c549.jpg'
]
if pandaType is "angry"
msg.send "grrrrr"
msg.send msg.random angry
else if pandaType is "sad"
msg.emote "sighs"
msg.send msg.random sad
else if pandaType is "frustrated"
msg.send "seriously?!"
msg.send msg.random frustrated
else if pandaType is "happy"
msg.emote "giggles"
msg.send msg.random happy
else if pandaType is "hungry"
msg.emote "stomach grumbles"
msg.send msg.random hungry
else if pandaType is "kungfu"
msg.emote "grunts"
msg.send msg.random kungfu
return
| 155041 | # Description
# listens for panda related trigger words and responds
#
# Dependencies:
# none
#
# Commands:
# sad panda, angry panda, frustrated panda, happy panda, hungry panda, kungfu panda - hubot will reply with an image that captures that emotion.
#
# Author:
# <NAME>
module.exports = (robot) ->
robot.hear /(.*) panda/i, (msg) ->
pandaType = msg.match[1].toLowerCase()
angry = [
'http://fc08.deviantart.net/fs70/f/2010/010/6/1/CROSS_ID_Panda_Version_by_xxcrossmaniac.jpg'
'http://www.electricdialogue.com/2012dev/wp-content/uploads/2012/04/angry-panda.png'
'http://2.bp.blogspot.com/-QCQupZ13FtA/TeV0Z8DmQzI/AAAAAAAAAGs/axFV7-ADzZw/s400/angry-panda.jpg'
'http://memecrunch.com/image/51c27308afa96f3383000052.jpg?w=269'
'https://farm1.staticflickr.com/57/211758568_8eb74e506e.jpg'
]
sad = [
'https://farm5.staticflickr.com/4083/4966109357_eb24f7b6a1.jpg'
'http://legendaryarchive.files.wordpress.com/2014/03/sad-panda.jpg'
'http://fc05.deviantart.net/fs70/f/2011/029/a/a/sad_panda_by_garnwraly-d38cf9k.jpg'
'https://farm4.staticflickr.com/3139/2829615734_a14e14c9e1.jpg'
]
frustrated = [
'http://media-cache-ak0.pinimg.com/736x/26/84/a2/2684a227bbace77222b9f8b6393c6419.jpg'
'http://news.bbcimg.co.uk/media/images/69193000/jpg/_69193264_69193263.jpg'
'https://farm4.staticflickr.com/3701/12329543123_60fdfed002.jpg'
]
happy = [
'http://media.tumblr.com/tumblr_lu71bnOkdD1qdljoj.jpg'
'http://www.asianstyle.cz/upload/files/3/7d469/7d4699bdd4c28588e837326cf825c2b5.jpg'
'http://2.bp.blogspot.com/--wvunLxIz0s/UHEJS8vqcnI/AAAAAAAAHZI/khje3PTQQxk/s1600/Happy%20Pandas%20Photo.jpg'
]
surprised = [
'https://farm1.staticflickr.com/165/438577300_eeb3c46b6f.jpg'
'https://farm4.staticflickr.com/3354/3406887187_ae7d802c85.jpg'
]
hungry = [
'https://farm3.staticflickr.com/2650/3851900028_fa765fd0df.jpg'
'https://farm4.staticflickr.com/3042/5872444975_6ed0abe1d1.jpg'
'https://farm4.staticflickr.com/3681/9195957186_3fb961ddc3.jpg'
]
kungfu = [
'https://farm4.staticflickr.com/3173/2759317285_253b40c549.jpg'
]
if pandaType is "angry"
msg.send "grrrrr"
msg.send msg.random angry
else if pandaType is "sad"
msg.emote "sighs"
msg.send msg.random sad
else if pandaType is "frustrated"
msg.send "seriously?!"
msg.send msg.random frustrated
else if pandaType is "happy"
msg.emote "giggles"
msg.send msg.random happy
else if pandaType is "hungry"
msg.emote "stomach grumbles"
msg.send msg.random hungry
else if pandaType is "kungfu"
msg.emote "grunts"
msg.send msg.random kungfu
return
| true | # Description
# listens for panda related trigger words and responds
#
# Dependencies:
# none
#
# Commands:
# sad panda, angry panda, frustrated panda, happy panda, hungry panda, kungfu panda - hubot will reply with an image that captures that emotion.
#
# Author:
# PI:NAME:<NAME>END_PI
module.exports = (robot) ->
robot.hear /(.*) panda/i, (msg) ->
pandaType = msg.match[1].toLowerCase()
angry = [
'http://fc08.deviantart.net/fs70/f/2010/010/6/1/CROSS_ID_Panda_Version_by_xxcrossmaniac.jpg'
'http://www.electricdialogue.com/2012dev/wp-content/uploads/2012/04/angry-panda.png'
'http://2.bp.blogspot.com/-QCQupZ13FtA/TeV0Z8DmQzI/AAAAAAAAAGs/axFV7-ADzZw/s400/angry-panda.jpg'
'http://memecrunch.com/image/51c27308afa96f3383000052.jpg?w=269'
'https://farm1.staticflickr.com/57/211758568_8eb74e506e.jpg'
]
sad = [
'https://farm5.staticflickr.com/4083/4966109357_eb24f7b6a1.jpg'
'http://legendaryarchive.files.wordpress.com/2014/03/sad-panda.jpg'
'http://fc05.deviantart.net/fs70/f/2011/029/a/a/sad_panda_by_garnwraly-d38cf9k.jpg'
'https://farm4.staticflickr.com/3139/2829615734_a14e14c9e1.jpg'
]
frustrated = [
'http://media-cache-ak0.pinimg.com/736x/26/84/a2/2684a227bbace77222b9f8b6393c6419.jpg'
'http://news.bbcimg.co.uk/media/images/69193000/jpg/_69193264_69193263.jpg'
'https://farm4.staticflickr.com/3701/12329543123_60fdfed002.jpg'
]
happy = [
'http://media.tumblr.com/tumblr_lu71bnOkdD1qdljoj.jpg'
'http://www.asianstyle.cz/upload/files/3/7d469/7d4699bdd4c28588e837326cf825c2b5.jpg'
'http://2.bp.blogspot.com/--wvunLxIz0s/UHEJS8vqcnI/AAAAAAAAHZI/khje3PTQQxk/s1600/Happy%20Pandas%20Photo.jpg'
]
surprised = [
'https://farm1.staticflickr.com/165/438577300_eeb3c46b6f.jpg'
'https://farm4.staticflickr.com/3354/3406887187_ae7d802c85.jpg'
]
hungry = [
'https://farm3.staticflickr.com/2650/3851900028_fa765fd0df.jpg'
'https://farm4.staticflickr.com/3042/5872444975_6ed0abe1d1.jpg'
'https://farm4.staticflickr.com/3681/9195957186_3fb961ddc3.jpg'
]
kungfu = [
'https://farm4.staticflickr.com/3173/2759317285_253b40c549.jpg'
]
if pandaType is "angry"
msg.send "grrrrr"
msg.send msg.random angry
else if pandaType is "sad"
msg.emote "sighs"
msg.send msg.random sad
else if pandaType is "frustrated"
msg.send "seriously?!"
msg.send msg.random frustrated
else if pandaType is "happy"
msg.emote "giggles"
msg.send msg.random happy
else if pandaType is "hungry"
msg.emote "stomach grumbles"
msg.send msg.random hungry
else if pandaType is "kungfu"
msg.emote "grunts"
msg.send msg.random kungfu
return
|
[
{
"context": "rteilung elektrischer Energie},\n author={Schwab, A.J.},\n isbn={9783662553169},\n url={ht",
"end": 1229,
"score": 0.999850869178772,
"start": 1218,
"tag": "NAME",
"value": "Schwab, A.J"
},
{
"context": "rteilung elektrischer Energie},\n ... | spec/cite-manager-spec.coffee | smparker/atom-autocomplete-latex-cite | 4 | CiteManager = require '../lib/cite-manager'
path = require 'path'
fs = require 'fs-extra'
os = require 'os'
describe "When the CiteManger gets initialized", ->
manager = null
beforeEach ->
atom.project.setPaths([__dirname])
manager = new CiteManager()
waitsForPromise ->
manager.initialize()
it "is not null", ->
expect(manager).not.toEqual(null)
it "parsed the entries in the bib file", ->
expect(Object.keys(manager.database).length).toEqual(4)
expect(manager.database['kundur1994power']['id']).toEqual('kundur1994power')
it "can search with author in the database", ->
result = manager.searchForPrefixInDatabase('Hess')
expect(result[0].id).toEqual('7856203')
it "can search with title in the database", ->
result = manager.searchForPrefixInDatabase('Studies on provision')
expect(result[0].id).toEqual('7856203')
describe "When a secound bibtex file is added", ->
bibFile2 = path.join(__dirname,'lib2.bib')
beforeEach ->
runs ->
fs.appendFileSync bibFile2, '@book{schwab2017elektroenergiesysteme,
title={Elektroenergiesysteme: Erzeugung, {\"U}bertragung und Verteilung elektrischer Energie},
author={Schwab, A.J.},
isbn={9783662553169},
url={https://books.google.de/books?id=Gq80DwAAQBAJ},
year={2017},
publisher={Springer Berlin Heidelberg}
}'
waitsForPromise ->
manager.addBibtexFile(bibFile2)
afterEach ->
fs.removeSync bibFile2
it "add the file to the databse", ->
expect(Object.keys(manager.database).length).toEqual(5)
expect(manager.database['schwab2017elektroenergiesysteme']['id']).toEqual('schwab2017elektroenergiesysteme')
it "remove the entries when the file is removed", ->
fs.removeSync bibFile2
manager.removeBibtexFile(bibFile2)
expect(Object.keys(manager.database).length).toEqual(4)
describe "When the bibtex file is not valid", ->
bibFile2 = path.join(__dirname,'lib2.bib')
beforeEach ->
fs.appendFileSync bibFile2, '@book{schwab2017elektroenergiesysteme,
title={Elektroenergiesysteme: Erzeugung, {\"U}bertragung und Verteilung elektrischer Energie},
author={Schwab, A.J.},
isbn={9783662553169}
url={https://books.google.de/books?id=Gq80DwAAQBAJ},
year={2017,
publisher={Springer Berlin Heidelberg}
}'
waitsForPromise ->
manager.addBibtexFile(bibFile2)
afterEach ->
fs.removeSync bibFile2
it "show a warning", ->
noti = atom.notifications.getNotifications()
expect(noti.length).toEqual 1
expect(noti[0].message).toEqual "Autocomplete Latex Cite Warning"
expect(noti[0].type).toEqual "warning"
expect(noti[0].options.description).toContain "lib2.bib"
expect(noti[0].options.description).toContain "Token mismatch: match"
describe "When the global Path is enabled", ->
manager = null
beforeEach ->
atom.config.set 'autocomplete-latex-cite.globalBibPath', __dirname
atom.config.set 'autocomplete-latex-cite.includeGlobalBibFiles', true
manager = new CiteManager()
waitsForPromise ->
manager.initialize()
it "Add the entries to the database", ->
expect(Object.keys(manager.database).length).toEqual(4)
expect(manager.database['kundur1994power']['id']).toEqual('kundur1994power')
it "Removes the entries when the global path is disabled", ->
runs ->
atom.config.set 'autocomplete-latex-cite.includeGlobalBibFiles', false
waitsFor ->
Object.keys(manager.database).length < 4
runs ->
expect(Object.keys(manager.database).length).toEqual(0)
it "Changes the entries when the path is changed", ->
runs ->
atom.config.set 'autocomplete-latex-cite.globalBibPath', path.join(__dirname,'..','lib')
waitsFor ->
Object.keys(manager.database).length < 4
runs ->
expect(Object.keys(manager.database).length).toEqual(0)
it "Removes the entries when the path is set to empty string", ->
runs ->
atom.config.set 'autocomplete-latex-cite.globalBibPath', ''
waitsFor ->
Object.keys(manager.database).length < 4
runs ->
expect(Object.keys(manager.database).length).toEqual(0)
| 93882 | CiteManager = require '../lib/cite-manager'
path = require 'path'
fs = require 'fs-extra'
os = require 'os'
describe "When the CiteManger gets initialized", ->
manager = null
beforeEach ->
atom.project.setPaths([__dirname])
manager = new CiteManager()
waitsForPromise ->
manager.initialize()
it "is not null", ->
expect(manager).not.toEqual(null)
it "parsed the entries in the bib file", ->
expect(Object.keys(manager.database).length).toEqual(4)
expect(manager.database['kundur1994power']['id']).toEqual('kundur1994power')
it "can search with author in the database", ->
result = manager.searchForPrefixInDatabase('Hess')
expect(result[0].id).toEqual('7856203')
it "can search with title in the database", ->
result = manager.searchForPrefixInDatabase('Studies on provision')
expect(result[0].id).toEqual('7856203')
describe "When a secound bibtex file is added", ->
bibFile2 = path.join(__dirname,'lib2.bib')
beforeEach ->
runs ->
fs.appendFileSync bibFile2, '@book{schwab2017elektroenergiesysteme,
title={Elektroenergiesysteme: Erzeugung, {\"U}bertragung und Verteilung elektrischer Energie},
author={<NAME>.},
isbn={9783662553169},
url={https://books.google.de/books?id=Gq80DwAAQBAJ},
year={2017},
publisher={Springer Berlin Heidelberg}
}'
waitsForPromise ->
manager.addBibtexFile(bibFile2)
afterEach ->
fs.removeSync bibFile2
it "add the file to the databse", ->
expect(Object.keys(manager.database).length).toEqual(5)
expect(manager.database['schwab2017elektroenergiesysteme']['id']).toEqual('schwab2017elektroenergiesysteme')
it "remove the entries when the file is removed", ->
fs.removeSync bibFile2
manager.removeBibtexFile(bibFile2)
expect(Object.keys(manager.database).length).toEqual(4)
describe "When the bibtex file is not valid", ->
bibFile2 = path.join(__dirname,'lib2.bib')
beforeEach ->
fs.appendFileSync bibFile2, '@book{schwab2017elektroenergiesysteme,
title={Elektroenergiesysteme: Erzeugung, {\"U}bertragung und Verteilung elektrischer Energie},
author={<NAME>.},
isbn={9783662553169}
url={https://books.google.de/books?id=Gq80DwAAQBAJ},
year={2017,
publisher={Springer Berlin Heidelberg}
}'
waitsForPromise ->
manager.addBibtexFile(bibFile2)
afterEach ->
fs.removeSync bibFile2
it "show a warning", ->
noti = atom.notifications.getNotifications()
expect(noti.length).toEqual 1
expect(noti[0].message).toEqual "Autocomplete Latex Cite Warning"
expect(noti[0].type).toEqual "warning"
expect(noti[0].options.description).toContain "lib2.bib"
expect(noti[0].options.description).toContain "Token mismatch: match"
describe "When the global Path is enabled", ->
manager = null
beforeEach ->
atom.config.set 'autocomplete-latex-cite.globalBibPath', __dirname
atom.config.set 'autocomplete-latex-cite.includeGlobalBibFiles', true
manager = new CiteManager()
waitsForPromise ->
manager.initialize()
it "Add the entries to the database", ->
expect(Object.keys(manager.database).length).toEqual(4)
expect(manager.database['kundur1994power']['id']).toEqual('kundur1994power')
it "Removes the entries when the global path is disabled", ->
runs ->
atom.config.set 'autocomplete-latex-cite.includeGlobalBibFiles', false
waitsFor ->
Object.keys(manager.database).length < 4
runs ->
expect(Object.keys(manager.database).length).toEqual(0)
it "Changes the entries when the path is changed", ->
runs ->
atom.config.set 'autocomplete-latex-cite.globalBibPath', path.join(__dirname,'..','lib')
waitsFor ->
Object.keys(manager.database).length < 4
runs ->
expect(Object.keys(manager.database).length).toEqual(0)
it "Removes the entries when the path is set to empty string", ->
runs ->
atom.config.set 'autocomplete-latex-cite.globalBibPath', ''
waitsFor ->
Object.keys(manager.database).length < 4
runs ->
expect(Object.keys(manager.database).length).toEqual(0)
| true | CiteManager = require '../lib/cite-manager'
path = require 'path'
fs = require 'fs-extra'
os = require 'os'
describe "When the CiteManger gets initialized", ->
manager = null
beforeEach ->
atom.project.setPaths([__dirname])
manager = new CiteManager()
waitsForPromise ->
manager.initialize()
it "is not null", ->
expect(manager).not.toEqual(null)
it "parsed the entries in the bib file", ->
expect(Object.keys(manager.database).length).toEqual(4)
expect(manager.database['kundur1994power']['id']).toEqual('kundur1994power')
it "can search with author in the database", ->
result = manager.searchForPrefixInDatabase('Hess')
expect(result[0].id).toEqual('7856203')
it "can search with title in the database", ->
result = manager.searchForPrefixInDatabase('Studies on provision')
expect(result[0].id).toEqual('7856203')
describe "When a secound bibtex file is added", ->
bibFile2 = path.join(__dirname,'lib2.bib')
beforeEach ->
runs ->
fs.appendFileSync bibFile2, '@book{schwab2017elektroenergiesysteme,
title={Elektroenergiesysteme: Erzeugung, {\"U}bertragung und Verteilung elektrischer Energie},
author={PI:NAME:<NAME>END_PI.},
isbn={9783662553169},
url={https://books.google.de/books?id=Gq80DwAAQBAJ},
year={2017},
publisher={Springer Berlin Heidelberg}
}'
waitsForPromise ->
manager.addBibtexFile(bibFile2)
afterEach ->
fs.removeSync bibFile2
it "add the file to the databse", ->
expect(Object.keys(manager.database).length).toEqual(5)
expect(manager.database['schwab2017elektroenergiesysteme']['id']).toEqual('schwab2017elektroenergiesysteme')
it "remove the entries when the file is removed", ->
fs.removeSync bibFile2
manager.removeBibtexFile(bibFile2)
expect(Object.keys(manager.database).length).toEqual(4)
describe "When the bibtex file is not valid", ->
bibFile2 = path.join(__dirname,'lib2.bib')
beforeEach ->
fs.appendFileSync bibFile2, '@book{schwab2017elektroenergiesysteme,
title={Elektroenergiesysteme: Erzeugung, {\"U}bertragung und Verteilung elektrischer Energie},
author={PI:NAME:<NAME>END_PI.},
isbn={9783662553169}
url={https://books.google.de/books?id=Gq80DwAAQBAJ},
year={2017,
publisher={Springer Berlin Heidelberg}
}'
waitsForPromise ->
manager.addBibtexFile(bibFile2)
afterEach ->
fs.removeSync bibFile2
it "show a warning", ->
noti = atom.notifications.getNotifications()
expect(noti.length).toEqual 1
expect(noti[0].message).toEqual "Autocomplete Latex Cite Warning"
expect(noti[0].type).toEqual "warning"
expect(noti[0].options.description).toContain "lib2.bib"
expect(noti[0].options.description).toContain "Token mismatch: match"
describe "When the global Path is enabled", ->
manager = null
beforeEach ->
atom.config.set 'autocomplete-latex-cite.globalBibPath', __dirname
atom.config.set 'autocomplete-latex-cite.includeGlobalBibFiles', true
manager = new CiteManager()
waitsForPromise ->
manager.initialize()
it "Add the entries to the database", ->
expect(Object.keys(manager.database).length).toEqual(4)
expect(manager.database['kundur1994power']['id']).toEqual('kundur1994power')
it "Removes the entries when the global path is disabled", ->
runs ->
atom.config.set 'autocomplete-latex-cite.includeGlobalBibFiles', false
waitsFor ->
Object.keys(manager.database).length < 4
runs ->
expect(Object.keys(manager.database).length).toEqual(0)
it "Changes the entries when the path is changed", ->
runs ->
atom.config.set 'autocomplete-latex-cite.globalBibPath', path.join(__dirname,'..','lib')
waitsFor ->
Object.keys(manager.database).length < 4
runs ->
expect(Object.keys(manager.database).length).toEqual(0)
it "Removes the entries when the path is set to empty string", ->
runs ->
atom.config.set 'autocomplete-latex-cite.globalBibPath', ''
waitsFor ->
Object.keys(manager.database).length < 4
runs ->
expect(Object.keys(manager.database).length).toEqual(0)
|
[
{
"context": " window.ini = new AppLauncherParser 'C:\\\\Users\\\\Tim\\\\Documents\\\\Rainmeter\\\\Skins\\\\SysTracker\\\\App Lau",
"end": 745,
"score": 0.999152421951294,
"start": 742,
"tag": "NAME",
"value": "Tim"
}
] | app/scripts/Main.coffee | kaiyote/rainmeter_launcher_config | 1 | MainCtrl =
view: (ctrl) -> [
m '.ctrlbar', [
m '.title', 'Config Launcher'
m '.close',
onclick: -> do ctrl.close
, 'x'
]
m '.tabs', [
m 'a.tab',
href: '#/add'
class: ctrl.isActive '/add'
, 'Add'
m 'a.tab',
href: '#/edit'
class: ctrl.isActive '/edit'
, 'Edit'
m 'a.tab',
href: '#/remove'
class: ctrl.isActive '/remove'
, 'Remove'
m 'a.tab',
href: '#/reorder'
class: ctrl.isActive '/reorder'
, 'Reorder'
]
]
controller: class
constructor: ->
gui = require 'nw.gui'
@window = do gui.Window.get
@app = gui.App
window.ini = new AppLauncherParser 'C:\\Users\\Tim\\Documents\\Rainmeter\\Skins\\SysTracker\\App Launcher\\App_Launcher.ini', ->
m.route document.querySelector('.content'), '/add',
'/add': AddCtrl
'/remove': RemoveCtrl
'/reorder': ReorderCtrl
'/edit': EditCtrl
close: ->
do @window.close
isActive: (route) ->
if route is do m.route
return 'active'
''
| 126855 | MainCtrl =
view: (ctrl) -> [
m '.ctrlbar', [
m '.title', 'Config Launcher'
m '.close',
onclick: -> do ctrl.close
, 'x'
]
m '.tabs', [
m 'a.tab',
href: '#/add'
class: ctrl.isActive '/add'
, 'Add'
m 'a.tab',
href: '#/edit'
class: ctrl.isActive '/edit'
, 'Edit'
m 'a.tab',
href: '#/remove'
class: ctrl.isActive '/remove'
, 'Remove'
m 'a.tab',
href: '#/reorder'
class: ctrl.isActive '/reorder'
, 'Reorder'
]
]
controller: class
constructor: ->
gui = require 'nw.gui'
@window = do gui.Window.get
@app = gui.App
window.ini = new AppLauncherParser 'C:\\Users\\<NAME>\\Documents\\Rainmeter\\Skins\\SysTracker\\App Launcher\\App_Launcher.ini', ->
m.route document.querySelector('.content'), '/add',
'/add': AddCtrl
'/remove': RemoveCtrl
'/reorder': ReorderCtrl
'/edit': EditCtrl
close: ->
do @window.close
isActive: (route) ->
if route is do m.route
return 'active'
''
| true | MainCtrl =
view: (ctrl) -> [
m '.ctrlbar', [
m '.title', 'Config Launcher'
m '.close',
onclick: -> do ctrl.close
, 'x'
]
m '.tabs', [
m 'a.tab',
href: '#/add'
class: ctrl.isActive '/add'
, 'Add'
m 'a.tab',
href: '#/edit'
class: ctrl.isActive '/edit'
, 'Edit'
m 'a.tab',
href: '#/remove'
class: ctrl.isActive '/remove'
, 'Remove'
m 'a.tab',
href: '#/reorder'
class: ctrl.isActive '/reorder'
, 'Reorder'
]
]
controller: class
constructor: ->
gui = require 'nw.gui'
@window = do gui.Window.get
@app = gui.App
window.ini = new AppLauncherParser 'C:\\Users\\PI:NAME:<NAME>END_PI\\Documents\\Rainmeter\\Skins\\SysTracker\\App Launcher\\App_Launcher.ini', ->
m.route document.querySelector('.content'), '/add',
'/add': AddCtrl
'/remove': RemoveCtrl
'/reorder': ReorderCtrl
'/edit': EditCtrl
close: ->
do @window.close
isActive: (route) ->
if route is do m.route
return 'active'
''
|
[
{
"context": " /email/i.test(it.attr('name'))\n action: -> \"fill@llthethings.org\"\n ,\n test: (it) -> it.is('[type=\"tel\"]') ",
"end": 772,
"score": 0.9999261498451233,
"start": 752,
"tag": "EMAIL",
"value": "fill@llthethings.org"
}
] | src/fill-all-the-things.coffee | searls/fill-all-the-things | 10 | ###
fill-all-the-things @@VERSION@@
Fills out forms with dummy data
site: https://searls.github.com/fill-all-the-things
@depend ../vendor/jquery-no-conflict.js
@depend ../vendor/underscore-no-conflict.js
###
f = window.FillAllTheThings ||= {}
( ($,_) ->
types = [
test: (it) -> it.is(':checkbox,:radio')
action: (it) -> it.attr('checked','checked')
,
test: (it) -> it.is('select')
action: (it) -> it.find('option[value="1975"],option:last').val()
,
test: -> true
action: (it, val) -> figureOutAValue(it, val)
]
textFills = [
test: (it) -> it.is(':password')
action: -> "f1llTh!NG$?"
,
test: (it) -> it.is('[type="email"]') or /email/i.test(it.attr('name'))
action: -> "fill@llthethings.org"
,
test: (it) -> it.is('[type="tel"]') or /phone/i.test(it.attr('name'))
action: -> "1234567890"
,
test: (it) -> it.is('[type="url"]')
action: -> "http://www.w3.org"
,
test: (it) -> it.is('[type="range"],.numeric,[max],[min]')
action: (it) -> it.attr('max') or it.attr('min') or "0"
,
test: (it, val) -> !val
action: -> "Filling a Thing"
,
test: -> true
action: (it, val) -> val
]
mutations = [
test: (it) -> it.attr('maxlength')
action: (it, val) -> val.substring(0, it.attr('maxlength'))
,
]
f.fill = ->
$inputs = $(':input:visible:enabled:not([readonly])').val (i, val) ->
_(doFirst(types, [$(@), val])).tap (newVal) =>
if val != newVal then _.defer => $(@).trigger('change')
figureOutAValue = (it, val) ->
val = doFirst(textFills, [it,val])
doAll(mutations, [it, val])
doFirst = (actions, args) ->
match = undefined
_(actions).find (o) ->
if o.test.apply(@, args)
match = o.action.apply(@, args)
true
match
doAll = (actions, args) ->
thing = it: args[0], val: args[1]
_(actions).find (o) ->
if o.test.call(@, thing.it, thing.val)
thing.val = o.action.call(@, thing.it, thing.val)
true
thing.val
$ -> f.fill()
)(f.$,f._)
| 163659 | ###
fill-all-the-things @@VERSION@@
Fills out forms with dummy data
site: https://searls.github.com/fill-all-the-things
@depend ../vendor/jquery-no-conflict.js
@depend ../vendor/underscore-no-conflict.js
###
f = window.FillAllTheThings ||= {}
( ($,_) ->
types = [
test: (it) -> it.is(':checkbox,:radio')
action: (it) -> it.attr('checked','checked')
,
test: (it) -> it.is('select')
action: (it) -> it.find('option[value="1975"],option:last').val()
,
test: -> true
action: (it, val) -> figureOutAValue(it, val)
]
textFills = [
test: (it) -> it.is(':password')
action: -> "f1llTh!NG$?"
,
test: (it) -> it.is('[type="email"]') or /email/i.test(it.attr('name'))
action: -> "<EMAIL>"
,
test: (it) -> it.is('[type="tel"]') or /phone/i.test(it.attr('name'))
action: -> "1234567890"
,
test: (it) -> it.is('[type="url"]')
action: -> "http://www.w3.org"
,
test: (it) -> it.is('[type="range"],.numeric,[max],[min]')
action: (it) -> it.attr('max') or it.attr('min') or "0"
,
test: (it, val) -> !val
action: -> "Filling a Thing"
,
test: -> true
action: (it, val) -> val
]
mutations = [
test: (it) -> it.attr('maxlength')
action: (it, val) -> val.substring(0, it.attr('maxlength'))
,
]
f.fill = ->
$inputs = $(':input:visible:enabled:not([readonly])').val (i, val) ->
_(doFirst(types, [$(@), val])).tap (newVal) =>
if val != newVal then _.defer => $(@).trigger('change')
figureOutAValue = (it, val) ->
val = doFirst(textFills, [it,val])
doAll(mutations, [it, val])
doFirst = (actions, args) ->
match = undefined
_(actions).find (o) ->
if o.test.apply(@, args)
match = o.action.apply(@, args)
true
match
doAll = (actions, args) ->
thing = it: args[0], val: args[1]
_(actions).find (o) ->
if o.test.call(@, thing.it, thing.val)
thing.val = o.action.call(@, thing.it, thing.val)
true
thing.val
$ -> f.fill()
)(f.$,f._)
| true | ###
fill-all-the-things @@VERSION@@
Fills out forms with dummy data
site: https://searls.github.com/fill-all-the-things
@depend ../vendor/jquery-no-conflict.js
@depend ../vendor/underscore-no-conflict.js
###
f = window.FillAllTheThings ||= {}
( ($,_) ->
types = [
test: (it) -> it.is(':checkbox,:radio')
action: (it) -> it.attr('checked','checked')
,
test: (it) -> it.is('select')
action: (it) -> it.find('option[value="1975"],option:last').val()
,
test: -> true
action: (it, val) -> figureOutAValue(it, val)
]
textFills = [
test: (it) -> it.is(':password')
action: -> "f1llTh!NG$?"
,
test: (it) -> it.is('[type="email"]') or /email/i.test(it.attr('name'))
action: -> "PI:EMAIL:<EMAIL>END_PI"
,
test: (it) -> it.is('[type="tel"]') or /phone/i.test(it.attr('name'))
action: -> "1234567890"
,
test: (it) -> it.is('[type="url"]')
action: -> "http://www.w3.org"
,
test: (it) -> it.is('[type="range"],.numeric,[max],[min]')
action: (it) -> it.attr('max') or it.attr('min') or "0"
,
test: (it, val) -> !val
action: -> "Filling a Thing"
,
test: -> true
action: (it, val) -> val
]
mutations = [
test: (it) -> it.attr('maxlength')
action: (it, val) -> val.substring(0, it.attr('maxlength'))
,
]
f.fill = ->
$inputs = $(':input:visible:enabled:not([readonly])').val (i, val) ->
_(doFirst(types, [$(@), val])).tap (newVal) =>
if val != newVal then _.defer => $(@).trigger('change')
figureOutAValue = (it, val) ->
val = doFirst(textFills, [it,val])
doAll(mutations, [it, val])
doFirst = (actions, args) ->
match = undefined
_(actions).find (o) ->
if o.test.apply(@, args)
match = o.action.apply(@, args)
true
match
doAll = (actions, args) ->
thing = it: args[0], val: args[1]
_(actions).find (o) ->
if o.test.call(@, thing.it, thing.val)
thing.val = o.action.call(@, thing.it, thing.val)
true
thing.val
$ -> f.fill()
)(f.$,f._)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.