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": "else odataV4Mongodb.createQuery()\n\t\t\t\t\tif key is 'cfs.files.filerecord'\n\t\t\t\t\t\tcreateQuery.query['metadata.space'] = spac",
"end": 6437,
"score": 0.9986519813537598,
"start": 6417,
"tag": "KEY",
"value": "cfs.files.filerecord"
},
{
"context": "['metadata.space'] = spaceId\n\t\t\t\t\telse if key is 'spaces'\n\t\t\t\t\t\tif spaceId isnt 'guest'\n\t\t\t\t\t\t\tcreateQuery",
"end": 6518,
"score": 0.5211649537086487,
"start": 6512,
"tag": "KEY",
"value": "spaces"
},
{
"context": "ce(spaceId)\n\t\t\t\t\t\tif Creator.isSpaceAdmin(spaceId, @userId)\n\t\t\t\t\t\t\tif key is 'spaces'\n\t\t\t\t\t\t\t\tdelete c",
"end": 6748,
"score": 0.7533701062202454,
"start": 6748,
"tag": "USERNAME",
"value": ""
},
{
"context": "= Creator.getCollection(\"space_users\").find({user: @userId}, {fields: {space: 1}}).fetch()\n\t\t\t\t\t\t\tif key is ",
"end": 6960,
"score": 0.9564507007598877,
"start": 6953,
"tag": "USERNAME",
"value": "@userId"
},
{
"context": "\treadable_fields = Creator.getFields(key, spaceId, @userId)\n\t\t\t\t\t\tfields = Creator.getObject(key).fields\n\t\t\t",
"end": 8685,
"score": 0.9970574378967285,
"start": 8678,
"tag": "USERNAME",
"value": "@userId"
},
{
"context": "\t\t\t\t\t\torgs = Steedos.getUserOrganizations(spaceId, @userId, true)\n\t\t\t\t\t\t\tshares.push {\"owner\": @userId",
"end": 9089,
"score": 0.5120996236801147,
"start": 9089,
"tag": "USERNAME",
"value": ""
},
{
"context": "owner\": @userId}\n\t\t\t\t\t\t\tshares.push { \"sharing.u\": @userId }\n\t\t\t\t\t\t\tshares.push { \"sharing.o\": { $in: ",
"end": 9176,
"score": 0.5090930461883545,
"start": 9176,
"tag": "USERNAME",
"value": ""
},
{
"context": "shares\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tcreateQuery.query.owner = @userId\n\t\t\t\t\tentities = []\n\t\t\t\t\tif @queryParams.$to",
"end": 9321,
"score": 0.6188717484474182,
"start": 9321,
"tag": "USERNAME",
"value": ""
},
{
"context": "else odataV4Mongodb.createQuery()\n\t\t\t\t\tif key is 'cfs.files.filerecord'\n\t\t\t\t\t\tcreateQuery.query['metadata.space'] = @url",
"end": 13702,
"score": 0.9994277954101562,
"start": 13682,
"tag": "KEY",
"value": "cfs.files.filerecord"
},
{
"context": "uery.query._id = @urlParams._id\n\t\t\t\t\t\tif key is 'cfs.files.filerecord'\n\t\t\t\t\t\t\tcreateQuery.query['metadata.space'] = @ur",
"end": 20749,
"score": 0.9994373321533203,
"start": 20729,
"tag": "KEY",
"value": "cfs.files.filerecord"
},
{
"context": "\t\t\t\t\t\tif entity\n\t\t\t\t\t\t\tisAllowed = entity.owner == @userId or permissions.viewAllRecords\n\t\t\t\t\t\t\tif object.en",
"end": 21800,
"score": 0.8310049176216125,
"start": 21793,
"tag": "USERNAME",
"value": "@userId"
},
{
"context": " @userId, true)\n\t\t\t\t\t\t\t\tshares.push { \"sharing.u\": @userId }\n\t\t\t\t\t\t\t\tshares.push { \"sharing.o\": { $in: orgs ",
"end": 22017,
"score": 0.7481464147567749,
"start": 22010,
"tag": "USERNAME",
"value": "@userId"
},
{
"context": "ermissions = Creator.getObjectPermissions(spaceId, @userId, key)\n\t\t\t\trecord_owner = collection.findOne({ _id",
"end": 23811,
"score": 0.6213549375534058,
"start": 23804,
"tag": "USERNAME",
"value": "@userId"
},
{
"context": "ords or (permissions.allowEdit and record_owner == @userId )\n\t\t\t\tif isAllowed\n\t\t\t\t\tselector = {_id: @urlPara",
"end": 24012,
"score": 0.7557544708251953,
"start": 24005,
"tag": "USERNAME",
"value": "@userId"
},
{
"context": "odataV4Mongodb.createQuery()\n\n\t\t\t\t\t\t\t\t\tif key is 'cfs.files.filerecord'\n\t\t\t\t\t\t\t\t\t\tcreateQuery.query['metadata.space'] = ",
"end": 29641,
"score": 0.9995648264884949,
"start": 29621,
"tag": "KEY",
"value": "cfs.files.filerecord"
}
] | packages/steedos-odata/server/odata.coffee | zonglu233/fuel-car | 0 | Meteor.startup ->
odataV4Mongodb = Npm.require 'odata-v4-mongodb'
querystring = Npm.require 'querystring'
visitorParser = (visitor)->
parsedOpt = {}
if visitor.projection
parsedOpt.fields = visitor.projection
if visitor.hasOwnProperty('limit')
parsedOpt.limit = visitor.limit
if visitor.hasOwnProperty('skip')
parsedOpt.skip = visitor.skip
if visitor.sort
parsedOpt.sort = visitor.sort
parsedOpt
dealWithExpand = (createQuery, entities, key,action)->
if _.isEmpty createQuery.includes
return
obj = Creator.objectsByName[key]
_.each createQuery.includes, (include)->
# console.log 'include: ', include
navigationProperty = include.navigationProperty
# console.log 'navigationProperty: ', navigationProperty
field = obj.fields[navigationProperty]
if field and (field.type is 'lookup' or field.type is 'master_detail')
if _.isFunction(field.reference_to)
field.reference_to = field.reference_to()
if field.reference_to
queryOptions = visitorParser(include)
if _.isString field.reference_to
referenceToCollection = Creator.Collections[field.reference_to]
_.each entities, (entity, idx)->
if entity[navigationProperty]
if field.multiple
originalData = _.clone(entity[navigationProperty])
multiQuery = _.extend {_id: {$in: entity[navigationProperty]}}, include.query
entities[idx][navigationProperty] = referenceToCollection.find(multiQuery, queryOptions).fetch()
if !entities[idx][navigationProperty].length
entities[idx][navigationProperty] = originalData
#排序
entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], originalData)
else
singleQuery = _.extend {_id: entity[navigationProperty]}, include.query
# 特殊处理在相关表中没有找到数据的情况,返回原数据
entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions) || entities[idx][navigationProperty]
if _.isArray field.reference_to
_.each entities, (entity, idx)->
if entity[navigationProperty]?.ids
_o = entity[navigationProperty].o
referenceToCollection = Creator.Collections[entity[navigationProperty].o]
if referenceToCollection
if field.multiple
_ids = _.clone(entity[navigationProperty].ids)
multiQuery = _.extend {_id: {$in: entity[navigationProperty].ids}}, include.query
entities[idx][navigationProperty] = _.map referenceToCollection.find(multiQuery, queryOptions).fetch(), (o)->
o['reference_to.o'] = referenceToCollection._name
return o
#排序
entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], _ids)
else
singleQuery = _.extend {_id: entity[navigationProperty].ids[0]}, include.query
entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions)
if entities[idx][navigationProperty]
entities[idx][navigationProperty]['reference_to.o'] = referenceToCollection._name
entities[idx][navigationProperty]['reference_to._o'] = _o
else
# TODO
return
setOdataProperty=(entities,space,key)->
entities_OdataProperties = []
_.each entities, (entity, idx)->
entity_OdataProperties = {}
id = entities[idx]["_id"]
entity_OdataProperties['@odata.id'] = SteedosOData.getODataNextLinkPath(space,key)+ '(\'' + "#{id}" + '\')'
entity_OdataProperties['@odata.etag'] = "W/\"08D589720BBB3DB1\""
entity_OdataProperties['@odata.editLink'] = entity_OdataProperties['@odata.id']
_.extend entity_OdataProperties,entity
entities_OdataProperties.push entity_OdataProperties
return entities_OdataProperties
setErrorMessage = (statusCode,collection,key,action)->
body = {}
error = {}
innererror = {}
if statusCode == 404
if collection
if action == 'post'
innererror['message'] = t("creator_odata_post_fail")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 404
error['message'] = "creator_odata_post_fail"
else
innererror['message'] = t("creator_odata_record_query_fail")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 404
error['message'] = "creator_odata_record_query_fail"
else
innererror['message'] = t("creator_odata_collection_query_fail")+ key
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 404
error['message'] = "creator_odata_collection_query_fail"
if statusCode == 401
innererror['message'] = t("creator_odata_authentication_required")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 401
error['message'] = "creator_odata_authentication_required"
if statusCode == 403
switch action
when 'get' then innererror['message'] = t("creator_odata_user_access_fail")
when 'post' then innererror['message'] = t("creator_odata_user_create_fail")
when 'put' then innererror['message'] = t("creator_odata_user_update_fail")
when 'delete' then innererror['message'] = t("creator_odata_user_remove_fail")
innererror['message'] = t("creator_odata_user_access_fail")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 403
error['message'] = "creator_odata_user_access_fail"
error['innererror'] = innererror
body['error'] = error
return body
SteedosOdataAPI.addRoute(':object_name', {authRequired: true, spaceRequired: false}, {
get: ()->
try
key = @urlParams.object_name
object = Creator.objectsByName[key]
if not object?.enable_api
return {
statusCode: 401
body:setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return {
statusCode: 404
body:setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(spaceId, @userId, key)
if permissions.viewAllRecords or (permissions.allowRead and @userId)
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
if key is 'cfs.files.filerecord'
createQuery.query['metadata.space'] = spaceId
else if key is 'spaces'
if spaceId isnt 'guest'
createQuery.query._id = spaceId
else
if spaceId isnt 'guest'
createQuery.query.space = spaceId
if Creator.isCommonSpace(spaceId)
if Creator.isSpaceAdmin(spaceId, @userId)
if key is 'spaces'
delete createQuery.query._id
else
delete createQuery.query.space
else
user_spaces = Creator.getCollection("space_users").find({user: @userId}, {fields: {space: 1}}).fetch()
if key is 'spaces'
# space 对所有用户记录为只读
delete createQuery.query._id
# createQuery.query._id = {$in: _.pluck(user_spaces, 'space')}
else
createQuery.query.space = {$in: _.pluck(user_spaces, 'space')}
if not createQuery.sort or !_.size(createQuery.sort)
createQuery.sort = { modified: -1 }
is_enterprise = Steedos.isLegalVersion(spaceId,"workflow.enterprise")
is_professional = Steedos.isLegalVersion(spaceId,"workflow.professional")
is_standard = Steedos.isLegalVersion(spaceId,"workflow.standard")
if createQuery.limit
limit = createQuery.limit
if is_enterprise and limit>100000
createQuery.limit = 100000
else if is_professional and limit>10000 and !is_enterprise
createQuery.limit = 10000
else if is_standard and limit>1000 and !is_professional and !is_enterprise
createQuery.limit = 1000
else
if is_enterprise
createQuery.limit = 100000
else if is_professional and !is_enterprise
createQuery.limit = 10000
else if is_standard and !is_enterprise and !is_professional
createQuery.limit = 1000
unreadable_fields = permissions.unreadable_fields || []
if createQuery.projection
projection = {}
_.keys(createQuery.projection).forEach (key)->
if _.indexOf(unreadable_fields, key) < 0
#if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple)
projection[key] = 1
createQuery.projection = projection
if not createQuery.projection or !_.size(createQuery.projection)
readable_fields = Creator.getFields(key, spaceId, @userId)
fields = Creator.getObject(key).fields
_.each readable_fields,(field)->
if field.indexOf('$')<0
#if fields[field]?.multiple!= true
createQuery.projection[field] = 1
if not permissions.viewAllRecords
if object.enable_share
# 满足共享规则中的记录也要搜索出来
delete createQuery.query.owner
shares = []
orgs = Steedos.getUserOrganizations(spaceId, @userId, true)
shares.push {"owner": @userId}
shares.push { "sharing.u": @userId }
shares.push { "sharing.o": { $in: orgs } }
createQuery.query["$or"] = shares
else
createQuery.query.owner = @userId
entities = []
if @queryParams.$top isnt '0'
entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch()
scannedCount = collection.find(createQuery.query,{fields:{_id: 1}}).count()
if entities
dealWithExpand(createQuery, entities, key)
#scannedCount = entities.length
body = {}
headers = {}
body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key)
# body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(spaceId,key)+"?%24skip="+ 10
body['@odata.count'] = scannedCount
entities_OdataProperties = setOdataProperty(entities,spaceId, key)
body['value'] = entities_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,"get")
}
catch e
console.error e.stack
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
post: ()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return {
statusCode: 401
body:setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return {
statusCode: 404
body:setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(spaceId, @userId, key)
if permissions.allowCreate
@bodyParams.space = spaceId
if spaceId is 'guest'
delete @bodyParams.space
entityId = collection.insert @bodyParams
entity = collection.findOne entityId
entities = []
if entity
body = {}
headers = {}
entities.push entity
body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity'
entity_OdataProperties = setOdataProperty(entities,spaceId, key)
body['value'] = entity_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'post')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'post')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
SteedosOdataAPI.addRoute(':object_name/recent', {authRequired: true, spaceRequired: false}, {
get:()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return {
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowRead
recent_view_collection = Creator.Collections["object_recent_viewed"]
recent_view_selector = {"record.o":key,created_by:@userId}
recent_view_options = {}
recent_view_options.sort = {created: -1}
recent_view_options.fields = {record:1}
recent_view_records = recent_view_collection.find(recent_view_selector,recent_view_options).fetch()
recent_view_records_ids = _.pluck(recent_view_records,'record')
recent_view_records_ids = recent_view_records_ids.getProperty("ids")
recent_view_records_ids = _.flatten(recent_view_records_ids)
recent_view_records_ids = _.uniq(recent_view_records_ids)
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
if key is 'cfs.files.filerecord'
createQuery.query['metadata.space'] = @urlParams.spaceId
else
createQuery.query.space = @urlParams.spaceId
if not createQuery.limit
createQuery.limit = 100
if createQuery.limit and recent_view_records_ids.length>createQuery.limit
recent_view_records_ids = _.first(recent_view_records_ids,createQuery.limit)
createQuery.query._id = {$in:recent_view_records_ids}
unreadable_fields = permissions.unreadable_fields || []
# fields = Creator.getObject(key).fields
if createQuery.projection
projection = {}
_.keys(createQuery.projection).forEach (key)->
if _.indexOf(unreadable_fields, key) < 0
# if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple)
projection[key] = 1
createQuery.projection = projection
if not createQuery.projection or !_.size(createQuery.projection)
readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId)
fields = Creator.getObject(key).fields
_.each readable_fields,(field)->
if field.indexOf('$')<0
#if fields[field]?.multiple!= true
createQuery.projection[field] = 1
if @queryParams.$top isnt '0'
entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch()
entities_index = []
entities_ids = _.pluck(entities,'_id')
sort_entities = []
if not createQuery.sort or !_.size(createQuery.sort)
_.each recent_view_records_ids ,(recent_view_records_id)->
index = _.indexOf(entities_ids,recent_view_records_id)
if index>-1
sort_entities.push entities[index]
else
sort_entities = entities
if sort_entities
dealWithExpand(createQuery, sort_entities, key)
body = {}
headers = {}
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key)
# body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(@urlParams.spaceId,key)+"?%24skip="+ 10
body['@odata.count'] = sort_entities.length
entities_OdataProperties = setOdataProperty(sort_entities,@urlParams.spaceId, key)
body['value'] = entities_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'get')
}
else
console.error e
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'get')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
SteedosOdataAPI.addRoute(':object_name/:_id', {authRequired: true, spaceRequired: false}, {
post: ()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowCreate
@bodyParams.space = @urlParams.spaceId
entityId = collection.insert @bodyParams
entity = collection.findOne entityId
entities = []
if entity
body = {}
headers = {}
entities.push entity
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity'
entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key)
body['value'] = entity_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'post')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'post')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
get:()->
key = @urlParams.object_name
if key.indexOf("(") > -1
body = {}
headers = {}
collectionInfo = key
fieldName = @urlParams._id.split('_expand')[0]
collectionInfoSplit = collectionInfo.split('(')
collectionName = collectionInfoSplit[0]
id = collectionInfoSplit[1].split('\'')[1]
collection = Creator.Collections[collectionName]
fieldsOptions = {}
fieldsOptions[fieldName] = 1
entity = collection.findOne({_id: id}, {fields: fieldsOptions})
fieldValue = null
if entity
fieldValue = entity[fieldName]
obj = Creator.objectsByName[collectionName]
field = obj.fields[fieldName]
if field and fieldValue and (field.type is 'lookup' or field.type is 'master_detail')
lookupCollection = Creator.Collections[field.reference_to]
lookupObj = Creator.objectsByName[field.reference_to]
queryOptions = {fields: {}}
_.each lookupObj.fields, (v, k)->
queryOptions.fields[k] = 1
if field.multiple
body['value'] = lookupCollection.find({_id: {$in: fieldValue}}, queryOptions).fetch()
body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}"
else
body = lookupCollection.findOne({_id: fieldValue}, queryOptions) || {}
body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{field.reference_to}/$entity"
else
body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}"
body['value'] = fieldValue
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
try
object = Creator.objectsByName[key]
if not object?.enable_api
return {
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowRead
unreadable_fields = permissions.unreadable_fields || []
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
createQuery.query._id = @urlParams._id
if key is 'cfs.files.filerecord'
createQuery.query['metadata.space'] = @urlParams.spaceId
else
createQuery.query.space = @urlParams.spaceId
unreadable_fields = permissions.unreadable_fields || []
#fields = Creator.getObject(key).fields
if createQuery.projection
projection = {}
_.keys(createQuery.projection).forEach (key)->
if _.indexOf(unreadable_fields, key) < 0
# if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple)
projection[key] = 1
createQuery.projection = projection
if not createQuery.projection or !_.size(createQuery.projection)
readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId)
fields = Creator.getObject(key).fields
_.each readable_fields,(field)->
if field.indexOf('$')<0
createQuery.projection[field] = 1
entity = collection.findOne(createQuery.query,visitorParser(createQuery))
entities = []
if entity
isAllowed = entity.owner == @userId or permissions.viewAllRecords
if object.enable_share and !isAllowed
shares = []
orgs = Steedos.getUserOrganizations(@urlParams.spaceId, @userId, true)
shares.push { "sharing.u": @userId }
shares.push { "sharing.o": { $in: orgs } }
isAllowed = collection.findOne({ _id: @urlParams._id, "$or": shares }, { fields: { _id: 1 } })
if isAllowed
body = {}
headers = {}
entities.push entity
dealWithExpand(createQuery, entities, key)
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity'
entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key)
_.extend body,entity_OdataProperties[0]
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'get')
}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'get')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'get')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
put:()->
try
key = @urlParams.object_name
object = Creator.objectsByName[key]
if not object?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(spaceId, @userId, key)
record_owner = collection.findOne({ _id: @urlParams._id }, { fields: { owner: 1 } })?.owner
isAllowed = permissions.modifyAllRecords or (permissions.allowEdit and record_owner == @userId )
if isAllowed
selector = {_id: @urlParams._id, space: spaceId}
if spaceId is 'guest'
delete selector.space
fields_editable = true
_.keys(@bodyParams.$set).forEach (key)->
if _.indexOf(permissions.uneditable_fields, key) > -1
fields_editable = false
if fields_editable
entityIsUpdated = collection.update selector, @bodyParams
if entityIsUpdated
#statusCode: 201
# entity = collection.findOne @urlParams._id
# entities = []
# body = {}
headers = {}
body = {}
# entities.push entity
# body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity'
# entity_OdataProperties = setOdataProperty(entities,spaceId, key)
# _.extend body,entity_OdataProperties[0]
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{headers: headers,body:body}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'put')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'put')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
delete:()->
try
key = @urlParams.object_name
object = Creator.objectsByName[key]
if not object?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
record_owner = collection.findOne({_id: @urlParams._id})?.owner
isAllowed = (permissions.modifyAllRecords and permissions.allowDelete) or (permissions.allowDelete and record_owner==@userId )
if isAllowed
selector = {_id: @urlParams._id, space: spaceId}
if spaceId is 'guest'
delete selector.space
if collection.remove selector
headers = {}
body = {}
# entities.push entity
# body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity'
# entity_OdataProperties = setOdataProperty(entities,spaceId, key)
# _.extend body,entity_OdataProperties[0]
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{headers: headers,body:body}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return {
statusCode: 403
body: setErrorMessage(403,collection,key)
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
SteedosOdataAPI.addRoute(':object_name/:_id/:methodName', {authRequired: true, spaceRequired: false}, {
post: ()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowRead
methodName = @urlParams.methodName
methods = Creator.Objects[key]?.methods || {}
if methods.hasOwnProperty(methodName)
thisObj = {
object_name: key
record_id: @urlParams._id
space_id: @urlParams.spaceId
user_id: @userId
permissions: permissions
}
methods[methodName].apply(thisObj, [@bodyParams])
{}
else
return {
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return {
statusCode: 403
body: setErrorMessage(403,collection,key)
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
#TODO remove
_.each [], (value, key, list)-> #Creator.Collections
if not Creator.objectsByName[key]?.enable_api
return
if SteedosOdataAPI
SteedosOdataAPI.addCollection Creator.Collections[key],
excludedEndpoints: []
routeOptions:
authRequired: true
spaceRequired: false
endpoints:
getAll:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.viewAllRecords or (permissions.allowRead and @userId)
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
if key is 'cfs.files.filerecord'
createQuery.query['metadata.space'] = @urlParams.spaceId
else
createQuery.query.space = @urlParams.spaceId
if not permissions.viewAllRecords
createQuery.query.owner = @userId
entities = []
if @queryParams.$top isnt '0'
entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch()
scannedCount = collection.find(createQuery.query).count()
if entities
dealWithExpand(createQuery, entities, key)
body = {}
headers = {}
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key)
body['@odata.count'] = scannedCount
body['value'] = entities
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
statusCode: 404
body: {status: 'fail', message: 'Unable to retrieve items from collection'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
post:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowCreate
@bodyParams.space = @spaceId
entityId = collection.insert @bodyParams
entity = collection.findOne entityId
if entity
statusCode: 201
{status: 'success', value: entity}
else
statusCode: 404
body: {status: 'fail', message: 'No item added'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
get:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowRead
selector = {_id: @urlParams.id, space: @spaceId}
entity = collection.findOne selector
if entity
{status: 'success', value: entity}
else
statusCode: 404
body: {status: 'fail', message: 'Item not found'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
put:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowEdit
selector = {_id: @urlParams.id, space: @spaceId}
entityIsUpdated = collection.update selector, $set: @bodyParams
if entityIsUpdated
entity = collection.findOne @urlParams.id
{status: 'success', value: entity}
else
statusCode: 404
body: {status: 'fail', message: 'Item not found'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
delete:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowDelete
selector = {_id: @urlParams.id, space: @spaceId}
if collection.remove selector
{status: 'success', message: 'Item removed'}
else
statusCode: 404
body: {status: 'fail', message: 'Item not found'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
| 171931 | Meteor.startup ->
odataV4Mongodb = Npm.require 'odata-v4-mongodb'
querystring = Npm.require 'querystring'
visitorParser = (visitor)->
parsedOpt = {}
if visitor.projection
parsedOpt.fields = visitor.projection
if visitor.hasOwnProperty('limit')
parsedOpt.limit = visitor.limit
if visitor.hasOwnProperty('skip')
parsedOpt.skip = visitor.skip
if visitor.sort
parsedOpt.sort = visitor.sort
parsedOpt
dealWithExpand = (createQuery, entities, key,action)->
if _.isEmpty createQuery.includes
return
obj = Creator.objectsByName[key]
_.each createQuery.includes, (include)->
# console.log 'include: ', include
navigationProperty = include.navigationProperty
# console.log 'navigationProperty: ', navigationProperty
field = obj.fields[navigationProperty]
if field and (field.type is 'lookup' or field.type is 'master_detail')
if _.isFunction(field.reference_to)
field.reference_to = field.reference_to()
if field.reference_to
queryOptions = visitorParser(include)
if _.isString field.reference_to
referenceToCollection = Creator.Collections[field.reference_to]
_.each entities, (entity, idx)->
if entity[navigationProperty]
if field.multiple
originalData = _.clone(entity[navigationProperty])
multiQuery = _.extend {_id: {$in: entity[navigationProperty]}}, include.query
entities[idx][navigationProperty] = referenceToCollection.find(multiQuery, queryOptions).fetch()
if !entities[idx][navigationProperty].length
entities[idx][navigationProperty] = originalData
#排序
entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], originalData)
else
singleQuery = _.extend {_id: entity[navigationProperty]}, include.query
# 特殊处理在相关表中没有找到数据的情况,返回原数据
entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions) || entities[idx][navigationProperty]
if _.isArray field.reference_to
_.each entities, (entity, idx)->
if entity[navigationProperty]?.ids
_o = entity[navigationProperty].o
referenceToCollection = Creator.Collections[entity[navigationProperty].o]
if referenceToCollection
if field.multiple
_ids = _.clone(entity[navigationProperty].ids)
multiQuery = _.extend {_id: {$in: entity[navigationProperty].ids}}, include.query
entities[idx][navigationProperty] = _.map referenceToCollection.find(multiQuery, queryOptions).fetch(), (o)->
o['reference_to.o'] = referenceToCollection._name
return o
#排序
entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], _ids)
else
singleQuery = _.extend {_id: entity[navigationProperty].ids[0]}, include.query
entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions)
if entities[idx][navigationProperty]
entities[idx][navigationProperty]['reference_to.o'] = referenceToCollection._name
entities[idx][navigationProperty]['reference_to._o'] = _o
else
# TODO
return
setOdataProperty=(entities,space,key)->
entities_OdataProperties = []
_.each entities, (entity, idx)->
entity_OdataProperties = {}
id = entities[idx]["_id"]
entity_OdataProperties['@odata.id'] = SteedosOData.getODataNextLinkPath(space,key)+ '(\'' + "#{id}" + '\')'
entity_OdataProperties['@odata.etag'] = "W/\"08D589720BBB3DB1\""
entity_OdataProperties['@odata.editLink'] = entity_OdataProperties['@odata.id']
_.extend entity_OdataProperties,entity
entities_OdataProperties.push entity_OdataProperties
return entities_OdataProperties
setErrorMessage = (statusCode,collection,key,action)->
body = {}
error = {}
innererror = {}
if statusCode == 404
if collection
if action == 'post'
innererror['message'] = t("creator_odata_post_fail")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 404
error['message'] = "creator_odata_post_fail"
else
innererror['message'] = t("creator_odata_record_query_fail")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 404
error['message'] = "creator_odata_record_query_fail"
else
innererror['message'] = t("creator_odata_collection_query_fail")+ key
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 404
error['message'] = "creator_odata_collection_query_fail"
if statusCode == 401
innererror['message'] = t("creator_odata_authentication_required")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 401
error['message'] = "creator_odata_authentication_required"
if statusCode == 403
switch action
when 'get' then innererror['message'] = t("creator_odata_user_access_fail")
when 'post' then innererror['message'] = t("creator_odata_user_create_fail")
when 'put' then innererror['message'] = t("creator_odata_user_update_fail")
when 'delete' then innererror['message'] = t("creator_odata_user_remove_fail")
innererror['message'] = t("creator_odata_user_access_fail")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 403
error['message'] = "creator_odata_user_access_fail"
error['innererror'] = innererror
body['error'] = error
return body
SteedosOdataAPI.addRoute(':object_name', {authRequired: true, spaceRequired: false}, {
get: ()->
try
key = @urlParams.object_name
object = Creator.objectsByName[key]
if not object?.enable_api
return {
statusCode: 401
body:setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return {
statusCode: 404
body:setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(spaceId, @userId, key)
if permissions.viewAllRecords or (permissions.allowRead and @userId)
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
if key is '<KEY>'
createQuery.query['metadata.space'] = spaceId
else if key is '<KEY>'
if spaceId isnt 'guest'
createQuery.query._id = spaceId
else
if spaceId isnt 'guest'
createQuery.query.space = spaceId
if Creator.isCommonSpace(spaceId)
if Creator.isSpaceAdmin(spaceId, @userId)
if key is 'spaces'
delete createQuery.query._id
else
delete createQuery.query.space
else
user_spaces = Creator.getCollection("space_users").find({user: @userId}, {fields: {space: 1}}).fetch()
if key is 'spaces'
# space 对所有用户记录为只读
delete createQuery.query._id
# createQuery.query._id = {$in: _.pluck(user_spaces, 'space')}
else
createQuery.query.space = {$in: _.pluck(user_spaces, 'space')}
if not createQuery.sort or !_.size(createQuery.sort)
createQuery.sort = { modified: -1 }
is_enterprise = Steedos.isLegalVersion(spaceId,"workflow.enterprise")
is_professional = Steedos.isLegalVersion(spaceId,"workflow.professional")
is_standard = Steedos.isLegalVersion(spaceId,"workflow.standard")
if createQuery.limit
limit = createQuery.limit
if is_enterprise and limit>100000
createQuery.limit = 100000
else if is_professional and limit>10000 and !is_enterprise
createQuery.limit = 10000
else if is_standard and limit>1000 and !is_professional and !is_enterprise
createQuery.limit = 1000
else
if is_enterprise
createQuery.limit = 100000
else if is_professional and !is_enterprise
createQuery.limit = 10000
else if is_standard and !is_enterprise and !is_professional
createQuery.limit = 1000
unreadable_fields = permissions.unreadable_fields || []
if createQuery.projection
projection = {}
_.keys(createQuery.projection).forEach (key)->
if _.indexOf(unreadable_fields, key) < 0
#if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple)
projection[key] = 1
createQuery.projection = projection
if not createQuery.projection or !_.size(createQuery.projection)
readable_fields = Creator.getFields(key, spaceId, @userId)
fields = Creator.getObject(key).fields
_.each readable_fields,(field)->
if field.indexOf('$')<0
#if fields[field]?.multiple!= true
createQuery.projection[field] = 1
if not permissions.viewAllRecords
if object.enable_share
# 满足共享规则中的记录也要搜索出来
delete createQuery.query.owner
shares = []
orgs = Steedos.getUserOrganizations(spaceId, @userId, true)
shares.push {"owner": @userId}
shares.push { "sharing.u": @userId }
shares.push { "sharing.o": { $in: orgs } }
createQuery.query["$or"] = shares
else
createQuery.query.owner = @userId
entities = []
if @queryParams.$top isnt '0'
entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch()
scannedCount = collection.find(createQuery.query,{fields:{_id: 1}}).count()
if entities
dealWithExpand(createQuery, entities, key)
#scannedCount = entities.length
body = {}
headers = {}
body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key)
# body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(spaceId,key)+"?%24skip="+ 10
body['@odata.count'] = scannedCount
entities_OdataProperties = setOdataProperty(entities,spaceId, key)
body['value'] = entities_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,"get")
}
catch e
console.error e.stack
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
post: ()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return {
statusCode: 401
body:setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return {
statusCode: 404
body:setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(spaceId, @userId, key)
if permissions.allowCreate
@bodyParams.space = spaceId
if spaceId is 'guest'
delete @bodyParams.space
entityId = collection.insert @bodyParams
entity = collection.findOne entityId
entities = []
if entity
body = {}
headers = {}
entities.push entity
body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity'
entity_OdataProperties = setOdataProperty(entities,spaceId, key)
body['value'] = entity_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'post')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'post')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
SteedosOdataAPI.addRoute(':object_name/recent', {authRequired: true, spaceRequired: false}, {
get:()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return {
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowRead
recent_view_collection = Creator.Collections["object_recent_viewed"]
recent_view_selector = {"record.o":key,created_by:@userId}
recent_view_options = {}
recent_view_options.sort = {created: -1}
recent_view_options.fields = {record:1}
recent_view_records = recent_view_collection.find(recent_view_selector,recent_view_options).fetch()
recent_view_records_ids = _.pluck(recent_view_records,'record')
recent_view_records_ids = recent_view_records_ids.getProperty("ids")
recent_view_records_ids = _.flatten(recent_view_records_ids)
recent_view_records_ids = _.uniq(recent_view_records_ids)
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
if key is '<KEY>'
createQuery.query['metadata.space'] = @urlParams.spaceId
else
createQuery.query.space = @urlParams.spaceId
if not createQuery.limit
createQuery.limit = 100
if createQuery.limit and recent_view_records_ids.length>createQuery.limit
recent_view_records_ids = _.first(recent_view_records_ids,createQuery.limit)
createQuery.query._id = {$in:recent_view_records_ids}
unreadable_fields = permissions.unreadable_fields || []
# fields = Creator.getObject(key).fields
if createQuery.projection
projection = {}
_.keys(createQuery.projection).forEach (key)->
if _.indexOf(unreadable_fields, key) < 0
# if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple)
projection[key] = 1
createQuery.projection = projection
if not createQuery.projection or !_.size(createQuery.projection)
readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId)
fields = Creator.getObject(key).fields
_.each readable_fields,(field)->
if field.indexOf('$')<0
#if fields[field]?.multiple!= true
createQuery.projection[field] = 1
if @queryParams.$top isnt '0'
entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch()
entities_index = []
entities_ids = _.pluck(entities,'_id')
sort_entities = []
if not createQuery.sort or !_.size(createQuery.sort)
_.each recent_view_records_ids ,(recent_view_records_id)->
index = _.indexOf(entities_ids,recent_view_records_id)
if index>-1
sort_entities.push entities[index]
else
sort_entities = entities
if sort_entities
dealWithExpand(createQuery, sort_entities, key)
body = {}
headers = {}
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key)
# body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(@urlParams.spaceId,key)+"?%24skip="+ 10
body['@odata.count'] = sort_entities.length
entities_OdataProperties = setOdataProperty(sort_entities,@urlParams.spaceId, key)
body['value'] = entities_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'get')
}
else
console.error e
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'get')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
SteedosOdataAPI.addRoute(':object_name/:_id', {authRequired: true, spaceRequired: false}, {
post: ()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowCreate
@bodyParams.space = @urlParams.spaceId
entityId = collection.insert @bodyParams
entity = collection.findOne entityId
entities = []
if entity
body = {}
headers = {}
entities.push entity
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity'
entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key)
body['value'] = entity_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'post')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'post')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
get:()->
key = @urlParams.object_name
if key.indexOf("(") > -1
body = {}
headers = {}
collectionInfo = key
fieldName = @urlParams._id.split('_expand')[0]
collectionInfoSplit = collectionInfo.split('(')
collectionName = collectionInfoSplit[0]
id = collectionInfoSplit[1].split('\'')[1]
collection = Creator.Collections[collectionName]
fieldsOptions = {}
fieldsOptions[fieldName] = 1
entity = collection.findOne({_id: id}, {fields: fieldsOptions})
fieldValue = null
if entity
fieldValue = entity[fieldName]
obj = Creator.objectsByName[collectionName]
field = obj.fields[fieldName]
if field and fieldValue and (field.type is 'lookup' or field.type is 'master_detail')
lookupCollection = Creator.Collections[field.reference_to]
lookupObj = Creator.objectsByName[field.reference_to]
queryOptions = {fields: {}}
_.each lookupObj.fields, (v, k)->
queryOptions.fields[k] = 1
if field.multiple
body['value'] = lookupCollection.find({_id: {$in: fieldValue}}, queryOptions).fetch()
body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}"
else
body = lookupCollection.findOne({_id: fieldValue}, queryOptions) || {}
body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{field.reference_to}/$entity"
else
body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}"
body['value'] = fieldValue
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
try
object = Creator.objectsByName[key]
if not object?.enable_api
return {
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowRead
unreadable_fields = permissions.unreadable_fields || []
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
createQuery.query._id = @urlParams._id
if key is '<KEY>'
createQuery.query['metadata.space'] = @urlParams.spaceId
else
createQuery.query.space = @urlParams.spaceId
unreadable_fields = permissions.unreadable_fields || []
#fields = Creator.getObject(key).fields
if createQuery.projection
projection = {}
_.keys(createQuery.projection).forEach (key)->
if _.indexOf(unreadable_fields, key) < 0
# if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple)
projection[key] = 1
createQuery.projection = projection
if not createQuery.projection or !_.size(createQuery.projection)
readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId)
fields = Creator.getObject(key).fields
_.each readable_fields,(field)->
if field.indexOf('$')<0
createQuery.projection[field] = 1
entity = collection.findOne(createQuery.query,visitorParser(createQuery))
entities = []
if entity
isAllowed = entity.owner == @userId or permissions.viewAllRecords
if object.enable_share and !isAllowed
shares = []
orgs = Steedos.getUserOrganizations(@urlParams.spaceId, @userId, true)
shares.push { "sharing.u": @userId }
shares.push { "sharing.o": { $in: orgs } }
isAllowed = collection.findOne({ _id: @urlParams._id, "$or": shares }, { fields: { _id: 1 } })
if isAllowed
body = {}
headers = {}
entities.push entity
dealWithExpand(createQuery, entities, key)
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity'
entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key)
_.extend body,entity_OdataProperties[0]
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'get')
}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'get')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'get')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
put:()->
try
key = @urlParams.object_name
object = Creator.objectsByName[key]
if not object?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(spaceId, @userId, key)
record_owner = collection.findOne({ _id: @urlParams._id }, { fields: { owner: 1 } })?.owner
isAllowed = permissions.modifyAllRecords or (permissions.allowEdit and record_owner == @userId )
if isAllowed
selector = {_id: @urlParams._id, space: spaceId}
if spaceId is 'guest'
delete selector.space
fields_editable = true
_.keys(@bodyParams.$set).forEach (key)->
if _.indexOf(permissions.uneditable_fields, key) > -1
fields_editable = false
if fields_editable
entityIsUpdated = collection.update selector, @bodyParams
if entityIsUpdated
#statusCode: 201
# entity = collection.findOne @urlParams._id
# entities = []
# body = {}
headers = {}
body = {}
# entities.push entity
# body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity'
# entity_OdataProperties = setOdataProperty(entities,spaceId, key)
# _.extend body,entity_OdataProperties[0]
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{headers: headers,body:body}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'put')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'put')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
delete:()->
try
key = @urlParams.object_name
object = Creator.objectsByName[key]
if not object?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
record_owner = collection.findOne({_id: @urlParams._id})?.owner
isAllowed = (permissions.modifyAllRecords and permissions.allowDelete) or (permissions.allowDelete and record_owner==@userId )
if isAllowed
selector = {_id: @urlParams._id, space: spaceId}
if spaceId is 'guest'
delete selector.space
if collection.remove selector
headers = {}
body = {}
# entities.push entity
# body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity'
# entity_OdataProperties = setOdataProperty(entities,spaceId, key)
# _.extend body,entity_OdataProperties[0]
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{headers: headers,body:body}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return {
statusCode: 403
body: setErrorMessage(403,collection,key)
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
SteedosOdataAPI.addRoute(':object_name/:_id/:methodName', {authRequired: true, spaceRequired: false}, {
post: ()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowRead
methodName = @urlParams.methodName
methods = Creator.Objects[key]?.methods || {}
if methods.hasOwnProperty(methodName)
thisObj = {
object_name: key
record_id: @urlParams._id
space_id: @urlParams.spaceId
user_id: @userId
permissions: permissions
}
methods[methodName].apply(thisObj, [@bodyParams])
{}
else
return {
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return {
statusCode: 403
body: setErrorMessage(403,collection,key)
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
#TODO remove
_.each [], (value, key, list)-> #Creator.Collections
if not Creator.objectsByName[key]?.enable_api
return
if SteedosOdataAPI
SteedosOdataAPI.addCollection Creator.Collections[key],
excludedEndpoints: []
routeOptions:
authRequired: true
spaceRequired: false
endpoints:
getAll:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.viewAllRecords or (permissions.allowRead and @userId)
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
if key is '<KEY>'
createQuery.query['metadata.space'] = @urlParams.spaceId
else
createQuery.query.space = @urlParams.spaceId
if not permissions.viewAllRecords
createQuery.query.owner = @userId
entities = []
if @queryParams.$top isnt '0'
entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch()
scannedCount = collection.find(createQuery.query).count()
if entities
dealWithExpand(createQuery, entities, key)
body = {}
headers = {}
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key)
body['@odata.count'] = scannedCount
body['value'] = entities
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
statusCode: 404
body: {status: 'fail', message: 'Unable to retrieve items from collection'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
post:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowCreate
@bodyParams.space = @spaceId
entityId = collection.insert @bodyParams
entity = collection.findOne entityId
if entity
statusCode: 201
{status: 'success', value: entity}
else
statusCode: 404
body: {status: 'fail', message: 'No item added'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
get:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowRead
selector = {_id: @urlParams.id, space: @spaceId}
entity = collection.findOne selector
if entity
{status: 'success', value: entity}
else
statusCode: 404
body: {status: 'fail', message: 'Item not found'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
put:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowEdit
selector = {_id: @urlParams.id, space: @spaceId}
entityIsUpdated = collection.update selector, $set: @bodyParams
if entityIsUpdated
entity = collection.findOne @urlParams.id
{status: 'success', value: entity}
else
statusCode: 404
body: {status: 'fail', message: 'Item not found'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
delete:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowDelete
selector = {_id: @urlParams.id, space: @spaceId}
if collection.remove selector
{status: 'success', message: 'Item removed'}
else
statusCode: 404
body: {status: 'fail', message: 'Item not found'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
| true | Meteor.startup ->
odataV4Mongodb = Npm.require 'odata-v4-mongodb'
querystring = Npm.require 'querystring'
visitorParser = (visitor)->
parsedOpt = {}
if visitor.projection
parsedOpt.fields = visitor.projection
if visitor.hasOwnProperty('limit')
parsedOpt.limit = visitor.limit
if visitor.hasOwnProperty('skip')
parsedOpt.skip = visitor.skip
if visitor.sort
parsedOpt.sort = visitor.sort
parsedOpt
dealWithExpand = (createQuery, entities, key,action)->
if _.isEmpty createQuery.includes
return
obj = Creator.objectsByName[key]
_.each createQuery.includes, (include)->
# console.log 'include: ', include
navigationProperty = include.navigationProperty
# console.log 'navigationProperty: ', navigationProperty
field = obj.fields[navigationProperty]
if field and (field.type is 'lookup' or field.type is 'master_detail')
if _.isFunction(field.reference_to)
field.reference_to = field.reference_to()
if field.reference_to
queryOptions = visitorParser(include)
if _.isString field.reference_to
referenceToCollection = Creator.Collections[field.reference_to]
_.each entities, (entity, idx)->
if entity[navigationProperty]
if field.multiple
originalData = _.clone(entity[navigationProperty])
multiQuery = _.extend {_id: {$in: entity[navigationProperty]}}, include.query
entities[idx][navigationProperty] = referenceToCollection.find(multiQuery, queryOptions).fetch()
if !entities[idx][navigationProperty].length
entities[idx][navigationProperty] = originalData
#排序
entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], originalData)
else
singleQuery = _.extend {_id: entity[navigationProperty]}, include.query
# 特殊处理在相关表中没有找到数据的情况,返回原数据
entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions) || entities[idx][navigationProperty]
if _.isArray field.reference_to
_.each entities, (entity, idx)->
if entity[navigationProperty]?.ids
_o = entity[navigationProperty].o
referenceToCollection = Creator.Collections[entity[navigationProperty].o]
if referenceToCollection
if field.multiple
_ids = _.clone(entity[navigationProperty].ids)
multiQuery = _.extend {_id: {$in: entity[navigationProperty].ids}}, include.query
entities[idx][navigationProperty] = _.map referenceToCollection.find(multiQuery, queryOptions).fetch(), (o)->
o['reference_to.o'] = referenceToCollection._name
return o
#排序
entities[idx][navigationProperty] = Creator.getOrderlySetByIds(entities[idx][navigationProperty], _ids)
else
singleQuery = _.extend {_id: entity[navigationProperty].ids[0]}, include.query
entities[idx][navigationProperty] = referenceToCollection.findOne(singleQuery, queryOptions)
if entities[idx][navigationProperty]
entities[idx][navigationProperty]['reference_to.o'] = referenceToCollection._name
entities[idx][navigationProperty]['reference_to._o'] = _o
else
# TODO
return
setOdataProperty=(entities,space,key)->
entities_OdataProperties = []
_.each entities, (entity, idx)->
entity_OdataProperties = {}
id = entities[idx]["_id"]
entity_OdataProperties['@odata.id'] = SteedosOData.getODataNextLinkPath(space,key)+ '(\'' + "#{id}" + '\')'
entity_OdataProperties['@odata.etag'] = "W/\"08D589720BBB3DB1\""
entity_OdataProperties['@odata.editLink'] = entity_OdataProperties['@odata.id']
_.extend entity_OdataProperties,entity
entities_OdataProperties.push entity_OdataProperties
return entities_OdataProperties
setErrorMessage = (statusCode,collection,key,action)->
body = {}
error = {}
innererror = {}
if statusCode == 404
if collection
if action == 'post'
innererror['message'] = t("creator_odata_post_fail")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 404
error['message'] = "creator_odata_post_fail"
else
innererror['message'] = t("creator_odata_record_query_fail")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 404
error['message'] = "creator_odata_record_query_fail"
else
innererror['message'] = t("creator_odata_collection_query_fail")+ key
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 404
error['message'] = "creator_odata_collection_query_fail"
if statusCode == 401
innererror['message'] = t("creator_odata_authentication_required")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 401
error['message'] = "creator_odata_authentication_required"
if statusCode == 403
switch action
when 'get' then innererror['message'] = t("creator_odata_user_access_fail")
when 'post' then innererror['message'] = t("creator_odata_user_create_fail")
when 'put' then innererror['message'] = t("creator_odata_user_update_fail")
when 'delete' then innererror['message'] = t("creator_odata_user_remove_fail")
innererror['message'] = t("creator_odata_user_access_fail")
innererror['type'] = 'Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException'
error['code'] = 403
error['message'] = "creator_odata_user_access_fail"
error['innererror'] = innererror
body['error'] = error
return body
SteedosOdataAPI.addRoute(':object_name', {authRequired: true, spaceRequired: false}, {
get: ()->
try
key = @urlParams.object_name
object = Creator.objectsByName[key]
if not object?.enable_api
return {
statusCode: 401
body:setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return {
statusCode: 404
body:setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(spaceId, @userId, key)
if permissions.viewAllRecords or (permissions.allowRead and @userId)
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
if key is 'PI:KEY:<KEY>END_PI'
createQuery.query['metadata.space'] = spaceId
else if key is 'PI:KEY:<KEY>END_PI'
if spaceId isnt 'guest'
createQuery.query._id = spaceId
else
if spaceId isnt 'guest'
createQuery.query.space = spaceId
if Creator.isCommonSpace(spaceId)
if Creator.isSpaceAdmin(spaceId, @userId)
if key is 'spaces'
delete createQuery.query._id
else
delete createQuery.query.space
else
user_spaces = Creator.getCollection("space_users").find({user: @userId}, {fields: {space: 1}}).fetch()
if key is 'spaces'
# space 对所有用户记录为只读
delete createQuery.query._id
# createQuery.query._id = {$in: _.pluck(user_spaces, 'space')}
else
createQuery.query.space = {$in: _.pluck(user_spaces, 'space')}
if not createQuery.sort or !_.size(createQuery.sort)
createQuery.sort = { modified: -1 }
is_enterprise = Steedos.isLegalVersion(spaceId,"workflow.enterprise")
is_professional = Steedos.isLegalVersion(spaceId,"workflow.professional")
is_standard = Steedos.isLegalVersion(spaceId,"workflow.standard")
if createQuery.limit
limit = createQuery.limit
if is_enterprise and limit>100000
createQuery.limit = 100000
else if is_professional and limit>10000 and !is_enterprise
createQuery.limit = 10000
else if is_standard and limit>1000 and !is_professional and !is_enterprise
createQuery.limit = 1000
else
if is_enterprise
createQuery.limit = 100000
else if is_professional and !is_enterprise
createQuery.limit = 10000
else if is_standard and !is_enterprise and !is_professional
createQuery.limit = 1000
unreadable_fields = permissions.unreadable_fields || []
if createQuery.projection
projection = {}
_.keys(createQuery.projection).forEach (key)->
if _.indexOf(unreadable_fields, key) < 0
#if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple)
projection[key] = 1
createQuery.projection = projection
if not createQuery.projection or !_.size(createQuery.projection)
readable_fields = Creator.getFields(key, spaceId, @userId)
fields = Creator.getObject(key).fields
_.each readable_fields,(field)->
if field.indexOf('$')<0
#if fields[field]?.multiple!= true
createQuery.projection[field] = 1
if not permissions.viewAllRecords
if object.enable_share
# 满足共享规则中的记录也要搜索出来
delete createQuery.query.owner
shares = []
orgs = Steedos.getUserOrganizations(spaceId, @userId, true)
shares.push {"owner": @userId}
shares.push { "sharing.u": @userId }
shares.push { "sharing.o": { $in: orgs } }
createQuery.query["$or"] = shares
else
createQuery.query.owner = @userId
entities = []
if @queryParams.$top isnt '0'
entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch()
scannedCount = collection.find(createQuery.query,{fields:{_id: 1}}).count()
if entities
dealWithExpand(createQuery, entities, key)
#scannedCount = entities.length
body = {}
headers = {}
body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key)
# body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(spaceId,key)+"?%24skip="+ 10
body['@odata.count'] = scannedCount
entities_OdataProperties = setOdataProperty(entities,spaceId, key)
body['value'] = entities_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,"get")
}
catch e
console.error e.stack
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
post: ()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return {
statusCode: 401
body:setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return {
statusCode: 404
body:setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(spaceId, @userId, key)
if permissions.allowCreate
@bodyParams.space = spaceId
if spaceId is 'guest'
delete @bodyParams.space
entityId = collection.insert @bodyParams
entity = collection.findOne entityId
entities = []
if entity
body = {}
headers = {}
entities.push entity
body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity'
entity_OdataProperties = setOdataProperty(entities,spaceId, key)
body['value'] = entity_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'post')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'post')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
SteedosOdataAPI.addRoute(':object_name/recent', {authRequired: true, spaceRequired: false}, {
get:()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return {
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowRead
recent_view_collection = Creator.Collections["object_recent_viewed"]
recent_view_selector = {"record.o":key,created_by:@userId}
recent_view_options = {}
recent_view_options.sort = {created: -1}
recent_view_options.fields = {record:1}
recent_view_records = recent_view_collection.find(recent_view_selector,recent_view_options).fetch()
recent_view_records_ids = _.pluck(recent_view_records,'record')
recent_view_records_ids = recent_view_records_ids.getProperty("ids")
recent_view_records_ids = _.flatten(recent_view_records_ids)
recent_view_records_ids = _.uniq(recent_view_records_ids)
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
if key is 'PI:KEY:<KEY>END_PI'
createQuery.query['metadata.space'] = @urlParams.spaceId
else
createQuery.query.space = @urlParams.spaceId
if not createQuery.limit
createQuery.limit = 100
if createQuery.limit and recent_view_records_ids.length>createQuery.limit
recent_view_records_ids = _.first(recent_view_records_ids,createQuery.limit)
createQuery.query._id = {$in:recent_view_records_ids}
unreadable_fields = permissions.unreadable_fields || []
# fields = Creator.getObject(key).fields
if createQuery.projection
projection = {}
_.keys(createQuery.projection).forEach (key)->
if _.indexOf(unreadable_fields, key) < 0
# if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple)
projection[key] = 1
createQuery.projection = projection
if not createQuery.projection or !_.size(createQuery.projection)
readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId)
fields = Creator.getObject(key).fields
_.each readable_fields,(field)->
if field.indexOf('$')<0
#if fields[field]?.multiple!= true
createQuery.projection[field] = 1
if @queryParams.$top isnt '0'
entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch()
entities_index = []
entities_ids = _.pluck(entities,'_id')
sort_entities = []
if not createQuery.sort or !_.size(createQuery.sort)
_.each recent_view_records_ids ,(recent_view_records_id)->
index = _.indexOf(entities_ids,recent_view_records_id)
if index>-1
sort_entities.push entities[index]
else
sort_entities = entities
if sort_entities
dealWithExpand(createQuery, sort_entities, key)
body = {}
headers = {}
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key)
# body['@odata.nextLink'] = SteedosOData.getODataNextLinkPath(@urlParams.spaceId,key)+"?%24skip="+ 10
body['@odata.count'] = sort_entities.length
entities_OdataProperties = setOdataProperty(sort_entities,@urlParams.spaceId, key)
body['value'] = entities_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'get')
}
else
console.error e
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'get')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
SteedosOdataAPI.addRoute(':object_name/:_id', {authRequired: true, spaceRequired: false}, {
post: ()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowCreate
@bodyParams.space = @urlParams.spaceId
entityId = collection.insert @bodyParams
entity = collection.findOne entityId
entities = []
if entity
body = {}
headers = {}
entities.push entity
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity'
entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key)
body['value'] = entity_OdataProperties
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'post')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'post')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
get:()->
key = @urlParams.object_name
if key.indexOf("(") > -1
body = {}
headers = {}
collectionInfo = key
fieldName = @urlParams._id.split('_expand')[0]
collectionInfoSplit = collectionInfo.split('(')
collectionName = collectionInfoSplit[0]
id = collectionInfoSplit[1].split('\'')[1]
collection = Creator.Collections[collectionName]
fieldsOptions = {}
fieldsOptions[fieldName] = 1
entity = collection.findOne({_id: id}, {fields: fieldsOptions})
fieldValue = null
if entity
fieldValue = entity[fieldName]
obj = Creator.objectsByName[collectionName]
field = obj.fields[fieldName]
if field and fieldValue and (field.type is 'lookup' or field.type is 'master_detail')
lookupCollection = Creator.Collections[field.reference_to]
lookupObj = Creator.objectsByName[field.reference_to]
queryOptions = {fields: {}}
_.each lookupObj.fields, (v, k)->
queryOptions.fields[k] = 1
if field.multiple
body['value'] = lookupCollection.find({_id: {$in: fieldValue}}, queryOptions).fetch()
body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}"
else
body = lookupCollection.findOne({_id: fieldValue}, queryOptions) || {}
body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{field.reference_to}/$entity"
else
body['@odata.context'] = SteedosOData.getMetaDataPath(@urlParams.spaceId) + "##{collectionInfo}/#{@urlParams._id}"
body['value'] = fieldValue
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
try
object = Creator.objectsByName[key]
if not object?.enable_api
return {
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowRead
unreadable_fields = permissions.unreadable_fields || []
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
createQuery.query._id = @urlParams._id
if key is 'PI:KEY:<KEY>END_PI'
createQuery.query['metadata.space'] = @urlParams.spaceId
else
createQuery.query.space = @urlParams.spaceId
unreadable_fields = permissions.unreadable_fields || []
#fields = Creator.getObject(key).fields
if createQuery.projection
projection = {}
_.keys(createQuery.projection).forEach (key)->
if _.indexOf(unreadable_fields, key) < 0
# if not ((fields[key]?.type == 'lookup' or fields[key]?.type == 'master_detail') and fields[key].multiple)
projection[key] = 1
createQuery.projection = projection
if not createQuery.projection or !_.size(createQuery.projection)
readable_fields = Creator.getFields(key, @urlParams.spaceId, @userId)
fields = Creator.getObject(key).fields
_.each readable_fields,(field)->
if field.indexOf('$')<0
createQuery.projection[field] = 1
entity = collection.findOne(createQuery.query,visitorParser(createQuery))
entities = []
if entity
isAllowed = entity.owner == @userId or permissions.viewAllRecords
if object.enable_share and !isAllowed
shares = []
orgs = Steedos.getUserOrganizations(@urlParams.spaceId, @userId, true)
shares.push { "sharing.u": @userId }
shares.push { "sharing.o": { $in: orgs } }
isAllowed = collection.findOne({ _id: @urlParams._id, "$or": shares }, { fields: { _id: 1 } })
if isAllowed
body = {}
headers = {}
entities.push entity
dealWithExpand(createQuery, entities, key)
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key) + '/$entity'
entity_OdataProperties = setOdataProperty(entities,@urlParams.spaceId, key)
_.extend body,entity_OdataProperties[0]
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'get')
}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key,'get')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'get')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
put:()->
try
key = @urlParams.object_name
object = Creator.objectsByName[key]
if not object?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(spaceId, @userId, key)
record_owner = collection.findOne({ _id: @urlParams._id }, { fields: { owner: 1 } })?.owner
isAllowed = permissions.modifyAllRecords or (permissions.allowEdit and record_owner == @userId )
if isAllowed
selector = {_id: @urlParams._id, space: spaceId}
if spaceId is 'guest'
delete selector.space
fields_editable = true
_.keys(@bodyParams.$set).forEach (key)->
if _.indexOf(permissions.uneditable_fields, key) > -1
fields_editable = false
if fields_editable
entityIsUpdated = collection.update selector, @bodyParams
if entityIsUpdated
#statusCode: 201
# entity = collection.findOne @urlParams._id
# entities = []
# body = {}
headers = {}
body = {}
# entities.push entity
# body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity'
# entity_OdataProperties = setOdataProperty(entities,spaceId, key)
# _.extend body,entity_OdataProperties[0]
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{headers: headers,body:body}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'put')
}
else
return{
statusCode: 403
body: setErrorMessage(403,collection,key,'put')
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
delete:()->
try
key = @urlParams.object_name
object = Creator.objectsByName[key]
if not object?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
spaceId = @urlParams.spaceId
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
record_owner = collection.findOne({_id: @urlParams._id})?.owner
isAllowed = (permissions.modifyAllRecords and permissions.allowDelete) or (permissions.allowDelete and record_owner==@userId )
if isAllowed
selector = {_id: @urlParams._id, space: spaceId}
if spaceId is 'guest'
delete selector.space
if collection.remove selector
headers = {}
body = {}
# entities.push entity
# body['@odata.context'] = SteedosOData.getODataContextPath(spaceId, key) + '/$entity'
# entity_OdataProperties = setOdataProperty(entities,spaceId, key)
# _.extend body,entity_OdataProperties[0]
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{headers: headers,body:body}
else
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return {
statusCode: 403
body: setErrorMessage(403,collection,key)
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
SteedosOdataAPI.addRoute(':object_name/:_id/:methodName', {authRequired: true, spaceRequired: false}, {
post: ()->
try
key = @urlParams.object_name
if not Creator.objectsByName[key]?.enable_api
return{
statusCode: 401
body: setErrorMessage(401)
}
collection = Creator.Collections[key]
if not collection
return{
statusCode: 404
body: setErrorMessage(404,collection,key)
}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.allowRead
methodName = @urlParams.methodName
methods = Creator.Objects[key]?.methods || {}
if methods.hasOwnProperty(methodName)
thisObj = {
object_name: key
record_id: @urlParams._id
space_id: @urlParams.spaceId
user_id: @userId
permissions: permissions
}
methods[methodName].apply(thisObj, [@bodyParams])
{}
else
return {
statusCode: 404
body: setErrorMessage(404,collection,key)
}
else
return {
statusCode: 403
body: setErrorMessage(403,collection,key)
}
catch e
body = {}
error = {}
error['message'] = e.message
error['code'] = 500
error['error'] = e.error
error['details'] = e.details
error['reason'] = e.reason
body['error'] = error
return {
statusCode: 500
body:body
}
})
#TODO remove
_.each [], (value, key, list)-> #Creator.Collections
if not Creator.objectsByName[key]?.enable_api
return
if SteedosOdataAPI
SteedosOdataAPI.addCollection Creator.Collections[key],
excludedEndpoints: []
routeOptions:
authRequired: true
spaceRequired: false
endpoints:
getAll:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@urlParams.spaceId, @userId, key)
if permissions.viewAllRecords or (permissions.allowRead and @userId)
qs = decodeURIComponent(querystring.stringify(@queryParams))
createQuery = if qs then odataV4Mongodb.createQuery(qs) else odataV4Mongodb.createQuery()
if key is 'PI:KEY:<KEY>END_PI'
createQuery.query['metadata.space'] = @urlParams.spaceId
else
createQuery.query.space = @urlParams.spaceId
if not permissions.viewAllRecords
createQuery.query.owner = @userId
entities = []
if @queryParams.$top isnt '0'
entities = collection.find(createQuery.query, visitorParser(createQuery)).fetch()
scannedCount = collection.find(createQuery.query).count()
if entities
dealWithExpand(createQuery, entities, key)
body = {}
headers = {}
body['@odata.context'] = SteedosOData.getODataContextPath(@urlParams.spaceId, key)
body['@odata.count'] = scannedCount
body['value'] = entities
headers['Content-type'] = 'application/json;odata.metadata=minimal;charset=utf-8'
headers['OData-Version'] = SteedosOData.VERSION
{body: body, headers: headers}
else
statusCode: 404
body: {status: 'fail', message: 'Unable to retrieve items from collection'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
post:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowCreate
@bodyParams.space = @spaceId
entityId = collection.insert @bodyParams
entity = collection.findOne entityId
if entity
statusCode: 201
{status: 'success', value: entity}
else
statusCode: 404
body: {status: 'fail', message: 'No item added'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
get:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowRead
selector = {_id: @urlParams.id, space: @spaceId}
entity = collection.findOne selector
if entity
{status: 'success', value: entity}
else
statusCode: 404
body: {status: 'fail', message: 'Item not found'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
put:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowEdit
selector = {_id: @urlParams.id, space: @spaceId}
entityIsUpdated = collection.update selector, $set: @bodyParams
if entityIsUpdated
entity = collection.findOne @urlParams.id
{status: 'success', value: entity}
else
statusCode: 404
body: {status: 'fail', message: 'Item not found'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
delete:
action: ->
collection = Creator.Collections[key]
if not collection
statusCode: 404
body: {status: 'fail', message: 'Collection not found'}
permissions = Creator.getObjectPermissions(@spaceId, @userId, key)
if permissions.allowDelete
selector = {_id: @urlParams.id, space: @spaceId}
if collection.remove selector
{status: 'success', message: 'Item removed'}
else
statusCode: 404
body: {status: 'fail', message: 'Item not found'}
else
statusCode: 400
body: {status: 'fail', message: 'Action not permitted'}
|
[
{
"context": "->\n newTeam = teamsnap.createTeam\n name: 'New Test Team'\n sportId: 1\n locationCountry: 'United ",
"end": 533,
"score": 0.9987389445304871,
"start": 520,
"tag": "NAME",
"value": "New Test Team"
}
] | test/teams.coffee | teamsnap/teamsnap-javascript-sdk | 9 | describe 'Teams', ->
newTeam = null
it 'should be able to load all teams', (done) ->
teamsnap.loadTeams (err, result) ->
expect(err).to.be.null
result.should.be.an('array')
done()
it 'should be able to load a teams data in bulk', (done) ->
teamsnap.bulkLoad team.id, (err, result) ->
console.log(err)
expect(err).to.be.null
result.should.be.an('array')
done()
it 'should be able to create a new team', (done) ->
newTeam = teamsnap.createTeam
name: 'New Test Team'
sportId: 1
locationCountry: 'United States'
locationPostalCode: 80302
timeZone: 'America/Denver'
teamsnap.saveTeam newTeam, (err, result) ->
expect(err).to.be.null
result.should.have.property('type', 'team')
result.should.have.property('id')
result.should.equal(newTeam)
done()
it 'should be able to delete a team', (done) ->
teamsnap.deleteTeam newTeam, (err, result) ->
expect(err).to.be.null
done()
| 21474 | describe 'Teams', ->
newTeam = null
it 'should be able to load all teams', (done) ->
teamsnap.loadTeams (err, result) ->
expect(err).to.be.null
result.should.be.an('array')
done()
it 'should be able to load a teams data in bulk', (done) ->
teamsnap.bulkLoad team.id, (err, result) ->
console.log(err)
expect(err).to.be.null
result.should.be.an('array')
done()
it 'should be able to create a new team', (done) ->
newTeam = teamsnap.createTeam
name: '<NAME>'
sportId: 1
locationCountry: 'United States'
locationPostalCode: 80302
timeZone: 'America/Denver'
teamsnap.saveTeam newTeam, (err, result) ->
expect(err).to.be.null
result.should.have.property('type', 'team')
result.should.have.property('id')
result.should.equal(newTeam)
done()
it 'should be able to delete a team', (done) ->
teamsnap.deleteTeam newTeam, (err, result) ->
expect(err).to.be.null
done()
| true | describe 'Teams', ->
newTeam = null
it 'should be able to load all teams', (done) ->
teamsnap.loadTeams (err, result) ->
expect(err).to.be.null
result.should.be.an('array')
done()
it 'should be able to load a teams data in bulk', (done) ->
teamsnap.bulkLoad team.id, (err, result) ->
console.log(err)
expect(err).to.be.null
result.should.be.an('array')
done()
it 'should be able to create a new team', (done) ->
newTeam = teamsnap.createTeam
name: 'PI:NAME:<NAME>END_PI'
sportId: 1
locationCountry: 'United States'
locationPostalCode: 80302
timeZone: 'America/Denver'
teamsnap.saveTeam newTeam, (err, result) ->
expect(err).to.be.null
result.should.have.property('type', 'team')
result.should.have.property('id')
result.should.equal(newTeam)
done()
it 'should be able to delete a team', (done) ->
teamsnap.deleteTeam newTeam, (err, result) ->
expect(err).to.be.null
done()
|
[
{
"context": "class app.Settings\n DOCS_KEY = 'docs'\n DARK_KEY = 'dark'\n LAYOUT_KEY = 'layout'\n SI",
"end": 37,
"score": 0.9074428677558899,
"start": 33,
"tag": "KEY",
"value": "docs"
},
{
"context": "ss app.Settings\n DOCS_KEY = 'docs'\n DARK_KEY = 'dark'\n LAYOUT_KEY = 'layout'\n SIZE_KEY = 'size'\n TI",
"end": 57,
"score": 0.9830256700515747,
"start": 53,
"tag": "KEY",
"value": "dark"
},
{
"context": "_KEY = 'layout'\n SIZE_KEY = 'size'\n TIPS_KEY = 'tips'\n\n @defaults:\n count: 0\n hideDisabled: fal",
"end": 121,
"score": 0.8445194959640503,
"start": 117,
"tag": "KEY",
"value": "tips"
}
] | public/javascripts/app/settings.coffee | w3cub/docshub-node | 3 | class app.Settings
DOCS_KEY = 'docs'
DARK_KEY = 'dark'
LAYOUT_KEY = 'layout'
SIZE_KEY = 'size'
TIPS_KEY = 'tips'
@defaults:
count: 0
hideDisabled: false
hideIntro: false
news: 0
manualUpdate: false
schema: 1
constructor: ->
@store = new CookieStore
@cache = {}
get: (key) ->
return @cache[key] if @cache.hasOwnProperty(key)
@cache[key] = @store.get(key) ? @constructor.defaults[key]
set: (key, value) ->
@store.set(key, value)
delete @cache[key]
return
del: (key) ->
@store.del(key)
delete @cache[key]
return
hasDocs: ->
try !!@store.get(DOCS_KEY)
getDocs: ->
@store.get(DOCS_KEY)?.split('/') or app.config.default_docs
setDocs: (docs) ->
@set DOCS_KEY, docs.join('/')
return
getTips: ->
@store.get(TIPS_KEY)?.split('/') or []
setTips: (tips) ->
@set TIPS_KEY, tips.join('/')
return
setLayout: (name, enable) ->
layout = (@store.get(LAYOUT_KEY) || '').split(' ')
$.arrayDelete(layout, '')
if enable
layout.push(name) if layout.indexOf(name) is -1
else
$.arrayDelete(layout, name)
if layout.length > 0
@set LAYOUT_KEY, layout.join(' ')
else
@del LAYOUT_KEY
return
hasLayout: (name) ->
layout = (@store.get(LAYOUT_KEY) || '').split(' ')
layout.indexOf(name) isnt -1
setSize: (value) ->
@set SIZE_KEY, value
return
dump: ->
@store.dump()
reset: ->
@store.reset()
@cache = {}
return
| 211524 | class app.Settings
DOCS_KEY = '<KEY>'
DARK_KEY = '<KEY>'
LAYOUT_KEY = 'layout'
SIZE_KEY = 'size'
TIPS_KEY = '<KEY>'
@defaults:
count: 0
hideDisabled: false
hideIntro: false
news: 0
manualUpdate: false
schema: 1
constructor: ->
@store = new CookieStore
@cache = {}
get: (key) ->
return @cache[key] if @cache.hasOwnProperty(key)
@cache[key] = @store.get(key) ? @constructor.defaults[key]
set: (key, value) ->
@store.set(key, value)
delete @cache[key]
return
del: (key) ->
@store.del(key)
delete @cache[key]
return
hasDocs: ->
try !!@store.get(DOCS_KEY)
getDocs: ->
@store.get(DOCS_KEY)?.split('/') or app.config.default_docs
setDocs: (docs) ->
@set DOCS_KEY, docs.join('/')
return
getTips: ->
@store.get(TIPS_KEY)?.split('/') or []
setTips: (tips) ->
@set TIPS_KEY, tips.join('/')
return
setLayout: (name, enable) ->
layout = (@store.get(LAYOUT_KEY) || '').split(' ')
$.arrayDelete(layout, '')
if enable
layout.push(name) if layout.indexOf(name) is -1
else
$.arrayDelete(layout, name)
if layout.length > 0
@set LAYOUT_KEY, layout.join(' ')
else
@del LAYOUT_KEY
return
hasLayout: (name) ->
layout = (@store.get(LAYOUT_KEY) || '').split(' ')
layout.indexOf(name) isnt -1
setSize: (value) ->
@set SIZE_KEY, value
return
dump: ->
@store.dump()
reset: ->
@store.reset()
@cache = {}
return
| true | class app.Settings
DOCS_KEY = 'PI:KEY:<KEY>END_PI'
DARK_KEY = 'PI:KEY:<KEY>END_PI'
LAYOUT_KEY = 'layout'
SIZE_KEY = 'size'
TIPS_KEY = 'PI:KEY:<KEY>END_PI'
@defaults:
count: 0
hideDisabled: false
hideIntro: false
news: 0
manualUpdate: false
schema: 1
constructor: ->
@store = new CookieStore
@cache = {}
get: (key) ->
return @cache[key] if @cache.hasOwnProperty(key)
@cache[key] = @store.get(key) ? @constructor.defaults[key]
set: (key, value) ->
@store.set(key, value)
delete @cache[key]
return
del: (key) ->
@store.del(key)
delete @cache[key]
return
hasDocs: ->
try !!@store.get(DOCS_KEY)
getDocs: ->
@store.get(DOCS_KEY)?.split('/') or app.config.default_docs
setDocs: (docs) ->
@set DOCS_KEY, docs.join('/')
return
getTips: ->
@store.get(TIPS_KEY)?.split('/') or []
setTips: (tips) ->
@set TIPS_KEY, tips.join('/')
return
setLayout: (name, enable) ->
layout = (@store.get(LAYOUT_KEY) || '').split(' ')
$.arrayDelete(layout, '')
if enable
layout.push(name) if layout.indexOf(name) is -1
else
$.arrayDelete(layout, name)
if layout.length > 0
@set LAYOUT_KEY, layout.join(' ')
else
@del LAYOUT_KEY
return
hasLayout: (name) ->
layout = (@store.get(LAYOUT_KEY) || '').split(' ')
layout.indexOf(name) isnt -1
setSize: (value) ->
@set SIZE_KEY, value
return
dump: ->
@store.dump()
reset: ->
@store.reset()
@cache = {}
return
|
[
{
"context": "et \"/user/:id\", (req, res) ->\n res.send { name: 'Jane Doe', email: 'jane@doe.com' }\n\n# Spawns a child proce",
"end": 557,
"score": 0.9996359348297119,
"start": 549,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "q, res) ->\n res.send { name: 'Jane Doe', email: 'jane@doe.com' }\n\n# Spawns a child process with ENV variables t",
"end": 580,
"score": 0.9999205470085144,
"start": 568,
"tag": "EMAIL",
"value": "jane@doe.com"
}
] | test/helpers/integration.coffee | 1aurabrown/ervell | 118 | #
# Integration test helper that makes it easy to write fast integration tests.
# One of the ways it does this is by providing the methods `startServer` and
# `closeServer` that will spawn a child process of this project. This means
# a version of this project server will run on localhost:5000 using a fake
# API server exposed below a `api`.
#
spawn = require("child_process").spawn
express = require "express"
# Fake API server, edit this to stub your own API's behavior.
@api = express()
@api.get "/user/:id", (req, res) ->
res.send { name: 'Jane Doe', email: 'jane@doe.com' }
# Spawns a child process with ENV variables that will launch it in "test"
# mode. This includes an API_URL that points to the fake API server mounted
# under /__api.
@startServer = (callback) =>
return callback() if @child?
envVars =
NODE_ENV: "test"
API_URL: "http://localhost:5000/__api"
PORT: 5000
envVars[k] = val for k, val of process.env when not envVars[k]?
@child = spawn "make", ["s"],
customFds: [0, 1, 2]
stdio: ["ipc"]
env: envVars
@child.on "message", -> callback()
@child.stdout.on "data", (data) -> console.log data.toString()
# Closes the server child process, used in an `after` hook and on
# `process.exit` in case the test suite is interupted.
@closeServer = =>
@child?.kill()
@child = null
process.on "exit", @closeServer
# You can debug your integration app and run this app server by running
# this module directly and opening up localhost:5000.
# e.g. `coffee test/helpers/integration.coffee`
return unless module is require.main
@startServer => @child.stdout.on "data", (data) -> console.log data.toString()
| 26516 | #
# Integration test helper that makes it easy to write fast integration tests.
# One of the ways it does this is by providing the methods `startServer` and
# `closeServer` that will spawn a child process of this project. This means
# a version of this project server will run on localhost:5000 using a fake
# API server exposed below a `api`.
#
spawn = require("child_process").spawn
express = require "express"
# Fake API server, edit this to stub your own API's behavior.
@api = express()
@api.get "/user/:id", (req, res) ->
res.send { name: '<NAME>', email: '<EMAIL>' }
# Spawns a child process with ENV variables that will launch it in "test"
# mode. This includes an API_URL that points to the fake API server mounted
# under /__api.
@startServer = (callback) =>
return callback() if @child?
envVars =
NODE_ENV: "test"
API_URL: "http://localhost:5000/__api"
PORT: 5000
envVars[k] = val for k, val of process.env when not envVars[k]?
@child = spawn "make", ["s"],
customFds: [0, 1, 2]
stdio: ["ipc"]
env: envVars
@child.on "message", -> callback()
@child.stdout.on "data", (data) -> console.log data.toString()
# Closes the server child process, used in an `after` hook and on
# `process.exit` in case the test suite is interupted.
@closeServer = =>
@child?.kill()
@child = null
process.on "exit", @closeServer
# You can debug your integration app and run this app server by running
# this module directly and opening up localhost:5000.
# e.g. `coffee test/helpers/integration.coffee`
return unless module is require.main
@startServer => @child.stdout.on "data", (data) -> console.log data.toString()
| true | #
# Integration test helper that makes it easy to write fast integration tests.
# One of the ways it does this is by providing the methods `startServer` and
# `closeServer` that will spawn a child process of this project. This means
# a version of this project server will run on localhost:5000 using a fake
# API server exposed below a `api`.
#
spawn = require("child_process").spawn
express = require "express"
# Fake API server, edit this to stub your own API's behavior.
@api = express()
@api.get "/user/:id", (req, res) ->
res.send { name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' }
# Spawns a child process with ENV variables that will launch it in "test"
# mode. This includes an API_URL that points to the fake API server mounted
# under /__api.
@startServer = (callback) =>
return callback() if @child?
envVars =
NODE_ENV: "test"
API_URL: "http://localhost:5000/__api"
PORT: 5000
envVars[k] = val for k, val of process.env when not envVars[k]?
@child = spawn "make", ["s"],
customFds: [0, 1, 2]
stdio: ["ipc"]
env: envVars
@child.on "message", -> callback()
@child.stdout.on "data", (data) -> console.log data.toString()
# Closes the server child process, used in an `after` hook and on
# `process.exit` in case the test suite is interupted.
@closeServer = =>
@child?.kill()
@child = null
process.on "exit", @closeServer
# You can debug your integration app and run this app server by running
# this module directly and opening up localhost:5000.
# e.g. `coffee test/helpers/integration.coffee`
return unless module is require.main
@startServer => @child.stdout.on "data", (data) -> console.log data.toString()
|
[
{
"context": "###\npasswordCtrl.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.com>\n\nDistributed under terms of t",
"end": 51,
"score": 0.9983322620391846,
"start": 43,
"tag": "NAME",
"value": "ender xu"
},
{
"context": "\npasswordCtrl.coffee\nCopyright (C) 2014 ender xu <xuender@gmail.com>\n\nDistributed under terms of the MIT license.\n###",
"end": 70,
"score": 0.9999240040779114,
"start": 53,
"tag": "EMAIL",
"value": "xuender@gmail.com"
}
] | src/web/passwordCtrl.coffee | xuender/mindfulness | 0 | ###
passwordCtrl.coffee
Copyright (C) 2014 ender xu <xuender@gmail.com>
Distributed under terms of the MIT license.
###
PasswordCtrl = ($scope, $modalInstance, $http, $log)->
### 密码修改控制 ###
$scope.old = false
$scope.p =
old: ''
password: ''
password2: ''
$scope.ok= (valid)->
$scope.old = true
if valid
$http.post('/password', $scope.p).success((data)->
if data.ok
$modalInstance.dismiss('cancel')
else
alert(data.err)
)
$scope.cancel = ->
$modalInstance.dismiss('cancel')
PasswordCtrl.$inject = [
'$scope'
'$modalInstance'
'$http'
'$log'
]
| 162733 | ###
passwordCtrl.coffee
Copyright (C) 2014 <NAME> <<EMAIL>>
Distributed under terms of the MIT license.
###
PasswordCtrl = ($scope, $modalInstance, $http, $log)->
### 密码修改控制 ###
$scope.old = false
$scope.p =
old: ''
password: ''
password2: ''
$scope.ok= (valid)->
$scope.old = true
if valid
$http.post('/password', $scope.p).success((data)->
if data.ok
$modalInstance.dismiss('cancel')
else
alert(data.err)
)
$scope.cancel = ->
$modalInstance.dismiss('cancel')
PasswordCtrl.$inject = [
'$scope'
'$modalInstance'
'$http'
'$log'
]
| true | ###
passwordCtrl.coffee
Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Distributed under terms of the MIT license.
###
PasswordCtrl = ($scope, $modalInstance, $http, $log)->
### 密码修改控制 ###
$scope.old = false
$scope.p =
old: ''
password: ''
password2: ''
$scope.ok= (valid)->
$scope.old = true
if valid
$http.post('/password', $scope.p).success((data)->
if data.ok
$modalInstance.dismiss('cancel')
else
alert(data.err)
)
$scope.cancel = ->
$modalInstance.dismiss('cancel')
PasswordCtrl.$inject = [
'$scope'
'$modalInstance'
'$http'
'$log'
]
|
[
{
"context": "\n beforeEach ->\n rawToken =\n _id: '4f7c3891d95a479c6385720d240916d27e12708500471a50a4b2715a9e7a5576'\n exp: Math.round(Date.now() / 1000) + 360",
"end": 2294,
"score": 0.8454115986824036,
"start": 2230,
"tag": "PASSWORD",
"value": "4f7c3891d95a479c6385720d240916d27e12708500471a50a4b2715a9e7a5576"
},
{
"context": "pring_roll'\n rawExpiredToken =\n _id: '4f7c3891d95a479c6385720d240916d27e12708500471a50a4b2715a9e7a5576'\n exp: Math.round(Date.now() / 1000) - 360",
"end": 2495,
"score": 0.8738640546798706,
"start": 2431,
"tag": "PASSWORD",
"value": "4f7c3891d95a479c6385720d240916d27e12708500471a50a4b2715a9e7a5576"
}
] | test/unit/models/oneTimeTokenSpec.coffee | Zacaria/connect | 0 | # Test dependencies
cwd = process.cwd()
path = require 'path'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
proxyquire = require('proxyquire').noCallThru()
mockMulti = require '../lib/multi'
expect = chai.expect
redisMock = require 'redis-mock'
# Configure Chai and Sinon
chai.use sinonChai
chai.should()
redisMockClient = redisMock.createClient()
# Code under test
OneTimeToken = proxyquire(path.join(cwd, 'models/OneTimeToken'), {
'../boot/redis': {
getClient: () => redisMockClient
}
})
# Redis lib for spying and stubbing
{ client, multi } = {}
describe 'OneTimeToken', ->
before ->
client = redisMockClient
multi = mockMulti(redisMockClient)
after ->
redisMockClient.multi.restore()
describe 'constructor', ->
{ options, token } = {}
beforeEach ->
options =
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'dim_sum'
token = new OneTimeToken options
it 'should generate a collision-free random id', ->
token2 = new OneTimeToken options
token._id.should.not.equal token2._id
it 'should set the exp from options', ->
token.exp.should.equal options.exp
it 'should calculate the exp from ttl', ->
options2 =
ttl: 3600
use: options.use
sub: options.sub
exp = Math.round(Date.now() / 1000) + 3600
token2 = new OneTimeToken options2
expect(token2.exp).to.be.within(exp - 100, exp + 100)
it 'should set the use from options', ->
token.use.should.equal options.use
it 'should set the sub from options', ->
token.sub.should.equal options.sub
describe 'peek', ->
{ rawToken, rawExpiredToken } = {}
before ->
sinon.stub(redisMockClient, 'get').callsFake((key, callback) ->
key = key.split(':')[1]
if (key == 'valid')
callback null, JSON.stringify(rawToken)
else if (key == 'expired')
callback null, JSON.stringify(rawExpiredToken)
else if (key == 'malformed')
callback null, 'banh_mi'
else
callback null, null)
after ->
redisMockClient.get.restore()
beforeEach ->
rawToken =
_id: '4f7c3891d95a479c6385720d240916d27e12708500471a50a4b2715a9e7a5576'
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'spring_roll'
rawExpiredToken =
_id: '4f7c3891d95a479c6385720d240916d27e12708500471a50a4b2715a9e7a5576'
exp: Math.round(Date.now() / 1000) - 3600
use: 'test'
sub: 'pho'
describe 'with unknown token', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'unknown', (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a null value', ->
expect(token).to.be.null
describe 'with expired token', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'expired', (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a null value', ->
expect(token).to.be.null
describe 'with malformed result', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'malformed', (error, result) ->
err = error
token = result
done()
it 'should provide an error', ->
expect(err).to.be.an.instanceof Error
it 'should not provide a value', ->
expect(token).to.be.undefined
describe 'with valid token', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'valid', (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
token._id.should.equal rawToken._id
token.exp.should.be.within(rawToken.exp - 100, rawToken.exp + 100)
token.sub.should.equal rawToken.sub
token.use.should.equal rawToken.use
describe 'revoke', ->
{ err } = {}
before (done) ->
sinon.stub(redisMockClient, 'del').callsArgWith 1, null
OneTimeToken.revoke 'id', (error) ->
err = error
done()
after ->
redisMockClient.del.restore()
it 'should provide a falsy error', ->
expect(err).to.not.be.ok
it 'should delete the token', ->
redisMockClient.del.should.have.been.called
describe 'consume', ->
{ err, token } = {}
rawToken =
_id: 'valid'
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'nhung_dam'
before (done) ->
sinon.stub(OneTimeToken, 'peek')
.callsArgWith 1, null, new OneTimeToken rawToken
sinon.stub(OneTimeToken, 'revoke')
.callsArgWith 1, null
OneTimeToken.consume 'valid', (error, result) ->
err = error
token = result
done()
after ->
OneTimeToken.peek.restore()
OneTimeToken.revoke.restore()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
token._id.should.equal rawToken._id
token.exp.should.be.within(rawToken.exp - 100, rawToken.exp + 100)
token.use.should.equal rawToken.use
token.sub.should.equal rawToken.sub
it 'should revoke the token', ->
OneTimeToken.revoke.should.have.been.calledWith token._id
describe 'issue', ->
{ err, token } = {}
rawToken =
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'nem_nuong'
otToken = new OneTimeToken rawToken
noexpToken =
use: 'test'
sub: 'banh_flan'
beforeEach ->
sinon.stub multi, 'set'
sinon.stub multi, 'expireat'
sinon.stub(multi, 'exec').callsArgWith 0, null, []
afterEach ->
multi.set.restore()
multi.expireat.restore()
multi.exec.restore()
describe 'with raw token data', ->
{ err, token } = {}
beforeEach (done) ->
OneTimeToken.issue rawToken, (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should store the token', ->
multi.set.should.have.been.called
multi.exec.should.have.been.called
it 'should set the token to expire', ->
multi.expireat.should.have.been.called
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
token.exp.should.be.within rawToken.exp - 100, rawToken.exp + 100
token.use.should.equal rawToken.use
token.sub.should.equal rawToken.sub
describe 'with OneTimeToken instance', ->
{ err, token } = {}
beforeEach (done) ->
OneTimeToken.issue otToken, (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should store the token', ->
multi.set.should.have.been.calledWith(
'onetimetoken:' + otToken._id,
JSON.stringify(otToken)
)
it 'should set the token to expire', ->
multi.expireat.should.have.been.called
it 'should provide the same OneTimeToken instance', ->
token.should.eql otToken
describe 'without expiration date', ->
{ err, token } = {}
beforeEach (done) ->
OneTimeToken.issue noexpToken, (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should store the token', ->
multi.set.should.have.been.called
multi.exec.should.have.been.called
it 'should not set the token to expire', ->
multi.expireat.should.not.have.been.called
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
| 31803 | # Test dependencies
cwd = process.cwd()
path = require 'path'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
proxyquire = require('proxyquire').noCallThru()
mockMulti = require '../lib/multi'
expect = chai.expect
redisMock = require 'redis-mock'
# Configure Chai and Sinon
chai.use sinonChai
chai.should()
redisMockClient = redisMock.createClient()
# Code under test
OneTimeToken = proxyquire(path.join(cwd, 'models/OneTimeToken'), {
'../boot/redis': {
getClient: () => redisMockClient
}
})
# Redis lib for spying and stubbing
{ client, multi } = {}
describe 'OneTimeToken', ->
before ->
client = redisMockClient
multi = mockMulti(redisMockClient)
after ->
redisMockClient.multi.restore()
describe 'constructor', ->
{ options, token } = {}
beforeEach ->
options =
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'dim_sum'
token = new OneTimeToken options
it 'should generate a collision-free random id', ->
token2 = new OneTimeToken options
token._id.should.not.equal token2._id
it 'should set the exp from options', ->
token.exp.should.equal options.exp
it 'should calculate the exp from ttl', ->
options2 =
ttl: 3600
use: options.use
sub: options.sub
exp = Math.round(Date.now() / 1000) + 3600
token2 = new OneTimeToken options2
expect(token2.exp).to.be.within(exp - 100, exp + 100)
it 'should set the use from options', ->
token.use.should.equal options.use
it 'should set the sub from options', ->
token.sub.should.equal options.sub
describe 'peek', ->
{ rawToken, rawExpiredToken } = {}
before ->
sinon.stub(redisMockClient, 'get').callsFake((key, callback) ->
key = key.split(':')[1]
if (key == 'valid')
callback null, JSON.stringify(rawToken)
else if (key == 'expired')
callback null, JSON.stringify(rawExpiredToken)
else if (key == 'malformed')
callback null, 'banh_mi'
else
callback null, null)
after ->
redisMockClient.get.restore()
beforeEach ->
rawToken =
_id: '<PASSWORD>'
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'spring_roll'
rawExpiredToken =
_id: '<PASSWORD>'
exp: Math.round(Date.now() / 1000) - 3600
use: 'test'
sub: 'pho'
describe 'with unknown token', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'unknown', (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a null value', ->
expect(token).to.be.null
describe 'with expired token', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'expired', (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a null value', ->
expect(token).to.be.null
describe 'with malformed result', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'malformed', (error, result) ->
err = error
token = result
done()
it 'should provide an error', ->
expect(err).to.be.an.instanceof Error
it 'should not provide a value', ->
expect(token).to.be.undefined
describe 'with valid token', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'valid', (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
token._id.should.equal rawToken._id
token.exp.should.be.within(rawToken.exp - 100, rawToken.exp + 100)
token.sub.should.equal rawToken.sub
token.use.should.equal rawToken.use
describe 'revoke', ->
{ err } = {}
before (done) ->
sinon.stub(redisMockClient, 'del').callsArgWith 1, null
OneTimeToken.revoke 'id', (error) ->
err = error
done()
after ->
redisMockClient.del.restore()
it 'should provide a falsy error', ->
expect(err).to.not.be.ok
it 'should delete the token', ->
redisMockClient.del.should.have.been.called
describe 'consume', ->
{ err, token } = {}
rawToken =
_id: 'valid'
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'nhung_dam'
before (done) ->
sinon.stub(OneTimeToken, 'peek')
.callsArgWith 1, null, new OneTimeToken rawToken
sinon.stub(OneTimeToken, 'revoke')
.callsArgWith 1, null
OneTimeToken.consume 'valid', (error, result) ->
err = error
token = result
done()
after ->
OneTimeToken.peek.restore()
OneTimeToken.revoke.restore()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
token._id.should.equal rawToken._id
token.exp.should.be.within(rawToken.exp - 100, rawToken.exp + 100)
token.use.should.equal rawToken.use
token.sub.should.equal rawToken.sub
it 'should revoke the token', ->
OneTimeToken.revoke.should.have.been.calledWith token._id
describe 'issue', ->
{ err, token } = {}
rawToken =
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'nem_nuong'
otToken = new OneTimeToken rawToken
noexpToken =
use: 'test'
sub: 'banh_flan'
beforeEach ->
sinon.stub multi, 'set'
sinon.stub multi, 'expireat'
sinon.stub(multi, 'exec').callsArgWith 0, null, []
afterEach ->
multi.set.restore()
multi.expireat.restore()
multi.exec.restore()
describe 'with raw token data', ->
{ err, token } = {}
beforeEach (done) ->
OneTimeToken.issue rawToken, (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should store the token', ->
multi.set.should.have.been.called
multi.exec.should.have.been.called
it 'should set the token to expire', ->
multi.expireat.should.have.been.called
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
token.exp.should.be.within rawToken.exp - 100, rawToken.exp + 100
token.use.should.equal rawToken.use
token.sub.should.equal rawToken.sub
describe 'with OneTimeToken instance', ->
{ err, token } = {}
beforeEach (done) ->
OneTimeToken.issue otToken, (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should store the token', ->
multi.set.should.have.been.calledWith(
'onetimetoken:' + otToken._id,
JSON.stringify(otToken)
)
it 'should set the token to expire', ->
multi.expireat.should.have.been.called
it 'should provide the same OneTimeToken instance', ->
token.should.eql otToken
describe 'without expiration date', ->
{ err, token } = {}
beforeEach (done) ->
OneTimeToken.issue noexpToken, (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should store the token', ->
multi.set.should.have.been.called
multi.exec.should.have.been.called
it 'should not set the token to expire', ->
multi.expireat.should.not.have.been.called
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
| true | # Test dependencies
cwd = process.cwd()
path = require 'path'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
proxyquire = require('proxyquire').noCallThru()
mockMulti = require '../lib/multi'
expect = chai.expect
redisMock = require 'redis-mock'
# Configure Chai and Sinon
chai.use sinonChai
chai.should()
redisMockClient = redisMock.createClient()
# Code under test
OneTimeToken = proxyquire(path.join(cwd, 'models/OneTimeToken'), {
'../boot/redis': {
getClient: () => redisMockClient
}
})
# Redis lib for spying and stubbing
{ client, multi } = {}
describe 'OneTimeToken', ->
before ->
client = redisMockClient
multi = mockMulti(redisMockClient)
after ->
redisMockClient.multi.restore()
describe 'constructor', ->
{ options, token } = {}
beforeEach ->
options =
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'dim_sum'
token = new OneTimeToken options
it 'should generate a collision-free random id', ->
token2 = new OneTimeToken options
token._id.should.not.equal token2._id
it 'should set the exp from options', ->
token.exp.should.equal options.exp
it 'should calculate the exp from ttl', ->
options2 =
ttl: 3600
use: options.use
sub: options.sub
exp = Math.round(Date.now() / 1000) + 3600
token2 = new OneTimeToken options2
expect(token2.exp).to.be.within(exp - 100, exp + 100)
it 'should set the use from options', ->
token.use.should.equal options.use
it 'should set the sub from options', ->
token.sub.should.equal options.sub
describe 'peek', ->
{ rawToken, rawExpiredToken } = {}
before ->
sinon.stub(redisMockClient, 'get').callsFake((key, callback) ->
key = key.split(':')[1]
if (key == 'valid')
callback null, JSON.stringify(rawToken)
else if (key == 'expired')
callback null, JSON.stringify(rawExpiredToken)
else if (key == 'malformed')
callback null, 'banh_mi'
else
callback null, null)
after ->
redisMockClient.get.restore()
beforeEach ->
rawToken =
_id: 'PI:PASSWORD:<PASSWORD>END_PI'
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'spring_roll'
rawExpiredToken =
_id: 'PI:PASSWORD:<PASSWORD>END_PI'
exp: Math.round(Date.now() / 1000) - 3600
use: 'test'
sub: 'pho'
describe 'with unknown token', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'unknown', (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a null value', ->
expect(token).to.be.null
describe 'with expired token', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'expired', (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a null value', ->
expect(token).to.be.null
describe 'with malformed result', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'malformed', (error, result) ->
err = error
token = result
done()
it 'should provide an error', ->
expect(err).to.be.an.instanceof Error
it 'should not provide a value', ->
expect(token).to.be.undefined
describe 'with valid token', ->
{ err, token } = {}
before (done) ->
OneTimeToken.peek 'valid', (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
token._id.should.equal rawToken._id
token.exp.should.be.within(rawToken.exp - 100, rawToken.exp + 100)
token.sub.should.equal rawToken.sub
token.use.should.equal rawToken.use
describe 'revoke', ->
{ err } = {}
before (done) ->
sinon.stub(redisMockClient, 'del').callsArgWith 1, null
OneTimeToken.revoke 'id', (error) ->
err = error
done()
after ->
redisMockClient.del.restore()
it 'should provide a falsy error', ->
expect(err).to.not.be.ok
it 'should delete the token', ->
redisMockClient.del.should.have.been.called
describe 'consume', ->
{ err, token } = {}
rawToken =
_id: 'valid'
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'nhung_dam'
before (done) ->
sinon.stub(OneTimeToken, 'peek')
.callsArgWith 1, null, new OneTimeToken rawToken
sinon.stub(OneTimeToken, 'revoke')
.callsArgWith 1, null
OneTimeToken.consume 'valid', (error, result) ->
err = error
token = result
done()
after ->
OneTimeToken.peek.restore()
OneTimeToken.revoke.restore()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
token._id.should.equal rawToken._id
token.exp.should.be.within(rawToken.exp - 100, rawToken.exp + 100)
token.use.should.equal rawToken.use
token.sub.should.equal rawToken.sub
it 'should revoke the token', ->
OneTimeToken.revoke.should.have.been.calledWith token._id
describe 'issue', ->
{ err, token } = {}
rawToken =
exp: Math.round(Date.now() / 1000) + 3600
use: 'test'
sub: 'nem_nuong'
otToken = new OneTimeToken rawToken
noexpToken =
use: 'test'
sub: 'banh_flan'
beforeEach ->
sinon.stub multi, 'set'
sinon.stub multi, 'expireat'
sinon.stub(multi, 'exec').callsArgWith 0, null, []
afterEach ->
multi.set.restore()
multi.expireat.restore()
multi.exec.restore()
describe 'with raw token data', ->
{ err, token } = {}
beforeEach (done) ->
OneTimeToken.issue rawToken, (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should store the token', ->
multi.set.should.have.been.called
multi.exec.should.have.been.called
it 'should set the token to expire', ->
multi.expireat.should.have.been.called
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
token.exp.should.be.within rawToken.exp - 100, rawToken.exp + 100
token.use.should.equal rawToken.use
token.sub.should.equal rawToken.sub
describe 'with OneTimeToken instance', ->
{ err, token } = {}
beforeEach (done) ->
OneTimeToken.issue otToken, (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should store the token', ->
multi.set.should.have.been.calledWith(
'onetimetoken:' + otToken._id,
JSON.stringify(otToken)
)
it 'should set the token to expire', ->
multi.expireat.should.have.been.called
it 'should provide the same OneTimeToken instance', ->
token.should.eql otToken
describe 'without expiration date', ->
{ err, token } = {}
beforeEach (done) ->
OneTimeToken.issue noexpToken, (error, result) ->
err = error
token = result
done()
it 'should provide a null error', ->
expect(err).to.be.null
it 'should store the token', ->
multi.set.should.have.been.called
multi.exec.should.have.been.called
it 'should not set the token to expire', ->
multi.expireat.should.not.have.been.called
it 'should provide a OneTimeToken instance', ->
expect(token).to.be.an.instanceof OneTimeToken
|
[
{
"context": "\n\n services = ko.observableArray()\n\n randomKey = Math.random()\n\n register = (service) ->\n service.referenc",
"end": 350,
"score": 0.9928154945373535,
"start": 339,
"tag": "KEY",
"value": "Math.random"
}
] | app/assets/javascripts/models/data/service.js.coffee | evenstensberg/earthdata-search | 1 | ns = @edsc.models.data
ns.Service = do (ko
DetailsModel = @edsc.models.DetailsModel
extend=jQuery.extend
ajax = @edsc.util.xhr.ajax
dateUtil = @edsc.util.date
config = @edsc.config
) ->
services = ko.observableArray()
randomKey = Math.random()
register = (service) ->
service.reference()
services.push(service)
service
class Service extends DetailsModel
@awaitDatasources: (services, callback) ->
callback(services)
@findOrCreate: (jsonData, query) ->
id = jsonData.meta['concept-id']
for service in services()
if service.meta()['concept-id'] == id
if (jsonData.umm?.Name? && !service.hasAtomData())
service.fromJson(jsonData)
return service.reference()
register(new Service(jsonData, query, randomKey))
constructor: (jsonData, @query, inKey) ->
throw "Services should not be constructed directly" unless inKey == randomKey
@granuleCount = ko.observable(0)
@hasAtomData = ko.observable(false)
@fromJson(jsonData)
notifyRenderers: (action) ->
@_loadRenderers()
if @_loading
@_pendingRenderActions.push(action)
else
for renderer in @_renderers
renderer[action]?()
displayName: ->
@umm?['LongName'] || @umm?['Name']
fromJson: (jsonObj) ->
@json = jsonObj
@hasAtomData(jsonObj.umm?.Name?)
@_setObservable('meta', jsonObj)
@_setObservable('umm', jsonObj)
@_setObservable('associations', jsonObj)
for own key, value of jsonObj
this[key] = value unless ko.isObservable(this[key])
# @_loadDatasource()
_setObservable: (prop, jsonObj) =>
this[prop] ?= ko.observable(undefined)
this[prop](jsonObj[prop] ? this[prop]())
exports = Service
| 108694 | ns = @edsc.models.data
ns.Service = do (ko
DetailsModel = @edsc.models.DetailsModel
extend=jQuery.extend
ajax = @edsc.util.xhr.ajax
dateUtil = @edsc.util.date
config = @edsc.config
) ->
services = ko.observableArray()
randomKey = <KEY>()
register = (service) ->
service.reference()
services.push(service)
service
class Service extends DetailsModel
@awaitDatasources: (services, callback) ->
callback(services)
@findOrCreate: (jsonData, query) ->
id = jsonData.meta['concept-id']
for service in services()
if service.meta()['concept-id'] == id
if (jsonData.umm?.Name? && !service.hasAtomData())
service.fromJson(jsonData)
return service.reference()
register(new Service(jsonData, query, randomKey))
constructor: (jsonData, @query, inKey) ->
throw "Services should not be constructed directly" unless inKey == randomKey
@granuleCount = ko.observable(0)
@hasAtomData = ko.observable(false)
@fromJson(jsonData)
notifyRenderers: (action) ->
@_loadRenderers()
if @_loading
@_pendingRenderActions.push(action)
else
for renderer in @_renderers
renderer[action]?()
displayName: ->
@umm?['LongName'] || @umm?['Name']
fromJson: (jsonObj) ->
@json = jsonObj
@hasAtomData(jsonObj.umm?.Name?)
@_setObservable('meta', jsonObj)
@_setObservable('umm', jsonObj)
@_setObservable('associations', jsonObj)
for own key, value of jsonObj
this[key] = value unless ko.isObservable(this[key])
# @_loadDatasource()
_setObservable: (prop, jsonObj) =>
this[prop] ?= ko.observable(undefined)
this[prop](jsonObj[prop] ? this[prop]())
exports = Service
| true | ns = @edsc.models.data
ns.Service = do (ko
DetailsModel = @edsc.models.DetailsModel
extend=jQuery.extend
ajax = @edsc.util.xhr.ajax
dateUtil = @edsc.util.date
config = @edsc.config
) ->
services = ko.observableArray()
randomKey = PI:KEY:<KEY>END_PI()
register = (service) ->
service.reference()
services.push(service)
service
class Service extends DetailsModel
@awaitDatasources: (services, callback) ->
callback(services)
@findOrCreate: (jsonData, query) ->
id = jsonData.meta['concept-id']
for service in services()
if service.meta()['concept-id'] == id
if (jsonData.umm?.Name? && !service.hasAtomData())
service.fromJson(jsonData)
return service.reference()
register(new Service(jsonData, query, randomKey))
constructor: (jsonData, @query, inKey) ->
throw "Services should not be constructed directly" unless inKey == randomKey
@granuleCount = ko.observable(0)
@hasAtomData = ko.observable(false)
@fromJson(jsonData)
notifyRenderers: (action) ->
@_loadRenderers()
if @_loading
@_pendingRenderActions.push(action)
else
for renderer in @_renderers
renderer[action]?()
displayName: ->
@umm?['LongName'] || @umm?['Name']
fromJson: (jsonObj) ->
@json = jsonObj
@hasAtomData(jsonObj.umm?.Name?)
@_setObservable('meta', jsonObj)
@_setObservable('umm', jsonObj)
@_setObservable('associations', jsonObj)
for own key, value of jsonObj
this[key] = value unless ko.isObservable(this[key])
# @_loadDatasource()
_setObservable: (prop, jsonObj) =>
this[prop] ?= ko.observable(undefined)
this[prop](jsonObj[prop] ? this[prop]())
exports = Service
|
[
{
"context": "g data\n chats = [\n {\n id: 0\n name: 'Ben Sparrow'\n lastText: 'You on your way?'\n face: '",
"end": 196,
"score": 0.9998202919960022,
"start": 185,
"tag": "NAME",
"value": "Ben Sparrow"
},
{
"context": "img/ben.png'\n }\n {\n id: 1\n name: 'Max Lynx'\n lastText: 'Hey, it\\'s me'\n face: 'img",
"end": 304,
"score": 0.9998353719711304,
"start": 296,
"tag": "NAME",
"value": "Max Lynx"
},
{
"context": "img/max.png'\n }\n {\n id: 2\n name: 'Adam Bradleyson'\n lastText: 'I should buy a boat'\n face",
"end": 416,
"score": 0.999850869178772,
"start": 401,
"tag": "NAME",
"value": "Adam Bradleyson"
},
{
"context": "mg/adam.jpg'\n }\n {\n id: 3\n name: 'Perry Governor'\n lastText: 'Look at my mukluks!'\n face",
"end": 534,
"score": 0.9998468160629272,
"start": 520,
"tag": "NAME",
"value": "Perry Governor"
},
{
"context": "g/perry.png'\n }\n {\n id: 4\n name: 'Mike Harrington'\n lastText: 'This is wicked good ice cream.'",
"end": 654,
"score": 0.9998056888580322,
"start": 639,
"tag": "NAME",
"value": "Mike Harrington"
}
] | www/js/services.coffee | maruono/ionic | 0 | angular.module('starter.services', []).factory 'Chats', ->
# Might use a resource here that returns a JSON array
# Some fake testing data
chats = [
{
id: 0
name: 'Ben Sparrow'
lastText: 'You on your way?'
face: 'img/ben.png'
}
{
id: 1
name: 'Max Lynx'
lastText: 'Hey, it\'s me'
face: 'img/max.png'
}
{
id: 2
name: 'Adam Bradleyson'
lastText: 'I should buy a boat'
face: 'img/adam.jpg'
}
{
id: 3
name: 'Perry Governor'
lastText: 'Look at my mukluks!'
face: 'img/perry.png'
}
{
id: 4
name: 'Mike Harrington'
lastText: 'This is wicked good ice cream.'
face: 'img/mike.png'
}
]
{
all: ->
chats
remove: (chat) ->
chats.splice chats.indexOf(chat), 1
return
get: (chatId) ->
i = 0
while i < chats.length
if chats[i].id == parseInt(chatId)
return chats[i]
i++
null
}
# ---
# generated by js2coffee 2.2.0 | 70847 | angular.module('starter.services', []).factory 'Chats', ->
# Might use a resource here that returns a JSON array
# Some fake testing data
chats = [
{
id: 0
name: '<NAME>'
lastText: 'You on your way?'
face: 'img/ben.png'
}
{
id: 1
name: '<NAME>'
lastText: 'Hey, it\'s me'
face: 'img/max.png'
}
{
id: 2
name: '<NAME>'
lastText: 'I should buy a boat'
face: 'img/adam.jpg'
}
{
id: 3
name: '<NAME>'
lastText: 'Look at my mukluks!'
face: 'img/perry.png'
}
{
id: 4
name: '<NAME>'
lastText: 'This is wicked good ice cream.'
face: 'img/mike.png'
}
]
{
all: ->
chats
remove: (chat) ->
chats.splice chats.indexOf(chat), 1
return
get: (chatId) ->
i = 0
while i < chats.length
if chats[i].id == parseInt(chatId)
return chats[i]
i++
null
}
# ---
# generated by js2coffee 2.2.0 | true | angular.module('starter.services', []).factory 'Chats', ->
# Might use a resource here that returns a JSON array
# Some fake testing data
chats = [
{
id: 0
name: 'PI:NAME:<NAME>END_PI'
lastText: 'You on your way?'
face: 'img/ben.png'
}
{
id: 1
name: 'PI:NAME:<NAME>END_PI'
lastText: 'Hey, it\'s me'
face: 'img/max.png'
}
{
id: 2
name: 'PI:NAME:<NAME>END_PI'
lastText: 'I should buy a boat'
face: 'img/adam.jpg'
}
{
id: 3
name: 'PI:NAME:<NAME>END_PI'
lastText: 'Look at my mukluks!'
face: 'img/perry.png'
}
{
id: 4
name: 'PI:NAME:<NAME>END_PI'
lastText: 'This is wicked good ice cream.'
face: 'img/mike.png'
}
]
{
all: ->
chats
remove: (chat) ->
chats.splice chats.indexOf(chat), 1
return
get: (chatId) ->
i = 0
while i < chats.length
if chats[i].id == parseInt(chatId)
return chats[i]
i++
null
}
# ---
# generated by js2coffee 2.2.0 |
[
{
"context": "###\n * bag\n * getbag.io\n *\n * Copyright (c) 2015 Ryan Gaus\n * Licensed under the MIT license.\n###\n\nmongoose ",
"end": 58,
"score": 0.9998572468757629,
"start": 49,
"tag": "NAME",
"value": "Ryan Gaus"
}
] | src/models/foodstuff_model.coffee | 1egoman/bag-node | 0 | ###
* bag
* getbag.io
*
* Copyright (c) 2015 Ryan Gaus
* Licensed under the MIT license.
###
mongoose = require 'mongoose'
foodstuff = mongoose.Schema
name: String
desc: String
tags: Array
image: String
checked: Boolean
user: String
price: String
verified: Boolean
stores: Object
private: Boolean
foodstuff.set 'versionKey', false
module.exports = mongoose.model 'foodstuff', foodstuff
| 68692 | ###
* bag
* getbag.io
*
* Copyright (c) 2015 <NAME>
* Licensed under the MIT license.
###
mongoose = require 'mongoose'
foodstuff = mongoose.Schema
name: String
desc: String
tags: Array
image: String
checked: Boolean
user: String
price: String
verified: Boolean
stores: Object
private: Boolean
foodstuff.set 'versionKey', false
module.exports = mongoose.model 'foodstuff', foodstuff
| true | ###
* bag
* getbag.io
*
* Copyright (c) 2015 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
mongoose = require 'mongoose'
foodstuff = mongoose.Schema
name: String
desc: String
tags: Array
image: String
checked: Boolean
user: String
price: String
verified: Boolean
stores: Object
private: Boolean
foodstuff.set 'versionKey', false
module.exports = mongoose.model 'foodstuff', foodstuff
|
[
{
"context": "_WIN_CERTIFICATE_FILE\n certificatePassword: process.env.SIGN_WIN_CERTIFICATE_PASSWORD\n setupIc",
"end": 4929,
"score": 0.6423223614692688,
"start": 4922,
"tag": "PASSWORD",
"value": "process"
},
{
"context": " iconUrl: 'https://raw.githubusercontent.com/Aluxian/electron-superkit/master/resources/win/app.ico'\n ",
"end": 5076,
"score": 0.9995535016059875,
"start": 5069,
"tag": "USERNAME",
"value": "Aluxian"
}
] | tasks/pack.coffee | davemolton/electron-superkit | 28 | cp = require 'child_process'
path = require 'path'
fs = require 'fs'
asar = require 'asar'
async = require 'async'
del = require 'del'
gulp = require 'gulp'
zip = require 'gulp-zip'
winInstaller = require 'electron-windows-installer'
manifest = require '../src/package.json'
# Sign the app and create a dmg for darwin64; only works on OS X because of appdmg and codesign
gulp.task 'pack:darwin64', ['build:darwin64', 'clean:dist:darwin64'], (done) ->
if process.platform isnt 'darwin'
console.warn 'Skipping darwin64 packing; This only works on darwin due to `appdmg` and the `codesign` command.'
return done()
try
appdmg = require 'appdmg'
catch ex
console.warn 'Skipping darwin64 packing; `appdmg` not installed.'
return done()
for envName in ['SIGN_DARWIN_KEYCHAIN_PASSWORD', 'SIGN_DARWIN_KEYCHAIN_NAME', 'SIGN_DARWIN_IDENTITY']
if not process.env[envName]
console.warn envName + ' env var not set.'
return done()
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage,
'./build/darwin64/' + manifest.productName + '.app/Contents/Resources/app',
'./build/darwin64/' + manifest.productName + '.app/Contents/Resources/app.asar'
# Remove leftovers
async.apply del, './build/darwin64/' + manifest.productName + '.app/Contents/Resources/app'
# Unlock the keychain
async.apply cp.exec, [
'security'
'unlock-keychain'
'-p'
process.env.SIGN_DARWIN_KEYCHAIN_PASSWORD
process.env.SIGN_DARWIN_KEYCHAIN_NAME
].join(' ')
# Sign the app package
async.apply cp.exec, [
'codesign'
'--deep'
'--force'
'--verbose'
'--sign "' + process.env.SIGN_DARWIN_IDENTITY + '"'
'./build/darwin64/' + manifest.productName + '.app'
].join(' ')
# Create the dmg
(callback) ->
appdmg
source: './build/resources/darwin/dmg.json'
target: './dist/' + manifest.productName + '.dmg'
.on 'finish', callback
.on 'error', callback
], done
# Create deb and rpm packages for linux32 and linux64
[32, 64].forEach (arch) ->
['deb', 'rpm'].forEach (target) ->
gulp.task 'pack:linux' + arch + ':' + target, ['build:linux' + arch, 'clean:dist:linux' + arch], (done) ->
if arch == 32
archName = 'i386'
else if target is 'deb'
archName = 'amd64'
else
archName = 'x86_64'
args = [
'-s dir'
'-t ' + target
'--architecture ' + archName
'--rpm-os linux'
'--name ' + manifest.name
'--force' # Overwrite existing files
'--after-install ./build/resources/linux/after-install.sh'
'--after-remove ./build/resources/linux/after-remove.sh'
'--deb-changelog ./CHANGELOG.md'
'--rpm-changelog ./CHANGELOG.md'
'--license ' + manifest.license
'--category "' + manifest.linux.section + '"'
'--description "' + manifest.description + '"'
'--url "' + manifest.homepage + '"'
'--maintainer "' + manifest.author + '"'
'--version "' + manifest.version + '"'
'--package ' + './dist/' + manifest.name + '-VERSION-ARCH.' + target
'-C ./build/linux' + arch
'.'
]
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage,
'./build/linux' + arch + '/opt/' + manifest.name + '/resources/app',
'./build/linux' + arch + '/opt/' + manifest.name + '/resources/app.asar'
# Remove leftovers
async.apply del, './build/linux' + arch + '/opt/' + manifest.name + '/resources/app'
# Create a file with the target name
async.apply fs.writeFile, './build/linux' + arch + '/opt/' + manifest.name + '/pkgtarget', target
# Package the app
async.apply cp.exec, 'fpm ' + args.join(' ')
], done
# Create the win32 installer; only works on Windows
gulp.task 'pack:win32:installer', ['build:win32', 'clean:dist:win32'], (done) ->
if process.platform isnt 'win32'
return console.warn 'Skipping win32 installer packing; This only works on Windows due to Squirrel.Windows.'
for envName in ['SIGN_WIN_CERTIFICATE_FILE', 'SIGN_WIN_CERTIFICATE_PASSWORD']
if not process.env[envName]
return console.warn envName + ' env var not set.'
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage, './build/win32/resources/app', './build/win32/resources/app.asar'
# Remove leftovers
async.apply del, './build/win32/resources/app'
# Create the installer
(callback) ->
winInstaller
appDirectory: './build/win32'
outputDirectory: './dist'
loadingGif: './build/resources/win/install-spinner.gif'
certificateFile: process.env.SIGN_WIN_CERTIFICATE_FILE
certificatePassword: process.env.SIGN_WIN_CERTIFICATE_PASSWORD
setupIcon: './build/resources/win/setup.ico'
iconUrl: 'https://raw.githubusercontent.com/Aluxian/electron-superkit/master/resources/win/app.ico'
remoteReleases: manifest.repository.url
.then callback, callback
], done
# Create the win32 portable zip
gulp.task 'pack:win32:portable', ['build:win32', 'clean:dist:win32'], (done) ->
if process.platform isnt 'win32'
console.warn 'Skipping win32 portable packing; This only works on Windows due to signtool.'
return done()
for envName in ['SIGN_WIN_CERTIFICATE_FILE', 'SIGN_WIN_CERTIFICATE_PASSWORD']
if not process.env[envName]
console.warn envName + ' env var not set.'
return done()
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage, './build/win32/resources/app', './build/win32/resources/app.asar'
# Remove leftovers
async.apply del, './build/win32/resources/app'
# Sign the exe
(callback) ->
cp.exec [
if process.env.SIGNTOOL_PATH then '"' + process.env.SIGNTOOL_PATH + '"' else 'signtool'
'sign'
'/f ' + process.env.SIGN_WIN_CERTIFICATE_FILE
'/p ' + process.env.SIGN_WIN_CERTIFICATE_PASSWORD
path.win32.resolve './build/win32/' + manifest.productName + '.exe'
].join(' '), callback
# Archive the files
(callback) ->
gulp.src './build/win32/**/*'
.pipe zip manifest.name + '-win32-portable.zip'
.pipe gulp.dest './dist'
.on 'end', callback
], done
# Pack for all the platforms
gulp.task 'pack', [
'pack:darwin64'
'pack:linux32'
'pack:linux64'
'pack:win32:installer'
'pack:win32:portable'
]
| 220033 | cp = require 'child_process'
path = require 'path'
fs = require 'fs'
asar = require 'asar'
async = require 'async'
del = require 'del'
gulp = require 'gulp'
zip = require 'gulp-zip'
winInstaller = require 'electron-windows-installer'
manifest = require '../src/package.json'
# Sign the app and create a dmg for darwin64; only works on OS X because of appdmg and codesign
gulp.task 'pack:darwin64', ['build:darwin64', 'clean:dist:darwin64'], (done) ->
if process.platform isnt 'darwin'
console.warn 'Skipping darwin64 packing; This only works on darwin due to `appdmg` and the `codesign` command.'
return done()
try
appdmg = require 'appdmg'
catch ex
console.warn 'Skipping darwin64 packing; `appdmg` not installed.'
return done()
for envName in ['SIGN_DARWIN_KEYCHAIN_PASSWORD', 'SIGN_DARWIN_KEYCHAIN_NAME', 'SIGN_DARWIN_IDENTITY']
if not process.env[envName]
console.warn envName + ' env var not set.'
return done()
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage,
'./build/darwin64/' + manifest.productName + '.app/Contents/Resources/app',
'./build/darwin64/' + manifest.productName + '.app/Contents/Resources/app.asar'
# Remove leftovers
async.apply del, './build/darwin64/' + manifest.productName + '.app/Contents/Resources/app'
# Unlock the keychain
async.apply cp.exec, [
'security'
'unlock-keychain'
'-p'
process.env.SIGN_DARWIN_KEYCHAIN_PASSWORD
process.env.SIGN_DARWIN_KEYCHAIN_NAME
].join(' ')
# Sign the app package
async.apply cp.exec, [
'codesign'
'--deep'
'--force'
'--verbose'
'--sign "' + process.env.SIGN_DARWIN_IDENTITY + '"'
'./build/darwin64/' + manifest.productName + '.app'
].join(' ')
# Create the dmg
(callback) ->
appdmg
source: './build/resources/darwin/dmg.json'
target: './dist/' + manifest.productName + '.dmg'
.on 'finish', callback
.on 'error', callback
], done
# Create deb and rpm packages for linux32 and linux64
[32, 64].forEach (arch) ->
['deb', 'rpm'].forEach (target) ->
gulp.task 'pack:linux' + arch + ':' + target, ['build:linux' + arch, 'clean:dist:linux' + arch], (done) ->
if arch == 32
archName = 'i386'
else if target is 'deb'
archName = 'amd64'
else
archName = 'x86_64'
args = [
'-s dir'
'-t ' + target
'--architecture ' + archName
'--rpm-os linux'
'--name ' + manifest.name
'--force' # Overwrite existing files
'--after-install ./build/resources/linux/after-install.sh'
'--after-remove ./build/resources/linux/after-remove.sh'
'--deb-changelog ./CHANGELOG.md'
'--rpm-changelog ./CHANGELOG.md'
'--license ' + manifest.license
'--category "' + manifest.linux.section + '"'
'--description "' + manifest.description + '"'
'--url "' + manifest.homepage + '"'
'--maintainer "' + manifest.author + '"'
'--version "' + manifest.version + '"'
'--package ' + './dist/' + manifest.name + '-VERSION-ARCH.' + target
'-C ./build/linux' + arch
'.'
]
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage,
'./build/linux' + arch + '/opt/' + manifest.name + '/resources/app',
'./build/linux' + arch + '/opt/' + manifest.name + '/resources/app.asar'
# Remove leftovers
async.apply del, './build/linux' + arch + '/opt/' + manifest.name + '/resources/app'
# Create a file with the target name
async.apply fs.writeFile, './build/linux' + arch + '/opt/' + manifest.name + '/pkgtarget', target
# Package the app
async.apply cp.exec, 'fpm ' + args.join(' ')
], done
# Create the win32 installer; only works on Windows
gulp.task 'pack:win32:installer', ['build:win32', 'clean:dist:win32'], (done) ->
if process.platform isnt 'win32'
return console.warn 'Skipping win32 installer packing; This only works on Windows due to Squirrel.Windows.'
for envName in ['SIGN_WIN_CERTIFICATE_FILE', 'SIGN_WIN_CERTIFICATE_PASSWORD']
if not process.env[envName]
return console.warn envName + ' env var not set.'
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage, './build/win32/resources/app', './build/win32/resources/app.asar'
# Remove leftovers
async.apply del, './build/win32/resources/app'
# Create the installer
(callback) ->
winInstaller
appDirectory: './build/win32'
outputDirectory: './dist'
loadingGif: './build/resources/win/install-spinner.gif'
certificateFile: process.env.SIGN_WIN_CERTIFICATE_FILE
certificatePassword: <PASSWORD>.env.SIGN_WIN_CERTIFICATE_PASSWORD
setupIcon: './build/resources/win/setup.ico'
iconUrl: 'https://raw.githubusercontent.com/Aluxian/electron-superkit/master/resources/win/app.ico'
remoteReleases: manifest.repository.url
.then callback, callback
], done
# Create the win32 portable zip
gulp.task 'pack:win32:portable', ['build:win32', 'clean:dist:win32'], (done) ->
if process.platform isnt 'win32'
console.warn 'Skipping win32 portable packing; This only works on Windows due to signtool.'
return done()
for envName in ['SIGN_WIN_CERTIFICATE_FILE', 'SIGN_WIN_CERTIFICATE_PASSWORD']
if not process.env[envName]
console.warn envName + ' env var not set.'
return done()
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage, './build/win32/resources/app', './build/win32/resources/app.asar'
# Remove leftovers
async.apply del, './build/win32/resources/app'
# Sign the exe
(callback) ->
cp.exec [
if process.env.SIGNTOOL_PATH then '"' + process.env.SIGNTOOL_PATH + '"' else 'signtool'
'sign'
'/f ' + process.env.SIGN_WIN_CERTIFICATE_FILE
'/p ' + process.env.SIGN_WIN_CERTIFICATE_PASSWORD
path.win32.resolve './build/win32/' + manifest.productName + '.exe'
].join(' '), callback
# Archive the files
(callback) ->
gulp.src './build/win32/**/*'
.pipe zip manifest.name + '-win32-portable.zip'
.pipe gulp.dest './dist'
.on 'end', callback
], done
# Pack for all the platforms
gulp.task 'pack', [
'pack:darwin64'
'pack:linux32'
'pack:linux64'
'pack:win32:installer'
'pack:win32:portable'
]
| true | cp = require 'child_process'
path = require 'path'
fs = require 'fs'
asar = require 'asar'
async = require 'async'
del = require 'del'
gulp = require 'gulp'
zip = require 'gulp-zip'
winInstaller = require 'electron-windows-installer'
manifest = require '../src/package.json'
# Sign the app and create a dmg for darwin64; only works on OS X because of appdmg and codesign
gulp.task 'pack:darwin64', ['build:darwin64', 'clean:dist:darwin64'], (done) ->
if process.platform isnt 'darwin'
console.warn 'Skipping darwin64 packing; This only works on darwin due to `appdmg` and the `codesign` command.'
return done()
try
appdmg = require 'appdmg'
catch ex
console.warn 'Skipping darwin64 packing; `appdmg` not installed.'
return done()
for envName in ['SIGN_DARWIN_KEYCHAIN_PASSWORD', 'SIGN_DARWIN_KEYCHAIN_NAME', 'SIGN_DARWIN_IDENTITY']
if not process.env[envName]
console.warn envName + ' env var not set.'
return done()
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage,
'./build/darwin64/' + manifest.productName + '.app/Contents/Resources/app',
'./build/darwin64/' + manifest.productName + '.app/Contents/Resources/app.asar'
# Remove leftovers
async.apply del, './build/darwin64/' + manifest.productName + '.app/Contents/Resources/app'
# Unlock the keychain
async.apply cp.exec, [
'security'
'unlock-keychain'
'-p'
process.env.SIGN_DARWIN_KEYCHAIN_PASSWORD
process.env.SIGN_DARWIN_KEYCHAIN_NAME
].join(' ')
# Sign the app package
async.apply cp.exec, [
'codesign'
'--deep'
'--force'
'--verbose'
'--sign "' + process.env.SIGN_DARWIN_IDENTITY + '"'
'./build/darwin64/' + manifest.productName + '.app'
].join(' ')
# Create the dmg
(callback) ->
appdmg
source: './build/resources/darwin/dmg.json'
target: './dist/' + manifest.productName + '.dmg'
.on 'finish', callback
.on 'error', callback
], done
# Create deb and rpm packages for linux32 and linux64
[32, 64].forEach (arch) ->
['deb', 'rpm'].forEach (target) ->
gulp.task 'pack:linux' + arch + ':' + target, ['build:linux' + arch, 'clean:dist:linux' + arch], (done) ->
if arch == 32
archName = 'i386'
else if target is 'deb'
archName = 'amd64'
else
archName = 'x86_64'
args = [
'-s dir'
'-t ' + target
'--architecture ' + archName
'--rpm-os linux'
'--name ' + manifest.name
'--force' # Overwrite existing files
'--after-install ./build/resources/linux/after-install.sh'
'--after-remove ./build/resources/linux/after-remove.sh'
'--deb-changelog ./CHANGELOG.md'
'--rpm-changelog ./CHANGELOG.md'
'--license ' + manifest.license
'--category "' + manifest.linux.section + '"'
'--description "' + manifest.description + '"'
'--url "' + manifest.homepage + '"'
'--maintainer "' + manifest.author + '"'
'--version "' + manifest.version + '"'
'--package ' + './dist/' + manifest.name + '-VERSION-ARCH.' + target
'-C ./build/linux' + arch
'.'
]
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage,
'./build/linux' + arch + '/opt/' + manifest.name + '/resources/app',
'./build/linux' + arch + '/opt/' + manifest.name + '/resources/app.asar'
# Remove leftovers
async.apply del, './build/linux' + arch + '/opt/' + manifest.name + '/resources/app'
# Create a file with the target name
async.apply fs.writeFile, './build/linux' + arch + '/opt/' + manifest.name + '/pkgtarget', target
# Package the app
async.apply cp.exec, 'fpm ' + args.join(' ')
], done
# Create the win32 installer; only works on Windows
gulp.task 'pack:win32:installer', ['build:win32', 'clean:dist:win32'], (done) ->
if process.platform isnt 'win32'
return console.warn 'Skipping win32 installer packing; This only works on Windows due to Squirrel.Windows.'
for envName in ['SIGN_WIN_CERTIFICATE_FILE', 'SIGN_WIN_CERTIFICATE_PASSWORD']
if not process.env[envName]
return console.warn envName + ' env var not set.'
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage, './build/win32/resources/app', './build/win32/resources/app.asar'
# Remove leftovers
async.apply del, './build/win32/resources/app'
# Create the installer
(callback) ->
winInstaller
appDirectory: './build/win32'
outputDirectory: './dist'
loadingGif: './build/resources/win/install-spinner.gif'
certificateFile: process.env.SIGN_WIN_CERTIFICATE_FILE
certificatePassword: PI:PASSWORD:<PASSWORD>END_PI.env.SIGN_WIN_CERTIFICATE_PASSWORD
setupIcon: './build/resources/win/setup.ico'
iconUrl: 'https://raw.githubusercontent.com/Aluxian/electron-superkit/master/resources/win/app.ico'
remoteReleases: manifest.repository.url
.then callback, callback
], done
# Create the win32 portable zip
gulp.task 'pack:win32:portable', ['build:win32', 'clean:dist:win32'], (done) ->
if process.platform isnt 'win32'
console.warn 'Skipping win32 portable packing; This only works on Windows due to signtool.'
return done()
for envName in ['SIGN_WIN_CERTIFICATE_FILE', 'SIGN_WIN_CERTIFICATE_PASSWORD']
if not process.env[envName]
console.warn envName + ' env var not set.'
return done()
async.series [
# First, compress the source files into an asar archive
async.apply asar.createPackage, './build/win32/resources/app', './build/win32/resources/app.asar'
# Remove leftovers
async.apply del, './build/win32/resources/app'
# Sign the exe
(callback) ->
cp.exec [
if process.env.SIGNTOOL_PATH then '"' + process.env.SIGNTOOL_PATH + '"' else 'signtool'
'sign'
'/f ' + process.env.SIGN_WIN_CERTIFICATE_FILE
'/p ' + process.env.SIGN_WIN_CERTIFICATE_PASSWORD
path.win32.resolve './build/win32/' + manifest.productName + '.exe'
].join(' '), callback
# Archive the files
(callback) ->
gulp.src './build/win32/**/*'
.pipe zip manifest.name + '-win32-portable.zip'
.pipe gulp.dest './dist'
.on 'end', callback
], done
# Pack for all the platforms
gulp.task 'pack', [
'pack:darwin64'
'pack:linux32'
'pack:linux64'
'pack:win32:installer'
'pack:win32:portable'
]
|
[
{
"context": ", 0, 1, 2]\n uuid: 'fakeUUID'\n key: 'sadness'\n }\n {\n type: 'linearTracker'\n ",
"end": 2672,
"score": 0.8055868148803711,
"start": 2665,
"tag": "USERNAME",
"value": "sadness"
},
{
"context": ", 1, 2]\n uuid: 'fakeUUID'\n key: 'hogwarts'\n }\n {\n type: 'switcher'\n ",
"end": 3877,
"score": 0.8953969478607178,
"start": 3872,
"tag": "USERNAME",
"value": "warts"
},
{
"context": ", 3, 4, 2]\n uuid: 'fakeUUID'\n key: 'torso'\n }\n {\n type: 'text'\n nam",
"end": 4610,
"score": 0.7529150247573853,
"start": 4605,
"tag": "KEY",
"value": "torso"
},
{
"context": "ype: 'text'\n name: 'Hello'\n value: \"Boom\"\n pos: [8, 5, 4, 1]\n uuid: 'fake",
"end": 4688,
"score": 0.6702665090560913,
"start": 4687,
"tag": "NAME",
"value": "B"
}
] | public-source/javascripts/data/demoPanel.coffee | lekevicius/vijual | 1 | App.data.demoPanel = [
{
name: 'Gradient Color From'
uuid: 'fake'
color: 3
controls: [
{
type: 'slider'
color: '#d31f1f'
name: 'Red'
value: 0.31
pos: [0, 0, 1, 3]
uuid: 'fakeUUID'
key: 'red'
}
{
type: 'slider'
color: '#30c429'
name: 'Green'
value: 0.61
pos: [1, 0, 1, 3]
uuid: 'fakeUUID'
key: 'green'
}
{
type: 'slider'
color: '#1f71cd'
name: 'Blue'
value: 0.92
pos: [2, 0, 1, 3]
uuid: 'fakeUUID'
key: 'blue'
}
{
type: 'integerSlider'
color: '#cc8700'
name: 'Hue'
value: 230
max: 360
pos: [3, 0, 3, 1]
uuid: 'fakeUUID'
key: 'hue'
}
{
type: 'slider'
color: '#aaa'
name: 'Satur'
value: 0.5
pos: [3, 1, 3, 1]
uuid: 'fakeUUID'
key: 'saturation'
}
{
type: 'slider'
color: '#aaa'
name: 'Bright'
value: 0.5
pos: [3, 2, 3, 1]
uuid: 'fakeUUID'
key: 'brightness'
}
{
type: 'color'
name: 'Color'
value: '#8abd28'
pos: [6, 0, 4, 3]
uuid: 'fakeUUID'
key: 'color'
}
{
type: 'switcher'
name: 'PickerType'
options: [ 'Picker', 'Swatch' ]
value: 0
pos: [10, 0, 2, 1]
uuid: 'fakeUUID'
key: 'swatcher'
}
{
type: 'toggle'
name: 'Invert'
value: true
pos: [10, 1, 1, 2]
uuid: 'fakeUUID'
key: 'inversion'
}
{
type: 'triggerButton'
name: 'Save'
pos: [11, 1, 1, 1]
uuid: 'fakeUUID'
key: 'save'
}
{
type: 'holdButton'
name: 'Pulse'
pos: [11, 2, 1, 1]
uuid: 'fakeUUID'
key: 'pulse'
}
]
}
{
name: 'Behavior Properties'
uuid: 'faker'
color: 16
controls: [
{
type: 'knob'
name: 'Activity'
value: 0.6
pos: [0, 0, 2, 3]
uuid: 'fakeUUID'
key: 'activity'
}
{
type: 'angle'
name: 'Angle'
value: 2.1
pos: [2, 0, 2, 3]
uuid: 'fakeUUID'
key: 'angle'
}
{
type: 'knob'
name: 'Fun'
value: 0.8
pos: [4, 0, 1, 2]
uuid: 'fakeUUID'
key: 'fun'
}
{
type: 'angle'
name: 'Sad'
value: 1.2
pos: [5, 0, 1, 2]
uuid: 'fakeUUID'
key: 'sadness'
}
{
type: 'linearTracker'
name: 'Pos.Z'
value: 110
pos: [6, 0, 1, 2]
uuid: 'fakeUUID'
key: 'position.z'
}
{
type: 'linearTracker'
name: 'Pos.X'
value: 0.3
pos: [4, 2, 3, 1]
uuid: 'fakeUUID'
key: 'position.x'
}
{
type: 'exponentialTracker'
name: 'Pos.Y'
value: 12
pos: [7, 0, 1, 3]
uuid: 'fakeUUID'
key: 'position.y'
}
{
type: 'list'
name: 'Wave Function'
options: [ 'Sine', 'Sawtooth', 'Square', 'Triangle', 'Noise' ]
value: 1
pos: [8, 0, 4, 3]
uuid: 'fakeUUID'
key: 'wave'
}
{
type: 'area'
name: 'Head'
value: [0.2, 0.3]
pos: [0, 3, 4, 3]
uuid: 'fakeUUID'
key: 'head'
}
{
type: 'stepper'
name: 'Corners'
value: 2
pos: [4, 3, 2, 1]
uuid: 'fakeUUID'
key: 'corners'
}
{
type: 'stepper'
name: 'Points'
value: 10
step: 10
pos: [4, 4, 1, 2]
uuid: 'fakeUUID'
key: 'hogwarts'
}
{
type: 'switcher'
name: 'Move'
options: [ 'Forward', 'Stop', 'Backward' ]
value: 0
pos: [5, 4, 1, 2]
uuid: 'fakeUUID'
key: 'movetype'
}
{
type: 'integerSlider'
name: 'Right Arm'
value: 13
min: 10
max: 30
pos: [6, 3, 1, 3]
uuid: 'fakeUUID'
key: 'rightarm'
}
{
type: 'slider'
name: 'Left Arm'
step: 0.2
value: 0.6
pos: [7, 3, 1, 3]
uuid: 'fakeUUID'
key: 'leftarm'
}
{
type: 'area'
name: 'Torso'
value: [1, 0.23]
pos: [8, 3, 4, 2]
uuid: 'fakeUUID'
key: 'torso'
}
{
type: 'text'
name: 'Hello'
value: "Boom"
pos: [8, 5, 4, 1]
uuid: 'fakeUUID'
key: 'hello'
}
]
}
{
name: 'Media Things'
uuid: 'faker'
color: 20
controls: [
{
type: 'media'
name: 'Image'
options: ["European-Union.png", "IMG_3381.JPG", "IMG_3392.JPG", "IMG_3393.JPG", "IMG_3402.JPG", "colors-gather.jpg", "ic_action_call.png", "play-store.png"]
value: 'play-store.png'
pos: [0, 0, 4, 3]
uuid: 'fakeUUID'
key: 'wave'
}
{
type: 'knob'
name: 'Activity'
value: 0.6
pos: [8, 0, 2, 2]
uuid: 'fakeUUID'
key: 'activity'
}
{
type: 'knob'
name: 'Angle'
value: 0.1
pos: [10, 0, 2, 2]
uuid: 'fakeUUID'
key: 'angle'
}
{
type: 'area'
name: 'Head'
value: [0.2, 0.3]
pos: [4, 0, 4, 3]
uuid: 'fakeUUID'
key: 'head'
}
{
type: 'input'
name: 'Input 1'
value: 0.4
dataType: 'float'
pos: [8, 2, 1, 1]
uuid: 'fakeUUID'
key: 'input1'
}
{
type: 'input'
name: 'Input 2'
value: 21
dataType: 'integer'
pos: [9, 2, 1, 1]
uuid: 'fakeUUID'
key: 'input2'
}
{
type: 'output'
name: 'Output 1'
value: 21.1
dataType: 'float'
pos: [10, 2, 1, 1]
uuid: 'fakeUUID'
key: 'output1'
}
{
type: 'output'
name: 'Output 2'
value: 12
dataType: 'integer'
pos: [11, 2, 1, 1]
uuid: 'fakeUUID'
key: 'output2'
}
]
}
]
| 21801 | App.data.demoPanel = [
{
name: 'Gradient Color From'
uuid: 'fake'
color: 3
controls: [
{
type: 'slider'
color: '#d31f1f'
name: 'Red'
value: 0.31
pos: [0, 0, 1, 3]
uuid: 'fakeUUID'
key: 'red'
}
{
type: 'slider'
color: '#30c429'
name: 'Green'
value: 0.61
pos: [1, 0, 1, 3]
uuid: 'fakeUUID'
key: 'green'
}
{
type: 'slider'
color: '#1f71cd'
name: 'Blue'
value: 0.92
pos: [2, 0, 1, 3]
uuid: 'fakeUUID'
key: 'blue'
}
{
type: 'integerSlider'
color: '#cc8700'
name: 'Hue'
value: 230
max: 360
pos: [3, 0, 3, 1]
uuid: 'fakeUUID'
key: 'hue'
}
{
type: 'slider'
color: '#aaa'
name: 'Satur'
value: 0.5
pos: [3, 1, 3, 1]
uuid: 'fakeUUID'
key: 'saturation'
}
{
type: 'slider'
color: '#aaa'
name: 'Bright'
value: 0.5
pos: [3, 2, 3, 1]
uuid: 'fakeUUID'
key: 'brightness'
}
{
type: 'color'
name: 'Color'
value: '#8abd28'
pos: [6, 0, 4, 3]
uuid: 'fakeUUID'
key: 'color'
}
{
type: 'switcher'
name: 'PickerType'
options: [ 'Picker', 'Swatch' ]
value: 0
pos: [10, 0, 2, 1]
uuid: 'fakeUUID'
key: 'swatcher'
}
{
type: 'toggle'
name: 'Invert'
value: true
pos: [10, 1, 1, 2]
uuid: 'fakeUUID'
key: 'inversion'
}
{
type: 'triggerButton'
name: 'Save'
pos: [11, 1, 1, 1]
uuid: 'fakeUUID'
key: 'save'
}
{
type: 'holdButton'
name: 'Pulse'
pos: [11, 2, 1, 1]
uuid: 'fakeUUID'
key: 'pulse'
}
]
}
{
name: 'Behavior Properties'
uuid: 'faker'
color: 16
controls: [
{
type: 'knob'
name: 'Activity'
value: 0.6
pos: [0, 0, 2, 3]
uuid: 'fakeUUID'
key: 'activity'
}
{
type: 'angle'
name: 'Angle'
value: 2.1
pos: [2, 0, 2, 3]
uuid: 'fakeUUID'
key: 'angle'
}
{
type: 'knob'
name: 'Fun'
value: 0.8
pos: [4, 0, 1, 2]
uuid: 'fakeUUID'
key: 'fun'
}
{
type: 'angle'
name: 'Sad'
value: 1.2
pos: [5, 0, 1, 2]
uuid: 'fakeUUID'
key: 'sadness'
}
{
type: 'linearTracker'
name: 'Pos.Z'
value: 110
pos: [6, 0, 1, 2]
uuid: 'fakeUUID'
key: 'position.z'
}
{
type: 'linearTracker'
name: 'Pos.X'
value: 0.3
pos: [4, 2, 3, 1]
uuid: 'fakeUUID'
key: 'position.x'
}
{
type: 'exponentialTracker'
name: 'Pos.Y'
value: 12
pos: [7, 0, 1, 3]
uuid: 'fakeUUID'
key: 'position.y'
}
{
type: 'list'
name: 'Wave Function'
options: [ 'Sine', 'Sawtooth', 'Square', 'Triangle', 'Noise' ]
value: 1
pos: [8, 0, 4, 3]
uuid: 'fakeUUID'
key: 'wave'
}
{
type: 'area'
name: 'Head'
value: [0.2, 0.3]
pos: [0, 3, 4, 3]
uuid: 'fakeUUID'
key: 'head'
}
{
type: 'stepper'
name: 'Corners'
value: 2
pos: [4, 3, 2, 1]
uuid: 'fakeUUID'
key: 'corners'
}
{
type: 'stepper'
name: 'Points'
value: 10
step: 10
pos: [4, 4, 1, 2]
uuid: 'fakeUUID'
key: 'hogwarts'
}
{
type: 'switcher'
name: 'Move'
options: [ 'Forward', 'Stop', 'Backward' ]
value: 0
pos: [5, 4, 1, 2]
uuid: 'fakeUUID'
key: 'movetype'
}
{
type: 'integerSlider'
name: 'Right Arm'
value: 13
min: 10
max: 30
pos: [6, 3, 1, 3]
uuid: 'fakeUUID'
key: 'rightarm'
}
{
type: 'slider'
name: 'Left Arm'
step: 0.2
value: 0.6
pos: [7, 3, 1, 3]
uuid: 'fakeUUID'
key: 'leftarm'
}
{
type: 'area'
name: 'Torso'
value: [1, 0.23]
pos: [8, 3, 4, 2]
uuid: 'fakeUUID'
key: '<KEY>'
}
{
type: 'text'
name: 'Hello'
value: "<NAME>oom"
pos: [8, 5, 4, 1]
uuid: 'fakeUUID'
key: 'hello'
}
]
}
{
name: 'Media Things'
uuid: 'faker'
color: 20
controls: [
{
type: 'media'
name: 'Image'
options: ["European-Union.png", "IMG_3381.JPG", "IMG_3392.JPG", "IMG_3393.JPG", "IMG_3402.JPG", "colors-gather.jpg", "ic_action_call.png", "play-store.png"]
value: 'play-store.png'
pos: [0, 0, 4, 3]
uuid: 'fakeUUID'
key: 'wave'
}
{
type: 'knob'
name: 'Activity'
value: 0.6
pos: [8, 0, 2, 2]
uuid: 'fakeUUID'
key: 'activity'
}
{
type: 'knob'
name: 'Angle'
value: 0.1
pos: [10, 0, 2, 2]
uuid: 'fakeUUID'
key: 'angle'
}
{
type: 'area'
name: 'Head'
value: [0.2, 0.3]
pos: [4, 0, 4, 3]
uuid: 'fakeUUID'
key: 'head'
}
{
type: 'input'
name: 'Input 1'
value: 0.4
dataType: 'float'
pos: [8, 2, 1, 1]
uuid: 'fakeUUID'
key: 'input1'
}
{
type: 'input'
name: 'Input 2'
value: 21
dataType: 'integer'
pos: [9, 2, 1, 1]
uuid: 'fakeUUID'
key: 'input2'
}
{
type: 'output'
name: 'Output 1'
value: 21.1
dataType: 'float'
pos: [10, 2, 1, 1]
uuid: 'fakeUUID'
key: 'output1'
}
{
type: 'output'
name: 'Output 2'
value: 12
dataType: 'integer'
pos: [11, 2, 1, 1]
uuid: 'fakeUUID'
key: 'output2'
}
]
}
]
| true | App.data.demoPanel = [
{
name: 'Gradient Color From'
uuid: 'fake'
color: 3
controls: [
{
type: 'slider'
color: '#d31f1f'
name: 'Red'
value: 0.31
pos: [0, 0, 1, 3]
uuid: 'fakeUUID'
key: 'red'
}
{
type: 'slider'
color: '#30c429'
name: 'Green'
value: 0.61
pos: [1, 0, 1, 3]
uuid: 'fakeUUID'
key: 'green'
}
{
type: 'slider'
color: '#1f71cd'
name: 'Blue'
value: 0.92
pos: [2, 0, 1, 3]
uuid: 'fakeUUID'
key: 'blue'
}
{
type: 'integerSlider'
color: '#cc8700'
name: 'Hue'
value: 230
max: 360
pos: [3, 0, 3, 1]
uuid: 'fakeUUID'
key: 'hue'
}
{
type: 'slider'
color: '#aaa'
name: 'Satur'
value: 0.5
pos: [3, 1, 3, 1]
uuid: 'fakeUUID'
key: 'saturation'
}
{
type: 'slider'
color: '#aaa'
name: 'Bright'
value: 0.5
pos: [3, 2, 3, 1]
uuid: 'fakeUUID'
key: 'brightness'
}
{
type: 'color'
name: 'Color'
value: '#8abd28'
pos: [6, 0, 4, 3]
uuid: 'fakeUUID'
key: 'color'
}
{
type: 'switcher'
name: 'PickerType'
options: [ 'Picker', 'Swatch' ]
value: 0
pos: [10, 0, 2, 1]
uuid: 'fakeUUID'
key: 'swatcher'
}
{
type: 'toggle'
name: 'Invert'
value: true
pos: [10, 1, 1, 2]
uuid: 'fakeUUID'
key: 'inversion'
}
{
type: 'triggerButton'
name: 'Save'
pos: [11, 1, 1, 1]
uuid: 'fakeUUID'
key: 'save'
}
{
type: 'holdButton'
name: 'Pulse'
pos: [11, 2, 1, 1]
uuid: 'fakeUUID'
key: 'pulse'
}
]
}
{
name: 'Behavior Properties'
uuid: 'faker'
color: 16
controls: [
{
type: 'knob'
name: 'Activity'
value: 0.6
pos: [0, 0, 2, 3]
uuid: 'fakeUUID'
key: 'activity'
}
{
type: 'angle'
name: 'Angle'
value: 2.1
pos: [2, 0, 2, 3]
uuid: 'fakeUUID'
key: 'angle'
}
{
type: 'knob'
name: 'Fun'
value: 0.8
pos: [4, 0, 1, 2]
uuid: 'fakeUUID'
key: 'fun'
}
{
type: 'angle'
name: 'Sad'
value: 1.2
pos: [5, 0, 1, 2]
uuid: 'fakeUUID'
key: 'sadness'
}
{
type: 'linearTracker'
name: 'Pos.Z'
value: 110
pos: [6, 0, 1, 2]
uuid: 'fakeUUID'
key: 'position.z'
}
{
type: 'linearTracker'
name: 'Pos.X'
value: 0.3
pos: [4, 2, 3, 1]
uuid: 'fakeUUID'
key: 'position.x'
}
{
type: 'exponentialTracker'
name: 'Pos.Y'
value: 12
pos: [7, 0, 1, 3]
uuid: 'fakeUUID'
key: 'position.y'
}
{
type: 'list'
name: 'Wave Function'
options: [ 'Sine', 'Sawtooth', 'Square', 'Triangle', 'Noise' ]
value: 1
pos: [8, 0, 4, 3]
uuid: 'fakeUUID'
key: 'wave'
}
{
type: 'area'
name: 'Head'
value: [0.2, 0.3]
pos: [0, 3, 4, 3]
uuid: 'fakeUUID'
key: 'head'
}
{
type: 'stepper'
name: 'Corners'
value: 2
pos: [4, 3, 2, 1]
uuid: 'fakeUUID'
key: 'corners'
}
{
type: 'stepper'
name: 'Points'
value: 10
step: 10
pos: [4, 4, 1, 2]
uuid: 'fakeUUID'
key: 'hogwarts'
}
{
type: 'switcher'
name: 'Move'
options: [ 'Forward', 'Stop', 'Backward' ]
value: 0
pos: [5, 4, 1, 2]
uuid: 'fakeUUID'
key: 'movetype'
}
{
type: 'integerSlider'
name: 'Right Arm'
value: 13
min: 10
max: 30
pos: [6, 3, 1, 3]
uuid: 'fakeUUID'
key: 'rightarm'
}
{
type: 'slider'
name: 'Left Arm'
step: 0.2
value: 0.6
pos: [7, 3, 1, 3]
uuid: 'fakeUUID'
key: 'leftarm'
}
{
type: 'area'
name: 'Torso'
value: [1, 0.23]
pos: [8, 3, 4, 2]
uuid: 'fakeUUID'
key: 'PI:KEY:<KEY>END_PI'
}
{
type: 'text'
name: 'Hello'
value: "PI:NAME:<NAME>END_PIoom"
pos: [8, 5, 4, 1]
uuid: 'fakeUUID'
key: 'hello'
}
]
}
{
name: 'Media Things'
uuid: 'faker'
color: 20
controls: [
{
type: 'media'
name: 'Image'
options: ["European-Union.png", "IMG_3381.JPG", "IMG_3392.JPG", "IMG_3393.JPG", "IMG_3402.JPG", "colors-gather.jpg", "ic_action_call.png", "play-store.png"]
value: 'play-store.png'
pos: [0, 0, 4, 3]
uuid: 'fakeUUID'
key: 'wave'
}
{
type: 'knob'
name: 'Activity'
value: 0.6
pos: [8, 0, 2, 2]
uuid: 'fakeUUID'
key: 'activity'
}
{
type: 'knob'
name: 'Angle'
value: 0.1
pos: [10, 0, 2, 2]
uuid: 'fakeUUID'
key: 'angle'
}
{
type: 'area'
name: 'Head'
value: [0.2, 0.3]
pos: [4, 0, 4, 3]
uuid: 'fakeUUID'
key: 'head'
}
{
type: 'input'
name: 'Input 1'
value: 0.4
dataType: 'float'
pos: [8, 2, 1, 1]
uuid: 'fakeUUID'
key: 'input1'
}
{
type: 'input'
name: 'Input 2'
value: 21
dataType: 'integer'
pos: [9, 2, 1, 1]
uuid: 'fakeUUID'
key: 'input2'
}
{
type: 'output'
name: 'Output 1'
value: 21.1
dataType: 'float'
pos: [10, 2, 1, 1]
uuid: 'fakeUUID'
key: 'output1'
}
{
type: 'output'
name: 'Output 2'
value: 12
dataType: 'integer'
pos: [11, 2, 1, 1]
uuid: 'fakeUUID'
key: 'output2'
}
]
}
]
|
[
{
"context": " \n# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) \n# ",
"end": 824,
"score": 0.9998032450675964,
"start": 814,
"tag": "NAME",
"value": "Mark Masse"
}
] | wrmldoc/js/app/components/form/FormView.coffee | wrml/wrml | 47 | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 Mark Masse (OSS project WRML.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.
#
# CoffeeScript
@Wrmldoc.module "Components.Form", (Form, App, Backbone, Marionette, $, _) ->
class Form.FormWrapper extends App.Views.Layout
template: "form/form"
tagName: "form"
attributes: ->
"data-type": @getFormDataType()
regions:
formContentRegion: "#form-content-region"
ui:
buttonContainer: "ul.inline-list"
triggers:
"submit": "form:submit"
"click [data-form-button='cancel']": "form:cancel"
modelEvents:
"change:_errors": "changeErrors"
"sync:start": "syncStart"
"sync:stop": "syncStop"
initialize: ->
@setInstancePropertiesFor "config", "buttons"
serializeData: ->
footer: @config.footer
buttons: @buttons?.toJSON() ? false
onShow: ->
_.defer =>
@focusFirstInput() if @config.focusFirstInput
@buttonPlacement() if @buttons
buttonPlacement: ->
@ui.buttonContainer.addClass @buttons.placement
focusFirstInput: ->
@$(":input:visible:enabled:first").focus()
getFormDataType: ->
if @model.isNew() then "new" else "edit"
changeErrors: (model, errors, options) ->
if @config.errors
if _.isEmpty(errors) then @removeErrors() else @addErrors errors
removeErrors: ->
@$(".error").removeClass("error").find("small").remove()
addErrors: (errors = {}) ->
for name, array of errors
@addError name, array[0]
addError: (name, error) ->
el = @$("[name='#{name}']")
sm = $("<small>").text(error)
el.after(sm).closest(".row").addClass("error")
syncStart: (model) ->
@addOpacityWrapper() if @config.syncing
syncStop: (model) ->
@addOpacityWrapper(false) if @config.syncing | 217033 | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 <NAME> (OSS project WRML.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.
#
# CoffeeScript
@Wrmldoc.module "Components.Form", (Form, App, Backbone, Marionette, $, _) ->
class Form.FormWrapper extends App.Views.Layout
template: "form/form"
tagName: "form"
attributes: ->
"data-type": @getFormDataType()
regions:
formContentRegion: "#form-content-region"
ui:
buttonContainer: "ul.inline-list"
triggers:
"submit": "form:submit"
"click [data-form-button='cancel']": "form:cancel"
modelEvents:
"change:_errors": "changeErrors"
"sync:start": "syncStart"
"sync:stop": "syncStop"
initialize: ->
@setInstancePropertiesFor "config", "buttons"
serializeData: ->
footer: @config.footer
buttons: @buttons?.toJSON() ? false
onShow: ->
_.defer =>
@focusFirstInput() if @config.focusFirstInput
@buttonPlacement() if @buttons
buttonPlacement: ->
@ui.buttonContainer.addClass @buttons.placement
focusFirstInput: ->
@$(":input:visible:enabled:first").focus()
getFormDataType: ->
if @model.isNew() then "new" else "edit"
changeErrors: (model, errors, options) ->
if @config.errors
if _.isEmpty(errors) then @removeErrors() else @addErrors errors
removeErrors: ->
@$(".error").removeClass("error").find("small").remove()
addErrors: (errors = {}) ->
for name, array of errors
@addError name, array[0]
addError: (name, error) ->
el = @$("[name='#{name}']")
sm = $("<small>").text(error)
el.after(sm).closest(".row").addClass("error")
syncStart: (model) ->
@addOpacityWrapper() if @config.syncing
syncStop: (model) ->
@addOpacityWrapper(false) if @config.syncing | true | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 PI:NAME:<NAME>END_PI (OSS project WRML.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.
#
# CoffeeScript
@Wrmldoc.module "Components.Form", (Form, App, Backbone, Marionette, $, _) ->
class Form.FormWrapper extends App.Views.Layout
template: "form/form"
tagName: "form"
attributes: ->
"data-type": @getFormDataType()
regions:
formContentRegion: "#form-content-region"
ui:
buttonContainer: "ul.inline-list"
triggers:
"submit": "form:submit"
"click [data-form-button='cancel']": "form:cancel"
modelEvents:
"change:_errors": "changeErrors"
"sync:start": "syncStart"
"sync:stop": "syncStop"
initialize: ->
@setInstancePropertiesFor "config", "buttons"
serializeData: ->
footer: @config.footer
buttons: @buttons?.toJSON() ? false
onShow: ->
_.defer =>
@focusFirstInput() if @config.focusFirstInput
@buttonPlacement() if @buttons
buttonPlacement: ->
@ui.buttonContainer.addClass @buttons.placement
focusFirstInput: ->
@$(":input:visible:enabled:first").focus()
getFormDataType: ->
if @model.isNew() then "new" else "edit"
changeErrors: (model, errors, options) ->
if @config.errors
if _.isEmpty(errors) then @removeErrors() else @addErrors errors
removeErrors: ->
@$(".error").removeClass("error").find("small").remove()
addErrors: (errors = {}) ->
for name, array of errors
@addError name, array[0]
addError: (name, error) ->
el = @$("[name='#{name}']")
sm = $("<small>").text(error)
el.after(sm).closest(".row").addClass("error")
syncStart: (model) ->
@addOpacityWrapper() if @config.syncing
syncStop: (model) ->
@addOpacityWrapper(false) if @config.syncing |
[
{
"context": "n\\n')\n .on(/Enter the password:/).respond('p@ssw0rd\\n')\n .on(/Confirm the password/).respond('p@",
"end": 746,
"score": 0.9762868881225586,
"start": 736,
"tag": "PASSWORD",
"value": "p@ssw0rd\\n"
},
{
"context": "\\n')\n .on(/Confirm the password/).respond('p@ssw0rd\\n')\n .on(/encrypt your password/).respond('y",
"end": 804,
"score": 0.7710860967636108,
"start": 794,
"tag": "PASSWORD",
"value": "p@ssw0rd\\n"
},
{
"context": "\n process.env['MY_SECRET_DECRYPT_KEY'] = 'd€cypt'\n\n after ->\n process.env['MY_SECRET_D",
"end": 1568,
"score": 0.8112625479698181,
"start": 1563,
"tag": "KEY",
"value": "€cypt"
},
{
"context": "my.site.org\\n')\n .on(/user name/).respond('michael\\n')\n .on(/Enter the password:/).respond('p",
"end": 2529,
"score": 0.9959702491760254,
"start": 2522,
"tag": "USERNAME",
"value": "michael"
},
{
"context": "l\\n')\n .on(/Enter the password:/).respond('p@ssw0rd\\n')\n .on(/Confirm the password/).respond('p@",
"end": 2588,
"score": 0.9879308938980103,
"start": 2578,
"tag": "PASSWORD",
"value": "p@ssw0rd\\n"
},
{
"context": "\\n')\n .on(/Confirm the password/).respond('p@ssw0rd\\n')\n .on(/encrypt your password/).respond('n",
"end": 2646,
"score": 0.9844570159912109,
"start": 2636,
"tag": "PASSWORD",
"value": "p@ssw0rd\\n"
},
{
"context": "n\\n')\n .on(/Enter the password:/).respond('n€w_p@ssw0rd\\n')\n .on(/Confirm the password/",
"end": 3677,
"score": 0.620522677898407,
"start": 3676,
"tag": "PASSWORD",
"value": "n"
},
{
"context": " .on(/Enter the password:/).respond('n€w_p@ssw0rd\\n')\n .on(/Confirm the password/).respond('",
"end": 3688,
"score": 0.6095201969146729,
"start": 3682,
"tag": "PASSWORD",
"value": "ssw0rd"
},
{
"context": "\\n')\n .on(/Confirm the password/).respond('n€w_p@ssw0rd\\n')\n .on(/encrypt your password",
"end": 3739,
"score": 0.7102354168891907,
"start": 3738,
"tag": "PASSWORD",
"value": "n"
},
{
"context": "')\n .on(/Confirm the password/).respond('n€w_p@ssw0rd\\n')\n .on(/encrypt your password/)",
"end": 3741,
"score": 0.5302501320838928,
"start": 3740,
"tag": "PASSWORD",
"value": "w"
},
{
"context": "\n .on(/Confirm the password/).respond('n€w_p@ssw0rd\\n')\n .on(/encrypt your password/).respond(",
"end": 3750,
"score": 0.6370920538902283,
"start": 3742,
"tag": "PASSWORD",
"value": "p@ssw0rd"
},
{
"context": "auth.find('my.site.org').password()).to.be.equal('n€w_p@ssw0rd')\n\n describe 'list command', -> \n\n it 'shoul",
"end": 4637,
"score": 0.9778336882591248,
"start": 4625,
"tag": "PASSWORD",
"value": "n€w_p@ssw0rd"
},
{
"context": "\n\n suppose(\"#{cwd}/bin/authrc\", ['encrypt', 'p@s$w0rd'])\n .on(/Enter the password key/).respond(",
"end": 6063,
"score": 0.8200911283493042,
"start": 6055,
"tag": "PASSWORD",
"value": "p@s$w0rd"
},
{
"context": "on(/Enter the password key/).respond('my-d€crypt_k3y\\n')\n .error (err) ->\n throw new Err",
"end": 6130,
"score": 0.5862574577331543,
"start": 6126,
"tag": "PASSWORD",
"value": "3y\\n"
},
{
"context": "\n\n suppose(\"#{cwd}/bin/authrc\", ['decrypt', '8a87a8de71a9fab17af597dcd691d13d'])\n .on(/Enter the password key/).respond(",
"end": 6438,
"score": 0.9734185934066772,
"start": 6406,
"tag": "PASSWORD",
"value": "8a87a8de71a9fab17af597dcd691d13d"
},
{
"context": "/Enter the password key/).respond('my-d€crypt_k3y\\n')\n .error (err) ->\n throw new Err",
"end": 6505,
"score": 0.5093079805374146,
"start": 6504,
"tag": "PASSWORD",
"value": "n"
}
] | test/cliSpec.coffee | h2non/node-authrc | 1 | fs = require 'fs'
suppose = require 'suppose'
{ expect } = require 'chai'
Authrc = require '../lib/authrc'
cwd = process.cwd()
authrcPath = 'test/fixtures/tmp/'
fileExists = ->
fs.existsSync('.authrc')
removeFile = ->
fs.unlink '.authrc' if fileExists()
describe 'CLI', ->
auth = null
before ->
process.chdir authrcPath
removeFile()
after ->
removeFile()
process.chdir cwd
describe 'create command', ->
it 'should create a new .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['create'])
#.debug(fs.createWriteStream('../../cli.log'))
.on(/host name/).respond('my.server.org\n')
.on(/user name/).respond('john\n')
.on(/Enter the password:/).respond('p@ssw0rd\n')
.on(/Confirm the password/).respond('p@ssw0rd\n')
.on(/encrypt your password/).respond('y\n')
.on(/Choose the cipher/).respond('blowfish\n')
.on(/Enter the password key/).respond('d€cypt\n')
.on(/Confirm the password key/).respond('d€cypt\n')
.on(/Do you want to define a decrypt key/).respond('y\n')
.on(/Enter the decrypt key environment variable/).respond('MY_SECRET_DECRYPT_KEY\n')
.on(/Do you want to save/).respond('y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
before ->
process.env['MY_SECRET_DECRYPT_KEY'] = 'd€cypt'
after ->
process.env['MY_SECRET_DECRYPT_KEY'] = ''
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should exists the created host', ->
expect(auth.find('my.server.org').exists()).to.be.true
it 'should be a valid host', ->
expect(auth.find('my.server.org').valid()).to.be.true
it 'should have an encrypted password', ->
expect(auth.find('my.server.org').encrypted()).to.be.true
it 'should have the expected cipher', ->
expect(auth.find('my.server.org').cipher()).to.be.equal('blowfish')
it 'should can be transparently decrypted', ->
expect(auth.find('my.server.org').canDecrypt()).to.be.true
describe 'add command', ->
it 'should add a new host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['add'])
.on(/host name/).respond('my.site.org\n')
.on(/user name/).respond('michael\n')
.on(/Enter the password:/).respond('p@ssw0rd\n')
.on(/Confirm the password/).respond('p@ssw0rd\n')
.on(/encrypt your password/).respond('n\n')
.on(/Do you want to save/).respond('y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should exists the created host', ->
expect(auth.find('my.site.org').exists()).to.be.true
it 'should be a valid host', ->
expect(auth.find('my.site.org').valid()).to.be.true
it 'should not have an encrypted password', ->
expect(auth.find('my.site.org').encrypted()).to.be.false
describe 'update command', ->
it 'should add a update a host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['update', 'my.site.org'])
.on(/user name/).respond('john\n')
.on(/Enter the password:/).respond('n€w_p@ssw0rd\n')
.on(/Confirm the password/).respond('n€w_p@ssw0rd\n')
.on(/encrypt your password/).respond('n\n')
.on(/Do you want to save/).respond('y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should exists the created host', ->
expect(auth.find('my.site.org').exists()).to.be.true
it 'should be a valid host', ->
expect(auth.find('my.site.org').valid()).to.be.true
it 'should have the new username', ->
expect(auth.find('my.site.org').user()).to.be.equal('john')
it 'should have the new password', ->
expect(auth.find('my.site.org').password()).to.be.equal('n€w_p@ssw0rd')
describe 'list command', ->
it 'should list the existent hosts', (done) ->
suppose("#{cwd}/bin/authrc", ['list'])
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'copy command', ->
it 'should copy a host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['copy', 'my.site.org', 'new.site.org'])
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'remove command', ->
it 'should remove a host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['remove', 'my.site.org'])
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should be removed the host', ->
expect(auth.find('my.site.org').exists()).to.be.false
describe 'encrypt command', ->
it 'should encrypt a password property', (done) ->
suppose("#{cwd}/bin/authrc", ['encrypt', 'p@s$w0rd'])
.on(/Enter the password key/).respond('my-d€crypt_k3y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
done()
describe 'encrypt command', ->
it 'should encrypt a password property', (done) ->
suppose("#{cwd}/bin/authrc", ['decrypt', '8a87a8de71a9fab17af597dcd691d13d'])
.on(/Enter the password key/).respond('my-d€crypt_k3y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
done()
| 62636 | fs = require 'fs'
suppose = require 'suppose'
{ expect } = require 'chai'
Authrc = require '../lib/authrc'
cwd = process.cwd()
authrcPath = 'test/fixtures/tmp/'
fileExists = ->
fs.existsSync('.authrc')
removeFile = ->
fs.unlink '.authrc' if fileExists()
describe 'CLI', ->
auth = null
before ->
process.chdir authrcPath
removeFile()
after ->
removeFile()
process.chdir cwd
describe 'create command', ->
it 'should create a new .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['create'])
#.debug(fs.createWriteStream('../../cli.log'))
.on(/host name/).respond('my.server.org\n')
.on(/user name/).respond('john\n')
.on(/Enter the password:/).respond('<PASSWORD>')
.on(/Confirm the password/).respond('<PASSWORD>')
.on(/encrypt your password/).respond('y\n')
.on(/Choose the cipher/).respond('blowfish\n')
.on(/Enter the password key/).respond('d€cypt\n')
.on(/Confirm the password key/).respond('d€cypt\n')
.on(/Do you want to define a decrypt key/).respond('y\n')
.on(/Enter the decrypt key environment variable/).respond('MY_SECRET_DECRYPT_KEY\n')
.on(/Do you want to save/).respond('y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
before ->
process.env['MY_SECRET_DECRYPT_KEY'] = 'd<KEY>'
after ->
process.env['MY_SECRET_DECRYPT_KEY'] = ''
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should exists the created host', ->
expect(auth.find('my.server.org').exists()).to.be.true
it 'should be a valid host', ->
expect(auth.find('my.server.org').valid()).to.be.true
it 'should have an encrypted password', ->
expect(auth.find('my.server.org').encrypted()).to.be.true
it 'should have the expected cipher', ->
expect(auth.find('my.server.org').cipher()).to.be.equal('blowfish')
it 'should can be transparently decrypted', ->
expect(auth.find('my.server.org').canDecrypt()).to.be.true
describe 'add command', ->
it 'should add a new host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['add'])
.on(/host name/).respond('my.site.org\n')
.on(/user name/).respond('michael\n')
.on(/Enter the password:/).respond('<PASSWORD>')
.on(/Confirm the password/).respond('<PASSWORD>')
.on(/encrypt your password/).respond('n\n')
.on(/Do you want to save/).respond('y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should exists the created host', ->
expect(auth.find('my.site.org').exists()).to.be.true
it 'should be a valid host', ->
expect(auth.find('my.site.org').valid()).to.be.true
it 'should not have an encrypted password', ->
expect(auth.find('my.site.org').encrypted()).to.be.false
describe 'update command', ->
it 'should add a update a host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['update', 'my.site.org'])
.on(/user name/).respond('john\n')
.on(/Enter the password:/).respond('<PASSWORD>€w_p@<PASSWORD>\n')
.on(/Confirm the password/).respond('<PASSWORD>€<PASSWORD>_<PASSWORD>\n')
.on(/encrypt your password/).respond('n\n')
.on(/Do you want to save/).respond('y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should exists the created host', ->
expect(auth.find('my.site.org').exists()).to.be.true
it 'should be a valid host', ->
expect(auth.find('my.site.org').valid()).to.be.true
it 'should have the new username', ->
expect(auth.find('my.site.org').user()).to.be.equal('john')
it 'should have the new password', ->
expect(auth.find('my.site.org').password()).to.be.equal('<PASSWORD>')
describe 'list command', ->
it 'should list the existent hosts', (done) ->
suppose("#{cwd}/bin/authrc", ['list'])
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'copy command', ->
it 'should copy a host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['copy', 'my.site.org', 'new.site.org'])
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'remove command', ->
it 'should remove a host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['remove', 'my.site.org'])
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should be removed the host', ->
expect(auth.find('my.site.org').exists()).to.be.false
describe 'encrypt command', ->
it 'should encrypt a password property', (done) ->
suppose("#{cwd}/bin/authrc", ['encrypt', '<PASSWORD>'])
.on(/Enter the password key/).respond('my-d€crypt_k<PASSWORD>')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
done()
describe 'encrypt command', ->
it 'should encrypt a password property', (done) ->
suppose("#{cwd}/bin/authrc", ['decrypt', '<PASSWORD>'])
.on(/Enter the password key/).respond('my-d€crypt_k3y\<PASSWORD>')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
done()
| true | fs = require 'fs'
suppose = require 'suppose'
{ expect } = require 'chai'
Authrc = require '../lib/authrc'
cwd = process.cwd()
authrcPath = 'test/fixtures/tmp/'
fileExists = ->
fs.existsSync('.authrc')
removeFile = ->
fs.unlink '.authrc' if fileExists()
describe 'CLI', ->
auth = null
before ->
process.chdir authrcPath
removeFile()
after ->
removeFile()
process.chdir cwd
describe 'create command', ->
it 'should create a new .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['create'])
#.debug(fs.createWriteStream('../../cli.log'))
.on(/host name/).respond('my.server.org\n')
.on(/user name/).respond('john\n')
.on(/Enter the password:/).respond('PI:PASSWORD:<PASSWORD>END_PI')
.on(/Confirm the password/).respond('PI:PASSWORD:<PASSWORD>END_PI')
.on(/encrypt your password/).respond('y\n')
.on(/Choose the cipher/).respond('blowfish\n')
.on(/Enter the password key/).respond('d€cypt\n')
.on(/Confirm the password key/).respond('d€cypt\n')
.on(/Do you want to define a decrypt key/).respond('y\n')
.on(/Enter the decrypt key environment variable/).respond('MY_SECRET_DECRYPT_KEY\n')
.on(/Do you want to save/).respond('y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
before ->
process.env['MY_SECRET_DECRYPT_KEY'] = 'dPI:KEY:<KEY>END_PI'
after ->
process.env['MY_SECRET_DECRYPT_KEY'] = ''
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should exists the created host', ->
expect(auth.find('my.server.org').exists()).to.be.true
it 'should be a valid host', ->
expect(auth.find('my.server.org').valid()).to.be.true
it 'should have an encrypted password', ->
expect(auth.find('my.server.org').encrypted()).to.be.true
it 'should have the expected cipher', ->
expect(auth.find('my.server.org').cipher()).to.be.equal('blowfish')
it 'should can be transparently decrypted', ->
expect(auth.find('my.server.org').canDecrypt()).to.be.true
describe 'add command', ->
it 'should add a new host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['add'])
.on(/host name/).respond('my.site.org\n')
.on(/user name/).respond('michael\n')
.on(/Enter the password:/).respond('PI:PASSWORD:<PASSWORD>END_PI')
.on(/Confirm the password/).respond('PI:PASSWORD:<PASSWORD>END_PI')
.on(/encrypt your password/).respond('n\n')
.on(/Do you want to save/).respond('y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should exists the created host', ->
expect(auth.find('my.site.org').exists()).to.be.true
it 'should be a valid host', ->
expect(auth.find('my.site.org').valid()).to.be.true
it 'should not have an encrypted password', ->
expect(auth.find('my.site.org').encrypted()).to.be.false
describe 'update command', ->
it 'should add a update a host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['update', 'my.site.org'])
.on(/user name/).respond('john\n')
.on(/Enter the password:/).respond('PI:PASSWORD:<PASSWORD>END_PI€w_p@PI:PASSWORD:<PASSWORD>END_PI\n')
.on(/Confirm the password/).respond('PI:PASSWORD:<PASSWORD>END_PI€PI:PASSWORD:<PASSWORD>END_PI_PI:PASSWORD:<PASSWORD>END_PI\n')
.on(/encrypt your password/).respond('n\n')
.on(/Do you want to save/).respond('y\n')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should exists the created host', ->
expect(auth.find('my.site.org').exists()).to.be.true
it 'should be a valid host', ->
expect(auth.find('my.site.org').valid()).to.be.true
it 'should have the new username', ->
expect(auth.find('my.site.org').user()).to.be.equal('john')
it 'should have the new password', ->
expect(auth.find('my.site.org').password()).to.be.equal('PI:PASSWORD:<PASSWORD>END_PI')
describe 'list command', ->
it 'should list the existent hosts', (done) ->
suppose("#{cwd}/bin/authrc", ['list'])
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'copy command', ->
it 'should copy a host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['copy', 'my.site.org', 'new.site.org'])
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'remove command', ->
it 'should remove a host in an existent .authrc file', (done) ->
suppose("#{cwd}/bin/authrc", ['remove', 'my.site.org'])
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
expect(fileExists()).to.be.true
done()
describe 'file contents are the expected', ->
before ->
auth = new Authrc
it 'should exists data', ->
expect(auth.exists()).to.be.true
it 'should be removed the host', ->
expect(auth.find('my.site.org').exists()).to.be.false
describe 'encrypt command', ->
it 'should encrypt a password property', (done) ->
suppose("#{cwd}/bin/authrc", ['encrypt', 'PI:PASSWORD:<PASSWORD>END_PI'])
.on(/Enter the password key/).respond('my-d€crypt_kPI:PASSWORD:<PASSWORD>END_PI')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
done()
describe 'encrypt command', ->
it 'should encrypt a password property', (done) ->
suppose("#{cwd}/bin/authrc", ['decrypt', 'PI:PASSWORD:<PASSWORD>END_PI'])
.on(/Enter the password key/).respond('my-d€crypt_k3y\PI:PASSWORD:<PASSWORD>END_PI')
.error (err) ->
throw new Error err
.end (code) ->
expect(code).to.be.equal(0)
done()
|
[
{
"context": "one) ->\n model = new ManualIdModel({name: 'Bob'})\n model.save (err) ->\n assert.o",
"end": 2011,
"score": 0.9980498552322388,
"start": 2008,
"tag": "NAME",
"value": "Bob"
},
{
"context": "del = new ManualIdModel({id: _.uniqueId(), name: 'Bob'})\n model.save (err) ->\n assert.o",
"end": 2236,
"score": 0.9998317360877991,
"start": 2233,
"tag": "NAME",
"value": "Bob"
},
{
"context": "del = new ManualIdModel({id: _.uniqueId(), name: 'Bob'})\n model.save (err) ->\n assert.o",
"end": 2472,
"score": 0.9998464584350586,
"start": 2469,
"tag": "NAME",
"value": "Bob"
},
{
"context": "_id', (done) ->\n (new IndexedModel({name: 'Bob'})).save (err) ->\n assert.ok(!err, \"No e",
"end": 2885,
"score": 0.9998538494110107,
"start": 2882,
"tag": "NAME",
"value": "Bob"
},
{
"context": "rs: #{err}\")\n\n (new IndexedModel({name: 'Fred'})).save (err) ->\n assert.ok(!err, \"No",
"end": 2992,
"score": 0.9984918832778931,
"start": 2988,
"tag": "NAME",
"value": "Fred"
},
{
"context": "one) ->\n (new ManualIdModel({id: 3, name: 'Bob'})).save (err) ->\n assert.ok(!err, \"No e",
"end": 3476,
"score": 0.9998551607131958,
"start": 3473,
"tag": "NAME",
"value": "Bob"
},
{
"context": "r}\")\n\n (new ManualIdModel({id: 1, name: 'Bob'})).save (err) ->\n assert.ok(!err, \"No",
"end": 3590,
"score": 0.9998492002487183,
"start": 3587,
"tag": "NAME",
"value": "Bob"
}
] | test/unit/ids.coffee | michaelBenin/backbone-mongo | 1 | util = require 'util'
assert = require 'assert'
_ = require 'underscore'
Backbone = require 'backbone'
Queue = require 'backbone-orm/lib/queue'
ModelCache = require('backbone-orm/lib/cache/singletons').ModelCache
module.exports = (options, callback) ->
ModelCache.configure({enabled: !!options.cache, max: 100}) # configure caching
class IndexedModel extends Backbone.Model
schema:
_id: [indexed: true]
url: "#{require('../config/database')['test']}/indexed_models"
sync: require('../../lib/sync')(IndexedModel)
class ManualIdModel extends Backbone.Model
schema:
id: [indexed: true, manual_id: true]
url: "#{require('../config/database')['test']}/indexed_models"
sync: require('../../lib/sync')(ManualIdModel)
describe 'Id Functionality', ->
before (done) -> return done() unless options.before; options.before([IndexedModel, ManualIdModel], done)
after (done) -> callback(); done()
beforeEach (done) ->
queue = new Queue(1)
queue.defer (callback) -> IndexedModel.resetSchema(callback)
queue.defer (callback) -> ManualIdModel.resetSchema(callback)
queue.await done
######################################
# Indexing
######################################
describe 'indexing', ->
it 'should ensure indexes', (done) ->
# indexing is async so need to poll
checkIndexes = ->
IndexedModel::sync 'collection', (err, collection) ->
console.log "collection"
assert.ok(!err, "No errors: #{err}")
collection.indexExists '_id_', (err, exists) ->
assert.ok(!err, "No errors: #{err}")
return done() if exists
_.delay checkIndexes, 50
checkIndexes()
######################################
# Custom Ids
######################################
describe 'manual_id', ->
it 'should fail to save if you do not provide an id', (done) ->
model = new ManualIdModel({name: 'Bob'})
model.save (err) ->
assert.ok(err, 'should not save if missing an id')
done()
it 'should save if provide an id', (done) ->
model = new ManualIdModel({id: _.uniqueId(), name: 'Bob'})
model.save (err) ->
assert.ok(!err, "No errors: #{err}")
done()
it 'should fail to save if you delete the id after saving', (done) ->
model = new ManualIdModel({id: _.uniqueId(), name: 'Bob'})
model.save (err) ->
assert.ok(!err, "No errors: #{err}")
model.save {id: null}, (err) ->
assert.ok(err, 'should not save if missing an id')
done()
######################################
# Sort by Id
######################################
describe 'sorting', ->
it 'should sort by _id', (done) ->
(new IndexedModel({name: 'Bob'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
(new IndexedModel({name: 'Fred'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
IndexedModel.cursor().sort('id').toModels (err, models) ->
assert.ok(!err, "No errors: #{err}")
ids = (model.id for model in models)
sorted_ids = _.clone(ids).sort()
assert.deepEqual(ids, sorted_ids, "Models were returned in sorted order")
done()
it 'should sort by id', (done) ->
(new ManualIdModel({id: 3, name: 'Bob'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
(new ManualIdModel({id: 1, name: 'Bob'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
ManualIdModel.cursor().sort('id').toModels (err, models) ->
assert.ok(!err, "No errors: #{err}")
ids = (model.id for model in models)
sorted_ids = _.clone(ids).sort()
assert.deepEqual(ids, sorted_ids, "Models were returned in sorted order")
done()
| 111513 | util = require 'util'
assert = require 'assert'
_ = require 'underscore'
Backbone = require 'backbone'
Queue = require 'backbone-orm/lib/queue'
ModelCache = require('backbone-orm/lib/cache/singletons').ModelCache
module.exports = (options, callback) ->
ModelCache.configure({enabled: !!options.cache, max: 100}) # configure caching
class IndexedModel extends Backbone.Model
schema:
_id: [indexed: true]
url: "#{require('../config/database')['test']}/indexed_models"
sync: require('../../lib/sync')(IndexedModel)
class ManualIdModel extends Backbone.Model
schema:
id: [indexed: true, manual_id: true]
url: "#{require('../config/database')['test']}/indexed_models"
sync: require('../../lib/sync')(ManualIdModel)
describe 'Id Functionality', ->
before (done) -> return done() unless options.before; options.before([IndexedModel, ManualIdModel], done)
after (done) -> callback(); done()
beforeEach (done) ->
queue = new Queue(1)
queue.defer (callback) -> IndexedModel.resetSchema(callback)
queue.defer (callback) -> ManualIdModel.resetSchema(callback)
queue.await done
######################################
# Indexing
######################################
describe 'indexing', ->
it 'should ensure indexes', (done) ->
# indexing is async so need to poll
checkIndexes = ->
IndexedModel::sync 'collection', (err, collection) ->
console.log "collection"
assert.ok(!err, "No errors: #{err}")
collection.indexExists '_id_', (err, exists) ->
assert.ok(!err, "No errors: #{err}")
return done() if exists
_.delay checkIndexes, 50
checkIndexes()
######################################
# Custom Ids
######################################
describe 'manual_id', ->
it 'should fail to save if you do not provide an id', (done) ->
model = new ManualIdModel({name: '<NAME>'})
model.save (err) ->
assert.ok(err, 'should not save if missing an id')
done()
it 'should save if provide an id', (done) ->
model = new ManualIdModel({id: _.uniqueId(), name: '<NAME>'})
model.save (err) ->
assert.ok(!err, "No errors: #{err}")
done()
it 'should fail to save if you delete the id after saving', (done) ->
model = new ManualIdModel({id: _.uniqueId(), name: '<NAME>'})
model.save (err) ->
assert.ok(!err, "No errors: #{err}")
model.save {id: null}, (err) ->
assert.ok(err, 'should not save if missing an id')
done()
######################################
# Sort by Id
######################################
describe 'sorting', ->
it 'should sort by _id', (done) ->
(new IndexedModel({name: '<NAME>'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
(new IndexedModel({name: '<NAME>'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
IndexedModel.cursor().sort('id').toModels (err, models) ->
assert.ok(!err, "No errors: #{err}")
ids = (model.id for model in models)
sorted_ids = _.clone(ids).sort()
assert.deepEqual(ids, sorted_ids, "Models were returned in sorted order")
done()
it 'should sort by id', (done) ->
(new ManualIdModel({id: 3, name: '<NAME>'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
(new ManualIdModel({id: 1, name: '<NAME>'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
ManualIdModel.cursor().sort('id').toModels (err, models) ->
assert.ok(!err, "No errors: #{err}")
ids = (model.id for model in models)
sorted_ids = _.clone(ids).sort()
assert.deepEqual(ids, sorted_ids, "Models were returned in sorted order")
done()
| true | util = require 'util'
assert = require 'assert'
_ = require 'underscore'
Backbone = require 'backbone'
Queue = require 'backbone-orm/lib/queue'
ModelCache = require('backbone-orm/lib/cache/singletons').ModelCache
module.exports = (options, callback) ->
ModelCache.configure({enabled: !!options.cache, max: 100}) # configure caching
class IndexedModel extends Backbone.Model
schema:
_id: [indexed: true]
url: "#{require('../config/database')['test']}/indexed_models"
sync: require('../../lib/sync')(IndexedModel)
class ManualIdModel extends Backbone.Model
schema:
id: [indexed: true, manual_id: true]
url: "#{require('../config/database')['test']}/indexed_models"
sync: require('../../lib/sync')(ManualIdModel)
describe 'Id Functionality', ->
before (done) -> return done() unless options.before; options.before([IndexedModel, ManualIdModel], done)
after (done) -> callback(); done()
beforeEach (done) ->
queue = new Queue(1)
queue.defer (callback) -> IndexedModel.resetSchema(callback)
queue.defer (callback) -> ManualIdModel.resetSchema(callback)
queue.await done
######################################
# Indexing
######################################
describe 'indexing', ->
it 'should ensure indexes', (done) ->
# indexing is async so need to poll
checkIndexes = ->
IndexedModel::sync 'collection', (err, collection) ->
console.log "collection"
assert.ok(!err, "No errors: #{err}")
collection.indexExists '_id_', (err, exists) ->
assert.ok(!err, "No errors: #{err}")
return done() if exists
_.delay checkIndexes, 50
checkIndexes()
######################################
# Custom Ids
######################################
describe 'manual_id', ->
it 'should fail to save if you do not provide an id', (done) ->
model = new ManualIdModel({name: 'PI:NAME:<NAME>END_PI'})
model.save (err) ->
assert.ok(err, 'should not save if missing an id')
done()
it 'should save if provide an id', (done) ->
model = new ManualIdModel({id: _.uniqueId(), name: 'PI:NAME:<NAME>END_PI'})
model.save (err) ->
assert.ok(!err, "No errors: #{err}")
done()
it 'should fail to save if you delete the id after saving', (done) ->
model = new ManualIdModel({id: _.uniqueId(), name: 'PI:NAME:<NAME>END_PI'})
model.save (err) ->
assert.ok(!err, "No errors: #{err}")
model.save {id: null}, (err) ->
assert.ok(err, 'should not save if missing an id')
done()
######################################
# Sort by Id
######################################
describe 'sorting', ->
it 'should sort by _id', (done) ->
(new IndexedModel({name: 'PI:NAME:<NAME>END_PI'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
(new IndexedModel({name: 'PI:NAME:<NAME>END_PI'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
IndexedModel.cursor().sort('id').toModels (err, models) ->
assert.ok(!err, "No errors: #{err}")
ids = (model.id for model in models)
sorted_ids = _.clone(ids).sort()
assert.deepEqual(ids, sorted_ids, "Models were returned in sorted order")
done()
it 'should sort by id', (done) ->
(new ManualIdModel({id: 3, name: 'PI:NAME:<NAME>END_PI'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
(new ManualIdModel({id: 1, name: 'PI:NAME:<NAME>END_PI'})).save (err) ->
assert.ok(!err, "No errors: #{err}")
ManualIdModel.cursor().sort('id').toModels (err, models) ->
assert.ok(!err, "No errors: #{err}")
ids = (model.id for model in models)
sorted_ids = _.clone(ids).sort()
assert.deepEqual(ids, sorted_ids, "Models were returned in sorted order")
done()
|
[
{
"context": "io.com\n\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\n\nLicensed under the Apache License, Version 2.0 ",
"end": 194,
"score": 0.999923050403595,
"start": 178,
"tag": "EMAIL",
"value": "info@chaibio.com"
}
] | frontend/javascripts/app/directives/menu-overlay.js.coffee | MakerButt/chaipcr | 1 | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
window.ChaiBioTech.ngApp.directive 'menuOverlay', [
'$rootScope'
'$templateCache'
'$compile'
'$window'
($rootScope, $templateCache, $compile, $window) ->
restrict: 'EA'
transclude: true
#replace: true
scope:
sidemenuTemplate: '@'
templateUrl: 'app/views/directives/menu-overlay.html'
link: ($scope, elem) ->
$scope.sideMenuOpen = false
$rootScope.$on 'sidemenu:toggle', ->
$scope.sideMenuOpen = !$scope.sideMenuOpen
$($window).resize ->
console.log 'resizing'
]
| 205688 | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
window.ChaiBioTech.ngApp.directive 'menuOverlay', [
'$rootScope'
'$templateCache'
'$compile'
'$window'
($rootScope, $templateCache, $compile, $window) ->
restrict: 'EA'
transclude: true
#replace: true
scope:
sidemenuTemplate: '@'
templateUrl: 'app/views/directives/menu-overlay.html'
link: ($scope, elem) ->
$scope.sideMenuOpen = false
$rootScope.$on 'sidemenu:toggle', ->
$scope.sideMenuOpen = !$scope.sideMenuOpen
$($window).resize ->
console.log 'resizing'
]
| true | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>END_PI>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
window.ChaiBioTech.ngApp.directive 'menuOverlay', [
'$rootScope'
'$templateCache'
'$compile'
'$window'
($rootScope, $templateCache, $compile, $window) ->
restrict: 'EA'
transclude: true
#replace: true
scope:
sidemenuTemplate: '@'
templateUrl: 'app/views/directives/menu-overlay.html'
link: ($scope, elem) ->
$scope.sideMenuOpen = false
$rootScope.$on 'sidemenu:toggle', ->
$scope.sideMenuOpen = !$scope.sideMenuOpen
$($window).resize ->
console.log 'resizing'
]
|
[
{
"context": "ap/4.0.0-beta.2/css/bootstrap.min.css\" integrity=\"sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb\" crossorigin=\"anonymous\">\n </head>\n <bod",
"end": 549,
"score": 0.9943798780441284,
"start": 477,
"tag": "KEY",
"value": "sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb\""
},
{
"context": "MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb\" crossorigin=\"anonymous\">\n </head>\n <body>\n $2\n\n ",
"end": 572,
"score": 0.827937126159668,
"start": 563,
"tag": "KEY",
"value": "anonymous"
},
{
"context": "e.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"></script>\n <scrip",
"end": 869,
"score": 0.9996302127838135,
"start": 798,
"tag": "KEY",
"value": "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
},
{
"context": "bs/popper.js/1.12.3/umd/popper.min.js\" integrity=\"sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh\" crossorigin=\"anonymous\"></script>\n <scrip",
"end": 1083,
"score": 0.9996114373207092,
"start": 1012,
"tag": "KEY",
"value": "sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh"
},
{
"context": "trap/4.0.0-beta.2/js/bootstrap.min.js\" integrity=\"sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ\" crossorigin=\"anonymous\"></script>\n </body>\n",
"end": 1298,
"score": 0.9996314644813538,
"start": 1227,
"tag": "KEY",
"value": "sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ"
},
{
"context": "ap/4.0.0-beta.2/css/bootstrap.min.css\" integrity=\"sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb\" crossorigin=\"anonymous\">\n </head>\n <bo",
"end": 1853,
"score": 0.9996249079704285,
"start": 1782,
"tag": "KEY",
"value": "sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"
},
{
"context": "e.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"></script>\n <scrip",
"end": 2071,
"score": 0.999604344367981,
"start": 2000,
"tag": "KEY",
"value": "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
},
{
"context": "bs/popper.js/1.12.3/umd/popper.min.js\" integrity=\"sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh\" crossorigin=\"anonymous\"></script>\n <scrip",
"end": 2285,
"score": 0.9995805621147156,
"start": 2214,
"tag": "KEY",
"value": "sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh"
},
{
"context": "trap/4.0.0-beta.2/js/bootstrap.min.js\" integrity=\"sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ\" crossorigin=\"anonymous\"></script>\n </body>\n",
"end": 2500,
"score": 0.9995871186256409,
"start": 2429,
"tag": "KEY",
"value": "sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ"
}
] | snippets/templates.cson | hirschadway/v-bootstrap4 | 6 | '.text.html':
'Basic HTML Template':
'prefix': 'html-'
'body': """
<!doctype html>
<html lang="en">
<head>
<title>$1</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
$2
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
"""
'Minimal HTML Template (No Comment)':
'prefix': 'html-min'
'body': """
<!doctype html>
<html lang="en">
<head>
<title>$1</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
$2
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
"""
| 67097 | '.text.html':
'Basic HTML Template':
'prefix': 'html-'
'body': """
<!doctype html>
<html lang="en">
<head>
<title>$1</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="<KEY> crossorigin="<KEY>">
</head>
<body>
$2
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
"""
'Minimal HTML Template (No Comment)':
'prefix': 'html-min'
'body': """
<!doctype html>
<html lang="en">
<head>
<title>$1</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
$2
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
"""
| true | '.text.html':
'Basic HTML Template':
'prefix': 'html-'
'body': """
<!doctype html>
<html lang="en">
<head>
<title>$1</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="PI:KEY:<KEY>END_PI crossorigin="PI:KEY:<KEY>END_PI">
</head>
<body>
$2
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous"></script>
</body>
</html>
"""
'Minimal HTML Template (No Comment)':
'prefix': 'html-min'
'body': """
<!doctype html>
<html lang="en">
<head>
<title>$1</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous">
</head>
<body>
$2
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="PI:KEY:<KEY>END_PI" crossorigin="anonymous"></script>
</body>
</html>
"""
|
[
{
"context": "0272829'\n accKitVersion : 'v1.1'\n accKitToken: 'ed921b9e2248d0cb68329322c08e97b3'\n\nconfig.menuMainHome = [\n {\n title : 'Kênh O",
"end": 409,
"score": 0.9936593770980835,
"start": 377,
"tag": "PASSWORD",
"value": "ed921b9e2248d0cb68329322c08e97b3"
}
] | app/core/app.coffee | xitrumuit1991/ls-yuptv | 0 | config =
platform : 'web'
version : '1.0.0'
uuid : (new Fingerprint({canvas : true, screen_resolution : false})).get()
modelName : navigator.userAgent
# fBappId : '1933860780272829' #dev
fBappId : '144785392941236' #production
API_URL : "http://api.yuptv.vn/api/v1/"
env : 'production'
accKitAppId : '1933860780272829'
accKitVersion : 'v1.1'
accKitToken: 'ed921b9e2248d0cb68329322c08e97b3'
config.menuMainHome = [
{
title : 'Kênh On Air',
# icon : 'fa-video-camera'
href : 'base.on-air'
itemClass : 'col-md-4'
image : 'images/icon_livestream.png'
# backgroundColor : '#BB1275'
},
{
title : 'Lịch Diễn',
icon : 'fa-calendar-o'
href : 'base.schedule'
itemClass : 'col-md-4'
# image : 'images/Lich_dien.png'
},
{
title : 'Tin Tức',
icon : 'fa-bell-o'
href : 'http://tintuc.livestar.vn'
isLink : true
itemClass : 'col-md-4'
# image : 'images/blog.png'
},
]
config.menuMainProfile = [
{
title : 'Trang Cá Nhân',
href : 'base.profile',
itemClass : 'col-md-2'
},
{
title : 'Quản lý tài sản ',
href : 'base.profile.manage-property',
itemClass : 'col-md-2'
},
{
title : 'Nạp Ucoin',
href : 'base.profile.charge-ucoin',
itemClass : 'col-md-2'
},
{
title : 'Quản lý phòng',
href : 'base.profile.manage-room',
itemClass : 'col-md-2'
},
{
title : 'Cài Đặt Thông Báo',
href : 'base.profile.setting-notify',
itemClass : 'col-md-2'
},
]
switch window.ENV
when 'production'
config = _.extend config,
fBappId : '144785392941236'
API_URL : "http://api.yuptv.vn/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'https://socket.yuptv.vn/'
env : 'production'
when 'prod'
config = _.extend config,
fBappId : '144785392941236'
API_URL : "http://api.yuptv.vn/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'https://socket.yuptv.vn/'
env : 'production'
when 'development'
config = _.extend config,
fBappId : '1933860780272829'
API_URL : "http://dev.livestar.vn:1010/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'http://dev.livestar.vn:8050'
env : 'development'
when 'dev'
config = _.extend config,
fBappId : '1933860780272829'
API_URL : "http://dev.livestar.vn:1010/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'http://dev.livestar.vn:8050'
env : 'development'
initInjector = angular.injector(["ng"])
$http = initInjector.get("$http");
angular
.module("app", [
"ngResource",
"ngMessageFormat",
# 'ngAnimate',
"ui.router",
"facebook",
"ngSanitize",
"angularFileUpload",
"fancyboxplus",
"ui.bootstrap",
"ui.carousel",
"ui-notification",
"ngProgress",
"angular-loading-bar",
'ngFileUpload',
'720kb.datepicker',
'720kb.socialshare',
'ui.bootstrap.datetimepicker',
'slick'
# 'vjs-video'
])
.constant "AppName", "YUP"
.constant "GlobalConfig", config
appConfig = ($locationProvider,
$stateProvider,
$urlRouterProvider,
FacebookProvider,
GlobalConfig,
$httpProvider,
NotificationProvider, cfpLoadingBarProvider) ->
$httpProvider.interceptors.push "AuthInterceptor"
$locationProvider.html5Mode(true).hashPrefix "!"
$urlRouterProvider.otherwise "/"
FacebookProvider.init config.fBappId
NotificationProvider.setOptions({
delay : 5000,
startTop : 20,
startRight : 20,
verticalSpacing : 20,
horizontalSpacing : 20,
positionX : 'right',
positionY : 'top'
})
cfpLoadingBarProvider.includeSpinner = true
cfpLoadingBarProvider.includeBar = true
appConfig.$inject = [
'$locationProvider',
'$stateProvider',
'$urlRouterProvider',
'FacebookProvider',
'GlobalConfig',
'$httpProvider',
'NotificationProvider', 'cfpLoadingBarProvider'
]
angular
.module("app")
.config appConfig
angular.element(document).ready ()->
angular.bootstrap document, ['app'], strictDi : true | 73558 | config =
platform : 'web'
version : '1.0.0'
uuid : (new Fingerprint({canvas : true, screen_resolution : false})).get()
modelName : navigator.userAgent
# fBappId : '1933860780272829' #dev
fBappId : '144785392941236' #production
API_URL : "http://api.yuptv.vn/api/v1/"
env : 'production'
accKitAppId : '1933860780272829'
accKitVersion : 'v1.1'
accKitToken: '<PASSWORD>'
config.menuMainHome = [
{
title : 'Kênh On Air',
# icon : 'fa-video-camera'
href : 'base.on-air'
itemClass : 'col-md-4'
image : 'images/icon_livestream.png'
# backgroundColor : '#BB1275'
},
{
title : 'Lịch Diễn',
icon : 'fa-calendar-o'
href : 'base.schedule'
itemClass : 'col-md-4'
# image : 'images/Lich_dien.png'
},
{
title : 'Tin Tức',
icon : 'fa-bell-o'
href : 'http://tintuc.livestar.vn'
isLink : true
itemClass : 'col-md-4'
# image : 'images/blog.png'
},
]
config.menuMainProfile = [
{
title : 'Trang Cá Nhân',
href : 'base.profile',
itemClass : 'col-md-2'
},
{
title : 'Quản lý tài sản ',
href : 'base.profile.manage-property',
itemClass : 'col-md-2'
},
{
title : 'Nạp Ucoin',
href : 'base.profile.charge-ucoin',
itemClass : 'col-md-2'
},
{
title : 'Quản lý phòng',
href : 'base.profile.manage-room',
itemClass : 'col-md-2'
},
{
title : 'Cài Đặt Thông Báo',
href : 'base.profile.setting-notify',
itemClass : 'col-md-2'
},
]
switch window.ENV
when 'production'
config = _.extend config,
fBappId : '144785392941236'
API_URL : "http://api.yuptv.vn/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'https://socket.yuptv.vn/'
env : 'production'
when 'prod'
config = _.extend config,
fBappId : '144785392941236'
API_URL : "http://api.yuptv.vn/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'https://socket.yuptv.vn/'
env : 'production'
when 'development'
config = _.extend config,
fBappId : '1933860780272829'
API_URL : "http://dev.livestar.vn:1010/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'http://dev.livestar.vn:8050'
env : 'development'
when 'dev'
config = _.extend config,
fBappId : '1933860780272829'
API_URL : "http://dev.livestar.vn:1010/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'http://dev.livestar.vn:8050'
env : 'development'
initInjector = angular.injector(["ng"])
$http = initInjector.get("$http");
angular
.module("app", [
"ngResource",
"ngMessageFormat",
# 'ngAnimate',
"ui.router",
"facebook",
"ngSanitize",
"angularFileUpload",
"fancyboxplus",
"ui.bootstrap",
"ui.carousel",
"ui-notification",
"ngProgress",
"angular-loading-bar",
'ngFileUpload',
'720kb.datepicker',
'720kb.socialshare',
'ui.bootstrap.datetimepicker',
'slick'
# 'vjs-video'
])
.constant "AppName", "YUP"
.constant "GlobalConfig", config
appConfig = ($locationProvider,
$stateProvider,
$urlRouterProvider,
FacebookProvider,
GlobalConfig,
$httpProvider,
NotificationProvider, cfpLoadingBarProvider) ->
$httpProvider.interceptors.push "AuthInterceptor"
$locationProvider.html5Mode(true).hashPrefix "!"
$urlRouterProvider.otherwise "/"
FacebookProvider.init config.fBappId
NotificationProvider.setOptions({
delay : 5000,
startTop : 20,
startRight : 20,
verticalSpacing : 20,
horizontalSpacing : 20,
positionX : 'right',
positionY : 'top'
})
cfpLoadingBarProvider.includeSpinner = true
cfpLoadingBarProvider.includeBar = true
appConfig.$inject = [
'$locationProvider',
'$stateProvider',
'$urlRouterProvider',
'FacebookProvider',
'GlobalConfig',
'$httpProvider',
'NotificationProvider', 'cfpLoadingBarProvider'
]
angular
.module("app")
.config appConfig
angular.element(document).ready ()->
angular.bootstrap document, ['app'], strictDi : true | true | config =
platform : 'web'
version : '1.0.0'
uuid : (new Fingerprint({canvas : true, screen_resolution : false})).get()
modelName : navigator.userAgent
# fBappId : '1933860780272829' #dev
fBappId : '144785392941236' #production
API_URL : "http://api.yuptv.vn/api/v1/"
env : 'production'
accKitAppId : '1933860780272829'
accKitVersion : 'v1.1'
accKitToken: 'PI:PASSWORD:<PASSWORD>END_PI'
config.menuMainHome = [
{
title : 'Kênh On Air',
# icon : 'fa-video-camera'
href : 'base.on-air'
itemClass : 'col-md-4'
image : 'images/icon_livestream.png'
# backgroundColor : '#BB1275'
},
{
title : 'Lịch Diễn',
icon : 'fa-calendar-o'
href : 'base.schedule'
itemClass : 'col-md-4'
# image : 'images/Lich_dien.png'
},
{
title : 'Tin Tức',
icon : 'fa-bell-o'
href : 'http://tintuc.livestar.vn'
isLink : true
itemClass : 'col-md-4'
# image : 'images/blog.png'
},
]
config.menuMainProfile = [
{
title : 'Trang Cá Nhân',
href : 'base.profile',
itemClass : 'col-md-2'
},
{
title : 'Quản lý tài sản ',
href : 'base.profile.manage-property',
itemClass : 'col-md-2'
},
{
title : 'Nạp Ucoin',
href : 'base.profile.charge-ucoin',
itemClass : 'col-md-2'
},
{
title : 'Quản lý phòng',
href : 'base.profile.manage-room',
itemClass : 'col-md-2'
},
{
title : 'Cài Đặt Thông Báo',
href : 'base.profile.setting-notify',
itemClass : 'col-md-2'
},
]
switch window.ENV
when 'production'
config = _.extend config,
fBappId : '144785392941236'
API_URL : "http://api.yuptv.vn/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'https://socket.yuptv.vn/'
env : 'production'
when 'prod'
config = _.extend config,
fBappId : '144785392941236'
API_URL : "http://api.yuptv.vn/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'https://socket.yuptv.vn/'
env : 'production'
when 'development'
config = _.extend config,
fBappId : '1933860780272829'
API_URL : "http://dev.livestar.vn:1010/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'http://dev.livestar.vn:8050'
env : 'development'
when 'dev'
config = _.extend config,
fBappId : '1933860780272829'
API_URL : "http://dev.livestar.vn:1010/api/v1/"
LIVE_DOMAIN : 'http://livestream.yuptv.vn/'
SOCKET_DOMAIN : 'http://dev.livestar.vn:8050'
env : 'development'
initInjector = angular.injector(["ng"])
$http = initInjector.get("$http");
angular
.module("app", [
"ngResource",
"ngMessageFormat",
# 'ngAnimate',
"ui.router",
"facebook",
"ngSanitize",
"angularFileUpload",
"fancyboxplus",
"ui.bootstrap",
"ui.carousel",
"ui-notification",
"ngProgress",
"angular-loading-bar",
'ngFileUpload',
'720kb.datepicker',
'720kb.socialshare',
'ui.bootstrap.datetimepicker',
'slick'
# 'vjs-video'
])
.constant "AppName", "YUP"
.constant "GlobalConfig", config
appConfig = ($locationProvider,
$stateProvider,
$urlRouterProvider,
FacebookProvider,
GlobalConfig,
$httpProvider,
NotificationProvider, cfpLoadingBarProvider) ->
$httpProvider.interceptors.push "AuthInterceptor"
$locationProvider.html5Mode(true).hashPrefix "!"
$urlRouterProvider.otherwise "/"
FacebookProvider.init config.fBappId
NotificationProvider.setOptions({
delay : 5000,
startTop : 20,
startRight : 20,
verticalSpacing : 20,
horizontalSpacing : 20,
positionX : 'right',
positionY : 'top'
})
cfpLoadingBarProvider.includeSpinner = true
cfpLoadingBarProvider.includeBar = true
appConfig.$inject = [
'$locationProvider',
'$stateProvider',
'$urlRouterProvider',
'FacebookProvider',
'GlobalConfig',
'$httpProvider',
'NotificationProvider', 'cfpLoadingBarProvider'
]
angular
.module("app")
.config appConfig
angular.element(document).ready ()->
angular.bootstrap document, ['app'], strictDi : true |
[
{
"context": "# grunt-coffee-build\n# https://github.com/tarruda/grunt-coffee-build\n#\n# Copyright (c) 2013 Thiago ",
"end": 49,
"score": 0.9990901350975037,
"start": 42,
"tag": "USERNAME",
"value": "tarruda"
},
{
"context": "/tarruda/grunt-coffee-build\n#\n# Copyright (c) 2013 Thiago de Arruda\n# Licensed under the MIT license.\n\nfs = require('",
"end": 108,
"score": 0.9998825192451477,
"start": 92,
"tag": "NAME",
"value": "Thiago de Arruda"
},
{
"context": "{{/each}}\n \"\"\")\n\n\n# based on: https://github.com/alexlawrence/grunt-umd\numdTemplate = handlebars.compile(\n \"\"\"",
"end": 15022,
"score": 0.9995262026786804,
"start": 15010,
"tag": "USERNAME",
"value": "alexlawrence"
}
] | tasks/coffee_build.coffee | gruntjs-updater/grunt-coffee-build | 1 | # grunt-coffee-build
# https://github.com/tarruda/grunt-coffee-build
#
# Copyright (c) 2013 Thiago de Arruda
# Licensed under the MIT license.
fs = require('fs')
path = require('path')
handlebars = require('handlebars')
browserify = require('browserify')
parseScope = require('lexical-scope')
{compile} = require 'coffee-script'
{SourceMapConsumer, SourceMapGenerator} = require 'source-map'
UglifyJS = require 'uglify-js'
NAME = 'coffee_build'
DESC =
'Compiles Coffeescript files, optionally merging and generating source maps.'
# Cache of compiledfiles, keeps track of the last modified date
# so we can avoid processing it again.
buildCache = browserifyCache = timestampCache = null
TIMESTAMP_CACHE = '.timestamp_cache~'
BUILD_CACHE = '.build_cache~'
mtime = (fp) -> fs.statSync(fp).mtime.getTime()
process.on('exit', ->
# save caches to disk to speed up future builds
if timestampCache
fs.writeFileSync(TIMESTAMP_CACHE, JSON.stringify(timestampCache))
if buildCache
fs.writeFileSync(BUILD_CACHE, JSON.stringify(buildCache))
# don't save browserify build to disk since it can get complicated
# in situations where only dependencies versions change
)
process.on('SIGINT', process.exit)
process.on('SIGTERM', process.exit)
buildToDirectory = (grunt, options, src) ->
cwd = options.src_base
outDir = options.dest
if not timestampCache
if grunt.file.exists(TIMESTAMP_CACHE)
timestampCache = grunt.file.readJSON(TIMESTAMP_CACHE)
else
timestampCache = {}
if not grunt.file.exists(outDir)
grunt.file.mkdir(outDir)
src.forEach (file) ->
if file.indexOf(cwd) != 0
file = path.join(cwd, file)
if not grunt.file.exists(file)
grunt.log.warn('Source file "' + file + '" not found.')
return
outFile = path.join(outDir, path.relative(cwd, file))
entry = timestampCache[file]
mt = mtime(file)
if /\.js/.test(outFile)
if not grunt.file.exists(outFile) or mt != entry?.mtime
# plain js, just copy to the output dir
grunt.file.copy(file, outFile)
grunt.log.ok("Copied #{file} to #{outFile}")
timestampCache[file] = mtime: mt
return
outFile = outFile.replace(/\.coffee$/, '.js')
fileOutDir = path.dirname(outFile)
if not grunt.file.exists(outFile) or mt != entry?.mtime
src = grunt.file.read(file)
try
compiled = compile(src, {
sourceMap: options.sourceMap
bare: false
})
catch e
grunt.log.error("#{e.message}(file: #{file}, line: #{e.location.last_line + 1}, column: #{e.location.last_column})")
throw e
grunt.log.ok("Compiled #{file}")
if options.sourceMap
{js: compiled, v3SourceMap} = compiled
v3SourceMap = JSON.parse(v3SourceMap)
v3SourceMap.sourceRoot = path.relative(fileOutDir, cwd)
v3SourceMap.file = path.basename(outFile)
v3SourceMap.sources[0] = path.relative(cwd, file)
v3SourceMap = JSON.stringify(v3SourceMap)
compiled += "\n\n//@ sourceMappingURL=#{path.basename(outFile)}.map"
grunt.file.write("#{outFile}.map", v3SourceMap)
grunt.log.ok("File #{outFile}.map was created")
timestampCache[file] = mtime: mt
grunt.file.write(outFile, compiled)
grunt.log.ok("File #{outFile} was created")
# Function adapted from the helper function with same name thein traceur
# compiler source code.
#
# It generates an ugly identifier for a given pathname relative to
# the current file being processed, taking into consideration a base dir. eg:
# > generateNameForUrl('./b/c') # if the filename is 'a'
# '$$__a_b_c'
# > generateNameForUrl('../d') # if the filename is 'a/b/c'
# '$$__a_b_d'
#
# This assumes you won't name your variables using this prefix
generateNameForUrl = (grunt, url, from, cwd = '.', prefix = '$__') ->
try
cwd = path.resolve(cwd)
from = path.resolve(path.dirname(from))
url = path.resolve(path.join(from, url))
if grunt.file.isDir(url)
# its possible to require directories that have an index.coffee file
url = path.join(url, 'index')
ext = /\.(coffee|js)$/
if ext.test(url)
url = url.replace(ext, '')
catch e
grunt.log.warn(e)
return null
id = "$#{prefix + url.replace(cwd, '').replace(/[^\d\w$]/g, '_')}"
return {id: id, url: path.relative(cwd, url)}
# Replace all the require calls by the generated identifier that represents
# the corresponding module. This will also fill the 'deps' array so the
# main routine can concatenate the files in proper order. Require calls to
# non relative paths will be included in the requires array to be declared
# in the umd wrapper
replaceRequires = (grunt, js, fn, fp, cwd, deps, requires) ->
displayNode = (node) -> js.slice(node.start.pos, node.end.endpos)
transformer = new UglifyJS.TreeTransformer (node, descend) ->
if (not (node instanceof UglifyJS.AST_Call) or
node.expression.name != 'require' or
(node.args.length != 1 or
not /^\.(?:\.)?\//.test(node.args[0].value) and
grunt.log.writeln(
"Absolute 'require' call in file #{fn}: '#{displayNode(node)}'")) or
not (mod = generateNameForUrl(grunt, node.args[0].value, fp, cwd)))
if node instanceof UglifyJS.AST_Call and
node.expression.name == 'require' and node.args.length == 1
if node.args[0].value not of requires
grunt.log.writeln(
"Will add '#{node.args[0].value}' as an external dependency")
requires[node.args[0].value] = null
return
# I couldn't get Uglify to generate a correct mapping from the input
# map generated by coffeescript, so returning an identifier node
# to transform the tree wasn't an option.
#
# The best solution I found was to use the position information to
# replace using string slice
start = node.start.pos - posOffset
end = node.end.endpos - posOffset
posOffset += end - start - mod.id.length
before = js.slice(0, start)
after = js.slice(end)
js = before + mod.id + after
url = mod.url + '.coffee'
if not grunt.file.exists(path.join(cwd, url))
url = mod.url + '.js'
deps.push(url)
return
posOffset = 0
ast = UglifyJS.parse(js)
ast.transform(transformer)
return js
# Wraps the a javascript(possibly from compiled coffeescript) project file
# into a wrapper function that simulates a commonjs environment
makeModule = (grunt, js, v3SourceMap, fn, fp, cwd, deps, requires,
nodeGlobals) ->
moduleName = generateNameForUrl(grunt, fn, '.', '.')
{id, url} = moduleName
gen = new SourceMapGenerator({
file: fn
sourceRoot: 'tmp'
})
if v3SourceMap
# the module wrapper will push the source 2 lines down
orig = new SourceMapConsumer(v3SourceMap)
orig.eachMapping (m) ->
mapping =
source: fn
generated:
line: m.generatedLine + 3
column: m.generatedColumn
original:
line: m.originalLine or m.generatedLine
column: m.originalColumn or m.generatedColumn
gen.addMapping(mapping)
v3SourceMap = gen.toString()
ctx =
code: js
id: id
filename: null
dirname: null
scope = parseScope(js)
for name in ['Buffer', 'process', '__filename', '__dirname']
if name in scope.globals.implicit
switch name
when 'Buffer'
nodeGlobals.Buffer = true
when 'process'
nodeGlobals.process = true
when '__filename'
ctx.filename = fn
when '__dirname'
ctx.dirname = path.dirname(fn)
js = moduleTemplate(ctx)
return {
js: replaceRequires(grunt, js, fn, fp, cwd, deps, requires)
v3SourceMap: v3SourceMap
}
# This will create an 1-1 source map that will be used to map a section of the
# bundle to the original javascript file
generateJsSourceMap = (js) ->
gen = new SourceMapGenerator({
file: 'tmp'
sourceRoot: 'tmp'
})
for i in [1...js.split('\n').length]
gen.addMapping
generated:
line: i
column: 0
return gen.toString()
# Builds all input files into a single js file, parsing 'require' calls
# to resolve dependencies and concatenate in the proper order
buildToFile = (grunt, options, src) ->
cwd = options.src_base
pending = {}
allRequires = {}
processed = {}
nodeGlobals = {}
{dest: outFile, expand} = options
outDir = path.dirname(outFile)
if not buildCache
if grunt.file.exists(BUILD_CACHE)
buildCache = grunt.file.readJSON(BUILD_CACHE)
else
buildCache = {}
options.mainId = generateNameForUrl(grunt, options.main, './')
if options.disableSourceMap
disableSourceMap = grunt.file.expand(expand, options.disableSourceMap)
files = src.filter (file) ->
file = path.join(cwd, file)
if not grunt.file.exists(file)
grunt.log.warn('Source file "' + file + '" not found.')
return false
return true
gen = new SourceMapGenerator(
file: path.basename(outFile)
sourceRoot: path.relative(outDir, cwd))
output = ''
lineOffset = 6
while files.length
fn = files.shift()
fp = path.join(cwd, fn)
if fp of processed
continue
if fp of buildCache and not grunt.file.exists(fp)
# refresh the build cache
delete buildCache[fp]
if (not buildCache[fp]) or (mt = mtime(fp)) != buildCache[fp].mtime
requires = {}
deps = []
if (/\.coffee$/.test(fp))
try
{js, v3SourceMap} = compile(grunt.file.read(fp), {
sourceMap: true, bare: true})
catch e
grunt.log.error("#{e.message}(file: #{fn}, line: #{e.location.last_line + 1}, column: #{e.location.last_column})")
throw e
else # plain js
js = grunt.file.read(fp)
v3SourceMap = null
if not disableSourceMap or fn not in disableSourceMap
v3SourceMap = generateJsSourceMap(js)
{js, v3SourceMap} = makeModule(
grunt, js, v3SourceMap, fn, fp, cwd, deps, requires, nodeGlobals)
cacheEntry = buildCache[fp] =
js: js
mtime: mt
v3SourceMap: v3SourceMap
deps: deps
requires: requires
fn: fn
if /\.coffee$/.test(fp)
grunt.log.ok("Compiled #{fp}")
else
grunt.log.ok("Transformed #{fp}")
else
# Use the entry from cache
{deps, requires, js, v3SourceMap, fn} = cacheEntry = buildCache[fp]
for own k, v of requires
allRequires[k] = v
if deps.length
depsProcessed = true
for dep in deps
if dep not of processed
depsProcessed = false
break
if not depsProcessed and fp not of pending
pending[fp] = null
files.unshift(fn)
for dep in deps when dep not of pending
files.unshift(dep)
continue
# flag the file as processed
processed[fp] = null
if v3SourceMap
# concatenate the file output, and update the result source map with
# the input source map information
orig = new SourceMapConsumer(v3SourceMap)
orig.eachMapping (m) ->
gen.addMapping
generated:
line: m.generatedLine + lineOffset
column: m.generatedColumn
original:
line: m.originalLine or m.generatedLine
column: m.originalColumn or m.generatedColumn
source: fn
lineOffset += js.split('\n').length - 1
output += js
render(grunt, output, options, allRequires, nodeGlobals, (err, output) =>
if err then throw err
if options.sourceMap
sourceMapDest = path.basename(outFile) + '.map'
output += "\n\n//@ sourceMappingURL=#{sourceMapDest}"
grunt.file.write("#{outFile}.map", gen.toString())
grunt.log.ok("File #{outFile}.map was created")
grunt.file.write(outFile, output)
grunt.log.ok("File #{outFile} was created")
options.done())
render = (grunt, code, options, requires, nodeGlobals, cb) ->
bundleCb = (err, bundle) =>
if err
grunt.log.error(err)
throw err
ctx =
code: code
globalAliases: globalAliases
requires: ("'#{dep}'" for dep in requires).join(', ')
bundle: bundle
browserifyBuffer: options.browserify and 'Buffer' of nodeGlobals
browserifyProcess: options.browserify and 'process' of nodeGlobals
mainId: options.mainId.id
depAliases: depAliases
cb(null, umdTemplate(ctx))
requires = Object.keys(requires)
globalAliases = options.globalAliases
if not Array.isArray(globalAliases)
globalAliases = []
if not globalAliases.length
if grunt.file.exists('package.json')
pkg = grunt.file.readJSON('package.json')
if pkg.name
globalAliases.push(pkg.name)
if not globalAliases.length
throw new Error('cannot determine a global alias for the module')
include = options.include or []
depAliases = {}
for inc in include
if inc.alias and inc.global
depAliases[inc.alias] = inc.global
depAliases = JSON.stringify(depAliases)
buildBundle(grunt, options, requires, include, nodeGlobals, bundleCb)
buildBundle = (grunt, options, requires, include, nodeGlobals, cb) ->
browserifyCb = (err, bundle) =>
browserifyCache = bundle: bundle, deps: deps
cb(null, bundle)
if options.browserify
deps = requires.sort().toString()
if browserifyCache and browserifyCache.deps == deps
grunt.log.writeln(
'Dependencies not modified, will use the browserify cache')
# deps havent changed, return from cache
return cb(null, browserifyCache.bundle)
b = browserify()
count = 0
includedAliases = {}
if nodeGlobals.Buffer
count++
b.add('./node_buffer.js')
b.require('buffer')
if nodeGlobals.process
count++
b.add('./node_process.js')
for inc in include
count++
if not /^\./.test(inc.path)
inc.path = './' + inc.path
args = [inc.path]
if inc.alias
args.push(expose: inc.alias)
includedAliases[inc.alias] = true
b.require.apply(b, args)
if options.ignore
options.ignore = grunt.file.expand(options.ignore)
for ig in options.ignore
count++
if not /^\./.test(ig)
ig = './' + ig
b.ignore(ig)
if options.external
options.external = grunt.file.expand(options.external)
for ext in options.external
count++
if not /^\./.test(ext)
ext = './' + ext
b.external(ext)
for dep in requires
if dep of includedAliases
continue
count++
b.require(dep)
if not count
return cb(null, '')
b.bundle(ignoreMissing: true, browserifyCb)
else
includes = (grunt.file.read(inc.path) for inc in include)
bundle = bundleTemplate(includes: includes)
cb(null, bundle)
bundleTemplate = handlebars.compile(
"""
{{#each includes}}
(function() {
{{{.}}}
}).call(this);
{{/each}}
""")
# based on: https://github.com/alexlawrence/grunt-umd
umdTemplate = handlebars.compile(
"""
(function(root, factory, dependenciesFactory, setup) {
setup(root, factory, dependenciesFactory);
})(
this,
(function(require, exports, module, global{{#if browserifyBuffer}}, Buffer{{/if}}{{#if browserifyProcess}}, process{{/if}}, undefined) {
{{{code}}}
return {{{mainId}}};
}),
(function() {
var require;
{{{bundle}}}
return require;
}),
(function(root, factory, dependenciesFactory) {
if(typeof exports === 'object') {
module.exports = factory(require, exports, module);
}
else {
// provide a separate context for dependencies
var depContext = {};
var depAliases = {{{depAliases}}};
var depReq = dependenciesFactory.call(depContext);
var mod = {exports: {}};
var exp = mod.exports;
var exported = function(obj) {
// check if the module exported anything
if (typeof obj !== 'object') return true;
for (var k in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, k)) continue;
return true;
}
return false;
};
var req = function(id) {
var alias = id;
if (alias in depAliases) id = depAliases[alias];
if (typeof depReq == 'function') {
try {
var exp = depReq(alias);
if (exported(exp)) return exp;
} catch (e) {
if (id !== alias) {
// it is possible that the module wasn't loaded yet and
// its alias is not available in the depContext object
try {
exp = depReq(id);
if (exported(exp)) return exp;
} catch (e) {
}
}
}
}
if (!(id in depContext) && !(id in root))
throw new Error("Cannot find module '" + alias + "'");
return depContext[id] || root[id];
};
mod = factory(req, exp, mod, self{{#if browserifyBuffer}}, self.Buffer{{/if}}{{#if browserifyProcess}}, self.process{{/if}});
if (typeof define === 'function' && define.amd) {
define({{#if moduleId}}'{{moduleId}}', {{/if}}
[{{#if amdRequires}}{{{requires}}}, {{/if}}
'module', 'exports', 'require'], function(module, exports, require) {
module.exports = mod;
return mod;
});
} else {
{{#each globalAliases}}
root['{{{.}}}'] = mod;
{{/each}}
}
}
})
);
"""
)
moduleTemplate = handlebars.compile(
"""
var {{{id}}} = {};
{{{id}}} = (function(module, exports{{#if filename}}, __filename{{/if}}{{#if dirname}}, __dirname{{/if}}) {
{{{code}}}
return module.exports;
})({exports: {{{id}}}}, {{{id}}}{{#if filename}}, '{{{filename}}}'{{/if}}{{#if dirname}}, '{{{dirname}}}'{{/if}});
""")
module.exports = (grunt) ->
grunt.registerMultiTask NAME, DESC, ->
options = @options(
sourceMap: true
umd: true
src_base: '.'
browserify: true)
if not options.dest
throw new Error('task needs a destination')
if not options.main
if grunt.file.exists('package.json')
pkg = grunt.file.readJSON('package.json')
if pkg.main
if /\.(coffee|js)$/.test(pkg.main)
p = pkg.main
else
p = "#{pkg.main}.coffee"
p = path.normalize(p)
if not grunt.file.exists(p)
p = "#{pkg.main}.js"
if p not in src
throw new Error("'#{p}' not in src")
options.main = p
if not options.main
throw new Error('cannot determine main module')
if Array.isArray(options.src)
options.src.push(options.main)
else
current = options.src
options.src = [options.main]
if typeof current == 'string'
options.src.unshift(current)
options.expand = cwd: options.src_base
if options.src
src = grunt.file.expand(options.expand, options.src)
if /\.js$/.test(options.dest)
options.done = @async()
buildToFile(grunt, options, src)
else
buildToDirectory(grunt, options, src)
| 4288 | # grunt-coffee-build
# https://github.com/tarruda/grunt-coffee-build
#
# Copyright (c) 2013 <NAME>
# Licensed under the MIT license.
fs = require('fs')
path = require('path')
handlebars = require('handlebars')
browserify = require('browserify')
parseScope = require('lexical-scope')
{compile} = require 'coffee-script'
{SourceMapConsumer, SourceMapGenerator} = require 'source-map'
UglifyJS = require 'uglify-js'
NAME = 'coffee_build'
DESC =
'Compiles Coffeescript files, optionally merging and generating source maps.'
# Cache of compiledfiles, keeps track of the last modified date
# so we can avoid processing it again.
buildCache = browserifyCache = timestampCache = null
TIMESTAMP_CACHE = '.timestamp_cache~'
BUILD_CACHE = '.build_cache~'
mtime = (fp) -> fs.statSync(fp).mtime.getTime()
process.on('exit', ->
# save caches to disk to speed up future builds
if timestampCache
fs.writeFileSync(TIMESTAMP_CACHE, JSON.stringify(timestampCache))
if buildCache
fs.writeFileSync(BUILD_CACHE, JSON.stringify(buildCache))
# don't save browserify build to disk since it can get complicated
# in situations where only dependencies versions change
)
process.on('SIGINT', process.exit)
process.on('SIGTERM', process.exit)
buildToDirectory = (grunt, options, src) ->
cwd = options.src_base
outDir = options.dest
if not timestampCache
if grunt.file.exists(TIMESTAMP_CACHE)
timestampCache = grunt.file.readJSON(TIMESTAMP_CACHE)
else
timestampCache = {}
if not grunt.file.exists(outDir)
grunt.file.mkdir(outDir)
src.forEach (file) ->
if file.indexOf(cwd) != 0
file = path.join(cwd, file)
if not grunt.file.exists(file)
grunt.log.warn('Source file "' + file + '" not found.')
return
outFile = path.join(outDir, path.relative(cwd, file))
entry = timestampCache[file]
mt = mtime(file)
if /\.js/.test(outFile)
if not grunt.file.exists(outFile) or mt != entry?.mtime
# plain js, just copy to the output dir
grunt.file.copy(file, outFile)
grunt.log.ok("Copied #{file} to #{outFile}")
timestampCache[file] = mtime: mt
return
outFile = outFile.replace(/\.coffee$/, '.js')
fileOutDir = path.dirname(outFile)
if not grunt.file.exists(outFile) or mt != entry?.mtime
src = grunt.file.read(file)
try
compiled = compile(src, {
sourceMap: options.sourceMap
bare: false
})
catch e
grunt.log.error("#{e.message}(file: #{file}, line: #{e.location.last_line + 1}, column: #{e.location.last_column})")
throw e
grunt.log.ok("Compiled #{file}")
if options.sourceMap
{js: compiled, v3SourceMap} = compiled
v3SourceMap = JSON.parse(v3SourceMap)
v3SourceMap.sourceRoot = path.relative(fileOutDir, cwd)
v3SourceMap.file = path.basename(outFile)
v3SourceMap.sources[0] = path.relative(cwd, file)
v3SourceMap = JSON.stringify(v3SourceMap)
compiled += "\n\n//@ sourceMappingURL=#{path.basename(outFile)}.map"
grunt.file.write("#{outFile}.map", v3SourceMap)
grunt.log.ok("File #{outFile}.map was created")
timestampCache[file] = mtime: mt
grunt.file.write(outFile, compiled)
grunt.log.ok("File #{outFile} was created")
# Function adapted from the helper function with same name thein traceur
# compiler source code.
#
# It generates an ugly identifier for a given pathname relative to
# the current file being processed, taking into consideration a base dir. eg:
# > generateNameForUrl('./b/c') # if the filename is 'a'
# '$$__a_b_c'
# > generateNameForUrl('../d') # if the filename is 'a/b/c'
# '$$__a_b_d'
#
# This assumes you won't name your variables using this prefix
generateNameForUrl = (grunt, url, from, cwd = '.', prefix = '$__') ->
try
cwd = path.resolve(cwd)
from = path.resolve(path.dirname(from))
url = path.resolve(path.join(from, url))
if grunt.file.isDir(url)
# its possible to require directories that have an index.coffee file
url = path.join(url, 'index')
ext = /\.(coffee|js)$/
if ext.test(url)
url = url.replace(ext, '')
catch e
grunt.log.warn(e)
return null
id = "$#{prefix + url.replace(cwd, '').replace(/[^\d\w$]/g, '_')}"
return {id: id, url: path.relative(cwd, url)}
# Replace all the require calls by the generated identifier that represents
# the corresponding module. This will also fill the 'deps' array so the
# main routine can concatenate the files in proper order. Require calls to
# non relative paths will be included in the requires array to be declared
# in the umd wrapper
replaceRequires = (grunt, js, fn, fp, cwd, deps, requires) ->
displayNode = (node) -> js.slice(node.start.pos, node.end.endpos)
transformer = new UglifyJS.TreeTransformer (node, descend) ->
if (not (node instanceof UglifyJS.AST_Call) or
node.expression.name != 'require' or
(node.args.length != 1 or
not /^\.(?:\.)?\//.test(node.args[0].value) and
grunt.log.writeln(
"Absolute 'require' call in file #{fn}: '#{displayNode(node)}'")) or
not (mod = generateNameForUrl(grunt, node.args[0].value, fp, cwd)))
if node instanceof UglifyJS.AST_Call and
node.expression.name == 'require' and node.args.length == 1
if node.args[0].value not of requires
grunt.log.writeln(
"Will add '#{node.args[0].value}' as an external dependency")
requires[node.args[0].value] = null
return
# I couldn't get Uglify to generate a correct mapping from the input
# map generated by coffeescript, so returning an identifier node
# to transform the tree wasn't an option.
#
# The best solution I found was to use the position information to
# replace using string slice
start = node.start.pos - posOffset
end = node.end.endpos - posOffset
posOffset += end - start - mod.id.length
before = js.slice(0, start)
after = js.slice(end)
js = before + mod.id + after
url = mod.url + '.coffee'
if not grunt.file.exists(path.join(cwd, url))
url = mod.url + '.js'
deps.push(url)
return
posOffset = 0
ast = UglifyJS.parse(js)
ast.transform(transformer)
return js
# Wraps the a javascript(possibly from compiled coffeescript) project file
# into a wrapper function that simulates a commonjs environment
makeModule = (grunt, js, v3SourceMap, fn, fp, cwd, deps, requires,
nodeGlobals) ->
moduleName = generateNameForUrl(grunt, fn, '.', '.')
{id, url} = moduleName
gen = new SourceMapGenerator({
file: fn
sourceRoot: 'tmp'
})
if v3SourceMap
# the module wrapper will push the source 2 lines down
orig = new SourceMapConsumer(v3SourceMap)
orig.eachMapping (m) ->
mapping =
source: fn
generated:
line: m.generatedLine + 3
column: m.generatedColumn
original:
line: m.originalLine or m.generatedLine
column: m.originalColumn or m.generatedColumn
gen.addMapping(mapping)
v3SourceMap = gen.toString()
ctx =
code: js
id: id
filename: null
dirname: null
scope = parseScope(js)
for name in ['Buffer', 'process', '__filename', '__dirname']
if name in scope.globals.implicit
switch name
when 'Buffer'
nodeGlobals.Buffer = true
when 'process'
nodeGlobals.process = true
when '__filename'
ctx.filename = fn
when '__dirname'
ctx.dirname = path.dirname(fn)
js = moduleTemplate(ctx)
return {
js: replaceRequires(grunt, js, fn, fp, cwd, deps, requires)
v3SourceMap: v3SourceMap
}
# This will create an 1-1 source map that will be used to map a section of the
# bundle to the original javascript file
generateJsSourceMap = (js) ->
gen = new SourceMapGenerator({
file: 'tmp'
sourceRoot: 'tmp'
})
for i in [1...js.split('\n').length]
gen.addMapping
generated:
line: i
column: 0
return gen.toString()
# Builds all input files into a single js file, parsing 'require' calls
# to resolve dependencies and concatenate in the proper order
buildToFile = (grunt, options, src) ->
cwd = options.src_base
pending = {}
allRequires = {}
processed = {}
nodeGlobals = {}
{dest: outFile, expand} = options
outDir = path.dirname(outFile)
if not buildCache
if grunt.file.exists(BUILD_CACHE)
buildCache = grunt.file.readJSON(BUILD_CACHE)
else
buildCache = {}
options.mainId = generateNameForUrl(grunt, options.main, './')
if options.disableSourceMap
disableSourceMap = grunt.file.expand(expand, options.disableSourceMap)
files = src.filter (file) ->
file = path.join(cwd, file)
if not grunt.file.exists(file)
grunt.log.warn('Source file "' + file + '" not found.')
return false
return true
gen = new SourceMapGenerator(
file: path.basename(outFile)
sourceRoot: path.relative(outDir, cwd))
output = ''
lineOffset = 6
while files.length
fn = files.shift()
fp = path.join(cwd, fn)
if fp of processed
continue
if fp of buildCache and not grunt.file.exists(fp)
# refresh the build cache
delete buildCache[fp]
if (not buildCache[fp]) or (mt = mtime(fp)) != buildCache[fp].mtime
requires = {}
deps = []
if (/\.coffee$/.test(fp))
try
{js, v3SourceMap} = compile(grunt.file.read(fp), {
sourceMap: true, bare: true})
catch e
grunt.log.error("#{e.message}(file: #{fn}, line: #{e.location.last_line + 1}, column: #{e.location.last_column})")
throw e
else # plain js
js = grunt.file.read(fp)
v3SourceMap = null
if not disableSourceMap or fn not in disableSourceMap
v3SourceMap = generateJsSourceMap(js)
{js, v3SourceMap} = makeModule(
grunt, js, v3SourceMap, fn, fp, cwd, deps, requires, nodeGlobals)
cacheEntry = buildCache[fp] =
js: js
mtime: mt
v3SourceMap: v3SourceMap
deps: deps
requires: requires
fn: fn
if /\.coffee$/.test(fp)
grunt.log.ok("Compiled #{fp}")
else
grunt.log.ok("Transformed #{fp}")
else
# Use the entry from cache
{deps, requires, js, v3SourceMap, fn} = cacheEntry = buildCache[fp]
for own k, v of requires
allRequires[k] = v
if deps.length
depsProcessed = true
for dep in deps
if dep not of processed
depsProcessed = false
break
if not depsProcessed and fp not of pending
pending[fp] = null
files.unshift(fn)
for dep in deps when dep not of pending
files.unshift(dep)
continue
# flag the file as processed
processed[fp] = null
if v3SourceMap
# concatenate the file output, and update the result source map with
# the input source map information
orig = new SourceMapConsumer(v3SourceMap)
orig.eachMapping (m) ->
gen.addMapping
generated:
line: m.generatedLine + lineOffset
column: m.generatedColumn
original:
line: m.originalLine or m.generatedLine
column: m.originalColumn or m.generatedColumn
source: fn
lineOffset += js.split('\n').length - 1
output += js
render(grunt, output, options, allRequires, nodeGlobals, (err, output) =>
if err then throw err
if options.sourceMap
sourceMapDest = path.basename(outFile) + '.map'
output += "\n\n//@ sourceMappingURL=#{sourceMapDest}"
grunt.file.write("#{outFile}.map", gen.toString())
grunt.log.ok("File #{outFile}.map was created")
grunt.file.write(outFile, output)
grunt.log.ok("File #{outFile} was created")
options.done())
render = (grunt, code, options, requires, nodeGlobals, cb) ->
bundleCb = (err, bundle) =>
if err
grunt.log.error(err)
throw err
ctx =
code: code
globalAliases: globalAliases
requires: ("'#{dep}'" for dep in requires).join(', ')
bundle: bundle
browserifyBuffer: options.browserify and 'Buffer' of nodeGlobals
browserifyProcess: options.browserify and 'process' of nodeGlobals
mainId: options.mainId.id
depAliases: depAliases
cb(null, umdTemplate(ctx))
requires = Object.keys(requires)
globalAliases = options.globalAliases
if not Array.isArray(globalAliases)
globalAliases = []
if not globalAliases.length
if grunt.file.exists('package.json')
pkg = grunt.file.readJSON('package.json')
if pkg.name
globalAliases.push(pkg.name)
if not globalAliases.length
throw new Error('cannot determine a global alias for the module')
include = options.include or []
depAliases = {}
for inc in include
if inc.alias and inc.global
depAliases[inc.alias] = inc.global
depAliases = JSON.stringify(depAliases)
buildBundle(grunt, options, requires, include, nodeGlobals, bundleCb)
buildBundle = (grunt, options, requires, include, nodeGlobals, cb) ->
browserifyCb = (err, bundle) =>
browserifyCache = bundle: bundle, deps: deps
cb(null, bundle)
if options.browserify
deps = requires.sort().toString()
if browserifyCache and browserifyCache.deps == deps
grunt.log.writeln(
'Dependencies not modified, will use the browserify cache')
# deps havent changed, return from cache
return cb(null, browserifyCache.bundle)
b = browserify()
count = 0
includedAliases = {}
if nodeGlobals.Buffer
count++
b.add('./node_buffer.js')
b.require('buffer')
if nodeGlobals.process
count++
b.add('./node_process.js')
for inc in include
count++
if not /^\./.test(inc.path)
inc.path = './' + inc.path
args = [inc.path]
if inc.alias
args.push(expose: inc.alias)
includedAliases[inc.alias] = true
b.require.apply(b, args)
if options.ignore
options.ignore = grunt.file.expand(options.ignore)
for ig in options.ignore
count++
if not /^\./.test(ig)
ig = './' + ig
b.ignore(ig)
if options.external
options.external = grunt.file.expand(options.external)
for ext in options.external
count++
if not /^\./.test(ext)
ext = './' + ext
b.external(ext)
for dep in requires
if dep of includedAliases
continue
count++
b.require(dep)
if not count
return cb(null, '')
b.bundle(ignoreMissing: true, browserifyCb)
else
includes = (grunt.file.read(inc.path) for inc in include)
bundle = bundleTemplate(includes: includes)
cb(null, bundle)
bundleTemplate = handlebars.compile(
"""
{{#each includes}}
(function() {
{{{.}}}
}).call(this);
{{/each}}
""")
# based on: https://github.com/alexlawrence/grunt-umd
umdTemplate = handlebars.compile(
"""
(function(root, factory, dependenciesFactory, setup) {
setup(root, factory, dependenciesFactory);
})(
this,
(function(require, exports, module, global{{#if browserifyBuffer}}, Buffer{{/if}}{{#if browserifyProcess}}, process{{/if}}, undefined) {
{{{code}}}
return {{{mainId}}};
}),
(function() {
var require;
{{{bundle}}}
return require;
}),
(function(root, factory, dependenciesFactory) {
if(typeof exports === 'object') {
module.exports = factory(require, exports, module);
}
else {
// provide a separate context for dependencies
var depContext = {};
var depAliases = {{{depAliases}}};
var depReq = dependenciesFactory.call(depContext);
var mod = {exports: {}};
var exp = mod.exports;
var exported = function(obj) {
// check if the module exported anything
if (typeof obj !== 'object') return true;
for (var k in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, k)) continue;
return true;
}
return false;
};
var req = function(id) {
var alias = id;
if (alias in depAliases) id = depAliases[alias];
if (typeof depReq == 'function') {
try {
var exp = depReq(alias);
if (exported(exp)) return exp;
} catch (e) {
if (id !== alias) {
// it is possible that the module wasn't loaded yet and
// its alias is not available in the depContext object
try {
exp = depReq(id);
if (exported(exp)) return exp;
} catch (e) {
}
}
}
}
if (!(id in depContext) && !(id in root))
throw new Error("Cannot find module '" + alias + "'");
return depContext[id] || root[id];
};
mod = factory(req, exp, mod, self{{#if browserifyBuffer}}, self.Buffer{{/if}}{{#if browserifyProcess}}, self.process{{/if}});
if (typeof define === 'function' && define.amd) {
define({{#if moduleId}}'{{moduleId}}', {{/if}}
[{{#if amdRequires}}{{{requires}}}, {{/if}}
'module', 'exports', 'require'], function(module, exports, require) {
module.exports = mod;
return mod;
});
} else {
{{#each globalAliases}}
root['{{{.}}}'] = mod;
{{/each}}
}
}
})
);
"""
)
moduleTemplate = handlebars.compile(
"""
var {{{id}}} = {};
{{{id}}} = (function(module, exports{{#if filename}}, __filename{{/if}}{{#if dirname}}, __dirname{{/if}}) {
{{{code}}}
return module.exports;
})({exports: {{{id}}}}, {{{id}}}{{#if filename}}, '{{{filename}}}'{{/if}}{{#if dirname}}, '{{{dirname}}}'{{/if}});
""")
module.exports = (grunt) ->
grunt.registerMultiTask NAME, DESC, ->
options = @options(
sourceMap: true
umd: true
src_base: '.'
browserify: true)
if not options.dest
throw new Error('task needs a destination')
if not options.main
if grunt.file.exists('package.json')
pkg = grunt.file.readJSON('package.json')
if pkg.main
if /\.(coffee|js)$/.test(pkg.main)
p = pkg.main
else
p = "#{pkg.main}.coffee"
p = path.normalize(p)
if not grunt.file.exists(p)
p = "#{pkg.main}.js"
if p not in src
throw new Error("'#{p}' not in src")
options.main = p
if not options.main
throw new Error('cannot determine main module')
if Array.isArray(options.src)
options.src.push(options.main)
else
current = options.src
options.src = [options.main]
if typeof current == 'string'
options.src.unshift(current)
options.expand = cwd: options.src_base
if options.src
src = grunt.file.expand(options.expand, options.src)
if /\.js$/.test(options.dest)
options.done = @async()
buildToFile(grunt, options, src)
else
buildToDirectory(grunt, options, src)
| true | # grunt-coffee-build
# https://github.com/tarruda/grunt-coffee-build
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI
# Licensed under the MIT license.
fs = require('fs')
path = require('path')
handlebars = require('handlebars')
browserify = require('browserify')
parseScope = require('lexical-scope')
{compile} = require 'coffee-script'
{SourceMapConsumer, SourceMapGenerator} = require 'source-map'
UglifyJS = require 'uglify-js'
NAME = 'coffee_build'
DESC =
'Compiles Coffeescript files, optionally merging and generating source maps.'
# Cache of compiledfiles, keeps track of the last modified date
# so we can avoid processing it again.
buildCache = browserifyCache = timestampCache = null
TIMESTAMP_CACHE = '.timestamp_cache~'
BUILD_CACHE = '.build_cache~'
mtime = (fp) -> fs.statSync(fp).mtime.getTime()
process.on('exit', ->
# save caches to disk to speed up future builds
if timestampCache
fs.writeFileSync(TIMESTAMP_CACHE, JSON.stringify(timestampCache))
if buildCache
fs.writeFileSync(BUILD_CACHE, JSON.stringify(buildCache))
# don't save browserify build to disk since it can get complicated
# in situations where only dependencies versions change
)
process.on('SIGINT', process.exit)
process.on('SIGTERM', process.exit)
buildToDirectory = (grunt, options, src) ->
cwd = options.src_base
outDir = options.dest
if not timestampCache
if grunt.file.exists(TIMESTAMP_CACHE)
timestampCache = grunt.file.readJSON(TIMESTAMP_CACHE)
else
timestampCache = {}
if not grunt.file.exists(outDir)
grunt.file.mkdir(outDir)
src.forEach (file) ->
if file.indexOf(cwd) != 0
file = path.join(cwd, file)
if not grunt.file.exists(file)
grunt.log.warn('Source file "' + file + '" not found.')
return
outFile = path.join(outDir, path.relative(cwd, file))
entry = timestampCache[file]
mt = mtime(file)
if /\.js/.test(outFile)
if not grunt.file.exists(outFile) or mt != entry?.mtime
# plain js, just copy to the output dir
grunt.file.copy(file, outFile)
grunt.log.ok("Copied #{file} to #{outFile}")
timestampCache[file] = mtime: mt
return
outFile = outFile.replace(/\.coffee$/, '.js')
fileOutDir = path.dirname(outFile)
if not grunt.file.exists(outFile) or mt != entry?.mtime
src = grunt.file.read(file)
try
compiled = compile(src, {
sourceMap: options.sourceMap
bare: false
})
catch e
grunt.log.error("#{e.message}(file: #{file}, line: #{e.location.last_line + 1}, column: #{e.location.last_column})")
throw e
grunt.log.ok("Compiled #{file}")
if options.sourceMap
{js: compiled, v3SourceMap} = compiled
v3SourceMap = JSON.parse(v3SourceMap)
v3SourceMap.sourceRoot = path.relative(fileOutDir, cwd)
v3SourceMap.file = path.basename(outFile)
v3SourceMap.sources[0] = path.relative(cwd, file)
v3SourceMap = JSON.stringify(v3SourceMap)
compiled += "\n\n//@ sourceMappingURL=#{path.basename(outFile)}.map"
grunt.file.write("#{outFile}.map", v3SourceMap)
grunt.log.ok("File #{outFile}.map was created")
timestampCache[file] = mtime: mt
grunt.file.write(outFile, compiled)
grunt.log.ok("File #{outFile} was created")
# Function adapted from the helper function with same name thein traceur
# compiler source code.
#
# It generates an ugly identifier for a given pathname relative to
# the current file being processed, taking into consideration a base dir. eg:
# > generateNameForUrl('./b/c') # if the filename is 'a'
# '$$__a_b_c'
# > generateNameForUrl('../d') # if the filename is 'a/b/c'
# '$$__a_b_d'
#
# This assumes you won't name your variables using this prefix
generateNameForUrl = (grunt, url, from, cwd = '.', prefix = '$__') ->
try
cwd = path.resolve(cwd)
from = path.resolve(path.dirname(from))
url = path.resolve(path.join(from, url))
if grunt.file.isDir(url)
# its possible to require directories that have an index.coffee file
url = path.join(url, 'index')
ext = /\.(coffee|js)$/
if ext.test(url)
url = url.replace(ext, '')
catch e
grunt.log.warn(e)
return null
id = "$#{prefix + url.replace(cwd, '').replace(/[^\d\w$]/g, '_')}"
return {id: id, url: path.relative(cwd, url)}
# Replace all the require calls by the generated identifier that represents
# the corresponding module. This will also fill the 'deps' array so the
# main routine can concatenate the files in proper order. Require calls to
# non relative paths will be included in the requires array to be declared
# in the umd wrapper
replaceRequires = (grunt, js, fn, fp, cwd, deps, requires) ->
displayNode = (node) -> js.slice(node.start.pos, node.end.endpos)
transformer = new UglifyJS.TreeTransformer (node, descend) ->
if (not (node instanceof UglifyJS.AST_Call) or
node.expression.name != 'require' or
(node.args.length != 1 or
not /^\.(?:\.)?\//.test(node.args[0].value) and
grunt.log.writeln(
"Absolute 'require' call in file #{fn}: '#{displayNode(node)}'")) or
not (mod = generateNameForUrl(grunt, node.args[0].value, fp, cwd)))
if node instanceof UglifyJS.AST_Call and
node.expression.name == 'require' and node.args.length == 1
if node.args[0].value not of requires
grunt.log.writeln(
"Will add '#{node.args[0].value}' as an external dependency")
requires[node.args[0].value] = null
return
# I couldn't get Uglify to generate a correct mapping from the input
# map generated by coffeescript, so returning an identifier node
# to transform the tree wasn't an option.
#
# The best solution I found was to use the position information to
# replace using string slice
start = node.start.pos - posOffset
end = node.end.endpos - posOffset
posOffset += end - start - mod.id.length
before = js.slice(0, start)
after = js.slice(end)
js = before + mod.id + after
url = mod.url + '.coffee'
if not grunt.file.exists(path.join(cwd, url))
url = mod.url + '.js'
deps.push(url)
return
posOffset = 0
ast = UglifyJS.parse(js)
ast.transform(transformer)
return js
# Wraps the a javascript(possibly from compiled coffeescript) project file
# into a wrapper function that simulates a commonjs environment
makeModule = (grunt, js, v3SourceMap, fn, fp, cwd, deps, requires,
nodeGlobals) ->
moduleName = generateNameForUrl(grunt, fn, '.', '.')
{id, url} = moduleName
gen = new SourceMapGenerator({
file: fn
sourceRoot: 'tmp'
})
if v3SourceMap
# the module wrapper will push the source 2 lines down
orig = new SourceMapConsumer(v3SourceMap)
orig.eachMapping (m) ->
mapping =
source: fn
generated:
line: m.generatedLine + 3
column: m.generatedColumn
original:
line: m.originalLine or m.generatedLine
column: m.originalColumn or m.generatedColumn
gen.addMapping(mapping)
v3SourceMap = gen.toString()
ctx =
code: js
id: id
filename: null
dirname: null
scope = parseScope(js)
for name in ['Buffer', 'process', '__filename', '__dirname']
if name in scope.globals.implicit
switch name
when 'Buffer'
nodeGlobals.Buffer = true
when 'process'
nodeGlobals.process = true
when '__filename'
ctx.filename = fn
when '__dirname'
ctx.dirname = path.dirname(fn)
js = moduleTemplate(ctx)
return {
js: replaceRequires(grunt, js, fn, fp, cwd, deps, requires)
v3SourceMap: v3SourceMap
}
# This will create an 1-1 source map that will be used to map a section of the
# bundle to the original javascript file
generateJsSourceMap = (js) ->
gen = new SourceMapGenerator({
file: 'tmp'
sourceRoot: 'tmp'
})
for i in [1...js.split('\n').length]
gen.addMapping
generated:
line: i
column: 0
return gen.toString()
# Builds all input files into a single js file, parsing 'require' calls
# to resolve dependencies and concatenate in the proper order
buildToFile = (grunt, options, src) ->
cwd = options.src_base
pending = {}
allRequires = {}
processed = {}
nodeGlobals = {}
{dest: outFile, expand} = options
outDir = path.dirname(outFile)
if not buildCache
if grunt.file.exists(BUILD_CACHE)
buildCache = grunt.file.readJSON(BUILD_CACHE)
else
buildCache = {}
options.mainId = generateNameForUrl(grunt, options.main, './')
if options.disableSourceMap
disableSourceMap = grunt.file.expand(expand, options.disableSourceMap)
files = src.filter (file) ->
file = path.join(cwd, file)
if not grunt.file.exists(file)
grunt.log.warn('Source file "' + file + '" not found.')
return false
return true
gen = new SourceMapGenerator(
file: path.basename(outFile)
sourceRoot: path.relative(outDir, cwd))
output = ''
lineOffset = 6
while files.length
fn = files.shift()
fp = path.join(cwd, fn)
if fp of processed
continue
if fp of buildCache and not grunt.file.exists(fp)
# refresh the build cache
delete buildCache[fp]
if (not buildCache[fp]) or (mt = mtime(fp)) != buildCache[fp].mtime
requires = {}
deps = []
if (/\.coffee$/.test(fp))
try
{js, v3SourceMap} = compile(grunt.file.read(fp), {
sourceMap: true, bare: true})
catch e
grunt.log.error("#{e.message}(file: #{fn}, line: #{e.location.last_line + 1}, column: #{e.location.last_column})")
throw e
else # plain js
js = grunt.file.read(fp)
v3SourceMap = null
if not disableSourceMap or fn not in disableSourceMap
v3SourceMap = generateJsSourceMap(js)
{js, v3SourceMap} = makeModule(
grunt, js, v3SourceMap, fn, fp, cwd, deps, requires, nodeGlobals)
cacheEntry = buildCache[fp] =
js: js
mtime: mt
v3SourceMap: v3SourceMap
deps: deps
requires: requires
fn: fn
if /\.coffee$/.test(fp)
grunt.log.ok("Compiled #{fp}")
else
grunt.log.ok("Transformed #{fp}")
else
# Use the entry from cache
{deps, requires, js, v3SourceMap, fn} = cacheEntry = buildCache[fp]
for own k, v of requires
allRequires[k] = v
if deps.length
depsProcessed = true
for dep in deps
if dep not of processed
depsProcessed = false
break
if not depsProcessed and fp not of pending
pending[fp] = null
files.unshift(fn)
for dep in deps when dep not of pending
files.unshift(dep)
continue
# flag the file as processed
processed[fp] = null
if v3SourceMap
# concatenate the file output, and update the result source map with
# the input source map information
orig = new SourceMapConsumer(v3SourceMap)
orig.eachMapping (m) ->
gen.addMapping
generated:
line: m.generatedLine + lineOffset
column: m.generatedColumn
original:
line: m.originalLine or m.generatedLine
column: m.originalColumn or m.generatedColumn
source: fn
lineOffset += js.split('\n').length - 1
output += js
render(grunt, output, options, allRequires, nodeGlobals, (err, output) =>
if err then throw err
if options.sourceMap
sourceMapDest = path.basename(outFile) + '.map'
output += "\n\n//@ sourceMappingURL=#{sourceMapDest}"
grunt.file.write("#{outFile}.map", gen.toString())
grunt.log.ok("File #{outFile}.map was created")
grunt.file.write(outFile, output)
grunt.log.ok("File #{outFile} was created")
options.done())
render = (grunt, code, options, requires, nodeGlobals, cb) ->
bundleCb = (err, bundle) =>
if err
grunt.log.error(err)
throw err
ctx =
code: code
globalAliases: globalAliases
requires: ("'#{dep}'" for dep in requires).join(', ')
bundle: bundle
browserifyBuffer: options.browserify and 'Buffer' of nodeGlobals
browserifyProcess: options.browserify and 'process' of nodeGlobals
mainId: options.mainId.id
depAliases: depAliases
cb(null, umdTemplate(ctx))
requires = Object.keys(requires)
globalAliases = options.globalAliases
if not Array.isArray(globalAliases)
globalAliases = []
if not globalAliases.length
if grunt.file.exists('package.json')
pkg = grunt.file.readJSON('package.json')
if pkg.name
globalAliases.push(pkg.name)
if not globalAliases.length
throw new Error('cannot determine a global alias for the module')
include = options.include or []
depAliases = {}
for inc in include
if inc.alias and inc.global
depAliases[inc.alias] = inc.global
depAliases = JSON.stringify(depAliases)
buildBundle(grunt, options, requires, include, nodeGlobals, bundleCb)
buildBundle = (grunt, options, requires, include, nodeGlobals, cb) ->
browserifyCb = (err, bundle) =>
browserifyCache = bundle: bundle, deps: deps
cb(null, bundle)
if options.browserify
deps = requires.sort().toString()
if browserifyCache and browserifyCache.deps == deps
grunt.log.writeln(
'Dependencies not modified, will use the browserify cache')
# deps havent changed, return from cache
return cb(null, browserifyCache.bundle)
b = browserify()
count = 0
includedAliases = {}
if nodeGlobals.Buffer
count++
b.add('./node_buffer.js')
b.require('buffer')
if nodeGlobals.process
count++
b.add('./node_process.js')
for inc in include
count++
if not /^\./.test(inc.path)
inc.path = './' + inc.path
args = [inc.path]
if inc.alias
args.push(expose: inc.alias)
includedAliases[inc.alias] = true
b.require.apply(b, args)
if options.ignore
options.ignore = grunt.file.expand(options.ignore)
for ig in options.ignore
count++
if not /^\./.test(ig)
ig = './' + ig
b.ignore(ig)
if options.external
options.external = grunt.file.expand(options.external)
for ext in options.external
count++
if not /^\./.test(ext)
ext = './' + ext
b.external(ext)
for dep in requires
if dep of includedAliases
continue
count++
b.require(dep)
if not count
return cb(null, '')
b.bundle(ignoreMissing: true, browserifyCb)
else
includes = (grunt.file.read(inc.path) for inc in include)
bundle = bundleTemplate(includes: includes)
cb(null, bundle)
bundleTemplate = handlebars.compile(
"""
{{#each includes}}
(function() {
{{{.}}}
}).call(this);
{{/each}}
""")
# based on: https://github.com/alexlawrence/grunt-umd
umdTemplate = handlebars.compile(
"""
(function(root, factory, dependenciesFactory, setup) {
setup(root, factory, dependenciesFactory);
})(
this,
(function(require, exports, module, global{{#if browserifyBuffer}}, Buffer{{/if}}{{#if browserifyProcess}}, process{{/if}}, undefined) {
{{{code}}}
return {{{mainId}}};
}),
(function() {
var require;
{{{bundle}}}
return require;
}),
(function(root, factory, dependenciesFactory) {
if(typeof exports === 'object') {
module.exports = factory(require, exports, module);
}
else {
// provide a separate context for dependencies
var depContext = {};
var depAliases = {{{depAliases}}};
var depReq = dependenciesFactory.call(depContext);
var mod = {exports: {}};
var exp = mod.exports;
var exported = function(obj) {
// check if the module exported anything
if (typeof obj !== 'object') return true;
for (var k in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, k)) continue;
return true;
}
return false;
};
var req = function(id) {
var alias = id;
if (alias in depAliases) id = depAliases[alias];
if (typeof depReq == 'function') {
try {
var exp = depReq(alias);
if (exported(exp)) return exp;
} catch (e) {
if (id !== alias) {
// it is possible that the module wasn't loaded yet and
// its alias is not available in the depContext object
try {
exp = depReq(id);
if (exported(exp)) return exp;
} catch (e) {
}
}
}
}
if (!(id in depContext) && !(id in root))
throw new Error("Cannot find module '" + alias + "'");
return depContext[id] || root[id];
};
mod = factory(req, exp, mod, self{{#if browserifyBuffer}}, self.Buffer{{/if}}{{#if browserifyProcess}}, self.process{{/if}});
if (typeof define === 'function' && define.amd) {
define({{#if moduleId}}'{{moduleId}}', {{/if}}
[{{#if amdRequires}}{{{requires}}}, {{/if}}
'module', 'exports', 'require'], function(module, exports, require) {
module.exports = mod;
return mod;
});
} else {
{{#each globalAliases}}
root['{{{.}}}'] = mod;
{{/each}}
}
}
})
);
"""
)
moduleTemplate = handlebars.compile(
"""
var {{{id}}} = {};
{{{id}}} = (function(module, exports{{#if filename}}, __filename{{/if}}{{#if dirname}}, __dirname{{/if}}) {
{{{code}}}
return module.exports;
})({exports: {{{id}}}}, {{{id}}}{{#if filename}}, '{{{filename}}}'{{/if}}{{#if dirname}}, '{{{dirname}}}'{{/if}});
""")
module.exports = (grunt) ->
grunt.registerMultiTask NAME, DESC, ->
options = @options(
sourceMap: true
umd: true
src_base: '.'
browserify: true)
if not options.dest
throw new Error('task needs a destination')
if not options.main
if grunt.file.exists('package.json')
pkg = grunt.file.readJSON('package.json')
if pkg.main
if /\.(coffee|js)$/.test(pkg.main)
p = pkg.main
else
p = "#{pkg.main}.coffee"
p = path.normalize(p)
if not grunt.file.exists(p)
p = "#{pkg.main}.js"
if p not in src
throw new Error("'#{p}' not in src")
options.main = p
if not options.main
throw new Error('cannot determine main module')
if Array.isArray(options.src)
options.src.push(options.main)
else
current = options.src
options.src = [options.main]
if typeof current == 'string'
options.src.unshift(current)
options.expand = cwd: options.src_base
if options.src
src = grunt.file.expand(options.expand, options.src)
if /\.js$/.test(options.dest)
options.done = @async()
buildToFile(grunt, options, src)
else
buildToDirectory(grunt, options, src)
|
[
{
"context": "###\nCopyright 2016 Resin.io\n\nLicensed under the Apache License, Version 2.0 (",
"end": 27,
"score": 0.5602496862411499,
"start": 25,
"tag": "NAME",
"value": "io"
}
] | lib/pubnub.coffee | resin-io-modules/resin-device-logs | 0 | ###
Copyright 2016 Resin.io
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.
###
assign = require('lodash/assign')
memoize = require('lodash/memoize')
Promise = require('bluebird')
PubNub = require('pubnub')
getPublishKey = (options) -> options.publishKey or options.publish_key
getSubscribeKey = (options) -> options.subscribeKey or options.subscribe_key
###*
# @summary Get a PubNub instance
# @function
# @protected
#
# @param {Object} options - PubNub options
# @param {String} options.subscribeKey - subscribe key (`subscribe_key` is also supported)
# @param {String} options.publishKey - publish key (`publish_key` is also supported)
#
# @returns {Object} PubNub instance
###
exports.getInstance = memoize (options) ->
new PubNub({
publishKey: getPublishKey(options)
subscribeKey: getSubscribeKey(options)
ssl: true
})
, getSubscribeKey
###*
# @summary Get logs history from an instance
# @function
# @protected
#
# @description
# **Note:** For invalid (non-existent) channel this will return
# an empty array as if it exists but doesn't have any history messages.
#
# @param {Object} instance - PubNub instance
# @param {String} channel - channel
# @param {Object} [options] - other options supported by
# https://www.pubnub.com/docs/nodejs-javascript/api-reference#history
#
# @returns {Promise<any[]>} history messages
###
exports.history = (instance, channel, options = {}) ->
options = assign({ channel }, options)
return instance.history(options)
.then ({ messages }) ->
messages.map((m) -> m.entry)
| 144454 | ###
Copyright 2016 Resin.<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.
###
assign = require('lodash/assign')
memoize = require('lodash/memoize')
Promise = require('bluebird')
PubNub = require('pubnub')
getPublishKey = (options) -> options.publishKey or options.publish_key
getSubscribeKey = (options) -> options.subscribeKey or options.subscribe_key
###*
# @summary Get a PubNub instance
# @function
# @protected
#
# @param {Object} options - PubNub options
# @param {String} options.subscribeKey - subscribe key (`subscribe_key` is also supported)
# @param {String} options.publishKey - publish key (`publish_key` is also supported)
#
# @returns {Object} PubNub instance
###
exports.getInstance = memoize (options) ->
new PubNub({
publishKey: getPublishKey(options)
subscribeKey: getSubscribeKey(options)
ssl: true
})
, getSubscribeKey
###*
# @summary Get logs history from an instance
# @function
# @protected
#
# @description
# **Note:** For invalid (non-existent) channel this will return
# an empty array as if it exists but doesn't have any history messages.
#
# @param {Object} instance - PubNub instance
# @param {String} channel - channel
# @param {Object} [options] - other options supported by
# https://www.pubnub.com/docs/nodejs-javascript/api-reference#history
#
# @returns {Promise<any[]>} history messages
###
exports.history = (instance, channel, options = {}) ->
options = assign({ channel }, options)
return instance.history(options)
.then ({ messages }) ->
messages.map((m) -> m.entry)
| true | ###
Copyright 2016 Resin.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.
###
assign = require('lodash/assign')
memoize = require('lodash/memoize')
Promise = require('bluebird')
PubNub = require('pubnub')
getPublishKey = (options) -> options.publishKey or options.publish_key
getSubscribeKey = (options) -> options.subscribeKey or options.subscribe_key
###*
# @summary Get a PubNub instance
# @function
# @protected
#
# @param {Object} options - PubNub options
# @param {String} options.subscribeKey - subscribe key (`subscribe_key` is also supported)
# @param {String} options.publishKey - publish key (`publish_key` is also supported)
#
# @returns {Object} PubNub instance
###
exports.getInstance = memoize (options) ->
new PubNub({
publishKey: getPublishKey(options)
subscribeKey: getSubscribeKey(options)
ssl: true
})
, getSubscribeKey
###*
# @summary Get logs history from an instance
# @function
# @protected
#
# @description
# **Note:** For invalid (non-existent) channel this will return
# an empty array as if it exists but doesn't have any history messages.
#
# @param {Object} instance - PubNub instance
# @param {String} channel - channel
# @param {Object} [options] - other options supported by
# https://www.pubnub.com/docs/nodejs-javascript/api-reference#history
#
# @returns {Promise<any[]>} history messages
###
exports.history = (instance, channel, options = {}) ->
options = assign({ channel }, options)
return instance.history(options)
.then ({ messages }) ->
messages.map((m) -> m.entry)
|
[
{
"context": "_page\": \"47\",\n \"author\": [\n {\"name\": \"Jones Richard\"},\n {\"name\": \"MacGillivray Mark\"},\n ",
"end": 12398,
"score": 0.9997777938842773,
"start": 12385,
"tag": "NAME",
"value": "Jones Richard"
},
{
"context": " {\"name\": \"Jones Richard\"},\n {\"name\": \"MacGillivray Mark\"},\n {\"name\": \"Murray-Rust Peter\"},\n ",
"end": 12437,
"score": 0.9997816681861877,
"start": 12420,
"tag": "NAME",
"value": "MacGillivray Mark"
},
{
"context": " {\"name\": \"MacGillivray Mark\"},\n {\"name\": \"Murray-Rust Peter\"},\n {\"name\": \"Pitman Jim\"},\n {\"name",
"end": 12476,
"score": 0.9997962117195129,
"start": 12459,
"tag": "NAME",
"value": "Murray-Rust Peter"
},
{
"context": " {\"name\": \"Murray-Rust Peter\"},\n {\"name\": \"Pitman Jim\"},\n {\"name\": \"Sefton Peter\"},\n {\"na",
"end": 12508,
"score": 0.9997272491455078,
"start": 12498,
"tag": "NAME",
"value": "Pitman Jim"
},
{
"context": " {\"name\": \"Pitman Jim\"},\n {\"name\": \"Sefton Peter\"},\n {\"name\": \"O'Steen Ben\"},\n {\"nam",
"end": 12542,
"score": 0.9997869729995728,
"start": 12530,
"tag": "NAME",
"value": "Sefton Peter"
},
{
"context": " {\"name\": \"Sefton Peter\"},\n {\"name\": \"O'Steen Ben\"},\n {\"name\": \"Waites William\"}\n ],\n ",
"end": 12575,
"score": 0.9997950792312622,
"start": 12564,
"tag": "NAME",
"value": "O'Steen Ben"
},
{
"context": " {\"name\": \"O'Steen Ben\"},\n {\"name\": \"Waites William\"}\n ],\n \"journal\": {\n \"publisher\"",
"end": 12611,
"score": 0.9997149705886841,
"start": 12597,
"tag": "NAME",
"value": "Waites William"
}
] | server/use/doaj.coffee | leviathanindustries/noddy | 2 |
# use the doaj
# https://doaj.org/api/v1/docs
# DOAJ API only allows results up to 1000, regardless of page size or rate limit. Annoying...
import fs from 'fs'
import tar from 'tar'
import Future from 'fibers/future'
@doaj_journal = new API.collection {index:"doaj",type:"journal"}
@doaj_in_progress = new API.collection {index:"doaj",type:"inprogress"}
API.use ?= {}
API.use.doaj = {journals: {}, articles: {}}
API.add 'use/doaj/:which/es',
get: () -> return API.use.doaj.es this.urlParams.which, this.queryParams, undefined, this.queryParams.format
post: () -> return API.use.doaj.es this.urlParams.which, this.queryParams, this.bodyParams, this.queryParams.format
API.add 'use/doaj/articles/search/:qry',
get: () -> return API.use.doaj.articles.search this.urlParams.qry, this.queryParams, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/articles/title/:qry',
get: () -> return API.use.doaj.articles.title this.urlParams.qry, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/articles/doi/:doipre/:doipost',
get: () -> return API.use.doaj.articles.doi this.urlParams.doipre + '/' + this.urlParams.doipost, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/articles/doi/:doipre/:doipost/:doiextra',
get: () -> return API.use.doaj.articles.doi this.urlParams.doipre + '/' + this.urlParams.doipost + '/' + this.urlParams.doiextra, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/journals', () -> return doaj_journal.search this
API.add 'use/doaj/journals/inprogress', () -> return doaj_in_progress.search this
API.add 'use/doaj/journals/:issn',
get: () -> return API.use.doaj.journals.issn this.urlParams.issn
API.add 'use/doaj/journals/import',
get:
roleRequired: if API.settings.dev then undefined else 'doaj.admin'
action: () ->
Meteor.setTimeout (() => API.use.doaj.journals.import this.queryParams.refresh), 1
return true
API.use.doaj.es = (which='journal,article', params, body, format=true) ->
# which could be journal or article or journal,article
# but doaj only allows this type of query on journal,article, so will add this later as a query filter
url = 'https://doaj.org/query/journal,article/_search?ref=public_journal_article&'
# this only works with a source param, if one is not present, should convert the query into a source param
if body
for p of params
body[p] = params[p] # allow params to override body?
else
body = params
if body.format?
delete body.format
format ?= true
if not body.source?
tr = API.collection._translate body
body = source: tr # unless doing a post, in which case don't do this part
body.source.aggs ?= {} # requier this to get doaj to accept the query
body.source.query.filtered.query.bool.must.push({term: {_type: which}}) if which isnt 'journal,article'
#body.source.query = body.source.query.filtered.query.bool.must[0]
#body.source.query ?= {query_string: {query: ""}}
url += op + '=' + encodeURIComponent(JSON.stringify(body[op])) + '&' for op of body
API.log 'Using doaj ES for ' + url
try
res = HTTP.call 'GET', url
try res.data.query = body
if res.statusCode is 200
if format
res.data = res.data.hits
for d of res.data.hits
res.data.hits[d] = API.use.doaj.articles.format res.data.hits[d]._source
res.data.data = res.data.hits
delete res.data.hits
return res.data
else
return {status: 'error', data: res.data, query: body}
catch err
return {status: 'error', error: err, query: body, url: url}
API.use.doaj.journals.issn = (issn) ->
issn = issn.split(',') if typeof issn is 'string'
r = API.use.doaj.journals.search 'issn.exact:"' + issn.join(' OR issn.exact:"') + '"', undefined
return if r.hits?.total then r.hits.hits[0]._source else undefined
API.use.doaj.journals.search = (qry) ->
return doaj_journal.search qry
API.use.doaj.journals.inprogress = (qry) ->
return doaj_in_progress.search qry
API.use.doaj.journals.import = (refresh) ->
# doaj only updates their journal dump once a week so calling journal import
# won't actually do anything if the dump file name has not changed since last run
# or if a refresh is called
fldr = '/tmp/doaj' + (if API.settings.dev then '_dev' else '') + '/'
if not fs.existsSync fldr
fs.mkdirSync fldr
ret = false
try
prev = false
current = false
fs.writeFileSync fldr + 'doaj.tar', HTTP.call('GET', 'https://doaj.org/public-data-dump/journal', {npmRequestOptions:{encoding:null}}).content
tar.extract file: fldr + 'doaj.tar', cwd: fldr, sync: true # extracted doaj dump folders end 2020-10-01
for f in fs.readdirSync fldr # readdir alphasorts, so if more than one in tmp then last one will be newest
if f.indexOf('doaj_journal_data') isnt -1
if prev
try fs.unlinkSync fldr + prev + '/journal_batch_1.json'
try fs.rmdirSync fldr + prev
prev = current
current = f
if current and (prev or refresh)
doaj_journal.remove '*'
counter = 0
dely = 800
while counter < 5 and not doaj_journal.mapping().dynamic_templates?
future = new Future()
setTimeout (() -> future.return()), dely
future.wait()
doaj_journal.map API.es._mapping
dely = dely * 2
counter += 1
console.log counter
doaj_journal.insert JSON.parse fs.readFileSync fldr + current + '/journal_batch_1.json'
API.log 'Imported DOAJ journals'
ret = true
if not doaj_journal.mapping().dynamic_templates?
API.log notify: true, msg: 'DOAJ journals import did not successfully map'
else
API.log 'DOAJ journal import ran but found nothing new to import'
ret = false
catch
API.log 'Error trying to import DOAJ journals'
ret = false
if ret is true
# only get new doaj inprogress data if the journals load processed some doaj
# journals (otherwise we're between the week-long period when doaj doesn't update)
# and if doaj did update, load them into the catalogue too
try
r = HTTP.call 'GET', 'https://doaj.org/jct/inprogress?api_key=' + API.settings.service.doaj.apikey
rc = JSON.parse r.content
doaj_in_progress.remove '*'
doaj_in_progress.insert rc
return ret
_doaj_journals_import = () ->
if API.settings.cluster?.ip? and API.status.ip() not in API.settings.cluster.ip
API.log 'Setting up a DOAJ journal import to run each day if their dump file updated on ' + API.status.ip()
Meteor.setInterval API.use.doaj.journals.import, 43200000
Meteor.setTimeout _doaj_journals_import, 22000
API.use.doaj.articles.doi = (doi, format, refresh) ->
return API.use.doaj.articles.get 'doi:' + doi, format
API.use.doaj.articles.title = (title, format, refresh) ->
try title = title.toLowerCase().replace(/(<([^>]+)>)/g,'').replace(/[^a-z0-9 ]+/g, " ").replace(/\s\s+/g, ' ')
return API.use.doaj.articles.get 'title:"' + title + '"', format, refresh
API.use.doaj.articles.get = (qry, format=true, refresh) ->
res = API.use.doaj.articles.search qry, undefined, false, refresh
rec = if res?.data?.length then res.data[0] else undefined
if rec?
op = API.use.doaj.articles.redirect rec
rec.url = op.url
rec.redirect = op.redirect
return if format and typeof rec is 'object' then API.use.doaj.articles.format(rec) else rec
API.use.doaj.articles.search = (qry, params={}, format=true, refresh) ->
if refresh isnt true and cached = API.http.cache qry, 'doaj_articles', undefined, refresh
return cached
else
url = 'https://doaj.org/api/v1/search/articles/' + qry + '?'
#params.sort ?= 'bibjson.year:desc'
url += op + '=' + params[op] + '&' for op of params
API.log 'Using doaj for ' + url
try
#res = HTTP.call 'GET', url
res = API.job.limit 400, 'HTTP.call', ['GET',url], "DOAJ"
if res.statusCode is 200
if format
for d of res.data.results
res.data.results[d] = API.use.doaj.articles.format res.data.results[d]
res.data.data = res.data.results
delete res.data.results
API.http.cache qry, 'doaj_articles', res.data
return res.data
else
return {status: 'error', data: res.data}
catch err
return {status: 'error', data: 'DOAJ error', error: err}
API.use.doaj.articles.redirect = (record) ->
res = {}
if record.bibjson?.link?
for l in record.bibjson.link
if l.type is 'fulltext'
res.url = l.url
if res.url?
try
resolves = HTTP.call 'HEAD', res.url, {timeout: API.settings.use?.doaj?.timeout ? API.settings.use?._timeout ? 2000}
catch
res.url = undefined
res.redirect = API.service.oab.redirect(res.url) if API.service.oab?
break if res.url and res.redirect isnt false
return res
API.use.doaj.articles.format = (rec, metadata={}) ->
try metadata.pdf ?= rec.pdf
try metadata.url ?= rec.url
try metadata.redirect ?= rec.redirect
try
rec = rec.bibjson if rec.bibjson?
try metadata.title ?= rec.title
try metadata.abstract ?= rec.abstract.replace(/\n/g,' ')
try metadata.volume ?= rec.journal.volume
try metadata.issn ?= rec.journal.issns[0]
if not metadata.page?
try metadata.page = rec.start_page
try metadata.page += '-' + rec.end_page if rec.end_page?
try metadata.journal ?= rec.journal.title
try metadata.publisher ?= rec.journal.publisher
try metadata.year ?= rec.year
try
rm = rec.month ? '01'
rm = 1 if rm is 0 or rm is "0"
if rec.month?
try
rmt = rec.month.substring(0,3).toLowerCase()
if rmt.length is 3
idx = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf rmt
rm = idx+1 if idx isnt -1
metadata.published ?= rec.year + '-' + rm + '-' + (rec.day ? '01')
try
metadata.author ?= []
for a in rec.author
as = a.name.split(' ')
a.family = as[as.length-1]
a.given = a.name.replace(a.family,'').trim()
if a.affiliation?
a.affiliation = a.affiliation[0] if _.isArray a.affiliation
a.affiliation = {name: a.affiliation} if typeof a.affiliation is 'string'
metadata.author.push a
try
metadata.keyword ?= []
metadata.keyword.push(s.term) for s in rec.subject
try
for id in rec.identifier
if id.type.toLowerCase() is 'doi'
metadata.doi ?= id.id
break
try
for l in rec.journal.license
if l.open_access or not metadata.licence? or metadata.licence.indexOf('cc') isnt 0
metadata.licence ?= l.type
if l.open_access and not metadata.url?
try
for l in rec.link
if l.type is 'fulltext'
metadata.url = l.url
metadata.url ?= 'https://doi.org/' + metadata.doi if metadata.doi?
break
return metadata
API.use.doaj.status = () ->
try
return true if HTTP.call 'GET', 'https://doaj.org/api/v1/search/articles/_search', {timeout: API.settings.use?.doaj?.timeout ? API.settings.use?._timeout ? 2000}
catch err
return err.toString()
API.use.doaj.test = (verbose) ->
console.log('Starting doaj test') if API.settings.dev
result = {passed:[],failed:[]}
tests = [
() ->
result.record = HTTP.call('GET', 'https://doaj.org/api/v1/search/articles/doi:10.1186/1758-2946-3-47')
result.record = result.record.data.results[0] if result.record?.data?.results?
delete result.record.last_updated # remove things that could change for good reason
delete result.record.created_date
return false if not result.record.bibjson.subject?
delete result.record.bibjson.subject
return _.isEqual result.record, API.use.doaj.test._examples.record
]
(if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests
result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0
result = {passed:result.passed} if result.failed.length is 0 and not verbose
console.log('Ending doaj test') if API.settings.dev
return result
API.use.doaj.test._examples = {
record: {
"id": "616925712973412d8c8678b40269dfe5",
"bibjson": {
"start_page": "47",
"author": [
{"name": "Jones Richard"},
{"name": "MacGillivray Mark"},
{"name": "Murray-Rust Peter"},
{"name": "Pitman Jim"},
{"name": "Sefton Peter"},
{"name": "O'Steen Ben"},
{"name": "Waites William"}
],
"journal": {
"publisher": "Springer",
"language": ["EN"],
"license": [
{"url": "http://jcheminf.springeropen.com/submission-guidelines/copyright", "open_access": true, "type": "CC BY", "title": "CC BY"}
],
"title": "Journal of Cheminformatics",
"country": "GB",
"number": "1",
"volume": "3",
"issns": ["1758-2946"]
},
"title": "Open Bibliography for Science, Technology, and Medicine",
"month": "10",
"link": [
{"url": "http://www.jcheminf.com/content/3/1/47", "type": "fulltext"}
],
"year": "2011",
"identifier": [
{"type": "doi", "id": "10.1186/1758-2946-3-47"},
{"type": "pissn", "id": "1758-2946"}
],
"abstract": "<p>Abstract</p> <p>The concept of Open Bibliography in science, technology and medicine (STM) is introduced as a combination of Open Source tools, Open specifications and Open bibliographic data. An Openly searchable and navigable network of bibliographic information and associated knowledge representations, a Bibliographic Knowledge Network, across all branches of Science, Technology and Medicine, has been designed and initiated. For this large scale endeavour, the engagement and cooperation of the multiple stakeholders in STM publishing - authors, librarians, publishers and administrators - is sought.</p> "
}
}
}
| 72428 |
# use the doaj
# https://doaj.org/api/v1/docs
# DOAJ API only allows results up to 1000, regardless of page size or rate limit. Annoying...
import fs from 'fs'
import tar from 'tar'
import Future from 'fibers/future'
@doaj_journal = new API.collection {index:"doaj",type:"journal"}
@doaj_in_progress = new API.collection {index:"doaj",type:"inprogress"}
API.use ?= {}
API.use.doaj = {journals: {}, articles: {}}
API.add 'use/doaj/:which/es',
get: () -> return API.use.doaj.es this.urlParams.which, this.queryParams, undefined, this.queryParams.format
post: () -> return API.use.doaj.es this.urlParams.which, this.queryParams, this.bodyParams, this.queryParams.format
API.add 'use/doaj/articles/search/:qry',
get: () -> return API.use.doaj.articles.search this.urlParams.qry, this.queryParams, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/articles/title/:qry',
get: () -> return API.use.doaj.articles.title this.urlParams.qry, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/articles/doi/:doipre/:doipost',
get: () -> return API.use.doaj.articles.doi this.urlParams.doipre + '/' + this.urlParams.doipost, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/articles/doi/:doipre/:doipost/:doiextra',
get: () -> return API.use.doaj.articles.doi this.urlParams.doipre + '/' + this.urlParams.doipost + '/' + this.urlParams.doiextra, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/journals', () -> return doaj_journal.search this
API.add 'use/doaj/journals/inprogress', () -> return doaj_in_progress.search this
API.add 'use/doaj/journals/:issn',
get: () -> return API.use.doaj.journals.issn this.urlParams.issn
API.add 'use/doaj/journals/import',
get:
roleRequired: if API.settings.dev then undefined else 'doaj.admin'
action: () ->
Meteor.setTimeout (() => API.use.doaj.journals.import this.queryParams.refresh), 1
return true
API.use.doaj.es = (which='journal,article', params, body, format=true) ->
# which could be journal or article or journal,article
# but doaj only allows this type of query on journal,article, so will add this later as a query filter
url = 'https://doaj.org/query/journal,article/_search?ref=public_journal_article&'
# this only works with a source param, if one is not present, should convert the query into a source param
if body
for p of params
body[p] = params[p] # allow params to override body?
else
body = params
if body.format?
delete body.format
format ?= true
if not body.source?
tr = API.collection._translate body
body = source: tr # unless doing a post, in which case don't do this part
body.source.aggs ?= {} # requier this to get doaj to accept the query
body.source.query.filtered.query.bool.must.push({term: {_type: which}}) if which isnt 'journal,article'
#body.source.query = body.source.query.filtered.query.bool.must[0]
#body.source.query ?= {query_string: {query: ""}}
url += op + '=' + encodeURIComponent(JSON.stringify(body[op])) + '&' for op of body
API.log 'Using doaj ES for ' + url
try
res = HTTP.call 'GET', url
try res.data.query = body
if res.statusCode is 200
if format
res.data = res.data.hits
for d of res.data.hits
res.data.hits[d] = API.use.doaj.articles.format res.data.hits[d]._source
res.data.data = res.data.hits
delete res.data.hits
return res.data
else
return {status: 'error', data: res.data, query: body}
catch err
return {status: 'error', error: err, query: body, url: url}
API.use.doaj.journals.issn = (issn) ->
issn = issn.split(',') if typeof issn is 'string'
r = API.use.doaj.journals.search 'issn.exact:"' + issn.join(' OR issn.exact:"') + '"', undefined
return if r.hits?.total then r.hits.hits[0]._source else undefined
API.use.doaj.journals.search = (qry) ->
return doaj_journal.search qry
API.use.doaj.journals.inprogress = (qry) ->
return doaj_in_progress.search qry
API.use.doaj.journals.import = (refresh) ->
# doaj only updates their journal dump once a week so calling journal import
# won't actually do anything if the dump file name has not changed since last run
# or if a refresh is called
fldr = '/tmp/doaj' + (if API.settings.dev then '_dev' else '') + '/'
if not fs.existsSync fldr
fs.mkdirSync fldr
ret = false
try
prev = false
current = false
fs.writeFileSync fldr + 'doaj.tar', HTTP.call('GET', 'https://doaj.org/public-data-dump/journal', {npmRequestOptions:{encoding:null}}).content
tar.extract file: fldr + 'doaj.tar', cwd: fldr, sync: true # extracted doaj dump folders end 2020-10-01
for f in fs.readdirSync fldr # readdir alphasorts, so if more than one in tmp then last one will be newest
if f.indexOf('doaj_journal_data') isnt -1
if prev
try fs.unlinkSync fldr + prev + '/journal_batch_1.json'
try fs.rmdirSync fldr + prev
prev = current
current = f
if current and (prev or refresh)
doaj_journal.remove '*'
counter = 0
dely = 800
while counter < 5 and not doaj_journal.mapping().dynamic_templates?
future = new Future()
setTimeout (() -> future.return()), dely
future.wait()
doaj_journal.map API.es._mapping
dely = dely * 2
counter += 1
console.log counter
doaj_journal.insert JSON.parse fs.readFileSync fldr + current + '/journal_batch_1.json'
API.log 'Imported DOAJ journals'
ret = true
if not doaj_journal.mapping().dynamic_templates?
API.log notify: true, msg: 'DOAJ journals import did not successfully map'
else
API.log 'DOAJ journal import ran but found nothing new to import'
ret = false
catch
API.log 'Error trying to import DOAJ journals'
ret = false
if ret is true
# only get new doaj inprogress data if the journals load processed some doaj
# journals (otherwise we're between the week-long period when doaj doesn't update)
# and if doaj did update, load them into the catalogue too
try
r = HTTP.call 'GET', 'https://doaj.org/jct/inprogress?api_key=' + API.settings.service.doaj.apikey
rc = JSON.parse r.content
doaj_in_progress.remove '*'
doaj_in_progress.insert rc
return ret
_doaj_journals_import = () ->
if API.settings.cluster?.ip? and API.status.ip() not in API.settings.cluster.ip
API.log 'Setting up a DOAJ journal import to run each day if their dump file updated on ' + API.status.ip()
Meteor.setInterval API.use.doaj.journals.import, 43200000
Meteor.setTimeout _doaj_journals_import, 22000
API.use.doaj.articles.doi = (doi, format, refresh) ->
return API.use.doaj.articles.get 'doi:' + doi, format
API.use.doaj.articles.title = (title, format, refresh) ->
try title = title.toLowerCase().replace(/(<([^>]+)>)/g,'').replace(/[^a-z0-9 ]+/g, " ").replace(/\s\s+/g, ' ')
return API.use.doaj.articles.get 'title:"' + title + '"', format, refresh
API.use.doaj.articles.get = (qry, format=true, refresh) ->
res = API.use.doaj.articles.search qry, undefined, false, refresh
rec = if res?.data?.length then res.data[0] else undefined
if rec?
op = API.use.doaj.articles.redirect rec
rec.url = op.url
rec.redirect = op.redirect
return if format and typeof rec is 'object' then API.use.doaj.articles.format(rec) else rec
API.use.doaj.articles.search = (qry, params={}, format=true, refresh) ->
if refresh isnt true and cached = API.http.cache qry, 'doaj_articles', undefined, refresh
return cached
else
url = 'https://doaj.org/api/v1/search/articles/' + qry + '?'
#params.sort ?= 'bibjson.year:desc'
url += op + '=' + params[op] + '&' for op of params
API.log 'Using doaj for ' + url
try
#res = HTTP.call 'GET', url
res = API.job.limit 400, 'HTTP.call', ['GET',url], "DOAJ"
if res.statusCode is 200
if format
for d of res.data.results
res.data.results[d] = API.use.doaj.articles.format res.data.results[d]
res.data.data = res.data.results
delete res.data.results
API.http.cache qry, 'doaj_articles', res.data
return res.data
else
return {status: 'error', data: res.data}
catch err
return {status: 'error', data: 'DOAJ error', error: err}
API.use.doaj.articles.redirect = (record) ->
res = {}
if record.bibjson?.link?
for l in record.bibjson.link
if l.type is 'fulltext'
res.url = l.url
if res.url?
try
resolves = HTTP.call 'HEAD', res.url, {timeout: API.settings.use?.doaj?.timeout ? API.settings.use?._timeout ? 2000}
catch
res.url = undefined
res.redirect = API.service.oab.redirect(res.url) if API.service.oab?
break if res.url and res.redirect isnt false
return res
API.use.doaj.articles.format = (rec, metadata={}) ->
try metadata.pdf ?= rec.pdf
try metadata.url ?= rec.url
try metadata.redirect ?= rec.redirect
try
rec = rec.bibjson if rec.bibjson?
try metadata.title ?= rec.title
try metadata.abstract ?= rec.abstract.replace(/\n/g,' ')
try metadata.volume ?= rec.journal.volume
try metadata.issn ?= rec.journal.issns[0]
if not metadata.page?
try metadata.page = rec.start_page
try metadata.page += '-' + rec.end_page if rec.end_page?
try metadata.journal ?= rec.journal.title
try metadata.publisher ?= rec.journal.publisher
try metadata.year ?= rec.year
try
rm = rec.month ? '01'
rm = 1 if rm is 0 or rm is "0"
if rec.month?
try
rmt = rec.month.substring(0,3).toLowerCase()
if rmt.length is 3
idx = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf rmt
rm = idx+1 if idx isnt -1
metadata.published ?= rec.year + '-' + rm + '-' + (rec.day ? '01')
try
metadata.author ?= []
for a in rec.author
as = a.name.split(' ')
a.family = as[as.length-1]
a.given = a.name.replace(a.family,'').trim()
if a.affiliation?
a.affiliation = a.affiliation[0] if _.isArray a.affiliation
a.affiliation = {name: a.affiliation} if typeof a.affiliation is 'string'
metadata.author.push a
try
metadata.keyword ?= []
metadata.keyword.push(s.term) for s in rec.subject
try
for id in rec.identifier
if id.type.toLowerCase() is 'doi'
metadata.doi ?= id.id
break
try
for l in rec.journal.license
if l.open_access or not metadata.licence? or metadata.licence.indexOf('cc') isnt 0
metadata.licence ?= l.type
if l.open_access and not metadata.url?
try
for l in rec.link
if l.type is 'fulltext'
metadata.url = l.url
metadata.url ?= 'https://doi.org/' + metadata.doi if metadata.doi?
break
return metadata
API.use.doaj.status = () ->
try
return true if HTTP.call 'GET', 'https://doaj.org/api/v1/search/articles/_search', {timeout: API.settings.use?.doaj?.timeout ? API.settings.use?._timeout ? 2000}
catch err
return err.toString()
API.use.doaj.test = (verbose) ->
console.log('Starting doaj test') if API.settings.dev
result = {passed:[],failed:[]}
tests = [
() ->
result.record = HTTP.call('GET', 'https://doaj.org/api/v1/search/articles/doi:10.1186/1758-2946-3-47')
result.record = result.record.data.results[0] if result.record?.data?.results?
delete result.record.last_updated # remove things that could change for good reason
delete result.record.created_date
return false if not result.record.bibjson.subject?
delete result.record.bibjson.subject
return _.isEqual result.record, API.use.doaj.test._examples.record
]
(if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests
result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0
result = {passed:result.passed} if result.failed.length is 0 and not verbose
console.log('Ending doaj test') if API.settings.dev
return result
API.use.doaj.test._examples = {
record: {
"id": "616925712973412d8c8678b40269dfe5",
"bibjson": {
"start_page": "47",
"author": [
{"name": "<NAME>"},
{"name": "<NAME>"},
{"name": "<NAME>"},
{"name": "<NAME>"},
{"name": "<NAME>"},
{"name": "<NAME>"},
{"name": "<NAME>"}
],
"journal": {
"publisher": "Springer",
"language": ["EN"],
"license": [
{"url": "http://jcheminf.springeropen.com/submission-guidelines/copyright", "open_access": true, "type": "CC BY", "title": "CC BY"}
],
"title": "Journal of Cheminformatics",
"country": "GB",
"number": "1",
"volume": "3",
"issns": ["1758-2946"]
},
"title": "Open Bibliography for Science, Technology, and Medicine",
"month": "10",
"link": [
{"url": "http://www.jcheminf.com/content/3/1/47", "type": "fulltext"}
],
"year": "2011",
"identifier": [
{"type": "doi", "id": "10.1186/1758-2946-3-47"},
{"type": "pissn", "id": "1758-2946"}
],
"abstract": "<p>Abstract</p> <p>The concept of Open Bibliography in science, technology and medicine (STM) is introduced as a combination of Open Source tools, Open specifications and Open bibliographic data. An Openly searchable and navigable network of bibliographic information and associated knowledge representations, a Bibliographic Knowledge Network, across all branches of Science, Technology and Medicine, has been designed and initiated. For this large scale endeavour, the engagement and cooperation of the multiple stakeholders in STM publishing - authors, librarians, publishers and administrators - is sought.</p> "
}
}
}
| true |
# use the doaj
# https://doaj.org/api/v1/docs
# DOAJ API only allows results up to 1000, regardless of page size or rate limit. Annoying...
import fs from 'fs'
import tar from 'tar'
import Future from 'fibers/future'
@doaj_journal = new API.collection {index:"doaj",type:"journal"}
@doaj_in_progress = new API.collection {index:"doaj",type:"inprogress"}
API.use ?= {}
API.use.doaj = {journals: {}, articles: {}}
API.add 'use/doaj/:which/es',
get: () -> return API.use.doaj.es this.urlParams.which, this.queryParams, undefined, this.queryParams.format
post: () -> return API.use.doaj.es this.urlParams.which, this.queryParams, this.bodyParams, this.queryParams.format
API.add 'use/doaj/articles/search/:qry',
get: () -> return API.use.doaj.articles.search this.urlParams.qry, this.queryParams, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/articles/title/:qry',
get: () -> return API.use.doaj.articles.title this.urlParams.qry, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/articles/doi/:doipre/:doipost',
get: () -> return API.use.doaj.articles.doi this.urlParams.doipre + '/' + this.urlParams.doipost, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/articles/doi/:doipre/:doipost/:doiextra',
get: () -> return API.use.doaj.articles.doi this.urlParams.doipre + '/' + this.urlParams.doipost + '/' + this.urlParams.doiextra, this.queryParams.format, this.queryParams.refresh
API.add 'use/doaj/journals', () -> return doaj_journal.search this
API.add 'use/doaj/journals/inprogress', () -> return doaj_in_progress.search this
API.add 'use/doaj/journals/:issn',
get: () -> return API.use.doaj.journals.issn this.urlParams.issn
API.add 'use/doaj/journals/import',
get:
roleRequired: if API.settings.dev then undefined else 'doaj.admin'
action: () ->
Meteor.setTimeout (() => API.use.doaj.journals.import this.queryParams.refresh), 1
return true
API.use.doaj.es = (which='journal,article', params, body, format=true) ->
# which could be journal or article or journal,article
# but doaj only allows this type of query on journal,article, so will add this later as a query filter
url = 'https://doaj.org/query/journal,article/_search?ref=public_journal_article&'
# this only works with a source param, if one is not present, should convert the query into a source param
if body
for p of params
body[p] = params[p] # allow params to override body?
else
body = params
if body.format?
delete body.format
format ?= true
if not body.source?
tr = API.collection._translate body
body = source: tr # unless doing a post, in which case don't do this part
body.source.aggs ?= {} # requier this to get doaj to accept the query
body.source.query.filtered.query.bool.must.push({term: {_type: which}}) if which isnt 'journal,article'
#body.source.query = body.source.query.filtered.query.bool.must[0]
#body.source.query ?= {query_string: {query: ""}}
url += op + '=' + encodeURIComponent(JSON.stringify(body[op])) + '&' for op of body
API.log 'Using doaj ES for ' + url
try
res = HTTP.call 'GET', url
try res.data.query = body
if res.statusCode is 200
if format
res.data = res.data.hits
for d of res.data.hits
res.data.hits[d] = API.use.doaj.articles.format res.data.hits[d]._source
res.data.data = res.data.hits
delete res.data.hits
return res.data
else
return {status: 'error', data: res.data, query: body}
catch err
return {status: 'error', error: err, query: body, url: url}
API.use.doaj.journals.issn = (issn) ->
issn = issn.split(',') if typeof issn is 'string'
r = API.use.doaj.journals.search 'issn.exact:"' + issn.join(' OR issn.exact:"') + '"', undefined
return if r.hits?.total then r.hits.hits[0]._source else undefined
API.use.doaj.journals.search = (qry) ->
return doaj_journal.search qry
API.use.doaj.journals.inprogress = (qry) ->
return doaj_in_progress.search qry
API.use.doaj.journals.import = (refresh) ->
# doaj only updates their journal dump once a week so calling journal import
# won't actually do anything if the dump file name has not changed since last run
# or if a refresh is called
fldr = '/tmp/doaj' + (if API.settings.dev then '_dev' else '') + '/'
if not fs.existsSync fldr
fs.mkdirSync fldr
ret = false
try
prev = false
current = false
fs.writeFileSync fldr + 'doaj.tar', HTTP.call('GET', 'https://doaj.org/public-data-dump/journal', {npmRequestOptions:{encoding:null}}).content
tar.extract file: fldr + 'doaj.tar', cwd: fldr, sync: true # extracted doaj dump folders end 2020-10-01
for f in fs.readdirSync fldr # readdir alphasorts, so if more than one in tmp then last one will be newest
if f.indexOf('doaj_journal_data') isnt -1
if prev
try fs.unlinkSync fldr + prev + '/journal_batch_1.json'
try fs.rmdirSync fldr + prev
prev = current
current = f
if current and (prev or refresh)
doaj_journal.remove '*'
counter = 0
dely = 800
while counter < 5 and not doaj_journal.mapping().dynamic_templates?
future = new Future()
setTimeout (() -> future.return()), dely
future.wait()
doaj_journal.map API.es._mapping
dely = dely * 2
counter += 1
console.log counter
doaj_journal.insert JSON.parse fs.readFileSync fldr + current + '/journal_batch_1.json'
API.log 'Imported DOAJ journals'
ret = true
if not doaj_journal.mapping().dynamic_templates?
API.log notify: true, msg: 'DOAJ journals import did not successfully map'
else
API.log 'DOAJ journal import ran but found nothing new to import'
ret = false
catch
API.log 'Error trying to import DOAJ journals'
ret = false
if ret is true
# only get new doaj inprogress data if the journals load processed some doaj
# journals (otherwise we're between the week-long period when doaj doesn't update)
# and if doaj did update, load them into the catalogue too
try
r = HTTP.call 'GET', 'https://doaj.org/jct/inprogress?api_key=' + API.settings.service.doaj.apikey
rc = JSON.parse r.content
doaj_in_progress.remove '*'
doaj_in_progress.insert rc
return ret
_doaj_journals_import = () ->
if API.settings.cluster?.ip? and API.status.ip() not in API.settings.cluster.ip
API.log 'Setting up a DOAJ journal import to run each day if their dump file updated on ' + API.status.ip()
Meteor.setInterval API.use.doaj.journals.import, 43200000
Meteor.setTimeout _doaj_journals_import, 22000
API.use.doaj.articles.doi = (doi, format, refresh) ->
return API.use.doaj.articles.get 'doi:' + doi, format
API.use.doaj.articles.title = (title, format, refresh) ->
try title = title.toLowerCase().replace(/(<([^>]+)>)/g,'').replace(/[^a-z0-9 ]+/g, " ").replace(/\s\s+/g, ' ')
return API.use.doaj.articles.get 'title:"' + title + '"', format, refresh
API.use.doaj.articles.get = (qry, format=true, refresh) ->
res = API.use.doaj.articles.search qry, undefined, false, refresh
rec = if res?.data?.length then res.data[0] else undefined
if rec?
op = API.use.doaj.articles.redirect rec
rec.url = op.url
rec.redirect = op.redirect
return if format and typeof rec is 'object' then API.use.doaj.articles.format(rec) else rec
API.use.doaj.articles.search = (qry, params={}, format=true, refresh) ->
if refresh isnt true and cached = API.http.cache qry, 'doaj_articles', undefined, refresh
return cached
else
url = 'https://doaj.org/api/v1/search/articles/' + qry + '?'
#params.sort ?= 'bibjson.year:desc'
url += op + '=' + params[op] + '&' for op of params
API.log 'Using doaj for ' + url
try
#res = HTTP.call 'GET', url
res = API.job.limit 400, 'HTTP.call', ['GET',url], "DOAJ"
if res.statusCode is 200
if format
for d of res.data.results
res.data.results[d] = API.use.doaj.articles.format res.data.results[d]
res.data.data = res.data.results
delete res.data.results
API.http.cache qry, 'doaj_articles', res.data
return res.data
else
return {status: 'error', data: res.data}
catch err
return {status: 'error', data: 'DOAJ error', error: err}
API.use.doaj.articles.redirect = (record) ->
res = {}
if record.bibjson?.link?
for l in record.bibjson.link
if l.type is 'fulltext'
res.url = l.url
if res.url?
try
resolves = HTTP.call 'HEAD', res.url, {timeout: API.settings.use?.doaj?.timeout ? API.settings.use?._timeout ? 2000}
catch
res.url = undefined
res.redirect = API.service.oab.redirect(res.url) if API.service.oab?
break if res.url and res.redirect isnt false
return res
API.use.doaj.articles.format = (rec, metadata={}) ->
try metadata.pdf ?= rec.pdf
try metadata.url ?= rec.url
try metadata.redirect ?= rec.redirect
try
rec = rec.bibjson if rec.bibjson?
try metadata.title ?= rec.title
try metadata.abstract ?= rec.abstract.replace(/\n/g,' ')
try metadata.volume ?= rec.journal.volume
try metadata.issn ?= rec.journal.issns[0]
if not metadata.page?
try metadata.page = rec.start_page
try metadata.page += '-' + rec.end_page if rec.end_page?
try metadata.journal ?= rec.journal.title
try metadata.publisher ?= rec.journal.publisher
try metadata.year ?= rec.year
try
rm = rec.month ? '01'
rm = 1 if rm is 0 or rm is "0"
if rec.month?
try
rmt = rec.month.substring(0,3).toLowerCase()
if rmt.length is 3
idx = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'].indexOf rmt
rm = idx+1 if idx isnt -1
metadata.published ?= rec.year + '-' + rm + '-' + (rec.day ? '01')
try
metadata.author ?= []
for a in rec.author
as = a.name.split(' ')
a.family = as[as.length-1]
a.given = a.name.replace(a.family,'').trim()
if a.affiliation?
a.affiliation = a.affiliation[0] if _.isArray a.affiliation
a.affiliation = {name: a.affiliation} if typeof a.affiliation is 'string'
metadata.author.push a
try
metadata.keyword ?= []
metadata.keyword.push(s.term) for s in rec.subject
try
for id in rec.identifier
if id.type.toLowerCase() is 'doi'
metadata.doi ?= id.id
break
try
for l in rec.journal.license
if l.open_access or not metadata.licence? or metadata.licence.indexOf('cc') isnt 0
metadata.licence ?= l.type
if l.open_access and not metadata.url?
try
for l in rec.link
if l.type is 'fulltext'
metadata.url = l.url
metadata.url ?= 'https://doi.org/' + metadata.doi if metadata.doi?
break
return metadata
API.use.doaj.status = () ->
try
return true if HTTP.call 'GET', 'https://doaj.org/api/v1/search/articles/_search', {timeout: API.settings.use?.doaj?.timeout ? API.settings.use?._timeout ? 2000}
catch err
return err.toString()
API.use.doaj.test = (verbose) ->
console.log('Starting doaj test') if API.settings.dev
result = {passed:[],failed:[]}
tests = [
() ->
result.record = HTTP.call('GET', 'https://doaj.org/api/v1/search/articles/doi:10.1186/1758-2946-3-47')
result.record = result.record.data.results[0] if result.record?.data?.results?
delete result.record.last_updated # remove things that could change for good reason
delete result.record.created_date
return false if not result.record.bibjson.subject?
delete result.record.bibjson.subject
return _.isEqual result.record, API.use.doaj.test._examples.record
]
(if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests
result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0
result = {passed:result.passed} if result.failed.length is 0 and not verbose
console.log('Ending doaj test') if API.settings.dev
return result
API.use.doaj.test._examples = {
record: {
"id": "616925712973412d8c8678b40269dfe5",
"bibjson": {
"start_page": "47",
"author": [
{"name": "PI:NAME:<NAME>END_PI"},
{"name": "PI:NAME:<NAME>END_PI"},
{"name": "PI:NAME:<NAME>END_PI"},
{"name": "PI:NAME:<NAME>END_PI"},
{"name": "PI:NAME:<NAME>END_PI"},
{"name": "PI:NAME:<NAME>END_PI"},
{"name": "PI:NAME:<NAME>END_PI"}
],
"journal": {
"publisher": "Springer",
"language": ["EN"],
"license": [
{"url": "http://jcheminf.springeropen.com/submission-guidelines/copyright", "open_access": true, "type": "CC BY", "title": "CC BY"}
],
"title": "Journal of Cheminformatics",
"country": "GB",
"number": "1",
"volume": "3",
"issns": ["1758-2946"]
},
"title": "Open Bibliography for Science, Technology, and Medicine",
"month": "10",
"link": [
{"url": "http://www.jcheminf.com/content/3/1/47", "type": "fulltext"}
],
"year": "2011",
"identifier": [
{"type": "doi", "id": "10.1186/1758-2946-3-47"},
{"type": "pissn", "id": "1758-2946"}
],
"abstract": "<p>Abstract</p> <p>The concept of Open Bibliography in science, technology and medicine (STM) is introduced as a combination of Open Source tools, Open specifications and Open bibliographic data. An Openly searchable and navigable network of bibliographic information and associated knowledge representations, a Bibliographic Knowledge Network, across all branches of Science, Technology and Medicine, has been designed and initiated. For this large scale endeavour, the engagement and cooperation of the multiple stakeholders in STM publishing - authors, librarians, publishers and administrators - is sought.</p> "
}
}
}
|
[
{
"context": "###\n# @author Will Steinmetz\n# jQuery notification plug-in inspired by the not",
"end": 28,
"score": 0.999856173992157,
"start": 14,
"tag": "NAME",
"value": "Will Steinmetz"
},
{
"context": "ation style of Windows 8\n# Copyright (c)2013-2015, Will Steinmetz\n# Licensed under the BSD license.\n# http://openso",
"end": 147,
"score": 0.9998244047164917,
"start": 133,
"tag": "NAME",
"value": "Will Steinmetz"
}
] | public/third_party/notific8/grunt/contrib-jade.coffee | pvndn/spa | 130 | ###
# @author Will Steinmetz
# jQuery notification plug-in inspired by the notification style of Windows 8
# Copyright (c)2013-2015, Will Steinmetz
# Licensed under the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
###
module.exports = (grunt) ->
grunt.config('jade',
release:
files:
'demo/index.html': 'src/jade/index.jade'
)
grunt.loadNpmTasks 'grunt-contrib-jade'
| 217396 | ###
# @author <NAME>
# jQuery notification plug-in inspired by the notification style of Windows 8
# Copyright (c)2013-2015, <NAME>
# Licensed under the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
###
module.exports = (grunt) ->
grunt.config('jade',
release:
files:
'demo/index.html': 'src/jade/index.jade'
)
grunt.loadNpmTasks 'grunt-contrib-jade'
| true | ###
# @author PI:NAME:<NAME>END_PI
# jQuery notification plug-in inspired by the notification style of Windows 8
# Copyright (c)2013-2015, PI:NAME:<NAME>END_PI
# Licensed under the BSD license.
# http://opensource.org/licenses/BSD-3-Clause
###
module.exports = (grunt) ->
grunt.config('jade',
release:
files:
'demo/index.html': 'src/jade/index.jade'
)
grunt.loadNpmTasks 'grunt-contrib-jade'
|
[
{
"context": "adb6ce9d137c32b4528439\"\n personalAccessToken: \"64cdd5db0e81d378a15fddeff334f022977b632e\"\n welcome:\n showOnStartup: false\n\".asciidoc.s",
"end": 703,
"score": 0.9710825681686401,
"start": 663,
"tag": "KEY",
"value": "64cdd5db0e81d378a15fddeff334f022977b632e"
}
] | atom/config.cson | francissabado/dotfiles | 0 | "*":
"asciidoc-preview":
showTitle: false
"atom-beautify":
general:
_analyticsUserId: "0e5013f5-74c7-4ce2-a3ba-6800db4b27ee"
core:
themes: [
"seti-ui"
"monokai-seti"
]
editor:
fontSize: 10
"exception-reporting":
userId: "ae5f05ca-e8c5-e43d-003f-93ddf70737af"
minimap:
adjustAbsoluteModeHeight: true
plugins:
"find-and-replace": true
"find-and-replaceDecorationsZIndex": 0
"sync-settings":
_analyticsUserId: "7fec2e52-0220-4fdd-9198-6213caf9d891"
_lastBackupHash: "2c52db61621b6ede26acf4fbeaec53052f1be686"
gistId: "3d06c8d746adb6ce9d137c32b4528439"
personalAccessToken: "64cdd5db0e81d378a15fddeff334f022977b632e"
welcome:
showOnStartup: false
".asciidoc.source":
editor:
softWrap: true
| 58959 | "*":
"asciidoc-preview":
showTitle: false
"atom-beautify":
general:
_analyticsUserId: "0e5013f5-74c7-4ce2-a3ba-6800db4b27ee"
core:
themes: [
"seti-ui"
"monokai-seti"
]
editor:
fontSize: 10
"exception-reporting":
userId: "ae5f05ca-e8c5-e43d-003f-93ddf70737af"
minimap:
adjustAbsoluteModeHeight: true
plugins:
"find-and-replace": true
"find-and-replaceDecorationsZIndex": 0
"sync-settings":
_analyticsUserId: "7fec2e52-0220-4fdd-9198-6213caf9d891"
_lastBackupHash: "2c52db61621b6ede26acf4fbeaec53052f1be686"
gistId: "3d06c8d746adb6ce9d137c32b4528439"
personalAccessToken: "<KEY>"
welcome:
showOnStartup: false
".asciidoc.source":
editor:
softWrap: true
| true | "*":
"asciidoc-preview":
showTitle: false
"atom-beautify":
general:
_analyticsUserId: "0e5013f5-74c7-4ce2-a3ba-6800db4b27ee"
core:
themes: [
"seti-ui"
"monokai-seti"
]
editor:
fontSize: 10
"exception-reporting":
userId: "ae5f05ca-e8c5-e43d-003f-93ddf70737af"
minimap:
adjustAbsoluteModeHeight: true
plugins:
"find-and-replace": true
"find-and-replaceDecorationsZIndex": 0
"sync-settings":
_analyticsUserId: "7fec2e52-0220-4fdd-9198-6213caf9d891"
_lastBackupHash: "2c52db61621b6ede26acf4fbeaec53052f1be686"
gistId: "3d06c8d746adb6ce9d137c32b4528439"
personalAccessToken: "PI:KEY:<KEY>END_PI"
welcome:
showOnStartup: false
".asciidoc.source":
editor:
softWrap: true
|
[
{
"context": "tring(),\n contributing_authors: [{name: 'James'}, {name: 'Artsy Editorial'}]\n new Article",
"end": 1963,
"score": 0.9992526769638062,
"start": 1958,
"tag": "NAME",
"value": "James"
},
{
"context": "tring(),\n contributing_authors: [{name: 'James'}, {name: 'Artsy Editorial'}, {name: 'Alice'}]\n ",
"end": 2146,
"score": 0.9997536540031433,
"start": 2141,
"tag": "NAME",
"value": "James"
},
{
"context": " contributing_authors: [{name: 'James'}, {name: 'Artsy Editorial'}, {name: 'Alice'}]\n ]\n rendered = part",
"end": 2173,
"score": 0.9563766717910767,
"start": 2158,
"tag": "NAME",
"value": "Artsy Editorial"
},
{
"context": "ame: 'James'}, {name: 'Artsy Editorial'}, {name: 'Alice'}]\n ]\n rendered = partnerUpdatesTemplat",
"end": 2190,
"score": 0.9997994899749756,
"start": 2185,
"tag": "NAME",
"value": "Alice"
},
{
"context": "moment: moment)\n rendered.should.containEql 'James and Artsy Editorial'\n rendered.sho",
"end": 2325,
"score": 0.9955064058303833,
"start": 2320,
"tag": "NAME",
"value": "James"
},
{
"context": "rtsy Editorial'\n rendered.should.containEql 'James, Artsy Editorial and Alice'\n\n i",
"end": 2396,
"score": 0.9985256791114807,
"start": 2391,
"tag": "NAME",
"value": "James"
},
{
"context": "ainEql 'James, Artsy Editorial and Alice'\n\n it 'renders artsy partner updates when ther",
"end": 2438,
"score": 0.9993403553962708,
"start": 2433,
"tag": "NAME",
"value": "Alice"
},
{
"context": " article = new Article(\n lead_paragraph: 'Andy Foobar never wanted fame.'\n sections: [\n ",
"end": 3057,
"score": 0.9965834021568298,
"start": 3046,
"tag": "NAME",
"value": "Andy Foobar"
},
{
"context": "le: article)\n rendered.should.containEql '<p>Andy Foobar never wanted fame.</p><p>But sometimes fame choos",
"end": 3357,
"score": 0.9964793920516968,
"start": 3346,
"tag": "NAME",
"value": "Andy Foobar"
}
] | apps/rss/test/partner_updates.coffee | l2succes/force | 1 | _ = require 'underscore'
fs = require 'fs'
partnerUpdatesTemplate = require('jade').compileFile(require.resolve '../templates/partner_updates.jade')
articleTemplate = require('jade').compileFile(require.resolve '../templates/partner_updates_article.jade')
sd = APP_URL: 'http://localhost'
{ fabricate } = require 'antigravity'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
moment = require 'moment'
describe '/rss', ->
describe 'partner_updates', ->
it 'renders metadata', ->
rendered = partnerUpdatesTemplate(sd: sd, articles: new Articles)
rendered.should.containEql '<title>Artsy Partner Updates</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/partner-updates" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Artsy articles featured for Artsy Partner Updates.</description>'
it 'renders articles', ->
articles = new Articles [
new Article(thumbnail_title: 'Hello', published_at: new Date().toISOString(), contributing_authors: []),
new Article(thumbnail_title: 'World', published_at: new Date().toISOString(), contributing_authors: [])
]
rendered = partnerUpdatesTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql '<title>Artsy Partner Updates</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/partner-updates" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Artsy articles featured for Artsy Partner Updates.</description>'
rendered.should.containEql '<item><title>Hello</title>'
rendered.should.containEql '<item><title>World</title>'
it 'renders contributing authors', ->
articles = new Articles [
new Article
thumbnail_title: 'Hello',
published_at: new Date().toISOString(),
contributing_authors: [{name: 'James'}, {name: 'Artsy Editorial'}]
new Article
thumbnail_title: 'World',
published_at: new Date().toISOString(),
contributing_authors: [{name: 'James'}, {name: 'Artsy Editorial'}, {name: 'Alice'}]
]
rendered = partnerUpdatesTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql 'James and Artsy Editorial'
rendered.should.containEql 'James, Artsy Editorial and Alice'
it 'renders artsy partner updates when there is no contributing author', ->
articles = new Articles [
new Article
thumbnail_title: 'Hello',
published_at: new Date().toISOString(),
contributing_authors: [],
author: {name: 'Artsy Partner Updates'}
]
rendered = partnerUpdatesTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql '<author>Artsy Partner Updates</author>'
describe 'article', ->
it 'renders the lead paragraph and body text', ->
article = new Article(
lead_paragraph: 'Andy Foobar never wanted fame.'
sections: [
{
type: 'text'
body: 'But sometimes fame chooses you.'
}
]
contributing_authors: []
)
rendered = articleTemplate(sd: sd, article: article)
rendered.should.containEql '<p>Andy Foobar never wanted fame.</p><p>But sometimes fame chooses you.</p>'
| 165905 | _ = require 'underscore'
fs = require 'fs'
partnerUpdatesTemplate = require('jade').compileFile(require.resolve '../templates/partner_updates.jade')
articleTemplate = require('jade').compileFile(require.resolve '../templates/partner_updates_article.jade')
sd = APP_URL: 'http://localhost'
{ fabricate } = require 'antigravity'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
moment = require 'moment'
describe '/rss', ->
describe 'partner_updates', ->
it 'renders metadata', ->
rendered = partnerUpdatesTemplate(sd: sd, articles: new Articles)
rendered.should.containEql '<title>Artsy Partner Updates</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/partner-updates" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Artsy articles featured for Artsy Partner Updates.</description>'
it 'renders articles', ->
articles = new Articles [
new Article(thumbnail_title: 'Hello', published_at: new Date().toISOString(), contributing_authors: []),
new Article(thumbnail_title: 'World', published_at: new Date().toISOString(), contributing_authors: [])
]
rendered = partnerUpdatesTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql '<title>Artsy Partner Updates</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/partner-updates" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Artsy articles featured for Artsy Partner Updates.</description>'
rendered.should.containEql '<item><title>Hello</title>'
rendered.should.containEql '<item><title>World</title>'
it 'renders contributing authors', ->
articles = new Articles [
new Article
thumbnail_title: 'Hello',
published_at: new Date().toISOString(),
contributing_authors: [{name: '<NAME>'}, {name: 'Artsy Editorial'}]
new Article
thumbnail_title: 'World',
published_at: new Date().toISOString(),
contributing_authors: [{name: '<NAME>'}, {name: '<NAME>'}, {name: '<NAME>'}]
]
rendered = partnerUpdatesTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql '<NAME> and Artsy Editorial'
rendered.should.containEql '<NAME>, Artsy Editorial and <NAME>'
it 'renders artsy partner updates when there is no contributing author', ->
articles = new Articles [
new Article
thumbnail_title: 'Hello',
published_at: new Date().toISOString(),
contributing_authors: [],
author: {name: 'Artsy Partner Updates'}
]
rendered = partnerUpdatesTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql '<author>Artsy Partner Updates</author>'
describe 'article', ->
it 'renders the lead paragraph and body text', ->
article = new Article(
lead_paragraph: '<NAME> never wanted fame.'
sections: [
{
type: 'text'
body: 'But sometimes fame chooses you.'
}
]
contributing_authors: []
)
rendered = articleTemplate(sd: sd, article: article)
rendered.should.containEql '<p><NAME> never wanted fame.</p><p>But sometimes fame chooses you.</p>'
| true | _ = require 'underscore'
fs = require 'fs'
partnerUpdatesTemplate = require('jade').compileFile(require.resolve '../templates/partner_updates.jade')
articleTemplate = require('jade').compileFile(require.resolve '../templates/partner_updates_article.jade')
sd = APP_URL: 'http://localhost'
{ fabricate } = require 'antigravity'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
moment = require 'moment'
describe '/rss', ->
describe 'partner_updates', ->
it 'renders metadata', ->
rendered = partnerUpdatesTemplate(sd: sd, articles: new Articles)
rendered.should.containEql '<title>Artsy Partner Updates</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/partner-updates" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Artsy articles featured for Artsy Partner Updates.</description>'
it 'renders articles', ->
articles = new Articles [
new Article(thumbnail_title: 'Hello', published_at: new Date().toISOString(), contributing_authors: []),
new Article(thumbnail_title: 'World', published_at: new Date().toISOString(), contributing_authors: [])
]
rendered = partnerUpdatesTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql '<title>Artsy Partner Updates</title>'
rendered.should.containEql '<atom:link href="http://localhost/rss/partner-updates" rel="self" type="application/rss+xml">'
rendered.should.containEql '<description>Artsy articles featured for Artsy Partner Updates.</description>'
rendered.should.containEql '<item><title>Hello</title>'
rendered.should.containEql '<item><title>World</title>'
it 'renders contributing authors', ->
articles = new Articles [
new Article
thumbnail_title: 'Hello',
published_at: new Date().toISOString(),
contributing_authors: [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'Artsy Editorial'}]
new Article
thumbnail_title: 'World',
published_at: new Date().toISOString(),
contributing_authors: [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}]
]
rendered = partnerUpdatesTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql 'PI:NAME:<NAME>END_PI and Artsy Editorial'
rendered.should.containEql 'PI:NAME:<NAME>END_PI, Artsy Editorial and PI:NAME:<NAME>END_PI'
it 'renders artsy partner updates when there is no contributing author', ->
articles = new Articles [
new Article
thumbnail_title: 'Hello',
published_at: new Date().toISOString(),
contributing_authors: [],
author: {name: 'Artsy Partner Updates'}
]
rendered = partnerUpdatesTemplate(sd: sd, articles: articles, moment: moment)
rendered.should.containEql '<author>Artsy Partner Updates</author>'
describe 'article', ->
it 'renders the lead paragraph and body text', ->
article = new Article(
lead_paragraph: 'PI:NAME:<NAME>END_PI never wanted fame.'
sections: [
{
type: 'text'
body: 'But sometimes fame chooses you.'
}
]
contributing_authors: []
)
rendered = articleTemplate(sd: sd, article: article)
rendered.should.containEql '<p>PI:NAME:<NAME>END_PI never wanted fame.</p><p>But sometimes fame chooses you.</p>'
|
[
{
"context": "username = @config.username;\n result.password = @config.password;\n result.passphrase = @config.passphrase;\n ",
"end": 1718,
"score": 0.8735062479972839,
"start": 1702,
"tag": "PASSWORD",
"value": "@config.password"
}
] | lib/fs/ftp/sftp-filesystem.coffee | morassman/atom-commander | 43 | fs = require 'fs'
fsp = require 'fs-plus'
PathUtil = require('path').posix
VFileSystem = require '../vfilesystem'
FTPFile = require './ftp-file'
FTPDirectory = require './ftp-directory'
FTPSymLink = require './ftp-symlink'
SFTPSession = require './sftp-session'
Utils = require '../../utils'
module.exports =
class SFTPFileSystem extends VFileSystem
constructor: (main, @server, @config) ->
super(main);
@session = null;
@client = null;
if !@config.passwordDecrypted
if @config.password? and @config.password.length > 0
@config.password = Utils.decrypt(@config.password, @getDescription());
if @config.passphrase? and @config.passphrase.length > 0
@config.passphrase = Utils.decrypt(@config.passphrase, @getDescription());
@config.passwordDecrypted = true;
@clientConfig = @getClientConfig();
clone: ->
cloneFS = new SFTPFileSystem(@getMain(), @server, @config);
cloneFS.clientConfig = @clientConfig;
return cloneFS;
isLocal: ->
return false;
connectImpl: ->
@session = new SFTPSession(@);
@session.connect();
disconnectImpl: ->
if @session?
@session.disconnect();
sessionOpened: (session) ->
if session == @session
@client = session.getClient();
@setConnected(true);
sessionCanceled: (session) ->
if session == @session
@session = null;
@setConnected(false);
sessionClosed: (session) ->
if session == @session
@session = null;
@client = null;
@setConnected(false);
getClientConfig: ->
result = {};
result.host = @config.host;
result.port = @config.port;
result.username = @config.username;
result.password = @config.password;
result.passphrase = @config.passphrase;
result.tryKeyboard = true;
result.keepaliveInterval = 60000;
if !@config.loginWithPassword
try
result.privateKey = @getPrivateKey(@config.privateKeyPath);
catch err
Utils.showErrorWarning("Error reading private key", null, null, err, true);
return result;
getPrivateKey: (path) ->
if !path or path.length == 0
return '';
path = Utils.resolveHome(path);
if !fsp.isFileSync(path)
return '';
return fs.readFileSync(path, 'utf8');
getSafeConfig: ->
result = {};
for key, val of @config
result[key] = val;
if @config.storePassword
if @config.password? and @config.password.length > 0
result.password = Utils.encrypt(result.password, @getDescription());
if @config.passphrase? and @config.passphrase.length > 0
result.passphrase = Utils.encrypt(result.passphrase, @getDescription());
else
delete result.password;
delete result.passphrase;
delete result.privateKey;
delete result.passwordDecrypted;
return result;
getFile: (path) ->
return new FTPFile(@, false, path);
getDirectory: (path) ->
return new FTPDirectory(@, false, path);
getItemWithPathDescription: (pathDescription) ->
if pathDescription.isFile
return new FTPFile(@, pathDescription.isLink, pathDescription.path, pathDescription.name);
return new FTPDirectory(@, pathDescription.isLink, pathDescription.path);
getInitialDirectory: ->
return @getDirectory(@config.folder);
getURI: (item) ->
return @config.protocol+"://" + PathUtil.join(@config.host, item.path);
getPathUtil: ->
return PathUtil;
getPathFromURI: (uri) ->
root = @config.protocol+"://"+@config.host;
if uri.substring(0, root.length) == root
return uri.substring(root.length);
return null;
renameImpl: (oldPath, newPath, callback) ->
@client.rename oldPath, newPath, (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
makeDirectoryImpl: (path, callback) ->
@client.mkdir path, [], (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
deleteFileImpl: (path, callback) ->
@client.unlink path, (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
deleteDirectoryImpl: (path, callback) ->
@client.rmdir path, (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
getName: ->
return @config.name;
getDisplayName: ->
if @config.name and @config.name.trim().length > 0
return @config.name;
return @config.host;
getHost: ->
return @config.host;
getUsername: ->
return @config.username;
getID: ->
return @getLocalDirectoryName();
getLocalDirectoryName: ->
return @config.protocol+"_"+@config.host+"_"+@config.port+"_"+@config.username;
downloadImpl: (path, localPath, callback) ->
@client.fastGet(path, localPath, {}, callback);
uploadImpl: (localPath, path, callback) ->
@client.fastPut(localPath, path, {}, callback);
openFile: (file) ->
@server.getRemoteFileManager().openFile(file);
createReadStreamImpl: (path, callback) ->
rs = @client.createReadStream(path);
callback(null, rs);
getDescription: ->
return @config.protocol+"://"+@config.host+":"+@config.port;
getEntriesImpl: (directory, callback) ->
@list directory.getPath(), (err, entries) =>
callback(directory, err, entries);
list: (path, callback) ->
@client.readdir path, (err, entries) =>
if err?
callback(err, []);
else
callback(null, @wrapEntries(path, entries));
wrapEntries: (path, entries) ->
directories = [];
files = [];
for entry in entries
wrappedEntry = @wrapEntry(path, entry);
if wrappedEntry != null
if wrappedEntry.isFile()
files.push(wrappedEntry);
else
directories.push(wrappedEntry);
Utils.sortItems(files);
Utils.sortItems(directories);
return directories.concat(files);
wrapEntry: (path, entry) ->
item = null;
if entry.attrs.isDirectory()
item = new FTPDirectory(@, false, PathUtil.join(path, entry.filename));
else if entry.attrs.isFile()
item = new FTPFile(@, false, PathUtil.join(path, entry.filename));
else if entry.attrs.isSymbolicLink()
item = @wrapSymLinkEntry(path, entry);
if item?
item.modifyDate = new Date(entry.attrs.mtime*1000);
item.size = entry.attrs.size;
return item;
wrapSymLinkEntry: (path, entry) ->
fullPath = PathUtil.join(path, entry.filename);
result = new FTPSymLink(@, fullPath);
@client.stat fullPath, (err, stat) =>
if err?
return;
result.setModifyDate(new Date(entry.attrs.mtime*1000));
result.setSize(entry.attrs.size);
@client.readlink fullPath, (err, target) =>
if err?
return;
if stat.isFile()
result.setTargetFilePath(target);
else if stat.isDirectory()
result.setTargetDirectoryPath(PathUtil.join(path, target));
return result;
newFileImpl: (path, callback) ->
@client.open path, "w", {}, (err, handle) =>
if err?
callback(null, err);
return;
@client.close handle, (err) =>
if err?
callback(null, err);
return;
callback(@getFile(path), null);
| 67155 | fs = require 'fs'
fsp = require 'fs-plus'
PathUtil = require('path').posix
VFileSystem = require '../vfilesystem'
FTPFile = require './ftp-file'
FTPDirectory = require './ftp-directory'
FTPSymLink = require './ftp-symlink'
SFTPSession = require './sftp-session'
Utils = require '../../utils'
module.exports =
class SFTPFileSystem extends VFileSystem
constructor: (main, @server, @config) ->
super(main);
@session = null;
@client = null;
if !@config.passwordDecrypted
if @config.password? and @config.password.length > 0
@config.password = Utils.decrypt(@config.password, @getDescription());
if @config.passphrase? and @config.passphrase.length > 0
@config.passphrase = Utils.decrypt(@config.passphrase, @getDescription());
@config.passwordDecrypted = true;
@clientConfig = @getClientConfig();
clone: ->
cloneFS = new SFTPFileSystem(@getMain(), @server, @config);
cloneFS.clientConfig = @clientConfig;
return cloneFS;
isLocal: ->
return false;
connectImpl: ->
@session = new SFTPSession(@);
@session.connect();
disconnectImpl: ->
if @session?
@session.disconnect();
sessionOpened: (session) ->
if session == @session
@client = session.getClient();
@setConnected(true);
sessionCanceled: (session) ->
if session == @session
@session = null;
@setConnected(false);
sessionClosed: (session) ->
if session == @session
@session = null;
@client = null;
@setConnected(false);
getClientConfig: ->
result = {};
result.host = @config.host;
result.port = @config.port;
result.username = @config.username;
result.password = <PASSWORD>;
result.passphrase = @config.passphrase;
result.tryKeyboard = true;
result.keepaliveInterval = 60000;
if !@config.loginWithPassword
try
result.privateKey = @getPrivateKey(@config.privateKeyPath);
catch err
Utils.showErrorWarning("Error reading private key", null, null, err, true);
return result;
getPrivateKey: (path) ->
if !path or path.length == 0
return '';
path = Utils.resolveHome(path);
if !fsp.isFileSync(path)
return '';
return fs.readFileSync(path, 'utf8');
getSafeConfig: ->
result = {};
for key, val of @config
result[key] = val;
if @config.storePassword
if @config.password? and @config.password.length > 0
result.password = Utils.encrypt(result.password, @getDescription());
if @config.passphrase? and @config.passphrase.length > 0
result.passphrase = Utils.encrypt(result.passphrase, @getDescription());
else
delete result.password;
delete result.passphrase;
delete result.privateKey;
delete result.passwordDecrypted;
return result;
getFile: (path) ->
return new FTPFile(@, false, path);
getDirectory: (path) ->
return new FTPDirectory(@, false, path);
getItemWithPathDescription: (pathDescription) ->
if pathDescription.isFile
return new FTPFile(@, pathDescription.isLink, pathDescription.path, pathDescription.name);
return new FTPDirectory(@, pathDescription.isLink, pathDescription.path);
getInitialDirectory: ->
return @getDirectory(@config.folder);
getURI: (item) ->
return @config.protocol+"://" + PathUtil.join(@config.host, item.path);
getPathUtil: ->
return PathUtil;
getPathFromURI: (uri) ->
root = @config.protocol+"://"+@config.host;
if uri.substring(0, root.length) == root
return uri.substring(root.length);
return null;
renameImpl: (oldPath, newPath, callback) ->
@client.rename oldPath, newPath, (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
makeDirectoryImpl: (path, callback) ->
@client.mkdir path, [], (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
deleteFileImpl: (path, callback) ->
@client.unlink path, (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
deleteDirectoryImpl: (path, callback) ->
@client.rmdir path, (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
getName: ->
return @config.name;
getDisplayName: ->
if @config.name and @config.name.trim().length > 0
return @config.name;
return @config.host;
getHost: ->
return @config.host;
getUsername: ->
return @config.username;
getID: ->
return @getLocalDirectoryName();
getLocalDirectoryName: ->
return @config.protocol+"_"+@config.host+"_"+@config.port+"_"+@config.username;
downloadImpl: (path, localPath, callback) ->
@client.fastGet(path, localPath, {}, callback);
uploadImpl: (localPath, path, callback) ->
@client.fastPut(localPath, path, {}, callback);
openFile: (file) ->
@server.getRemoteFileManager().openFile(file);
createReadStreamImpl: (path, callback) ->
rs = @client.createReadStream(path);
callback(null, rs);
getDescription: ->
return @config.protocol+"://"+@config.host+":"+@config.port;
getEntriesImpl: (directory, callback) ->
@list directory.getPath(), (err, entries) =>
callback(directory, err, entries);
list: (path, callback) ->
@client.readdir path, (err, entries) =>
if err?
callback(err, []);
else
callback(null, @wrapEntries(path, entries));
wrapEntries: (path, entries) ->
directories = [];
files = [];
for entry in entries
wrappedEntry = @wrapEntry(path, entry);
if wrappedEntry != null
if wrappedEntry.isFile()
files.push(wrappedEntry);
else
directories.push(wrappedEntry);
Utils.sortItems(files);
Utils.sortItems(directories);
return directories.concat(files);
wrapEntry: (path, entry) ->
item = null;
if entry.attrs.isDirectory()
item = new FTPDirectory(@, false, PathUtil.join(path, entry.filename));
else if entry.attrs.isFile()
item = new FTPFile(@, false, PathUtil.join(path, entry.filename));
else if entry.attrs.isSymbolicLink()
item = @wrapSymLinkEntry(path, entry);
if item?
item.modifyDate = new Date(entry.attrs.mtime*1000);
item.size = entry.attrs.size;
return item;
wrapSymLinkEntry: (path, entry) ->
fullPath = PathUtil.join(path, entry.filename);
result = new FTPSymLink(@, fullPath);
@client.stat fullPath, (err, stat) =>
if err?
return;
result.setModifyDate(new Date(entry.attrs.mtime*1000));
result.setSize(entry.attrs.size);
@client.readlink fullPath, (err, target) =>
if err?
return;
if stat.isFile()
result.setTargetFilePath(target);
else if stat.isDirectory()
result.setTargetDirectoryPath(PathUtil.join(path, target));
return result;
newFileImpl: (path, callback) ->
@client.open path, "w", {}, (err, handle) =>
if err?
callback(null, err);
return;
@client.close handle, (err) =>
if err?
callback(null, err);
return;
callback(@getFile(path), null);
| true | fs = require 'fs'
fsp = require 'fs-plus'
PathUtil = require('path').posix
VFileSystem = require '../vfilesystem'
FTPFile = require './ftp-file'
FTPDirectory = require './ftp-directory'
FTPSymLink = require './ftp-symlink'
SFTPSession = require './sftp-session'
Utils = require '../../utils'
module.exports =
class SFTPFileSystem extends VFileSystem
constructor: (main, @server, @config) ->
super(main);
@session = null;
@client = null;
if !@config.passwordDecrypted
if @config.password? and @config.password.length > 0
@config.password = Utils.decrypt(@config.password, @getDescription());
if @config.passphrase? and @config.passphrase.length > 0
@config.passphrase = Utils.decrypt(@config.passphrase, @getDescription());
@config.passwordDecrypted = true;
@clientConfig = @getClientConfig();
clone: ->
cloneFS = new SFTPFileSystem(@getMain(), @server, @config);
cloneFS.clientConfig = @clientConfig;
return cloneFS;
isLocal: ->
return false;
connectImpl: ->
@session = new SFTPSession(@);
@session.connect();
disconnectImpl: ->
if @session?
@session.disconnect();
sessionOpened: (session) ->
if session == @session
@client = session.getClient();
@setConnected(true);
sessionCanceled: (session) ->
if session == @session
@session = null;
@setConnected(false);
sessionClosed: (session) ->
if session == @session
@session = null;
@client = null;
@setConnected(false);
getClientConfig: ->
result = {};
result.host = @config.host;
result.port = @config.port;
result.username = @config.username;
result.password = PI:PASSWORD:<PASSWORD>END_PI;
result.passphrase = @config.passphrase;
result.tryKeyboard = true;
result.keepaliveInterval = 60000;
if !@config.loginWithPassword
try
result.privateKey = @getPrivateKey(@config.privateKeyPath);
catch err
Utils.showErrorWarning("Error reading private key", null, null, err, true);
return result;
getPrivateKey: (path) ->
if !path or path.length == 0
return '';
path = Utils.resolveHome(path);
if !fsp.isFileSync(path)
return '';
return fs.readFileSync(path, 'utf8');
getSafeConfig: ->
result = {};
for key, val of @config
result[key] = val;
if @config.storePassword
if @config.password? and @config.password.length > 0
result.password = Utils.encrypt(result.password, @getDescription());
if @config.passphrase? and @config.passphrase.length > 0
result.passphrase = Utils.encrypt(result.passphrase, @getDescription());
else
delete result.password;
delete result.passphrase;
delete result.privateKey;
delete result.passwordDecrypted;
return result;
getFile: (path) ->
return new FTPFile(@, false, path);
getDirectory: (path) ->
return new FTPDirectory(@, false, path);
getItemWithPathDescription: (pathDescription) ->
if pathDescription.isFile
return new FTPFile(@, pathDescription.isLink, pathDescription.path, pathDescription.name);
return new FTPDirectory(@, pathDescription.isLink, pathDescription.path);
getInitialDirectory: ->
return @getDirectory(@config.folder);
getURI: (item) ->
return @config.protocol+"://" + PathUtil.join(@config.host, item.path);
getPathUtil: ->
return PathUtil;
getPathFromURI: (uri) ->
root = @config.protocol+"://"+@config.host;
if uri.substring(0, root.length) == root
return uri.substring(root.length);
return null;
renameImpl: (oldPath, newPath, callback) ->
@client.rename oldPath, newPath, (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
makeDirectoryImpl: (path, callback) ->
@client.mkdir path, [], (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
deleteFileImpl: (path, callback) ->
@client.unlink path, (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
deleteDirectoryImpl: (path, callback) ->
@client.rmdir path, (err) =>
if !callback?
return;
if err?
callback(err);
else
callback(null);
getName: ->
return @config.name;
getDisplayName: ->
if @config.name and @config.name.trim().length > 0
return @config.name;
return @config.host;
getHost: ->
return @config.host;
getUsername: ->
return @config.username;
getID: ->
return @getLocalDirectoryName();
getLocalDirectoryName: ->
return @config.protocol+"_"+@config.host+"_"+@config.port+"_"+@config.username;
downloadImpl: (path, localPath, callback) ->
@client.fastGet(path, localPath, {}, callback);
uploadImpl: (localPath, path, callback) ->
@client.fastPut(localPath, path, {}, callback);
openFile: (file) ->
@server.getRemoteFileManager().openFile(file);
createReadStreamImpl: (path, callback) ->
rs = @client.createReadStream(path);
callback(null, rs);
getDescription: ->
return @config.protocol+"://"+@config.host+":"+@config.port;
getEntriesImpl: (directory, callback) ->
@list directory.getPath(), (err, entries) =>
callback(directory, err, entries);
list: (path, callback) ->
@client.readdir path, (err, entries) =>
if err?
callback(err, []);
else
callback(null, @wrapEntries(path, entries));
wrapEntries: (path, entries) ->
directories = [];
files = [];
for entry in entries
wrappedEntry = @wrapEntry(path, entry);
if wrappedEntry != null
if wrappedEntry.isFile()
files.push(wrappedEntry);
else
directories.push(wrappedEntry);
Utils.sortItems(files);
Utils.sortItems(directories);
return directories.concat(files);
wrapEntry: (path, entry) ->
item = null;
if entry.attrs.isDirectory()
item = new FTPDirectory(@, false, PathUtil.join(path, entry.filename));
else if entry.attrs.isFile()
item = new FTPFile(@, false, PathUtil.join(path, entry.filename));
else if entry.attrs.isSymbolicLink()
item = @wrapSymLinkEntry(path, entry);
if item?
item.modifyDate = new Date(entry.attrs.mtime*1000);
item.size = entry.attrs.size;
return item;
wrapSymLinkEntry: (path, entry) ->
fullPath = PathUtil.join(path, entry.filename);
result = new FTPSymLink(@, fullPath);
@client.stat fullPath, (err, stat) =>
if err?
return;
result.setModifyDate(new Date(entry.attrs.mtime*1000));
result.setSize(entry.attrs.size);
@client.readlink fullPath, (err, target) =>
if err?
return;
if stat.isFile()
result.setTargetFilePath(target);
else if stat.isDirectory()
result.setTargetDirectoryPath(PathUtil.join(path, target));
return result;
newFileImpl: (path, callback) ->
@client.open path, "w", {}, (err, handle) =>
if err?
callback(null, err);
return;
@client.close handle, (err) =>
if err?
callback(null, err);
return;
callback(@getFile(path), null);
|
[
{
"context": "mpt } myUser = User.findOne({ where: { username: 'heath' })\n #{ config.prompt } myUser.updateAttrib",
"end": 3193,
"score": 0.9988476037979126,
"start": 3188,
"tag": "USERNAME",
"value": "heath"
},
{
"context": "nfig.prompt } myUser.updateAttribute('fullName', 'Heath Morrison)\n #{ config.prompt } myUser.widgets.add({ .",
"end": 3274,
"score": 0.9259620904922485,
"start": 3260,
"tag": "NAME",
"value": "Heath Morrison"
}
] | repl.coffee | BoLaMN/loopback-console-cs | 0 | 'use strict'
fs = require 'fs'
path = require 'path'
vm = require 'vm'
coffee = require 'coffee-script'
{ start, REPLServer } = require 'repl'
{ updateSyntaxError } = require 'coffee-script/lib/coffee-script/helpers'
sawSIGINT = false
wrap = (replServer) ->
defaultEval = replServer.eval
runInContext = (js, context, filename) ->
if context is global
vm.runInThisContext js, filename
else
vm.runInContext js, context, filename
CoffeeScriptEval = (input, context, filename, cb) ->
input = input
.replace /\uFF00/g, '\n'
.replace /^\(([\s\S]*)\n\)$/m, '$1'
.replace /^\s*try\s*{([\s\S]*)}\s*catch.*$/m, '$1'
{ Block, Assign, Value
Literal, Call, Code
} = require 'coffee-script/lib/coffee-script/nodes'
try
tokens = coffee.tokens input
referencedVars = token[1] for token in tokens when token[0] is 'IDENTIFIER'
ast = coffee.nodes tokens
ast = new Block [ new Assign (new Value new Literal '__'), ast, '=' ]
ast = new Code [], ast
{ isAsync } = ast
ast = new Block [ new Call ast ]
js = ast.compile
bare: true
locals: Object.keys(context)
sharedScope: true
referencedVars
result = runInContext js, context, filename
if isAsync
result.then (resolved) ->
cb null, resolved unless sawSIGINT
sawSIGINT = false
else
cb null, result
catch err
try
defaultEval.call @, input, context, filename, cb
catch e
updateSyntaxError err, input
cb err
(code, context, file, cb) ->
resolvePromises = (promise, resolved) ->
Object.keys(context).forEach (key) ->
if context[key] == promise
context[key] = resolved
return
CoffeeScriptEval code, context, file, (err, result) ->
if not result?.then
return cb err, result
success = (resolved) ->
resolvePromises result, resolved
replServer.context.result = resolved
cb null, resolved
error = (err) ->
resolvePromises result, err
console.log '[31m' + '[Promise Rejection]' + '[0m'
if err and err.message
console.log '[31m' + err.message + '[0m'
cb null, err
result
.then success
.catch err
usage = ({ models, handles, handleInfo, customHandleNames, config }, details) ->
modelHandleNames = Object.keys models
customHandleNames = Object.keys(handles).filter (k) ->
not handleInfo[k] and not models[k]
txt = """============================================
Loopback Console
Primary handles available:
"""
Object.keys(handleInfo).forEach (key) ->
txt += " - #{ key }: #{ handleInfo[key] }\n"
if modelHandleNames.length > 0 or customHandleNames.length > 0
txt += "\nOther handles available:\n"
if modelHandleNames.length > 0
txt += " - Models: #{ modelHandleNames.sort().join(', ') }\n"
if customHandleNames.length > 0
txt += " - Custom: #{ customHandleNames.join(', ') }\n"
if details
txt += """
Examples:
#{ config.prompt } myUser = User.findOne({ where: { username: 'heath' })
#{ config.prompt } myUser.updateAttribute('fullName', 'Heath Morrison)
#{ config.prompt } myUser.widgets.add({ ... })
"""
txt += "============================================\n\n"
txt
addMultilineHandler = ({rli, inputStream, outputStream, _prompt, prompt }) ->
origPrompt = _prompt or prompt
multiline =
enabled: off
initialPrompt: origPrompt.replace /^[^> ]*/, (x) -> x.replace /./g, '-'
prompt: origPrompt.replace /^[^> ]*>?/, (x) -> x.replace /./g, '.'
buffer: ''
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
rli.setPrompt origPrompt
nodeLineListener cmd
return
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
unless multiline.buffer.match /\n/
multiline.enabled = not multiline.enabled
rli.setPrompt origPrompt
rli.prompt true
return
return if rli.line? and not rli.line.match /^\s*$/
multiline.enabled = not multiline.enabled
rli.line = ''
rli.cursor = 0
rli.output.cursorTo 0
rli.output.clearLine 1
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
addModels = (replServer, { models }) ->
replServer.defineCommand 'models',
help: 'Display available Loopback models'
action: ->
@outputStream.write Object.keys(models).join(', ') + '\n'
@displayPrompt()
addUsage = (replServer, ctx) ->
replServer.defineCommand 'usage',
help: 'Detailed Loopback Console usage information'
action: ->
@outputStream.write usage(ctx, true)
@displayPrompt()
addHistory = (replServer, filename, maxSize) ->
lastLine = null
try
stat = fs.statSync filename
size = Math.min maxSize, stat.size
readFd = fs.openSync filename, 'r'
buffer = new Buffer(size)
fs.readSync readFd, buffer, 0, size, stat.size - size
fs.closeSync readFd
replServer.rli.history = buffer.toString().split('\n').reverse()
replServer.rli.history.pop() if stat.size > maxSize
replServer.rli.history.shift() if replServer.rli.history[0] is ''
replServer.rli.historyIndex = -1
lastLine = replServer.rli.history[0]
fd = fs.openSync filename, 'a'
replServer.rli.addListener 'line', (code) ->
if code and code.length and code isnt '.history' and code isnt '.exit' and lastLine isnt code
fs.writeSync fd, "#{code}\n"
lastLine = code
replServer.on 'exit', ->
fs.closeSync fd
replServer.defineCommand 'history',
help: 'Show command history'
action: ->
@outputStream.write "#{ replServer.rli.history[..].reverse().join '\n' }\n"
@displayPrompt()
addLoad = (replServer) ->
replServer.commands.load.help = 'Load CoffeeScript/JavaScript from a file into this REPL session'
module.exports = (ctx) ->
{ quiet, config, handles } = ctx
if not quiet
console.log usage ctx
config = Object.assign {}, config
replServer = start config
context = replServer.context
context.exit = ->
process.exit 0
replServer.on 'exit', ->
replServer.outputStream.write '\n' if not replServer.rli.closed
addMultilineHandler replServer
addHistory replServer, config.historyFile, config.historyMaxInputSize
addUsage replServer, ctx
addModels replServer, ctx
addLoad replServer
Object.assign context, handles
replServer.eval = wrap replServer
if handles.cb
context.result = undefined
context.cb = (err, result) ->
context.err = err
context.result = result
if err
console.error 'Error: ' + err
if not config.quiet
console.log result
replServer
| 221603 | 'use strict'
fs = require 'fs'
path = require 'path'
vm = require 'vm'
coffee = require 'coffee-script'
{ start, REPLServer } = require 'repl'
{ updateSyntaxError } = require 'coffee-script/lib/coffee-script/helpers'
sawSIGINT = false
wrap = (replServer) ->
defaultEval = replServer.eval
runInContext = (js, context, filename) ->
if context is global
vm.runInThisContext js, filename
else
vm.runInContext js, context, filename
CoffeeScriptEval = (input, context, filename, cb) ->
input = input
.replace /\uFF00/g, '\n'
.replace /^\(([\s\S]*)\n\)$/m, '$1'
.replace /^\s*try\s*{([\s\S]*)}\s*catch.*$/m, '$1'
{ Block, Assign, Value
Literal, Call, Code
} = require 'coffee-script/lib/coffee-script/nodes'
try
tokens = coffee.tokens input
referencedVars = token[1] for token in tokens when token[0] is 'IDENTIFIER'
ast = coffee.nodes tokens
ast = new Block [ new Assign (new Value new Literal '__'), ast, '=' ]
ast = new Code [], ast
{ isAsync } = ast
ast = new Block [ new Call ast ]
js = ast.compile
bare: true
locals: Object.keys(context)
sharedScope: true
referencedVars
result = runInContext js, context, filename
if isAsync
result.then (resolved) ->
cb null, resolved unless sawSIGINT
sawSIGINT = false
else
cb null, result
catch err
try
defaultEval.call @, input, context, filename, cb
catch e
updateSyntaxError err, input
cb err
(code, context, file, cb) ->
resolvePromises = (promise, resolved) ->
Object.keys(context).forEach (key) ->
if context[key] == promise
context[key] = resolved
return
CoffeeScriptEval code, context, file, (err, result) ->
if not result?.then
return cb err, result
success = (resolved) ->
resolvePromises result, resolved
replServer.context.result = resolved
cb null, resolved
error = (err) ->
resolvePromises result, err
console.log '[31m' + '[Promise Rejection]' + '[0m'
if err and err.message
console.log '[31m' + err.message + '[0m'
cb null, err
result
.then success
.catch err
usage = ({ models, handles, handleInfo, customHandleNames, config }, details) ->
modelHandleNames = Object.keys models
customHandleNames = Object.keys(handles).filter (k) ->
not handleInfo[k] and not models[k]
txt = """============================================
Loopback Console
Primary handles available:
"""
Object.keys(handleInfo).forEach (key) ->
txt += " - #{ key }: #{ handleInfo[key] }\n"
if modelHandleNames.length > 0 or customHandleNames.length > 0
txt += "\nOther handles available:\n"
if modelHandleNames.length > 0
txt += " - Models: #{ modelHandleNames.sort().join(', ') }\n"
if customHandleNames.length > 0
txt += " - Custom: #{ customHandleNames.join(', ') }\n"
if details
txt += """
Examples:
#{ config.prompt } myUser = User.findOne({ where: { username: 'heath' })
#{ config.prompt } myUser.updateAttribute('fullName', '<NAME>)
#{ config.prompt } myUser.widgets.add({ ... })
"""
txt += "============================================\n\n"
txt
addMultilineHandler = ({rli, inputStream, outputStream, _prompt, prompt }) ->
origPrompt = _prompt or prompt
multiline =
enabled: off
initialPrompt: origPrompt.replace /^[^> ]*/, (x) -> x.replace /./g, '-'
prompt: origPrompt.replace /^[^> ]*>?/, (x) -> x.replace /./g, '.'
buffer: ''
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
rli.setPrompt origPrompt
nodeLineListener cmd
return
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
unless multiline.buffer.match /\n/
multiline.enabled = not multiline.enabled
rli.setPrompt origPrompt
rli.prompt true
return
return if rli.line? and not rli.line.match /^\s*$/
multiline.enabled = not multiline.enabled
rli.line = ''
rli.cursor = 0
rli.output.cursorTo 0
rli.output.clearLine 1
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
addModels = (replServer, { models }) ->
replServer.defineCommand 'models',
help: 'Display available Loopback models'
action: ->
@outputStream.write Object.keys(models).join(', ') + '\n'
@displayPrompt()
addUsage = (replServer, ctx) ->
replServer.defineCommand 'usage',
help: 'Detailed Loopback Console usage information'
action: ->
@outputStream.write usage(ctx, true)
@displayPrompt()
addHistory = (replServer, filename, maxSize) ->
lastLine = null
try
stat = fs.statSync filename
size = Math.min maxSize, stat.size
readFd = fs.openSync filename, 'r'
buffer = new Buffer(size)
fs.readSync readFd, buffer, 0, size, stat.size - size
fs.closeSync readFd
replServer.rli.history = buffer.toString().split('\n').reverse()
replServer.rli.history.pop() if stat.size > maxSize
replServer.rli.history.shift() if replServer.rli.history[0] is ''
replServer.rli.historyIndex = -1
lastLine = replServer.rli.history[0]
fd = fs.openSync filename, 'a'
replServer.rli.addListener 'line', (code) ->
if code and code.length and code isnt '.history' and code isnt '.exit' and lastLine isnt code
fs.writeSync fd, "#{code}\n"
lastLine = code
replServer.on 'exit', ->
fs.closeSync fd
replServer.defineCommand 'history',
help: 'Show command history'
action: ->
@outputStream.write "#{ replServer.rli.history[..].reverse().join '\n' }\n"
@displayPrompt()
addLoad = (replServer) ->
replServer.commands.load.help = 'Load CoffeeScript/JavaScript from a file into this REPL session'
module.exports = (ctx) ->
{ quiet, config, handles } = ctx
if not quiet
console.log usage ctx
config = Object.assign {}, config
replServer = start config
context = replServer.context
context.exit = ->
process.exit 0
replServer.on 'exit', ->
replServer.outputStream.write '\n' if not replServer.rli.closed
addMultilineHandler replServer
addHistory replServer, config.historyFile, config.historyMaxInputSize
addUsage replServer, ctx
addModels replServer, ctx
addLoad replServer
Object.assign context, handles
replServer.eval = wrap replServer
if handles.cb
context.result = undefined
context.cb = (err, result) ->
context.err = err
context.result = result
if err
console.error 'Error: ' + err
if not config.quiet
console.log result
replServer
| true | 'use strict'
fs = require 'fs'
path = require 'path'
vm = require 'vm'
coffee = require 'coffee-script'
{ start, REPLServer } = require 'repl'
{ updateSyntaxError } = require 'coffee-script/lib/coffee-script/helpers'
sawSIGINT = false
wrap = (replServer) ->
defaultEval = replServer.eval
runInContext = (js, context, filename) ->
if context is global
vm.runInThisContext js, filename
else
vm.runInContext js, context, filename
CoffeeScriptEval = (input, context, filename, cb) ->
input = input
.replace /\uFF00/g, '\n'
.replace /^\(([\s\S]*)\n\)$/m, '$1'
.replace /^\s*try\s*{([\s\S]*)}\s*catch.*$/m, '$1'
{ Block, Assign, Value
Literal, Call, Code
} = require 'coffee-script/lib/coffee-script/nodes'
try
tokens = coffee.tokens input
referencedVars = token[1] for token in tokens when token[0] is 'IDENTIFIER'
ast = coffee.nodes tokens
ast = new Block [ new Assign (new Value new Literal '__'), ast, '=' ]
ast = new Code [], ast
{ isAsync } = ast
ast = new Block [ new Call ast ]
js = ast.compile
bare: true
locals: Object.keys(context)
sharedScope: true
referencedVars
result = runInContext js, context, filename
if isAsync
result.then (resolved) ->
cb null, resolved unless sawSIGINT
sawSIGINT = false
else
cb null, result
catch err
try
defaultEval.call @, input, context, filename, cb
catch e
updateSyntaxError err, input
cb err
(code, context, file, cb) ->
resolvePromises = (promise, resolved) ->
Object.keys(context).forEach (key) ->
if context[key] == promise
context[key] = resolved
return
CoffeeScriptEval code, context, file, (err, result) ->
if not result?.then
return cb err, result
success = (resolved) ->
resolvePromises result, resolved
replServer.context.result = resolved
cb null, resolved
error = (err) ->
resolvePromises result, err
console.log '[31m' + '[Promise Rejection]' + '[0m'
if err and err.message
console.log '[31m' + err.message + '[0m'
cb null, err
result
.then success
.catch err
usage = ({ models, handles, handleInfo, customHandleNames, config }, details) ->
modelHandleNames = Object.keys models
customHandleNames = Object.keys(handles).filter (k) ->
not handleInfo[k] and not models[k]
txt = """============================================
Loopback Console
Primary handles available:
"""
Object.keys(handleInfo).forEach (key) ->
txt += " - #{ key }: #{ handleInfo[key] }\n"
if modelHandleNames.length > 0 or customHandleNames.length > 0
txt += "\nOther handles available:\n"
if modelHandleNames.length > 0
txt += " - Models: #{ modelHandleNames.sort().join(', ') }\n"
if customHandleNames.length > 0
txt += " - Custom: #{ customHandleNames.join(', ') }\n"
if details
txt += """
Examples:
#{ config.prompt } myUser = User.findOne({ where: { username: 'heath' })
#{ config.prompt } myUser.updateAttribute('fullName', 'PI:NAME:<NAME>END_PI)
#{ config.prompt } myUser.widgets.add({ ... })
"""
txt += "============================================\n\n"
txt
addMultilineHandler = ({rli, inputStream, outputStream, _prompt, prompt }) ->
origPrompt = _prompt or prompt
multiline =
enabled: off
initialPrompt: origPrompt.replace /^[^> ]*/, (x) -> x.replace /./g, '-'
prompt: origPrompt.replace /^[^> ]*>?/, (x) -> x.replace /./g, '.'
buffer: ''
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
rli.setPrompt origPrompt
nodeLineListener cmd
return
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
unless multiline.buffer.match /\n/
multiline.enabled = not multiline.enabled
rli.setPrompt origPrompt
rli.prompt true
return
return if rli.line? and not rli.line.match /^\s*$/
multiline.enabled = not multiline.enabled
rli.line = ''
rli.cursor = 0
rli.output.cursorTo 0
rli.output.clearLine 1
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
addModels = (replServer, { models }) ->
replServer.defineCommand 'models',
help: 'Display available Loopback models'
action: ->
@outputStream.write Object.keys(models).join(', ') + '\n'
@displayPrompt()
addUsage = (replServer, ctx) ->
replServer.defineCommand 'usage',
help: 'Detailed Loopback Console usage information'
action: ->
@outputStream.write usage(ctx, true)
@displayPrompt()
addHistory = (replServer, filename, maxSize) ->
lastLine = null
try
stat = fs.statSync filename
size = Math.min maxSize, stat.size
readFd = fs.openSync filename, 'r'
buffer = new Buffer(size)
fs.readSync readFd, buffer, 0, size, stat.size - size
fs.closeSync readFd
replServer.rli.history = buffer.toString().split('\n').reverse()
replServer.rli.history.pop() if stat.size > maxSize
replServer.rli.history.shift() if replServer.rli.history[0] is ''
replServer.rli.historyIndex = -1
lastLine = replServer.rli.history[0]
fd = fs.openSync filename, 'a'
replServer.rli.addListener 'line', (code) ->
if code and code.length and code isnt '.history' and code isnt '.exit' and lastLine isnt code
fs.writeSync fd, "#{code}\n"
lastLine = code
replServer.on 'exit', ->
fs.closeSync fd
replServer.defineCommand 'history',
help: 'Show command history'
action: ->
@outputStream.write "#{ replServer.rli.history[..].reverse().join '\n' }\n"
@displayPrompt()
addLoad = (replServer) ->
replServer.commands.load.help = 'Load CoffeeScript/JavaScript from a file into this REPL session'
module.exports = (ctx) ->
{ quiet, config, handles } = ctx
if not quiet
console.log usage ctx
config = Object.assign {}, config
replServer = start config
context = replServer.context
context.exit = ->
process.exit 0
replServer.on 'exit', ->
replServer.outputStream.write '\n' if not replServer.rli.closed
addMultilineHandler replServer
addHistory replServer, config.historyFile, config.historyMaxInputSize
addUsage replServer, ctx
addModels replServer, ctx
addLoad replServer
Object.assign context, handles
replServer.eval = wrap replServer
if handles.cb
context.result = undefined
context.cb = (err, result) ->
context.err = err
context.result = result
if err
console.error 'Error: ' + err
if not config.quiet
console.log result
replServer
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9993118643760681,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-file-write-stream3.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.
removeTestFile = ->
try
fs.unlinkSync filepath
return
run_test_1 = ->
file = undefined
buffer = undefined
options = undefined
options = {}
file = fs.createWriteStream(filepath, options)
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
file.on "open", (fd) ->
cb_occurred += "open "
return
file.on "close", ->
cb_occurred += "close "
console.log " (debug: bytesWritten ", file.bytesWritten
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
assert.strictEqual file.bytesWritten, buffer.length
fileData = fs.readFileSync(filepath, "utf8")
console.log " (debug: file data ", fileData
console.log " (debug: expected ", fileDataExpected_1
assert.equal fileData, fileDataExpected_1
run_test_2()
return
file.on "error", (err) ->
cb_occurred += "error "
console.log " (debug: err event ", err
throw errreturn
buffer = new Buffer(fileDataInitial)
file.write buffer
cb_occurred += "write "
file.end()
return
run_test_2 = ->
file = undefined
buffer = undefined
options = undefined
buffer = new Buffer("123456")
options =
start: 10
flags: "r+"
file = fs.createWriteStream(filepath, options)
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
file.on "open", (fd) ->
cb_occurred += "open "
return
file.on "close", ->
cb_occurred += "close "
console.log " (debug: bytesWritten ", file.bytesWritten
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
assert.strictEqual file.bytesWritten, buffer.length
fileData = fs.readFileSync(filepath, "utf8")
console.log " (debug: file data ", fileData
console.log " (debug: expected ", fileDataExpected_2
assert.equal fileData, fileDataExpected_2
run_test_3()
return
file.on "error", (err) ->
cb_occurred += "error "
console.log " (debug: err event ", err
throw errreturn
file.write buffer
cb_occurred += "write "
file.end()
return
run_test_3 = ->
file = undefined
buffer = undefined
options = undefined
data = "……" # 3 bytes * 2 = 6 bytes in UTF-8
fileData = undefined
options =
start: 10
flags: "r+"
file = fs.createWriteStream(filepath, options)
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
file.on "open", (fd) ->
cb_occurred += "open "
return
file.on "close", ->
cb_occurred += "close "
console.log " (debug: bytesWritten ", file.bytesWritten
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
assert.strictEqual file.bytesWritten, data.length * 3
fileData = fs.readFileSync(filepath, "utf8")
console.log " (debug: file data ", fileData
console.log " (debug: expected ", fileDataExpected_3
assert.equal fileData, fileDataExpected_3
run_test_4()
return
file.on "error", (err) ->
cb_occurred += "error "
console.log " (debug: err event ", err
throw errreturn
file.write data, "utf8"
cb_occurred += "write "
file.end()
return
run_test_4 = ->
file = undefined
options = undefined
options =
start: -5
flags: "r+"
# Error: start must be >= zero
assert.throws (->
file = fs.createWriteStream(filepath, options)
return
), /start must be/
return
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
util = require("util")
filepath = path.join(common.tmpDir, "write_pos.txt")
cb_expected = "write open close write open close write open close "
cb_occurred = ""
fileDataInitial = "abcdefghijklmnopqrstuvwxyz"
fileDataExpected_1 = "abcdefghijklmnopqrstuvwxyz"
fileDataExpected_2 = "abcdefghij123456qrstuvwxyz"
fileDataExpected_3 = "abcdefghij……qrstuvwxyz"
process.on "exit", ->
removeTestFile()
if cb_occurred isnt cb_expected
console.log " Test callback events missing or out of order:"
console.log " expected: %j", cb_expected
console.log " occurred: %j", cb_occurred
assert.strictEqual cb_occurred, cb_expected, "events missing or out of order: \"" + cb_occurred + "\" !== \"" + cb_expected + "\""
return
removeTestFile()
run_test_1()
| 168647 | # 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.
removeTestFile = ->
try
fs.unlinkSync filepath
return
run_test_1 = ->
file = undefined
buffer = undefined
options = undefined
options = {}
file = fs.createWriteStream(filepath, options)
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
file.on "open", (fd) ->
cb_occurred += "open "
return
file.on "close", ->
cb_occurred += "close "
console.log " (debug: bytesWritten ", file.bytesWritten
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
assert.strictEqual file.bytesWritten, buffer.length
fileData = fs.readFileSync(filepath, "utf8")
console.log " (debug: file data ", fileData
console.log " (debug: expected ", fileDataExpected_1
assert.equal fileData, fileDataExpected_1
run_test_2()
return
file.on "error", (err) ->
cb_occurred += "error "
console.log " (debug: err event ", err
throw errreturn
buffer = new Buffer(fileDataInitial)
file.write buffer
cb_occurred += "write "
file.end()
return
run_test_2 = ->
file = undefined
buffer = undefined
options = undefined
buffer = new Buffer("123456")
options =
start: 10
flags: "r+"
file = fs.createWriteStream(filepath, options)
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
file.on "open", (fd) ->
cb_occurred += "open "
return
file.on "close", ->
cb_occurred += "close "
console.log " (debug: bytesWritten ", file.bytesWritten
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
assert.strictEqual file.bytesWritten, buffer.length
fileData = fs.readFileSync(filepath, "utf8")
console.log " (debug: file data ", fileData
console.log " (debug: expected ", fileDataExpected_2
assert.equal fileData, fileDataExpected_2
run_test_3()
return
file.on "error", (err) ->
cb_occurred += "error "
console.log " (debug: err event ", err
throw errreturn
file.write buffer
cb_occurred += "write "
file.end()
return
run_test_3 = ->
file = undefined
buffer = undefined
options = undefined
data = "……" # 3 bytes * 2 = 6 bytes in UTF-8
fileData = undefined
options =
start: 10
flags: "r+"
file = fs.createWriteStream(filepath, options)
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
file.on "open", (fd) ->
cb_occurred += "open "
return
file.on "close", ->
cb_occurred += "close "
console.log " (debug: bytesWritten ", file.bytesWritten
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
assert.strictEqual file.bytesWritten, data.length * 3
fileData = fs.readFileSync(filepath, "utf8")
console.log " (debug: file data ", fileData
console.log " (debug: expected ", fileDataExpected_3
assert.equal fileData, fileDataExpected_3
run_test_4()
return
file.on "error", (err) ->
cb_occurred += "error "
console.log " (debug: err event ", err
throw errreturn
file.write data, "utf8"
cb_occurred += "write "
file.end()
return
run_test_4 = ->
file = undefined
options = undefined
options =
start: -5
flags: "r+"
# Error: start must be >= zero
assert.throws (->
file = fs.createWriteStream(filepath, options)
return
), /start must be/
return
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
util = require("util")
filepath = path.join(common.tmpDir, "write_pos.txt")
cb_expected = "write open close write open close write open close "
cb_occurred = ""
fileDataInitial = "abcdefghijklmnopqrstuvwxyz"
fileDataExpected_1 = "abcdefghijklmnopqrstuvwxyz"
fileDataExpected_2 = "abcdefghij123456qrstuvwxyz"
fileDataExpected_3 = "abcdefghij……qrstuvwxyz"
process.on "exit", ->
removeTestFile()
if cb_occurred isnt cb_expected
console.log " Test callback events missing or out of order:"
console.log " expected: %j", cb_expected
console.log " occurred: %j", cb_occurred
assert.strictEqual cb_occurred, cb_expected, "events missing or out of order: \"" + cb_occurred + "\" !== \"" + cb_expected + "\""
return
removeTestFile()
run_test_1()
| 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.
removeTestFile = ->
try
fs.unlinkSync filepath
return
run_test_1 = ->
file = undefined
buffer = undefined
options = undefined
options = {}
file = fs.createWriteStream(filepath, options)
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
file.on "open", (fd) ->
cb_occurred += "open "
return
file.on "close", ->
cb_occurred += "close "
console.log " (debug: bytesWritten ", file.bytesWritten
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
assert.strictEqual file.bytesWritten, buffer.length
fileData = fs.readFileSync(filepath, "utf8")
console.log " (debug: file data ", fileData
console.log " (debug: expected ", fileDataExpected_1
assert.equal fileData, fileDataExpected_1
run_test_2()
return
file.on "error", (err) ->
cb_occurred += "error "
console.log " (debug: err event ", err
throw errreturn
buffer = new Buffer(fileDataInitial)
file.write buffer
cb_occurred += "write "
file.end()
return
run_test_2 = ->
file = undefined
buffer = undefined
options = undefined
buffer = new Buffer("123456")
options =
start: 10
flags: "r+"
file = fs.createWriteStream(filepath, options)
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
file.on "open", (fd) ->
cb_occurred += "open "
return
file.on "close", ->
cb_occurred += "close "
console.log " (debug: bytesWritten ", file.bytesWritten
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
assert.strictEqual file.bytesWritten, buffer.length
fileData = fs.readFileSync(filepath, "utf8")
console.log " (debug: file data ", fileData
console.log " (debug: expected ", fileDataExpected_2
assert.equal fileData, fileDataExpected_2
run_test_3()
return
file.on "error", (err) ->
cb_occurred += "error "
console.log " (debug: err event ", err
throw errreturn
file.write buffer
cb_occurred += "write "
file.end()
return
run_test_3 = ->
file = undefined
buffer = undefined
options = undefined
data = "……" # 3 bytes * 2 = 6 bytes in UTF-8
fileData = undefined
options =
start: 10
flags: "r+"
file = fs.createWriteStream(filepath, options)
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
file.on "open", (fd) ->
cb_occurred += "open "
return
file.on "close", ->
cb_occurred += "close "
console.log " (debug: bytesWritten ", file.bytesWritten
console.log " (debug: start ", file.start
console.log " (debug: pos ", file.pos
assert.strictEqual file.bytesWritten, data.length * 3
fileData = fs.readFileSync(filepath, "utf8")
console.log " (debug: file data ", fileData
console.log " (debug: expected ", fileDataExpected_3
assert.equal fileData, fileDataExpected_3
run_test_4()
return
file.on "error", (err) ->
cb_occurred += "error "
console.log " (debug: err event ", err
throw errreturn
file.write data, "utf8"
cb_occurred += "write "
file.end()
return
run_test_4 = ->
file = undefined
options = undefined
options =
start: -5
flags: "r+"
# Error: start must be >= zero
assert.throws (->
file = fs.createWriteStream(filepath, options)
return
), /start must be/
return
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
util = require("util")
filepath = path.join(common.tmpDir, "write_pos.txt")
cb_expected = "write open close write open close write open close "
cb_occurred = ""
fileDataInitial = "abcdefghijklmnopqrstuvwxyz"
fileDataExpected_1 = "abcdefghijklmnopqrstuvwxyz"
fileDataExpected_2 = "abcdefghij123456qrstuvwxyz"
fileDataExpected_3 = "abcdefghij……qrstuvwxyz"
process.on "exit", ->
removeTestFile()
if cb_occurred isnt cb_expected
console.log " Test callback events missing or out of order:"
console.log " expected: %j", cb_expected
console.log " occurred: %j", cb_occurred
assert.strictEqual cb_occurred, cb_expected, "events missing or out of order: \"" + cb_occurred + "\" !== \"" + cb_expected + "\""
return
removeTestFile()
run_test_1()
|
[
{
"context": "runch/\")\n\t\tclientid = \"sandbox\"\n\t\tclientSecret = \"YNXZHOH3GPYO6DF7B43K\"\n\t\tredirectURI = encodeURI(\"http://localhost\")\n\t\t",
"end": 325,
"score": 0.9996213912963867,
"start": 305,
"tag": "KEY",
"value": "YNXZHOH3GPYO6DF7B43K"
},
{
"context": "params = {\n\t\t\theaders: {\n\t\t\t\tAuthorization: \"OAuth AlmGg7p7ImEiOiJGZWVkbHkgRGV2ZWxvcGVyIiwiZSI6MTQ0Njc1ODQ4MjIwMSwiaSI6IjFlYjk2NjE4LTFmYmItNDUwYS04NjhlLWM1ZDg4MzRjMjBhYiIsInAiOjYsInQiOjEsInYiOiJwcm9kdWN0aW9uIiwidyI6IjIwMTUuMzEiLCJ4Ijoic3RhbmRhcmQifQ:feedlydev\"\n\t\t\t}\n\t\t\tsuccess: (data, textStatus) ->",
"end": 624,
"score": 0.9995642304420471,
"start": 426,
"tag": "KEY",
"value": "AlmGg7p7ImEiOiJGZWVkbHkgRGV2ZWxvcGVyIiwiZSI6MTQ0Njc1ODQ4MjIwMSwiaSI6IjFlYjk2NjE4LTFmYmItNDUwYS04NjhlLWM1ZDg4MzRjMjBhYiIsInAiOjYsInQiOjEsInYiOiJwcm9kdWN0aW9uIiwidyI6IjIwMTUuMzEiLCJ4Ijoic3RhbmRhcmQifQ"
}
] | app/scripts/coffeescripts/popup.coffee | mapguy/News-Tab | 1 | do ($=jQuery) ->
document.addEventListener "DOMContentLoaded", ->
url = "https://cloud.feedly.com"
auth = "/v3/auth/auth"
subs = "/v3/subscriptions"
mix = "/v3/mixes/contents?streamId=" + encodeURIComponent("feed/http://feeds.feedburner.com/TechCrunch/")
clientid = "sandbox"
clientSecret = "YNXZHOH3GPYO6DF7B43K"
redirectURI = encodeURI("http://localhost")
params = {
headers: {
Authorization: "OAuth AlmGg7p7ImEiOiJGZWVkbHkgRGV2ZWxvcGVyIiwiZSI6MTQ0Njc1ODQ4MjIwMSwiaSI6IjFlYjk2NjE4LTFmYmItNDUwYS04NjhlLWM1ZDg4MzRjMjBhYiIsInAiOjYsInQiOjEsInYiOiJwcm9kdWN0aW9uIiwidyI6IjIwMTUuMzEiLCJ4Ijoic3RhbmRhcmQifQ:feedlydev"
}
success: (data, textStatus) ->
for entry in data.items
$(".test").append "#{entry.originId}<br>"
# response_type: "code",
# client_id: clientid,
# redirect_uri: redirectURI,
# scope: "https://cloud.feedly.com/subscriptions"
}
$(window).bind "keydown", "meta+i", (e) ->
$.ajax "#{url}#{mix}", params | 136254 | do ($=jQuery) ->
document.addEventListener "DOMContentLoaded", ->
url = "https://cloud.feedly.com"
auth = "/v3/auth/auth"
subs = "/v3/subscriptions"
mix = "/v3/mixes/contents?streamId=" + encodeURIComponent("feed/http://feeds.feedburner.com/TechCrunch/")
clientid = "sandbox"
clientSecret = "<KEY>"
redirectURI = encodeURI("http://localhost")
params = {
headers: {
Authorization: "OAuth <KEY>:feedlydev"
}
success: (data, textStatus) ->
for entry in data.items
$(".test").append "#{entry.originId}<br>"
# response_type: "code",
# client_id: clientid,
# redirect_uri: redirectURI,
# scope: "https://cloud.feedly.com/subscriptions"
}
$(window).bind "keydown", "meta+i", (e) ->
$.ajax "#{url}#{mix}", params | true | do ($=jQuery) ->
document.addEventListener "DOMContentLoaded", ->
url = "https://cloud.feedly.com"
auth = "/v3/auth/auth"
subs = "/v3/subscriptions"
mix = "/v3/mixes/contents?streamId=" + encodeURIComponent("feed/http://feeds.feedburner.com/TechCrunch/")
clientid = "sandbox"
clientSecret = "PI:KEY:<KEY>END_PI"
redirectURI = encodeURI("http://localhost")
params = {
headers: {
Authorization: "OAuth PI:KEY:<KEY>END_PI:feedlydev"
}
success: (data, textStatus) ->
for entry in data.items
$(".test").append "#{entry.originId}<br>"
# response_type: "code",
# client_id: clientid,
# redirect_uri: redirectURI,
# scope: "https://cloud.feedly.com/subscriptions"
}
$(window).bind "keydown", "meta+i", (e) ->
$.ajax "#{url}#{mix}", params |
[
{
"context": " option value: securityGroup.name, key: securityGroup.id, securityGroup.name\n\n\n\n if metaData.router",
"end": 3204,
"score": 0.9634225368499756,
"start": 3196,
"tag": "KEY",
"value": "Group.id"
},
{
"context": " option value: router.id, key: router.id, router.name\n\n # Network\n if option",
"end": 4196,
"score": 0.8196746110916138,
"start": 4194,
"tag": "KEY",
"value": "id"
}
] | plugins/kubernetes/app/assets/javascripts/kubernetes/components/clusters/advancedoptions.coffee | renovate-reproductions/elektra | 1 | #= require components/form_helpers
{ div,form,input,textarea,h4, h5,label,span,button,abbr,select,option,optgroup,p,i,a } = React.DOM
{ connect } = ReactRedux
{ updateAdvancedOptions, changeVersion} = kubernetes
AdvancedOptions = ({
clusterForm,
metaData,
info,
handleChange,
handleVersionChange,
edit
}) ->
onChange=(e) ->
e.preventDefault()
handleChange(e.target.name,e.target.value)
isValidVersion= (currentVersion, newVersion) ->
# if we are not in the edit case there are no rules for which versions are valid, we get the acceptable ones from info.supportedClusterVersions
return true if !edit
currentNumbers = currentVersion.split('.').map((n) -> Math.trunc(n))
newNumbers = newVersion.split('.').map((n) -> Math.trunc(n))
# ensure that major version matches and that new minor version is either equal or exactly 1 greater than current minor version
newNumbers[0] == currentNumbers[0] &&
(newNumbers[1] == currentNumbers[1] || newNumbers[1] == currentNumbers[1] + 1)
# available versions are different for edit and new case. Filter versions so that only valid versions as per the rules are left
availableVersions= (currentVersion) ->
versions = if edit then info.availableClusterVersions else info.supportedClusterVersions
versions.filter((v) -> isValidVersion(currentVersion, v))
cluster = clusterForm.data
spec = cluster.spec
options = cluster.spec.openstack
div null,
if !metaData.loaded || metaData.error?
if metaData.error? && metaData.errorCount > 20
div className: 'alert alert-warning',
"We couldn't retrieve the advanced options at this time, please try again later"
else
div className: 'u-clearfix',
div className: 'pull-right',
'Loading options '
span className: 'spinner'
else
selectedRouterIndex = ReactHelpers.findIndexInArray(metaData.routers,options.routerID, 'id')
selectedRouter = metaData.routers[selectedRouterIndex]
if selectedRouter?
selectedNetworkIndex = ReactHelpers.findIndexInArray(selectedRouter.networks,options.networkID, 'id')
selectedNetwork = selectedRouter.networks[selectedNetworkIndex]
div null,
if metaData.securityGroups?
# SecurityGroups
div null,
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "securityGroupName",
abbr title: "required", '*'
' Security Group'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "securityGroupName",
className: "select required form-control",
value: (options.securityGroupName || ''),
disabled: ('disabled' if metaData.securityGroups.length == 1),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for securityGroup in metaData.securityGroups
option value: securityGroup.name, key: securityGroup.id, securityGroup.name
if metaData.routers? # TODO: Think about how to do this in the edit case if metadata empty or incomplete but there is a value set in the cluster spec, probably just display id without name
# Router
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "routerID",
abbr title: "required", '*'
' Router'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "routerID",
className: "select required form-control",
value: (options.routerID || ''),
disabled: ('disabled' if metaData.routers.length == 1 || edit),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for router in metaData.routers
option value: router.id, key: router.id, router.name
# Network
if options.routerID? && selectedRouter? && selectedRouter.networks?
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "networkID",
abbr title: "required", '*'
' Network'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "networkID",
className: "select required form-control",
value: (options.networkID || ''),
disabled: ('disabled' if selectedRouter.networks.length == 1 || edit),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for network in selectedRouter.networks
option value: network.id, key: network.id, network.name
# Subnet
if options.lbSubnetID? && selectedNetwork? && selectedNetwork.subnets?
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "subnetID",
abbr title: "required", '*'
' Subnet'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "lbSubnetID",
className: "select required form-control",
value: (options.lbSubnetID || ''),
disabled: ('disabled' if selectedNetwork.subnets.length == 1 || edit),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for subnet in selectedNetwork.subnets
option value: subnet.id, key: subnet.id, subnet.name
div className: "form-group required string" ,
label className: "string col-sm-4 control-label", htmlFor: "securityGroupName",
' Kubernetes Version'
div className: "col-sm-8",
if !info.loaded
div className: 'u-clearfix',
div className: 'pull-right',
'Loading versions '
span className: 'spinner'
else
div className: "input-wrapper",
select
name: "version",
className: "select form-control",
value: (spec.version || cluster.status.apiserverVersion || info.defaultClusterVersion),
onChange: ((e) -> handleVersionChange(e.target.value)),
for version in availableVersions(cluster.status.apiserverVersion)
option value: version, key: version, version
AdvancedOptions = connect(
(state) ->
clusterForm: state.clusterForm
metaData: state.metaData
info: state.info
(dispatch) ->
handleChange: (name, value) -> dispatch(updateAdvancedOptions(name, value))
handleVersionChange: (value) -> dispatch(changeVersion(value))
)(AdvancedOptions)
kubernetes.AdvancedOptions = AdvancedOptions
| 163199 | #= require components/form_helpers
{ div,form,input,textarea,h4, h5,label,span,button,abbr,select,option,optgroup,p,i,a } = React.DOM
{ connect } = ReactRedux
{ updateAdvancedOptions, changeVersion} = kubernetes
AdvancedOptions = ({
clusterForm,
metaData,
info,
handleChange,
handleVersionChange,
edit
}) ->
onChange=(e) ->
e.preventDefault()
handleChange(e.target.name,e.target.value)
isValidVersion= (currentVersion, newVersion) ->
# if we are not in the edit case there are no rules for which versions are valid, we get the acceptable ones from info.supportedClusterVersions
return true if !edit
currentNumbers = currentVersion.split('.').map((n) -> Math.trunc(n))
newNumbers = newVersion.split('.').map((n) -> Math.trunc(n))
# ensure that major version matches and that new minor version is either equal or exactly 1 greater than current minor version
newNumbers[0] == currentNumbers[0] &&
(newNumbers[1] == currentNumbers[1] || newNumbers[1] == currentNumbers[1] + 1)
# available versions are different for edit and new case. Filter versions so that only valid versions as per the rules are left
availableVersions= (currentVersion) ->
versions = if edit then info.availableClusterVersions else info.supportedClusterVersions
versions.filter((v) -> isValidVersion(currentVersion, v))
cluster = clusterForm.data
spec = cluster.spec
options = cluster.spec.openstack
div null,
if !metaData.loaded || metaData.error?
if metaData.error? && metaData.errorCount > 20
div className: 'alert alert-warning',
"We couldn't retrieve the advanced options at this time, please try again later"
else
div className: 'u-clearfix',
div className: 'pull-right',
'Loading options '
span className: 'spinner'
else
selectedRouterIndex = ReactHelpers.findIndexInArray(metaData.routers,options.routerID, 'id')
selectedRouter = metaData.routers[selectedRouterIndex]
if selectedRouter?
selectedNetworkIndex = ReactHelpers.findIndexInArray(selectedRouter.networks,options.networkID, 'id')
selectedNetwork = selectedRouter.networks[selectedNetworkIndex]
div null,
if metaData.securityGroups?
# SecurityGroups
div null,
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "securityGroupName",
abbr title: "required", '*'
' Security Group'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "securityGroupName",
className: "select required form-control",
value: (options.securityGroupName || ''),
disabled: ('disabled' if metaData.securityGroups.length == 1),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for securityGroup in metaData.securityGroups
option value: securityGroup.name, key: security<KEY>, securityGroup.name
if metaData.routers? # TODO: Think about how to do this in the edit case if metadata empty or incomplete but there is a value set in the cluster spec, probably just display id without name
# Router
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "routerID",
abbr title: "required", '*'
' Router'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "routerID",
className: "select required form-control",
value: (options.routerID || ''),
disabled: ('disabled' if metaData.routers.length == 1 || edit),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for router in metaData.routers
option value: router.id, key: router.<KEY>, router.name
# Network
if options.routerID? && selectedRouter? && selectedRouter.networks?
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "networkID",
abbr title: "required", '*'
' Network'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "networkID",
className: "select required form-control",
value: (options.networkID || ''),
disabled: ('disabled' if selectedRouter.networks.length == 1 || edit),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for network in selectedRouter.networks
option value: network.id, key: network.id, network.name
# Subnet
if options.lbSubnetID? && selectedNetwork? && selectedNetwork.subnets?
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "subnetID",
abbr title: "required", '*'
' Subnet'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "lbSubnetID",
className: "select required form-control",
value: (options.lbSubnetID || ''),
disabled: ('disabled' if selectedNetwork.subnets.length == 1 || edit),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for subnet in selectedNetwork.subnets
option value: subnet.id, key: subnet.id, subnet.name
div className: "form-group required string" ,
label className: "string col-sm-4 control-label", htmlFor: "securityGroupName",
' Kubernetes Version'
div className: "col-sm-8",
if !info.loaded
div className: 'u-clearfix',
div className: 'pull-right',
'Loading versions '
span className: 'spinner'
else
div className: "input-wrapper",
select
name: "version",
className: "select form-control",
value: (spec.version || cluster.status.apiserverVersion || info.defaultClusterVersion),
onChange: ((e) -> handleVersionChange(e.target.value)),
for version in availableVersions(cluster.status.apiserverVersion)
option value: version, key: version, version
AdvancedOptions = connect(
(state) ->
clusterForm: state.clusterForm
metaData: state.metaData
info: state.info
(dispatch) ->
handleChange: (name, value) -> dispatch(updateAdvancedOptions(name, value))
handleVersionChange: (value) -> dispatch(changeVersion(value))
)(AdvancedOptions)
kubernetes.AdvancedOptions = AdvancedOptions
| true | #= require components/form_helpers
{ div,form,input,textarea,h4, h5,label,span,button,abbr,select,option,optgroup,p,i,a } = React.DOM
{ connect } = ReactRedux
{ updateAdvancedOptions, changeVersion} = kubernetes
AdvancedOptions = ({
clusterForm,
metaData,
info,
handleChange,
handleVersionChange,
edit
}) ->
onChange=(e) ->
e.preventDefault()
handleChange(e.target.name,e.target.value)
isValidVersion= (currentVersion, newVersion) ->
# if we are not in the edit case there are no rules for which versions are valid, we get the acceptable ones from info.supportedClusterVersions
return true if !edit
currentNumbers = currentVersion.split('.').map((n) -> Math.trunc(n))
newNumbers = newVersion.split('.').map((n) -> Math.trunc(n))
# ensure that major version matches and that new minor version is either equal or exactly 1 greater than current minor version
newNumbers[0] == currentNumbers[0] &&
(newNumbers[1] == currentNumbers[1] || newNumbers[1] == currentNumbers[1] + 1)
# available versions are different for edit and new case. Filter versions so that only valid versions as per the rules are left
availableVersions= (currentVersion) ->
versions = if edit then info.availableClusterVersions else info.supportedClusterVersions
versions.filter((v) -> isValidVersion(currentVersion, v))
cluster = clusterForm.data
spec = cluster.spec
options = cluster.spec.openstack
div null,
if !metaData.loaded || metaData.error?
if metaData.error? && metaData.errorCount > 20
div className: 'alert alert-warning',
"We couldn't retrieve the advanced options at this time, please try again later"
else
div className: 'u-clearfix',
div className: 'pull-right',
'Loading options '
span className: 'spinner'
else
selectedRouterIndex = ReactHelpers.findIndexInArray(metaData.routers,options.routerID, 'id')
selectedRouter = metaData.routers[selectedRouterIndex]
if selectedRouter?
selectedNetworkIndex = ReactHelpers.findIndexInArray(selectedRouter.networks,options.networkID, 'id')
selectedNetwork = selectedRouter.networks[selectedNetworkIndex]
div null,
if metaData.securityGroups?
# SecurityGroups
div null,
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "securityGroupName",
abbr title: "required", '*'
' Security Group'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "securityGroupName",
className: "select required form-control",
value: (options.securityGroupName || ''),
disabled: ('disabled' if metaData.securityGroups.length == 1),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for securityGroup in metaData.securityGroups
option value: securityGroup.name, key: securityPI:KEY:<KEY>END_PI, securityGroup.name
if metaData.routers? # TODO: Think about how to do this in the edit case if metadata empty or incomplete but there is a value set in the cluster spec, probably just display id without name
# Router
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "routerID",
abbr title: "required", '*'
' Router'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "routerID",
className: "select required form-control",
value: (options.routerID || ''),
disabled: ('disabled' if metaData.routers.length == 1 || edit),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for router in metaData.routers
option value: router.id, key: router.PI:KEY:<KEY>END_PI, router.name
# Network
if options.routerID? && selectedRouter? && selectedRouter.networks?
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "networkID",
abbr title: "required", '*'
' Network'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "networkID",
className: "select required form-control",
value: (options.networkID || ''),
disabled: ('disabled' if selectedRouter.networks.length == 1 || edit),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for network in selectedRouter.networks
option value: network.id, key: network.id, network.name
# Subnet
if options.lbSubnetID? && selectedNetwork? && selectedNetwork.subnets?
div className: "form-group required string" ,
label className: "string required col-sm-4 control-label", htmlFor: "subnetID",
abbr title: "required", '*'
' Subnet'
div className: "col-sm-8",
div className: "input-wrapper",
select
name: "lbSubnetID",
className: "select required form-control",
value: (options.lbSubnetID || ''),
disabled: ('disabled' if selectedNetwork.subnets.length == 1 || edit),
onChange: ((e) -> handleChange(e.target.name, e.target.value)),
for subnet in selectedNetwork.subnets
option value: subnet.id, key: subnet.id, subnet.name
div className: "form-group required string" ,
label className: "string col-sm-4 control-label", htmlFor: "securityGroupName",
' Kubernetes Version'
div className: "col-sm-8",
if !info.loaded
div className: 'u-clearfix',
div className: 'pull-right',
'Loading versions '
span className: 'spinner'
else
div className: "input-wrapper",
select
name: "version",
className: "select form-control",
value: (spec.version || cluster.status.apiserverVersion || info.defaultClusterVersion),
onChange: ((e) -> handleVersionChange(e.target.value)),
for version in availableVersions(cluster.status.apiserverVersion)
option value: version, key: version, version
AdvancedOptions = connect(
(state) ->
clusterForm: state.clusterForm
metaData: state.metaData
info: state.info
(dispatch) ->
handleChange: (name, value) -> dispatch(updateAdvancedOptions(name, value))
handleVersionChange: (value) -> dispatch(changeVersion(value))
)(AdvancedOptions)
kubernetes.AdvancedOptions = AdvancedOptions
|
[
{
"context": "g')\n @swig.renderFile(lpath, locals: {author: \"Jeff Escalante\"}).done((res) =>\n should.match_expected(@swi",
"end": 781,
"score": 0.9998828172683716,
"start": 767,
"tag": "NAME",
"value": "Jeff Escalante"
},
{
"context": "m()});\\n\"\n partOfClientHelpers1 = 'https://paularmstrong.github.com/swig'\n partOfClientHelpers2 = '",
"end": 2396,
"score": 0.9960619211196899,
"start": 2383,
"tag": "USERNAME",
"value": "paularmstrong"
}
] | test/swig.coffee | slang800/accord | 0 | should = require 'should'
path = require 'path'
accord = require '../'
describe 'swig', ->
before ->
@swig = accord.load('swig')
@path = path.join(__dirname, 'fixtures', 'swig')
it 'should expose name, extensions, output, and engine', ->
@swig.extensions.should.be.an.instanceOf(Array)
@swig.output.should.be.type('string')
@swig.engine.should.be.ok
@swig.name.should.be.ok
it 'should render a string', (done) ->
text = '<h1>{% if foo %}Bar{% endif %}</h1>'
@swig.render(text, locals: {foo: true}).done((res) =>
should.match_expected(@swig, res, path.join(@path, 'string.swig'), done)
)
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.swig')
@swig.renderFile(lpath, locals: {author: "Jeff Escalante"}).done((res) =>
should.match_expected(@swig, res, lpath, done)
)
it 'should compile a string', (done) ->
@swig.compile("<h1>{{ title }}</h1>").done((res) =>
should.match_expected(
@swig
res(title: 'Hello!').trim() + '\n'
path.join(@path, 'pstring.swig')
done
)
)
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.swig')
@swig.compileFile(lpath).done((res) =>
should.match_expected(
@swig
res(title: 'Hello!').trim() + '\n'
lpath
done
)
)
it 'should client-compile a string', (done) ->
text = "<h1>{% if foo %}Bar{% endif %}</h1>"
@swig.compileClient(text, foo: true).done((res) =>
should.match_expected(
@swig
res
path.join(@path, 'cstring.swig'), done
)
)
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.swig')
@swig.compileFileClient(lpath).done((res) =>
should.match_expected(@swig, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.swig')
@swig.renderFile(lpath)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.swig')
@swig.compileFileClient(lpath).done (resTemplate) =>
@swig.clientHelpers().done (resHelpers) ->
text = "window = {}; #{resHelpers};\n var tpl = (#{(String resTemplate).trim()});\n"
partOfClientHelpers1 = 'https://paularmstrong.github.com/swig'
partOfClientHelpers2 = 'var tpl ='
partOfClientHelpers3 = 'anonymous(_swig,_ctx,_filters,_utils,_fn) {'
partOfClientHelpers4 = 'var _ext = _swig.extensions,'
text.should.containEql partOfClientHelpers1
text.should.containEql partOfClientHelpers2
text.should.containEql partOfClientHelpers3
text.should.containEql partOfClientHelpers4
done()
| 61397 | should = require 'should'
path = require 'path'
accord = require '../'
describe 'swig', ->
before ->
@swig = accord.load('swig')
@path = path.join(__dirname, 'fixtures', 'swig')
it 'should expose name, extensions, output, and engine', ->
@swig.extensions.should.be.an.instanceOf(Array)
@swig.output.should.be.type('string')
@swig.engine.should.be.ok
@swig.name.should.be.ok
it 'should render a string', (done) ->
text = '<h1>{% if foo %}Bar{% endif %}</h1>'
@swig.render(text, locals: {foo: true}).done((res) =>
should.match_expected(@swig, res, path.join(@path, 'string.swig'), done)
)
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.swig')
@swig.renderFile(lpath, locals: {author: "<NAME>"}).done((res) =>
should.match_expected(@swig, res, lpath, done)
)
it 'should compile a string', (done) ->
@swig.compile("<h1>{{ title }}</h1>").done((res) =>
should.match_expected(
@swig
res(title: 'Hello!').trim() + '\n'
path.join(@path, 'pstring.swig')
done
)
)
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.swig')
@swig.compileFile(lpath).done((res) =>
should.match_expected(
@swig
res(title: 'Hello!').trim() + '\n'
lpath
done
)
)
it 'should client-compile a string', (done) ->
text = "<h1>{% if foo %}Bar{% endif %}</h1>"
@swig.compileClient(text, foo: true).done((res) =>
should.match_expected(
@swig
res
path.join(@path, 'cstring.swig'), done
)
)
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.swig')
@swig.compileFileClient(lpath).done((res) =>
should.match_expected(@swig, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.swig')
@swig.renderFile(lpath)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.swig')
@swig.compileFileClient(lpath).done (resTemplate) =>
@swig.clientHelpers().done (resHelpers) ->
text = "window = {}; #{resHelpers};\n var tpl = (#{(String resTemplate).trim()});\n"
partOfClientHelpers1 = 'https://paularmstrong.github.com/swig'
partOfClientHelpers2 = 'var tpl ='
partOfClientHelpers3 = 'anonymous(_swig,_ctx,_filters,_utils,_fn) {'
partOfClientHelpers4 = 'var _ext = _swig.extensions,'
text.should.containEql partOfClientHelpers1
text.should.containEql partOfClientHelpers2
text.should.containEql partOfClientHelpers3
text.should.containEql partOfClientHelpers4
done()
| true | should = require 'should'
path = require 'path'
accord = require '../'
describe 'swig', ->
before ->
@swig = accord.load('swig')
@path = path.join(__dirname, 'fixtures', 'swig')
it 'should expose name, extensions, output, and engine', ->
@swig.extensions.should.be.an.instanceOf(Array)
@swig.output.should.be.type('string')
@swig.engine.should.be.ok
@swig.name.should.be.ok
it 'should render a string', (done) ->
text = '<h1>{% if foo %}Bar{% endif %}</h1>'
@swig.render(text, locals: {foo: true}).done((res) =>
should.match_expected(@swig, res, path.join(@path, 'string.swig'), done)
)
it 'should render a file', (done) ->
lpath = path.join(@path, 'basic.swig')
@swig.renderFile(lpath, locals: {author: "PI:NAME:<NAME>END_PI"}).done((res) =>
should.match_expected(@swig, res, lpath, done)
)
it 'should compile a string', (done) ->
@swig.compile("<h1>{{ title }}</h1>").done((res) =>
should.match_expected(
@swig
res(title: 'Hello!').trim() + '\n'
path.join(@path, 'pstring.swig')
done
)
)
it 'should compile a file', (done) ->
lpath = path.join(@path, 'precompile.swig')
@swig.compileFile(lpath).done((res) =>
should.match_expected(
@swig
res(title: 'Hello!').trim() + '\n'
lpath
done
)
)
it 'should client-compile a string', (done) ->
text = "<h1>{% if foo %}Bar{% endif %}</h1>"
@swig.compileClient(text, foo: true).done((res) =>
should.match_expected(
@swig
res
path.join(@path, 'cstring.swig'), done
)
)
it 'should client-compile a file', (done) ->
lpath = path.join(@path, 'client.swig')
@swig.compileFileClient(lpath).done((res) =>
should.match_expected(@swig, res, lpath, done))
it 'should handle external file requests', (done) ->
lpath = path.join(@path, 'partial.swig')
@swig.renderFile(lpath)
.done((res) => should.match_expected(@swig, res, lpath, done))
it 'should render with client side helpers', (done) ->
lpath = path.join(@path, 'client-complex.swig')
@swig.compileFileClient(lpath).done (resTemplate) =>
@swig.clientHelpers().done (resHelpers) ->
text = "window = {}; #{resHelpers};\n var tpl = (#{(String resTemplate).trim()});\n"
partOfClientHelpers1 = 'https://paularmstrong.github.com/swig'
partOfClientHelpers2 = 'var tpl ='
partOfClientHelpers3 = 'anonymous(_swig,_ctx,_filters,_utils,_fn) {'
partOfClientHelpers4 = 'var _ext = _swig.extensions,'
text.should.containEql partOfClientHelpers1
text.should.containEql partOfClientHelpers2
text.should.containEql partOfClientHelpers3
text.should.containEql partOfClientHelpers4
done()
|
[
{
"context": "\nclass PingdomService\n constructor: ({ @appKey, @username, @password }) ->\n throw new Error 'Missing app",
"end": 225,
"score": 0.7833731770515442,
"start": 217,
"tag": "USERNAME",
"value": "username"
},
{
"context": "y?\n throw new Error 'Missing username' unless @username?\n throw new Error 'Missing password' unless @p",
"end": 351,
"score": 0.6714429259300232,
"start": 343,
"tag": "USERNAME",
"value": "username"
},
{
"context": " 'App-Key': @appKey\n }\n auth: {\n @username\n @password\n }\n }\n debug 'pingdo",
"end": 3945,
"score": 0.991065263748169,
"start": 3936,
"tag": "USERNAME",
"value": "@username"
},
{
"context": "\n }\n auth: {\n @username\n @password\n }\n }\n debug 'pingdom request options'",
"end": 3963,
"score": 0.3849008083343506,
"start": 3955,
"tag": "PASSWORD",
"value": "password"
}
] | src/pingdom-service.coffee | octoblu/pingdom-util | 0 | _ = require 'lodash'
async = require 'async'
request = require 'request'
moment = require 'moment'
debug = require('debug')('pingdom-util:pingdom-service')
class PingdomService
constructor: ({ @appKey, @username, @password }) ->
throw new Error 'Missing appKey' unless @appKey?
throw new Error 'Missing username' unless @username?
throw new Error 'Missing password' unless @password?
@baseUrl = 'https://api.pingdom.com/api/2.0'
configure: ({ hostname, pathname }, callback) =>
@_getCheck { hostname }, (error, check) =>
return callback error if error?
return callback null if check?
@_create { hostname, pathname }, callback
_create: ({ hostname, pathname }, callback) =>
body = {
name: hostname
host: hostname
type: 'http'
resolution: 1
url: pathname
encryption: true
contactids: '11058966,10866214'
sendtoemail: true
use_legacy_notifications: true
}
@_request { method: 'POST', uri: '/checks', body }, (error, response) =>
return callback error if error?
debug 'response', response
callback null
resultsByTag: ({ to, from }, callback) =>
@_getChecksByTag {}, (error, tags) =>
return callback error if error?
async.mapValuesLimit tags, 10, async.apply(@_getResultsForTag, { to, from }), callback
_getResultsForTag: (options, checks, key, callback) =>
debug 'get results for tag'
async.mapValuesLimit checks, 20, async.apply(@_getResultsForCheck, options), (error, allResults) =>
return callback error if error?
minutes = {}
_.each _.values(allResults), (checkResults) =>
_.each checkResults, (result) =>
time = @_getTime result
up = result.status == 'up'
minutes[time] ?= { up, count: 0 }
minutes[time].up = up if minutes[time].up
total = _.size _.values(minutes)
passes = _.size _.filter(_.values(minutes), 'up')
failures = total - passes
percent = "#{_.round((passes / total) * 100, 3)}%"
callback null, {
percent,
total,
failures,
passes,
}
_getResultsForCheck: ({ offset, to, from, previous, i=0 }, { id }, key, callback) =>
limit = 1000
debug 'get results options', { i, to, from, offset, limit }
options = _.pickBy { offset, to, from, limit }
@_request { method: 'GET', uri: "/results/#{id}", qs: options }, (error, body) =>
return callback error if error?
results = _.get body, 'results', []
count = _.size results
results = _.union results, previous if previous?
debug 'results count', count
if count < limit
return callback null, results
i += 1
count = _.size results
@_getResultsForCheck { offset: count, to, from, previous: results, i }, { id }, key, callback
_getTime: ({ time }) =>
return time - (time % (60))
_getChecksByTag: ({}, callback) =>
options = { include_tags: true }
@_request { method: 'GET', uri: '/checks', qs: options }, (error, body) =>
return callback error if error?
{ checks } = body
tags = {}
_.each checks, (check) =>
{ id } = check
_.each check.tags, ({ name }) =>
debug 'found tag', { name, id }
tags[name] ?= {}
tags[name][id] = check
debug 'found tags', tags
callback null, tags
_getCheck: ({ hostname }, callback) =>
@_request { method: 'GET', uri: '/checks' }, (error, body) =>
return callback error if error?
{ checks } = body
debug 'found checks', _.size(checks)
check = _.find checks, { hostname }
debug 'found check', check
callback null, check
_request: ({ method, uri, body, qs }, callback) =>
options = {
method
uri
@baseUrl
form: body ? true
qs
headers: {
'App-Key': @appKey
}
auth: {
@username
@password
}
}
debug 'pingdom request options', options
request options, (error, response, body) =>
debug 'pingdom response', { error, statusCode: response?.statusCode }
return callback error if error?
return callback new Error('Invalid response') if response.statusCode > 499
body = JSON.parse body
return callback new Error _.get(body, 'error.errormessage') if response.statusCode > 399
callback null, body
module.exports = PingdomService
| 202290 | _ = require 'lodash'
async = require 'async'
request = require 'request'
moment = require 'moment'
debug = require('debug')('pingdom-util:pingdom-service')
class PingdomService
constructor: ({ @appKey, @username, @password }) ->
throw new Error 'Missing appKey' unless @appKey?
throw new Error 'Missing username' unless @username?
throw new Error 'Missing password' unless @password?
@baseUrl = 'https://api.pingdom.com/api/2.0'
configure: ({ hostname, pathname }, callback) =>
@_getCheck { hostname }, (error, check) =>
return callback error if error?
return callback null if check?
@_create { hostname, pathname }, callback
_create: ({ hostname, pathname }, callback) =>
body = {
name: hostname
host: hostname
type: 'http'
resolution: 1
url: pathname
encryption: true
contactids: '11058966,10866214'
sendtoemail: true
use_legacy_notifications: true
}
@_request { method: 'POST', uri: '/checks', body }, (error, response) =>
return callback error if error?
debug 'response', response
callback null
resultsByTag: ({ to, from }, callback) =>
@_getChecksByTag {}, (error, tags) =>
return callback error if error?
async.mapValuesLimit tags, 10, async.apply(@_getResultsForTag, { to, from }), callback
_getResultsForTag: (options, checks, key, callback) =>
debug 'get results for tag'
async.mapValuesLimit checks, 20, async.apply(@_getResultsForCheck, options), (error, allResults) =>
return callback error if error?
minutes = {}
_.each _.values(allResults), (checkResults) =>
_.each checkResults, (result) =>
time = @_getTime result
up = result.status == 'up'
minutes[time] ?= { up, count: 0 }
minutes[time].up = up if minutes[time].up
total = _.size _.values(minutes)
passes = _.size _.filter(_.values(minutes), 'up')
failures = total - passes
percent = "#{_.round((passes / total) * 100, 3)}%"
callback null, {
percent,
total,
failures,
passes,
}
_getResultsForCheck: ({ offset, to, from, previous, i=0 }, { id }, key, callback) =>
limit = 1000
debug 'get results options', { i, to, from, offset, limit }
options = _.pickBy { offset, to, from, limit }
@_request { method: 'GET', uri: "/results/#{id}", qs: options }, (error, body) =>
return callback error if error?
results = _.get body, 'results', []
count = _.size results
results = _.union results, previous if previous?
debug 'results count', count
if count < limit
return callback null, results
i += 1
count = _.size results
@_getResultsForCheck { offset: count, to, from, previous: results, i }, { id }, key, callback
_getTime: ({ time }) =>
return time - (time % (60))
_getChecksByTag: ({}, callback) =>
options = { include_tags: true }
@_request { method: 'GET', uri: '/checks', qs: options }, (error, body) =>
return callback error if error?
{ checks } = body
tags = {}
_.each checks, (check) =>
{ id } = check
_.each check.tags, ({ name }) =>
debug 'found tag', { name, id }
tags[name] ?= {}
tags[name][id] = check
debug 'found tags', tags
callback null, tags
_getCheck: ({ hostname }, callback) =>
@_request { method: 'GET', uri: '/checks' }, (error, body) =>
return callback error if error?
{ checks } = body
debug 'found checks', _.size(checks)
check = _.find checks, { hostname }
debug 'found check', check
callback null, check
_request: ({ method, uri, body, qs }, callback) =>
options = {
method
uri
@baseUrl
form: body ? true
qs
headers: {
'App-Key': @appKey
}
auth: {
@username
@<PASSWORD>
}
}
debug 'pingdom request options', options
request options, (error, response, body) =>
debug 'pingdom response', { error, statusCode: response?.statusCode }
return callback error if error?
return callback new Error('Invalid response') if response.statusCode > 499
body = JSON.parse body
return callback new Error _.get(body, 'error.errormessage') if response.statusCode > 399
callback null, body
module.exports = PingdomService
| true | _ = require 'lodash'
async = require 'async'
request = require 'request'
moment = require 'moment'
debug = require('debug')('pingdom-util:pingdom-service')
class PingdomService
constructor: ({ @appKey, @username, @password }) ->
throw new Error 'Missing appKey' unless @appKey?
throw new Error 'Missing username' unless @username?
throw new Error 'Missing password' unless @password?
@baseUrl = 'https://api.pingdom.com/api/2.0'
configure: ({ hostname, pathname }, callback) =>
@_getCheck { hostname }, (error, check) =>
return callback error if error?
return callback null if check?
@_create { hostname, pathname }, callback
_create: ({ hostname, pathname }, callback) =>
body = {
name: hostname
host: hostname
type: 'http'
resolution: 1
url: pathname
encryption: true
contactids: '11058966,10866214'
sendtoemail: true
use_legacy_notifications: true
}
@_request { method: 'POST', uri: '/checks', body }, (error, response) =>
return callback error if error?
debug 'response', response
callback null
resultsByTag: ({ to, from }, callback) =>
@_getChecksByTag {}, (error, tags) =>
return callback error if error?
async.mapValuesLimit tags, 10, async.apply(@_getResultsForTag, { to, from }), callback
_getResultsForTag: (options, checks, key, callback) =>
debug 'get results for tag'
async.mapValuesLimit checks, 20, async.apply(@_getResultsForCheck, options), (error, allResults) =>
return callback error if error?
minutes = {}
_.each _.values(allResults), (checkResults) =>
_.each checkResults, (result) =>
time = @_getTime result
up = result.status == 'up'
minutes[time] ?= { up, count: 0 }
minutes[time].up = up if minutes[time].up
total = _.size _.values(minutes)
passes = _.size _.filter(_.values(minutes), 'up')
failures = total - passes
percent = "#{_.round((passes / total) * 100, 3)}%"
callback null, {
percent,
total,
failures,
passes,
}
_getResultsForCheck: ({ offset, to, from, previous, i=0 }, { id }, key, callback) =>
limit = 1000
debug 'get results options', { i, to, from, offset, limit }
options = _.pickBy { offset, to, from, limit }
@_request { method: 'GET', uri: "/results/#{id}", qs: options }, (error, body) =>
return callback error if error?
results = _.get body, 'results', []
count = _.size results
results = _.union results, previous if previous?
debug 'results count', count
if count < limit
return callback null, results
i += 1
count = _.size results
@_getResultsForCheck { offset: count, to, from, previous: results, i }, { id }, key, callback
_getTime: ({ time }) =>
return time - (time % (60))
_getChecksByTag: ({}, callback) =>
options = { include_tags: true }
@_request { method: 'GET', uri: '/checks', qs: options }, (error, body) =>
return callback error if error?
{ checks } = body
tags = {}
_.each checks, (check) =>
{ id } = check
_.each check.tags, ({ name }) =>
debug 'found tag', { name, id }
tags[name] ?= {}
tags[name][id] = check
debug 'found tags', tags
callback null, tags
_getCheck: ({ hostname }, callback) =>
@_request { method: 'GET', uri: '/checks' }, (error, body) =>
return callback error if error?
{ checks } = body
debug 'found checks', _.size(checks)
check = _.find checks, { hostname }
debug 'found check', check
callback null, check
_request: ({ method, uri, body, qs }, callback) =>
options = {
method
uri
@baseUrl
form: body ? true
qs
headers: {
'App-Key': @appKey
}
auth: {
@username
@PI:PASSWORD:<PASSWORD>END_PI
}
}
debug 'pingdom request options', options
request options, (error, response, body) =>
debug 'pingdom response', { error, statusCode: response?.statusCode }
return callback error if error?
return callback new Error('Invalid response') if response.statusCode > 499
body = JSON.parse body
return callback new Error _.get(body, 'error.errormessage') if response.statusCode > 399
callback null, body
module.exports = PingdomService
|
[
{
"context": "= node.getAttribute 'data-view-name'\n viewKey = \"#{data.yaml.type}/#{name}\"\n descriptor = \"#{data._id}/#{name}\"\n else\n ",
"end": 63681,
"score": 0.994579017162323,
"start": 63654,
"tag": "KEY",
"value": "\"#{data.yaml.type}/#{name}\""
},
{
"context": "= \"#{data._id}/#{name}\"\n else\n viewKey = data.yaml.type\n descriptor = data._id\n if root.viewTypeData[",
"end": 63757,
"score": 0.9585031270980835,
"start": 63748,
"tag": "KEY",
"value": "yaml.type"
}
] | METEOR-OLD/client/28-fancyOrg.coffee | zot/Leisure | 58 | {
Node,
resolve,
lazy,
defaultEnv,
} = root = module.exports = require '15-base'
rz = resolve
lz = lazy
{
TAB,
ENTER,
BS,
DEL,
} = require '21-browserSupport'
{
getType,
define,
makeSyncMonad,
} = require '16-ast'
{
runMonad,
isMonad,
escapePresentationHtml,
unescapePresentationHtml,
} = require '17-runtime'
{
parseOrgMode,
Headline,
headlineRE,
HL_TAGS,
Fragment,
Meat,
Keyword,
keywordRE,
KW_BOILERPLATE,
KW_NAME,
KW_INFO,
Source,
srcStartRE,
HTML,
Results,
AttrHtml,
resultsRE,
ListItem,
SimpleMarkup,
Link,
Drawer,
drawerRE,
parseTags,
matchLine,
} = require '11-org'
yaml = root.yaml
{
getCodeItems,
isCodeBlock,
isYaml,
lineCodeBlockType,
} = require '12-docOrg'
{
isCollapsed,
selectRange,
} = window.DOMCursor
{
handleDelete,
handleInsert,
domCursorForCaret,
textPositionForDomCursor,
SelectionDescriptor,
checkLast,
changeSavedSelectionOffset,
currentSelectionDescriptor,
parentForNode,
savePosition,
findOrIs,
orgNotebook,
parseOrgMode,
orgAttrs,
content,
contentSpan,
checkStart,
checkEnterReparse,
checkExtraNewline,
followingSpan,
currentLine,
checkSourceMod,
nextOrgId,
modifyingKey,
handleKeyup,
backspace,
getOrgParent,
getOrgType,
executeDef,
swapMarkup,
modifiers,
keyFuncs,
defaultBindings,
addKeyPress,
adjustSelection,
findKeyBinding,
setCurKeyBinding,
installEnvLang,
propsFor,
escapeAttr,
splitLines,
orgSrcAttrs,
baseEnv,
getNodeLang,
getNodeSource,
resultsType,
isDef,
getTextPosition,
findDomPosition,
nativeRange,
nodeBefore,
textNodeAfter,
textNodeBefore,
visibleTextNodeAfter,
getOrgText,
nonOrg,
errorDiv,
blockIdsForSelection,
PAGEUP,
PAGEDOWN,
HOME,
END,
markupData,
orgForNode,
plainOrg,
blockElementForNode,
executeSource,
redrawDoc,
isNode,
} = require '24-orgSupport'
{
redrawAllIssues,
createComment,
} = require '26-storage'
{
dataTypeIds,
edited,
pretty,
setData,
getBlock,
getBlockNamed,
getDataNamed,
setDataNamed,
addChangeContextWhile,
getSourceAttribute,
setSourceAttribute,
codeString,
controllerDescriptorIds,
codeContexts,
indexedCursor,
getRenderCount,
incRenderCount,
viewTypeData,
viewIdTypes,
mapDocumentBlocks,
importedDocs,
isCurrent,
} = require '23-collaborate'
{
nodeText,
createTemplateRenderer,
escapeHtml,
getDeepestActiveElement,
setShadowHtml,
clearView,
viewMarkup,
appendAndActivate,
viewRoots,
} = Templating # require '27-templating'
_ = require 'lodash.min'
fancyOrg = null
slideMode = false
lastOrgOffset = -1
curPos = -1
emptyPresenter =
hide: ->
isRelated: -> false
presenter = emptyPresenter
class FancySelectionDescriptor
constructor: (parent)->
sel = getSelection()
el = getDeepestActiveElement()
@parent = $(parent)[0] ? (slideParent sel.focusNode)
@focusNode = sel.focusNode
if inputNum = el?.getAttribute "data-input-number"
@linkParent = $(el).closest("[data-view-link]").attr("data-view-id")
@inputNum = inputNum
@inputSel = [el.selectionStart, el.selectionEnd]
@x = window.scrollX
@y = window.scrollY
if sel.type != 'None'
startNode = sel.getRangeAt(0).startContainer
[start, end, offset, note] = getDocRange()
@toString = -> "Selection(doc: #{start}, #{end})"
@restore = (delta, doc)->
if @linkParent && (input = $("[data-view-id='#{@linkParent}']").find("[data-input-number='#{@inputNum}']")).length > 0
input[0].focus()
[input[0].selectionStart, input[0].selectionEnd] = @inputSel
else
sel = getSelection()
if (sel.type != 'None' && sel.getRangeAt(0))?.startContainer != startNode
restoreDocRange doc, [start + delta, end + delta, offset, note]
window.scrollTo @x, @y
#[id, start, end, left, top] = pos = getSlidePosition sel.focusNode
#if id
# @toString = -> "Selection(doc: #{id}, start: #{start}, end: #{end}, left: #{left}, top: #{top})"
# @restore = -> setSlidePosition pos
#console.log "NEW SELECTION: #{this}"
restore: ->
toString: -> "Selection(none)"
isParentSelectionOf = (parent, child)-> parent?.parent?.contains child.parent
restoreStack = []
fancySaveSelection = root.saveSelection
root.restorePosition = restorePosition = (parent, block)->
savePosition fancySaveSelection, block
getSlidePosition = (node)->
if block = blockElementForNode node
{top, left} = block.getBoundingClientRect()
r = getSelection().getRangeAt 0
start = getTextPosition block, r.startContainer, r.startOffset
end = getTextPosition block, r.endContainer, r.endOffset
[block.id, start, end, left, top]
else []
setSlidePosition = ([id, start, end, left, top])->
block = $("##{id}")[0]
{curTop, curLeft} = block.getBoundingClientRect()
window.scrollBy curLeft - left, curTop - top
r1 = findDomPosition block, start, true
r2 = findDomPosition block, end, true
s = getSelection()
r = document.createRange()
r.startContainer = r1[0]
r.startOffset = r1[1]
r.endContainer = r2[0]
r.endOffset = r2[1]
selectRange r
# get a logical document range with an optional note
# [startPos, endPos, scrollOffset, noteId]
# if note is null, the positions are in the main doc
# otherwise, note is the id of a note
#
# Assumes the document has only two levels -- the main doc and notes
getDocRange = ->
s = getSelection()
r = s.getRangeAt 0
offset = getDocumentOffset r
if s.rangeCount == 1 && r.collapsed && r.startContainer.nodeType == 1 && shadow = r.startContainer.children[r.startOffset]?.shadowRoot
s = shadow.getSelection()
note = $(s.focusNode).closest('[data-note-origin]')?[0]
if note then [getTextPosition(note, s.anchorNode, s.anchorOffset), getTextPosition(note, s.extentNode, s.extentOffset), window.pageYOffset - offset, note.id]
else [null, null, null]
else
doc = topNode s.focusNode
[getTextPosition(doc, r.startContainer, r.startOffset), getTextPosition(doc, r.endContainer, r.endOffset), window.pageYOffset - offset]
restoreDocRange = (parent, [start, end, offset, noteId])->
if noteId
noteNode = $("[data-org-note-instances~='#{noteId}']")[0]
parent = $(noteNode).shadow().find("##{noteId}")[0]
[startContainer, startOffset] = findDomPosition parent, start, true
[endContainer, endOffset] = findDomPosition parent, Math.min(end, getOrgText(parent).length - 1), true
r = document.createRange()
r.setStart startContainer, startOffset
r.setEnd endContainer, endOffset
if noteId
offR = document.createRange()
offR.selectNode noteNode
window.scrollTo window.pageXOffset, offset + getDocumentOffset(offR)
s = noteNode.shadowRoot.getSelection()
else
window.scrollTo window.pageXOffset, offset + getDocumentOffset(r)
s = getSelection()
selectRange r
getDocumentOffset = (r)->
parent = parentForNode r.startContainer
c = (if r.startOffset == 0 then (textNodeBefore parent, r.startContainer) ? r.startContainer else r.startContainer)
while isCollapsed c
c = textNodeBefore parent, c
documentTop c
rootNode = (node)->
while node.parentNode
node = node.parentNode
node
topNode = (node)->
top = node
while node
if node.hasAttribute? 'data-org-headline' then top = node
node = node.parentNode
return top
replaceUnrelatedPresenter = (target, newPres)->
if result = !presenter || !presenter.isRelated target
replacePresenter newPres
result
replaceRelatedPresenter = (target, newPres)->
if result = (presenter && presenter.isRelated target)
replacePresenter newPres
result
replacePresenter = (pres)->
presenter?.hide()
presenter = pres || emptyPresenter
markupOrg = (text)->
[node, result] = markupOrgWithNode text
result
markupOrgWithNode = (text, note, replace)->
nodes = {}
if typeof text == 'string'
# ensure trailing newline -- contenteditable doesn't like it, otherwise
if text[text.length - 1] != '\n' then text = text + '\n'
org = parseOrgMode text
if isNode text then org = text
if org
[org, markupNewNode org, null, null, note, replace]
else
console.log "Attempt to display uknown object type: ", text
throw new Error "Attempt to display unknown type of object: #{text}"
markupNewNode = (org, middleOfLine, delay, note, replace)->
lastOrgOffset = -1
markupNode org, middleOfLine, delay, note, replace
getCodeAttribute = (node, attr)->
if (top = $(node).closest('[data-shared]'))[0]
getSourceAttribute top.find('[data-source-lead]').text(), attr
setCodeAttributes = (node, attrs...)->
if (top = $(node).closest('[data-shared]'))[0]
lead = top.find('[data-source-lead]')
oldTxt = txt = lead.text()
for [k, v] in L(attrs).chunk(2).toArray()
txt = setSourceAttribute txt, k, v
if txt != oldTxt
lead.text escapeHtml txt
edited top[0], true
clearCodeAttributes = (node, attrs...)->
if (top = $(node).closest('[data-shared]'))[0]
lead = top.find('[data-source-lead]')
oldTxt = txt = lead.text()
for attr in attrs
txt = setSourceAttribute txt, attr
if txt != oldTxt
lead.text escapeHtml txt
edited top[0], true
markupNode = (org, middleOfLine, delay, note, replace, inFragment)->
if (org.shared && isHidden org.nodeId) || org.offset <= lastOrgOffset then ''
else if org instanceof Results
pos = org.contentPos
text = org.text.substring pos
"<span #{orgAttrs org}><span data-org-type='text'>#{escapeHtml org.text.substring(0, pos)}</span>#{contentSpan text}"
else if org instanceof Fragment then markupFragment org, delay, note
else if org instanceof HTML then markupHtml org
else if org instanceof AttrHtml then markupAttr org
else if org instanceof Keyword
if org.name.match /^name$/i
intertext = ''
name = org
src = org.next
while src instanceof Meat && !(src instanceof Source)
intertext += src.text
src = src.next
if src instanceof Source then markupSource src, name, intertext, delay, inFragment
else defaultMarkup org
else if org instanceof Source then markupSource org, null, null, delay, inFragment
else defaultMarkup org
else if org instanceof Headline then markupHeadline org, delay, note, replace
else if org instanceof Drawer && org.name.toLowerCase() == 'properties' then markupProperties org, delay
else if org instanceof Drawer && org.name.toLowerCase() == 'data' then markupData org
else if org instanceof ListItem then markupListItem org, delay
else if org instanceof SimpleMarkup then markupSimple org
else if org instanceof Link then markupLink org
else if content(org.text).length then defaultMarkup org
else
tag = (if middleOfLine then 'span' else 'div')
"<#{tag} #{orgAttrs org}>#{meatText org.text}</#{tag}>"
meatText = (meat)->
result = if meat.match /^\n/
meat = meat.substring 1
"<span class='meat-break'>\n</span>"
else ""
paras = escapeHtml(meat).split /\n\n/
last = paras.pop()
result += _(paras).map((i)-> "<span class='meat-text#{checkBlankMeat i}'>#{i}\n</span>").join "<span class='meat-break'>\n</span>"
if result then result += "<span class='meat-break'>\n</span>"
if last
if last[last.length - 1] == '\n'
end = '\n'
last = last.substring 0, last.length - 1
if last then result += "<span class='meat-text#{checkBlankMeat last}'>#{last}</span>"
if end then result += "<span class='hidden'>\n</span><span data-nonorg contenteditable='false'>\n</span>"
result
checkBlankMeat = (hunk)-> if hunk in ['', '\n'] then " blank" else ""
isLeisure = (org)-> org instanceof Source && org.getLanguage().toLowerCase() == 'leisure'
isExecutable = (org)->
org instanceof Source && (org.getLanguage() in ['javascript', 'leisure'])
markupFragment = (org, delay, note)->
{first, name, source, last} = getCodeItems org.children[0]
if source
if first == name then first = first.next
if first in [org.children[0], org.children[1]] && !last.next
prelude = ''
while first != source
prelude += first.allText()
first = first.next
return "<span #{orgAttrs org}#{blockForLeisure source}>#{markupSource source, name, prelude, delay, true}</span>"
"<span #{orgAttrs org}>#{(markupNode child, false, delay, note, false, true for child in org.children).join ''}</span>"
blockForLeisure = (source)->
if source.getLanguage() == 'leisure' then " class='inline'" else ''
markupProperties = (org, delay)->"<span data-note-location class='hidden'>#{escapeHtml org.text}</span>"
lastAttr = null
markupAttr = (org)->
lastAttr = org
"<span class='hidden'>#{org.text}</span>"
markupLink = (org)->
if leisureMatch = org.isLeisure()
viewName = if leisureMatch[2] then " data-view-name='#{leisureMatch[2]}'" else ''
"<span data-view-link='#{leisureMatch[1]}'#{viewName}><span class='hidden'>#{org.allText()}</span></span>"
else if org.isImage()
title = (if desc = org.descriptionText() then " title='#{escapeAttr desc}'" else "")
"<span><img src='#{escapeAttr org.path}'#{title}><span class='hidden'>#{escapeHtml org.allText()}</span></span>"
else
guts = ''
for c in org.children
guts += markupNode c, true
if !guts then "<span class='hidden'>[[</span><a onclick='Leisure.followLink(event)' href='#{org.path}'>#{org.path}</a><span class='hidden'>]]</span>"
else "<span class='hidden'>[[#{org.path}][</span><a onclick='Leisure.followLink(event)' href='#{org.path}'>#{guts}</a><span class='hidden'>]]</span>"
root.followLink = (e)->
t = e.target
while t && t.nodeName != 'A'
t = t.parentNode
if t then window.open t.href, "links"
markupSimple = (org)->
guts = ''
for c in org.children
guts += markupNode c, true
text = switch org.markupType
when 'bold' then "<b>#{guts}</b>"
when 'italic' then "<i>#{guts}</i>"
when 'underline' then "<span style='text-decoration: underline'>#{guts}</span>"
when 'strikethrough' then "<span style='text-decoration: line-through'>#{guts}</span>"
when 'code' then "<code>#{guts}</code>"
when 'verbatim' then "<code>#{guts}</code>"
"<span class='hidden'>#{org.text[0]}</span>#{text}<span class='hidden'>#{org.text[0]}</span>"
hlStars = /^\*+ */
markupHeadline = (org, delay, note, replace)->
match = org.text.match headlineRE
start = "#{org.text.substring 0, org.text.length - (match?[HL_TAGS] ? '').length}".trim()
if org.text[org.text.length - 1] == '\n'
tags = escapeHtml org.text.substring start.length, org.text.length - 1
else
tags = escapeHtml org.text.substring start.length - 1
if starsM = start.match hlStars
stars = start.substring 0, starsM[0].length
start = start.substring stars.length
else stars = ''
properties = []
for k, v of org.properties
properties.push "#{k} = #{v}"
properties = if properties.length then "<span class='headline-properties' title='#{escapeAttr properties.join '<br>'}' data-nonorg='true'><i class='fa fa-wrench'></i></span>" else ''
optImport = if org.properties.import
imp = if root.currentDocument.demo then "tmp/#{importedDocs['demo/' + org.properties.import]._name}"
else new URI("x://h/#{root.currentDocument.leisure.name}", org.properties.import).path.substring 1
"<div class='import' data-nonorg='true' contenteditable='false'><span><a href='#load=/#{imp}' target='_blank'>#{org.properties.import}</a></span></div>"
else ''
editMode = if org.level == 1 then " data-edit-mode='fancy'" else ""
if org.level == 1 && !note && !org.properties?.note
if org.text.trim() != ''
"#{startNewSlide replace, org}<div #{orgAttrs org}#{editMode} data-org-headline-text='#{escapeAttr start}'#{noteAttrs org}><span class='maincontent'><span class='hidden'>#{stars}</span><span data-org-type='text'><div data-org-type='headline-content'><div class='textborder' contenteditable='false'></div><div class='headline-content'>#{escapeHtml start}<span class='tags'>#{properties}#{tags}</span></div></div><span class='meat-break'>\n</span></span>#{optImport}#{markupGuts org, checkStart start, org.text}</span></div>"
else "#{startNewSlide()}<div #{orgAttrs org}#{editMode}><span data-org-type='text'><span data-org-type='headline-content'><span class='hidden'>#{org.text}</span></span></span>#{optImport}#{markupGuts org, checkStart start, org.text}</div>"
else
slide = if org.text.trim() != ''
"<div #{orgAttrs org}#{editMode} data-org-headline-text='#{escapeAttr start}'#{noteAttrs org}><span class='hidden'>#{stars}</span><span data-org-type='text'><div data-org-type='headline-content'><div class='headline-content'>#{escapeHtml start}</div><span class='tags'>#{properties}#{tags}</span>\n</div></span>#{markupGuts org, checkStart start, org.text}</div>"
else "<div #{orgAttrs org}#{editMode}><span data-org-type='text'><span data-org-type='headline-content'><span class='hidden'>#{org.text}</span></span></span>#{markupGuts org, checkStart start, org.text}</div>"
floatize org, slide
#slide
#noteAttrs = (org)->
# if org.properties?.notes then "data-org-notes='#{org.properties.notes}'"
# else ''
nextNoteId = 0
noteAttrs = (org)->
if org.level != 1 then ''
else if org.properties?.note == 'sidebar' then " data-org-note='sidebar' data-org-noteid='#{nextNoteId++}'"
else if org.properties?.note?.match /^float / then " data-org-note='float' data-org-noteid='#{nextNoteId++}' data-org-floatval='#{org.properties.note}'"
else " data-org-note='main'"
floatize = (org, slide)->
if org.properties?.note?.match /^float /
"<div data-draggable data-float-holder='#{nextNoteId - 1}'><div data-resizable style='width: 600px; height: 600px; background: lightgray;'><h2 class='note_drag_handle' contenteditable='false'>YOUR NOTE</h2><div contenteditable='true'>#{slide}</div></div></div>"
else slide
updateNoteProperties = (span, index, txt) ->
old = getOrgText span
lines = old.split /\n/
s = lines[1].split /\s*,\s*/
if index != 0 then s[index] = txt else s[index] = ":notes: " + txt
lines[1] = s.join ', '
span.textContent = lines.join '\n'
saveNoteLocation = (target) ->
drag = target.closest("[data-draggable]")
resize = $(drag.children()[0])
orig_id = drag.attr 'data-note-origin'
orig = $("#" + orig_id)
span = orig.find("[data-note-location]")[0]
if span
index = drag.attr 'data-note-index'
#console.log "span: " + span + " => " + index
updateNoteProperties span, index, "float #{drag.css('top')} #{drag.css('left')} #{resize.width()}px #{resize.height()}px"
createNotes = (node)->
$(node).addClass 'herpderp'
for noteSpec in node.getAttribute('data-org-notes').split /\s*,\s*/
#console.log "NOTE FOR #{node.id}: #{noteSpec}"
noteId = "note-#{nextNoteId++}"
[org, html] = markupOrgWithNode getOrgText(node), true
newNote = $("<div class='sidebar_notes' data-note-origin='#{node.id}' id='#{noteId}' contenteditable='true'>#{html}</div>")[0]
switch (splitSpec = noteSpec.split(/\s+/))[0]
when 'sidebar'
if dest = $("[data-org-headline-text='#{splitSpec[1]}'] div.sidebar")[0]
if !dest.shadowRoot then setShadowHtml dest, "<div contenteditable='true'></div>"
$(dest).shadow().append newNote
when 'float'
parent = topNode node
dest = $(document.body).find('[data-org-floats]')[0]
if !dest then $(document.body).prepend dest = $("<div data-org-floats='true' contenteditable='true'></div>")[0]
inside = $('<div data-resizable style="width: 600px; height: 600px; background: black;"><h2 class="note_drag_handle" contenteditable="false">YOUR NOTE</h2><div></div></div>')
holder = $("<div data-draggable data-note-origin='#{node.id}' data-note-index='#{nextNoteId - 1}'></div>")
#console.log node
holder.append inside
dest.appendChild holder[0]
holder.draggable({handle: 'h2'})
inside.resizable()
holder.bind 'dragstop', (event) ->
saveNoteLocation $(event.target)
inside.bind 'resizestop', ->
saveNoteLocation $(event.target)
child = inside[0].children[1]
setShadowHtml child, "<div contenteditable='true' class='float_note'></div>"
$(child).shadow().append newNote
dest = child
orig = $("#" + node.id)[0]
[skip, top, left, width, height] = noteSpec.split /\s+/
holder.css({top: top, left: left})
inside.css({width: width, height: height})
saveNoteLocation holder
else continue
if dest
addWord dest, 'data-org-note-content', node.id
addWord dest, 'data-org-note-instances', noteId
fixupHtml newNote
addWord = (node, attr, value)->
vals = (node.getAttribute(attr) ? '').split ' '
vals = vals.filter (el) ->
el.length != 0
if !(value in vals) then vals.push value
node.setAttribute attr, vals.join ' '
editing = false
editedNote = (mainId, editedId)-> ->
if !editing
setTimeout (->
restorePosition $("##{editedId}")[0], ->
targets = $("##{mainId}")
main = targets[0]
for node in $("[data-org-note-content~='#{mainId}']")
targets = targets.add($(node).shadow().find "[data-note-origin='#{mainId}']")
origin = targets.filter "##{editedId}"
editing = true
try
t = targets.not("##{editedId}")
t.html origin.html()
for node in t
fixupHtml node, node != main
finally
setTimeout (-> editing = false), 1), 1
markupHtml = (org)->
if v = org.attributes()?.view
pre = org.text.substring 0, org.contentPos
post = org.text.substring org.contentPos + org.contentLength
"<span #{orgAttrs org} data-html-view='#{v}'><span contenteditable='false' data-org-html='true'></span><span class='hidden'>#{escapeHtml pre}</span><span class='hidden' data-content>#{escapeHtml org.content()}</span><span class='hidden'>#{escapeHtml post}</span><span></span></span>"
else
"<span #{orgAttrs org}><span contenteditable='false' data-nonorg='true' data-org-html='true'>#{nodeText(org.content())}</span><span class='hidden'>#{escapeHtml org.text}</span><span></span></span>"
chooseSourceMarkup = (org)->
if isYaml org then markupYaml
else if isExecutable org then markupLeisure
#else if org.lead()?.trim().toLowerCase() == 'html' then (org)-> defaultMarkup org, 'div', 'class', 'default-lang', 'data-lang', org.lead()?.trim()
else if org.info.match /^ *css\b/i then markupCSS
else markupCode
markupSource = (org, name, doctext, delay, inFragment)->
(chooseSourceMarkup org) org, name, doctext, delay, inFragment
findLinks = (name)->
if m = name.match /^([^/]*)\/(.*)$/ then $("[data-view-link='#{m[1]}'][data-view-name='#{m[2]}']") else $("[data-view-link='#{name}']")
findViews = (name)-> findLinks(name)
getSourceSegments = (name, org)->
{first, name, source, results, expected, last} = getCodeItems(name || org)
pos = source.contentPos
pre = ''
while first != source
pre += first.allText()
first = first.next
pre += source.text.substring 0, pos
post = ''
cur = source.next
while cur != last.next
post += cur.allText()
cur = cur.next
post = source.text.substring(pos + source.content.length) + post
[pre, source.content, post]
markupYaml = (org, name, doctext, delay, inFragment)->
[pre, src, post] = getSourceSegments name, org
{name, source, results, expected, last} = getCodeItems(name || org)
lastOrgOffset = last.offset
shared = (if org.shared then org else org.fragment)
yamlAttr = "data-lang='yaml'"
if shared
data = getBlock shared.nodeId
type = data.yaml?.type
if type
err = if !viewMarkup[type] then errorDiv "No value view type for data nodeId: #{shared.nodeId}" else ''
yamlAttr += " data-yaml-type='#{type}'"
err = ''
if name
n = escapeAttr name.info.trim()
yamlAttr += " data-org-codeblock='#{n}' data-yaml-name='#{n}'"
"<div #{orgAttrs source}#{yamlAttr}>#{err}<span class='Xhidden codeHeading'>#{escapeHtml pre}</span><span data-org-src data-contain>#{Highlighting.highlight 'yaml', source.content}</span><span class='Xhidden codeHeading'>#{escapeHtml post}</span></div>"
markupCode = (org, name, doctext, delay, inFragment)->
[pre, src, post] = getSourceSegments name, org
{name, source, results, expected, last} = getCodeItems(name || org)
lastOrgOffset = last.offset
lang = org.getLanguage() || ''
if name
n = escapeAttr name.info.trim()
addAttr = " data-org-codeblock='#{n}'"
else addAttr = ''
if (l = source.getLanguage()) #&& !inFragment
addAttr += " data-lang='#{l}' id='#{org.nodeId}'"
"<div class='default-lang' data-#{orgAttrs source}#{addAttr}><span class='Xhidden codeHeading'>#{escapeHtml pre}</span><span data-org-src data-contain>#{Highlighting.highlight lang, source.content}</span><span class='Xhidden codeHeading'>#{escapeHtml post}</span></div>"
markupCSS = (org, name, doctext, delay, inFragment)->
[pre, src, post] = getSourceSegments name, org
{name, source, results, expected, last} = getCodeItems(name || org)
lastOrgOffset = last.offset
lang = org.getLanguage() || ''
if name
n = escapeAttr name.info.trim()
addAttr = " data-org-codeblock='#{n}'"
styleName = " name='#{escapeAttr n}'"
else
addAttr = ''
styleName = ''
if (l = source.getLanguage()) #&& !inFragment
addAttr += " data-lang='#{l}' id='#{org.nodeId}'"
cssBlock = nonOrg("<style name='css'#{styleName}>#{src}</style>")[0].outerHTML
"<div class='default-lang' data-#{orgAttrs source}#{addAttr}><span class='Xhidden codeHeading'>#{escapeHtml pre}</span><span data-org-src data-contain>#{Highlighting.highlight lang, source.content}</span><span class='Xhidden codeHeading'>#{escapeHtml post}</span>#{cssBlock}</div>"
dragging = false
butLast = (str)-> str.substring 0, str.length - 1
markupLeisure = (org, name, doctext, delay, inFragment)->
attr = org.attributes()
lang = org.getLanguage() || ''
lastOrgOffset = org.offset
startHtml = "<div class='codeblock' contenteditable='false' data-lang='#{lang}' #{orgAttrs org}"
parts = parseSrcBlock org
if name then startHtml += " data-org-codeblock='#{escapeAttr name.info.trim()}'"
if view = attr?.view
return "#{startHtml} data-code-view='#{escapeAttr view.trim()}'>#{simpleLeisure org, doctext, attr, parts}</div>"
startHtml += "><div class='codeborder'></div>"
{lead, srcContent, trail, resText, intertext, resOrg} = parts
if name
codeName = "<div class='codename' contenteditable='true'><span class='hidden'>#{nameBoilerplate name}</span><div class='name'>#{escapeHtml butLast name.info}</div><span class='meat-break'>\n</span>#{meatText doctext}</div>"
else codeName = "<div class='codename' contenteditable='true'></div>"
wrapper = "<table class='codewrapper'><tr><td class='code-buttons'>"
if testCaseButton = toTestCaseButton org
wrapper += "<div>#{testCaseButton}</div>"
wrapper += "<div><button class='results-indicator' onclick='Leisure.executeCode(event)'><i class='fa fa-gear'></i><div></div></button></div>"
wrapper += "<div><button class='dyntoggle-button' onclick='Leisure.toggleDynamic(event)'><span class='dyntoggle'><i class='fa fa-link'></i><i class='fa fa-unlink'></i></span></button></div>"
if name then wrapper += "<div>#{commentButton name.info.trim()}</div>"
wrapper += "</td><td class='code-content'>"
wrapper += codeName
wrapper += "<div class='hidden' data-source-lead>#{escapeHtml lead}</div>"
wrapper += "<div #{orgSrcAttrs org} data-contain contenteditable='true'>#{escapeHtml srcContent}</div><span class='hidden' data-org-type='boundary'>#{escapeHtml trail}</span>"
wrapper += "<span class='hidden'>#{intertext}</span>" + htmlForResults resText, resOrg
wrapper += "</td></tr></table>"
top = name ? org
fluff = if top.prev instanceof Source || top.prev instanceof Results then "<div class='fluff' data-newline></div>" else ''
result = startHtml + wrapper + (if name then "</div>#{commentBlock name.info.trim()}" else "</div>")
inner = fluff + result
if view then inner += "</span>"
"<div></div>" + (if inFragment then inner
else '<div>' + inner + '</div>') + "<div></div>"
nameBoilerplate = (name)->
if nameM = name.text.match keywordRE then escapeHtml nameM[KW_BOILERPLATE]
parseSrcBlock = (org, name)->
result =
intertext: ''
lead: org.text.substring 0, org.contentPos
trail: org.text.substring org.contentPos + org.content.length
srcContent: org.content
if name
result.nameBoilerplate = nameBoilerplate name
result.name = name.info
node = org.next
intertext = ''
while node
if node instanceof Results
lastOrgOffset = node.offset
result.resBoilerplate = node.text.substring 0, node.contentPos
result.resText = node.text.substring node.contentPos
result.resOrg = node
result.intertext = intertext
break
else if node instanceof Drawer
if node.name.toLowerCase() == 'expected'
lastOrgOffset = node.offset
result.intertext = intertext + escapeHtml node.text
else break
else if node instanceof Headline || node instanceof Keyword
break
else intertext += escapeHtml node.text
node = node.next
result
editable = 'contenteditable="true"'
simpleLeisure = (org, doctext, attr, parts)->
html = sourceSpan 'name-boilerplate', parts.nameBoilerplate
html += sourceSpan 'name', parts.name
html += sourceSpan 'doctext', doctext, meatText
html += sourceSpan 'lead', parts.lead
html += "<div #{orgSrcAttrs org} data-contain data-source-content>#{escapeHtml parts.srcContent}</div>"
html += sourceSpan 'trail', parts.trail
html += sourceSpan 'intertext', parts.intertext
if parts.resText? then html += htmlForViewResults parts.resText, parts.resBoilerplate
html
sourceSpan = (type, content, process, attrs)->
if content
"<span#{if attrs then ' ' + attrs else ''} data-source-#{type}>#{(process ? escapeHtml) content}</span>"
else ''
updateChannels = (org)-> org instanceof Source && (org.info.match /:update *([^:]*)/)?[1]
testResult = (expected, actual)->
if actual == '' then 'unknown'
else if expected == actual then 'pass'
else 'fail'
root.toggleTestCase = (evt)->
node = codeBlockForNode evt.target
selectPrevious node
if node then replaceCodeBlock node, changeResultType getOrgText(node), (if node.getAttribute('data-org-results') == 'autotest' then 'dynamic' else 'static')
selectPrevious = (node)->
top = topNode node
pos = getTextPosition top, node, 0
r = nativeRange findDomPosition top, Math.max 0, pos - 1
selectRange r
replaceCodeBlock = (node, text)->
newNode = null
restorePosition null, ->
org = parseOrgMode text, 0, true
org.nodeId = $(node)[0].id
org.shared = 'code'
newNode = $(markupNewNode org, false, true)[0]
$(node).replaceWith(newNode)
edited newNode
fixupHtml blockElementForNode newNode
setTimeout (=>
nn = $(newNode)
(if nn.is('.codeblock') then nn else nn.find('.codeblock')).addClass 'ready'
for n in $(newNode).find('[data-org-comments]')
setShadowHtml n.firstElementChild, "<div class='#{theme ? ''}'>" + newCommentBox n.getAttribute('data-org-comments') + '</div>', codeBlockForNode(n.previousElementSibling).id
redrawAllIssues()), 1
newNode
markupListItem = (org, delay)->
if org.level == 0
start = !org.getPreviousListItem()
end = !org.getNextListItem()
else
start = (parent = org.getParent()) && parent == org.getPreviousListItem()
next = org.getNextListItem()
end = !next || next.level < org.level
"""#{if start then '<ul>' else ''}<li #{orgAttrs org} data-org-listlevel='#{
org.level
}'#{
if org.checked? then ' data-org-checked="' + org.checked + '"' else ''
}><span class='hidden'>#{
escapeHtml org.text.substring 0, org.contentOffset
}</span><span>#{markupListContents org.children}</span></li>#{
eatListItem org
}#{if end then '</ul>' else ''}"""
markupListContents = (children)-> (markupNode child, true for child in children).join ''
legalListContent = (org)->
org && (!(org instanceof Meat) || !org.inNewMeat()) && !(org instanceof Headline || org instanceof ListItem)
eatListItem = (org)->
item = org
result = ''
while legalListContent org = org.next
result += markupNode org
lastOrgOffset = Math.max(lastOrgOffset, org.offset)
result
unwrap = (node)->
parent = node.parentNode
if parent
while node.firstChild?
parent.insertBefore node.firstChild, node
parent.removeChild node
createValueSliders = (node, slideFunc)->
if !(top = $(node).closest('[data-org-src]')[0]) then return
$(node).find('.org-num').children().unwrap()
node.normalize()
createNextValueSliders node, slideFunc, node
chunkSize = 30
chunkDelay = 1000
createNextValueSliders = (node, slideFunc, cur)->
if (cur = visibleTextNodeAfter parentForNode(cur), cur) && node?.contains cur
createNextValueSlider node, slideFunc, cur
numPat = /[0-9][0-9.]*|\.[0-9.]+/
createNextValueSlider = (node, slideFunc, cur)->
setTimeout (->
done = false
if mnum = cur.data.match numPat
restorePosition top, ->
orig = cur
mid = cur.splitText mnum.index
cur = (if mid.length > mnum[0].length then mid.splitText mnum[0].length
else
done = true
mid)
numberSpan = $(mid).wrap("<span class='org-num'></span>").parent()[0]
do (n = numberSpan)-> n.onmousedown = (e)->
showSliderButton node, n, slideFunc
if !done
return createNextValueSlider node, slideFunc, cur
createNextValueSliders node, slideFunc, cur), 1
leisureNumberSlider = (numberSpan)->
orgParent = $(numberSpan).closest('[data-org-results]')[0]
orgType = orgParent.getAttribute 'data-org-results'
computing = false
pending = false
newValue = ->
computing = true
pending = false
doc = topNode orgParent
selection = new FancySelectionDescriptor doc
done = ->
selection.restore 0, doc
computing = false
if pending then newValue()
setTimeout (->
if orgType == 'dynamic' then root.orgApi.executeSource parent, numberSpan.parentNode, done
else if orgType == 'def' then root.orgApi.executeDef orgParent, done
else done()), 1
if orgType in ['dynamic', 'def']
(event, ui)->
numberSpan.innerHTML = String(ui.value)
if !computing then newValue()
else pending = true
else ->
regularNumberSlider = (numberSpan)->
Lodash.throttle ((event, ui)->
numberSpan.innerHTML = String(ui.value)
edited numberSpan), 20,
leading: true
trailing: true
lineStart = /^[^ ].*$/gm
recreateAstButtons = (node)->
if !(top = $(node).closest('.codeblock')[0]) then return
restorePosition top, ->
$(node).find('[data-ast-offset]').remove()
t = getOrgText node
while m = lineStart.exec t
if (tr = m[0].trim()) && tr[0] != '#'
[cur, offset] = findDomPosition node, m.index
if offset > 0 then cur = cur.splitText offset
div = document.createElement 'div'
div.setAttribute 'class', 'ast-button'
div.setAttribute 'contenteditable', 'false'
div.setAttribute 'data-ast-offset', m.index
do (d = div)-> d.onmousedown = (e)->
e.preventDefault()
e.stopPropagation()
showAst d
cur.parentNode.insertBefore div, cur
node.normalize()
newCodeContent = (name, content)->
parent = $("[data-org-codeblock='#{name}']")
if node = parent.find('[data-org-src]')[0]
node.innerHTML = escapeHtml content
recreateAstButtons node
createValueSliders node, leisureNumberSlider
define 'newCodeContent', (name)->(content)->
makeSyncMonad (env, cont)->
newCodeContent rz(name), rz(content)
cont rz L_true
isOrContains = (parent, node)->
n = parent.compareDocumentPosition(node)
(n & Element.DOCUMENT_POSITION_CONTAINED_BY) || n == 0
redrawAst = (code, pos)->
[button] = findDomPosition code, pos
while (button = nodeBefore button) != code && !$(button).is '.ast-button' then
console.log "redraw ast", button
showAst button, true
linePat = /\r?\n(?=[^ ]|$)/
showAst = (astButton, force)->
offset = Number(astButton.getAttribute 'data-ast-offset')
#if force || !replaceRelatedPresenter presenter.button, emptyPresenter
if force || !replaceRelatedPresenter astButton, emptyPresenter
$(astButton).children().remove()
text = getOrgText(astButton.parentNode).substring offset
text = text.substring 0, (if m = text.match linePat then m.index else text.length)
result = rz(L_newParseLine)(lz 0)(L_nil)(lz text)
runMonad result, baseEnv, (ast)->
if getType(ast) != 'parseErr'
console.log "SIMPLIFIED: #{show lz(runMonad rz(L_simplify) lz text)}"
try
astContent = nonOrg "<div class='#{theme ? ''} ast'>#{rz(L_wrappedTreeFor)(lz ast)(L_id)}</div>"
if theme then astContent.addClass theme
$(astButton).append astContent
replacePresenter
hide: -> astButton.firstChild?.remove()
isRelated: (node)-> isOrContains astButton, node
button: astButton
astCodeContains: (pos)-> 0 <= pos - offset < text.length
astCode: getCodeContainer astButton
catch err
console.log "Error showing AST: #{err.stack}"
show = (obj)-> rz(L_show)(lz obj)
commentButton = (name)->
"<button class='comment-button' onclick='Leisure.toggleComment(\"#{escapeAttr name}\", event)' contenteditable='false' data-org-commentcount='0'><i class='fa fa-comment'></i><span></span><div></div></button>"
toTestCaseButton = (org)->
if isDef org then ''
else "<button class='testcase-button' onclick='Leisure.createTestCase(event)' contenteditable='false' data-org-commentcount='0'><i class='fa fa-mail-reply'></i><div></div><span></span></button>"
codeBlockForNode = (node)->
node = $(node).closest '[data-org-type="source"]'
if node.is '[data-org-test]' then node[0] else node[0].parentNode
createTestCase = (evt)->
restorePosition null, ->
node = codeBlockForNode evt.target
selectPrevious node
attrs = ['view', 'testcase']
if !getCodeAttribute evt.target, 'observe' then attrs.push 'observe', '*'
setCodeAttributes evt.target, attrs...
node = $("##{node.id}")[0]
text = getOrgText node
rest = text
while match = rest.match drawerRE
if match[0].trim().toLowerCase() == ':expected:'
drawer = parseOrgMode(rest.substring(match.index), text.length - rest.length + match.index).children[0]
break
rest = rest.substring match.index + match[0].length
resultsText = (if drawer then text.substring drawer.offset + drawer.text.length else text)
if match = resultsRE.exec resultsText
results = parseOrgMode(resultsText.substring(match.index), text.length - resultsText.length + match.index).children[0]
if results.text.substring results.contentPos
newExpectation = ":EXPECTED:\n#{results.text.substring results.contentPos}:END:\n"
start = (if drawer then drawer else results).offset
end = (if drawer then drawer.offset + drawer.text.length else results.offset)
src = parseOrgMode(text).children[0]
pre = text.substring 0, start
#return replaceCodeBlock node, pre + newExpectation + text.substring end
return replaceCodeBlock $("##{node.id}"), pre + newExpectation + text.substring end
alert('You have to have results in order to make a test case')
newChangeResultType = (node, newType)->
org = src = orgForNode node
while src && !(src instanceof Source)
src = src.next
if src
if m = src.text.match /(:results *)([\w]*)/i
start = m.index + m[1].length
end = start + m[2].length
src.text = src.text.substring(0, start) + newType + src.text.substring(end)
else
pos = src.contentPos - 1
src.text = src.text.substring(0, pos) + " :results #{newType}" + src.text.substring pos
org
changeResultType = (text, newType)->
src = parseOrgMode(text).children[0]
while src && !(src instanceof Source)
src = src.next
if src
if m = src.text.match /(:results *)([\w]*)/i
start = src.offset + m.index + m[1].length
end = start + m[2].length
text.substring(0, start) + newType + text.substring(end)
else
pos = src.offset + src.contentPos - 1
text.substring(0, pos) + " :results #{newType}" + text.substring pos
else text
commentBlock = (name)->
"<div class='comments' data-org-comments='#{escapeAttr name}'><div></div></div>"
toggleComment = (name, evt)->
button = $(evt.target).closest('button')[0]
block = $("[data-org-comments='#{name}']")
console.log "comments clicked!"
if block.hasClass 'showcomments'
if !replaceRelatedPresenter button, null then block.removeClass 'showcomments'
else
block.addClass 'showcomments'
$("[data-org-codeblock='#{escapeAttr name}'] button.comment-button").removeClass 'new-comments'
replacePresenter
hide: -> block.removeClass 'showcomments'
isRelated: (target)->
button == $(target).closest('button')[0] || $(target).closest("[data-org-comments]").is(block)
addComment = (name, event)->
box = $(event.target.parentNode.querySelector('textarea'))
createComment name, box.val()
box.val ''
defaultMarkup = (org, tag, attrs...)->
tag = tag || 'span'
attrs = if attrs.length then " " + Lazy(attrs).chunk(2).map(([k, v])-> "#{k}='#{v}'").join(' ')
else ''
"<#{tag} #{orgAttrs org}#{attrs}>#{meatText org.text}</#{tag}>"
htmlForResults = (text, org)->
attr = if org?.shared then " id='#{org.nodeId}' data-shared='#{org.shared}'" else ''
bareResults = ''
for line in splitLines text ? ''
if line.match /^: / then bareResults += "<div class='resultsline'>#{unescapeString line.substring(2)}</div>"
"""
<div class='coderesults' data-org-type='results'#{attr}><span data-results-boilerplate class='hidden'>#+RESULTS:\n</span><div class='resultscontent'><div data-results-display data-nonorg>#{bareResults}</div><span data-results-content class='hidden'>#{escapeHtml text}</span></div></div>"""
htmlForViewResults = (text, boilerplate)->
html = sourceSpan 'results-boilerplate', boilerplate ? '#+RESULTS:\n'
html += "<div data-source-results class='resultscontent'><div data-results-display data-nonorg>"
for line in splitLines text
if line.match /^: / then html += "<div class='resultsline'>#{unescapeString line.substring(2)}</div>"
html += "</div><span data-results-content class='hidden'>#{text}</span></div>"
toggleDynamic = (event)->
block = codeBlockForNode event.target
bl = $(block)
resType = bl.attr('data-org-results') || bl.find('[data-org-results]').attr('data-org-results')
top = topNode block
newResType = if resType == 'dynamic' then 'static' else 'dynamic'
newNode = replaceCodeBlock block, changeResultType getOrgText(block), newResType
if newResType == 'dynamic' then executeSource top, $(newNode).find('[data-org-type="source"]')[0]
nonl = (txt)-> if txt[txt.length - 1] == '\n' then txt.substring 0, txt.length - 1 else txt
createResults = (srcNode)->
srcNode = $(srcNode).closest('.codeblock')
if created = (srcNode && !$(srcNode).find('[data-results-boilerplate]').length)
if $(srcNode).is('[data-code-view]')
$(srcNode).find('.codewrapper').append htmlForViewResults ''
else $(srcNode).find('.codewrapper').append htmlForResults ''
created
executeCode = (event)->
selectPrevious codeBlockForNode event.target
executeSource topNode(event.target), event.target, ->
#
# When to cancel line joins
# - BS at the start of a SRC block
# - DEL at the end of a SRC block
#
shouldCancelBS = (parent, r)-> atTextStart(r) && crossesHidden -1
atTextStart = (r)-> r.collapsed && (r.startContainer.nodeType == 1 || (r.startContainer.nodeType == 3 && r.startOffset == 0))
# returns:
# false if not at the end
# 1 if at the end
# 2 at an ending \n
atTextEnd = (r)-> r.collapsed && (r.startContainer.nodeType == 1 || (r.startContainer.nodeType == 3 &&
((r.startOffset == r.startContainer.length && 1) ||
(r.startOffset == r.startContainer.length - 1 &&
getOrgText(r.startContainer)[r.startOffset] == '\n' && 2))))
shouldCancelDEL = (parent, r)-> (atEnd = atTextEnd r) && crossesHidden atEnd + 1
matchLineAt = (parent, pos)->
text = getOrgText parent
start = text.substring(0, pos).lastIndexOf('\n')
end = text.indexOf '\n', start + 1
if end == -1 then end = text.length
matchLine text.substring start + 1, end
slideStart = (headline)-> "<div class='slideholder'#{headlineSlideProperties headline}>"
headlineSlideProperties = (headline)->
props = ''
if headline.level == 1
for k of headline?.properties ? {}
props += "data-slide-property-#{k}='#{headline.properties[k]}'"
if props then " " + props else ''
slideEnd = -> "</div>"
firstSlideFlag = false
startNewSlide = (replace, headline)->
if replace then ''
else if firstSlideFlag
firstSlideFlag = false
''
else "#{slideEnd()}#{slideStart headline}"
createNoteShadows = ->
for node in $('.slideholder')
setShadowHtml node, "<div class='page'><div class='border'></div><table class='pagecontent slideshadow'><tr class='slideshadowrow'><td class='slidemain'><content select='[data-org-note=\"main\"]'></content></td><td class='sidebarholder'><div class='sidebar'><div class='sidebarcontent'><content select='[data-org-note=\"sidebar\"]'></content></div></div></td></tr></table></div><content select='[data-org-note=\"skip\"],[data-float-holder]'></content>"
for node in $('[data-float-holder]')
holder = $(node)
inside = $(node.firstChild)
noteSpec = $(node).find('[data-org-floatval]').attr 'data-org-floatval'
holder.draggable handle: 'h2'
inside.resizable()
holder.bind 'dragstop', (event) -> saveNoteLocation $(event.target)
inside.bind 'resizestop', -> saveNoteLocation $(event.target)
[skip, top, left, width, height] = noteSpec.split /\s+/
window.setTimeout (->
holder.css top: top, left: left
inside.css width: width, height: height), 1
markupGuts = (org, start)->
if !org.children.length then ''
else
prev = if start then null else org
hline = 'first'
if org.level == 0 then firstSlideFlag = true
guts = ((for c in org.children
s = start
start = false
p = prev
prev = c
h = hline
if c instanceof Headline then hline = 'inner'
(hlineFor c, h) + markupNode(c, s)).join "") + (if org.level == 0 then "<hr class='last'>" else '')
if org.level == 0
"#{slideStart org.children[0]}#{guts}#{slideEnd()}"
else guts
hlineFor = (headline, hline)->
if !(headline instanceof Headline) || headline.level != 1 then ''
else "<hr class='#{hline}'>"
currentTextPosition = (parent, r)->
if curPos > -1 then curPos
else curPos = getTextPosition parent, r || getSelection().getRangeAt(0)
crossesHidden = (delta)->
r = getSelection().getRangeAt 0
!(0 <= r.startOffset < r.startContainer.length) && isCollapsed (if delta < 0 then textNodeBefore else textNodeAfter) parentForNode(r.startContainer), r.startContainer
bindContent = (div)->
div.addEventListener 'drop', (e)-> root.orgApi.handleDrop e
div.addEventListener 'mousedown', (e)->
if replaceUnrelatedPresenter e.target, emptyPresenter
setCurKeyBinding null
div.addEventListener 'keydown', handleKey div
div.addEventListener 'keyup', handleKeyup div
handleKey = (div)->(e)->
if !(e.target instanceof HTMLInputElement || e.target.getAttribute 'data-view-id')
root.modCancelled = false
curPos = -1
c = (e.charCode || e.keyCode || e.which)
if !addKeyPress e, c then return
s = getSelection()
r = s.rangeCount > 0 && s.getRangeAt(0)
root.currentBlockIds = blockIdsForSelection s, r
[bound, checkMod] = findKeyBinding e, div, r
if bound then root.modCancelled = !checkMod
else
root.modCancelled = false
if c == ENTER then handleInsert e, s, newLinesForNode r.startContainer
else if c == BS then fancyBackspace div, e, s, r
else if c == DEL then fancyDel div, e, s, r
else if modifyingKey c, e then handleInsert e, s
childIndex = (el)->
count = 0
while el = el.previousSibling
count++
count
newLinesForNode = (node)->
if $(node).closest('[data-shared]').attr('data-shared') in ['chunk','headline']
'\n\n'
else '\n'
whitespaceEnd = /(\n | )*(\n*)$/
fancyBackspace = (div, e, s, r)->
handleDelete e, s, false, (text, pos)->
if pos == 0 then false
else if $(s.anchorNode).closest('.code-content').length then true
else if text[pos - 1] in [' ', '\n']
fore = text.substring 0, pos
ws = (m = fore.match(whitespaceEnd))?[0] ? ''
nls = m?[2] ? ''
if nls.length > 3 then [pos - 2, pos]
else [pos - ws.length, pos]
else [pos - 1, pos]
isEmptyText = (text)-> text in ['\n', '\n\n']
fancyDel = (div, e, s, r)->
handleDelete e, s, true, (text, pos)->
if pos in [text.length, text.length - 1] then false
else if isEmptyText text then [0, '']
else if $(s.anchorNode).closest('.code-content').length then pos < text.length - 1
else if text[pos] != '\n' then [pos, pos + 1]
else if text[pos + 1] == '\n' then [pos, pos + 2]
else if text[pos - 1] == '\n' then [pos - 1, pos + 1]
else [pos, pos + 1]
beginsMeat = (s)->
n = s.anchorNode
s.anchorOffset == 0 &&
(isMeatText(n) || (n.nodeType == Node.TEXT_NODE && isMeatText n.parentNode))
endsMeat = (s)->
n = s.anchorNode
p = s.anchorOffset
(isMeatText(n) && n.textContent.match /^\s*\n/) ||
(n.nodeType == Node.TEXT_NODE && isMeatText(n.parentNode) && p == n.length - 1 && n.data[p] == '\n')
isMeatText = (n)-> n.nodeType == Node.ELEMENT_NODE && n.classList.contains 'meat-text'
isMeatBreak = (n)-> n.nodeType == Node.ELEMENT_NODE && n.classList.contains 'meat-break'
fancyCheckExtraNewline = (range, n, parent)->
if range.collapsed && n.nodeType == Node.TEXT_NODE && range.startOffset == n.length && getOrgText(n)[n.length - 1] != '\n' then checkLast n, parent
else if $(n).closest('[data-org-type=meat]').length
'\n\n'
else '\n'
cancelAndReselect = (event, selection, oldRange, currentRange)->
e.preventDefault()
root.modCancelled = true
if oldRange != currentRange
selectRange oldRange
null
getCodeContainer = (node)->
$(node).closest("[data-org-src]")[0] || $(node).find("[data-org-src]")[0]
needsNewline = (el)->
if !el then false
else if el.nodeType == 3 then needsNewline el.parentNode
else el.nodeType == 1 && $(el).is('[data-newline]')
bsWillDestroyParent = (r)->
if r.startContainer.nodeType == 3 && r.startOffset == 1 && r.startContainer.data.match /^.\n?$/
getOrgText(r.startContainer.parentNode) == r.startContainer.data
else false
allowEvents = true
executeSource = (parent, node, env, cont, skipTests)->
if typeof env == 'function' then [env, cont, skipTests] = [null, env, cont]
doc = topNode node
[srcNode, text] = getNodeSource node
if srcNode
createResults srcNode
if text.trim().length
lang = getNodeLang node
orgEnv(parent, srcNode).executeText text.trim(), propsFor(srcNode), (env)->
cont? env
if !skipTests then runAutotests doc
else
if r = $(srcNode).find('[data-results-content]').length then clearResults srcNode
cont?()
fancyExecuteDef = (node, cont)->
doc = topNode node
executeDef node, ->
cont?()
runAutotests doc
runAutotests = (doc)->
for n in $(doc).find("[data-org-results='autotest']").add($(doc).find("[data-org-update~='any']"))
runTest doc, n
runTest = (doc, node)-> executeSource doc, node, (if $(node).is("[data-org-results='autotest']") then (-> checkTestResults node)), true
checkTestResults = (node)->
node.setAttribute 'data-org-test', (if node.getAttribute('data-org-expected') == $(node).find('[data-results-content]').text() then 'pass' else 'fail')
processResults = (str, node, skipText)->
if !(node.hasAttribute 'data-no-results')
if resultsNode = $(node).find('[data-results-display]')[0]
if !skipText
$(node).find('[data-results-content]')[0]?.textContent += str
edited node
classes = 'resultsline'
if theme != null then classes = theme + ' ' + classes
if $("body").hasClass 'bar_collapse' then classes += ' bar_collapse'
for line in splitLines str
if line.match /^: / then resultsNode.innerHTML += "<div class='#{classes}'>#{unescapeString line.substring(2)}</div>"
else console.log str
charCodes =
"b": '\b'
"f": '\f'
"n": '\n'
"r": '\r'
"t": '\t'
"v": '\v'
"'": '\''
"\"": '\"'
"\\": '\\'
unescapeString = (str)-> str.replace /\\./g, (str)-> charCodes[str[1]] || str
redrawIssue = (issue)->
issueName = issue.leisureName
if (name = $("[data-org-comments='#{issueName}']")).length
count = issue.comments.length + 1
button = $("[data-org-codeblock='#{issueName}'] button.comment-button")
if button.attr('data-org-commentcount') != count
button.attr 'data-org-commentcount', count
button.addClass 'new-comments'
setShadowHtml button.find('span')[0], count
setShadowHtml name[0].firstChild, "<div class='#{theme ? ''}'>#{commentHtml issue, 'main'}#{(commentHtml c, 'added' for c in issue.comments).join ''}#{newCommentBox issueName, $(name[0].parentNode).find('.codeblock').attr 'id'}</div>"
commentHtml = (comment, type)->
"<div class='commentbox'><img src='http://gravatar.com/avatar/#{comment.user.gravatar_id}?s=48'><div class='#{type}'>#{comment.body}</div></div>"
newCommentBox = (name, codeId)->
"<div><textarea pseudo='x-new-comment'></textarea><br><button class='add_comment' onclick='Leisure.addComment(\"#{name}\", event)'>Add Comment</button></div>"
colonify = (str)-> ': ' + (str.replace /[\n\\]/g, (c)-> if c == '\n' then '\\n' else '\\\\') + '\n'
clearResults = (node)->
$(node).find('[data-results-display]').html ''
$(node).find('[data-results-content]').html ''
# like orgSupport's orgEnv, but wrap the leading ': ' in hidden spans
orgEnv = (parent, node)->
if id = $(node).closest('[data-shared]')[0]?.id
r = -> $("##{id}")[0]
env = if r?() && !r().hasAttribute 'data-no-results'
pendingResults = ''
__proto__: defaultEnv
readFile: (filename, cont)-> window.setTimeout (->$.get filename, (data)-> cont false, data), 1
write: (str)-> pendingResults += colonify String str
clear: ->
pendingResults = ''
clearResults r()
newCodeContent: (name, con)-> console.log "NEW CODE CONTENT: #{name}, #{con}"
finishedComputation: ->
clearResults r()
processResults pendingResults, r()
else
__proto__: defaultEnv
readFile: (filename, cont)-> window.setTimeout (->$.get filename, (data)-> cont false, data), 1
write: (str)-> console.log colonify String str
newCodeContent: (name, con)-> console.log "NEW CODE CONTENT: #{name}, #{con}"
finishedComputation: ->
installEnvLang node, env
et = env.executeText
env.executeText = (text, props, cont)->
et.call this, text, props, ->
env.finishedComputation()
cont? env
env
#################
# Value sliders
#################
hideSlider = (numberSpan)-> replaceRelatedPresenter numberSpan, emptyPresenter
showSliderButton = (parent, numberSpan, slideFunc)->
if hideSlider numberSpan then return
inside = false
sliding = false
d = $("<div style='z-index: 1; position: absolute; width: 200px; background: white; border: solid green 1px' slider contentEditable='false'></div>")[0]
d.style.top = "#{numberSpan.offsetTop + numberSpan.offsetHeight + 5}px"
d.style.minTop = '0px'
d.style.left = "#{Math.max(0, numberSpan.offsetLeft + numberSpan.offsetWidth/2 - 100)}px"
d.addEventListener 'mouseover', (e)->
if !inside then inside = true
d.addEventListener 'mouseout', (e)->
if e.toElement != d && !d.contains e.toElement
inside = false
if !sliding then hideSlider numberSpan
value = Number getOrgText numberSpan
min = if value < 0 then value * 2 else value / 2
max = if value == 0 then 10 else value * 2
sl = $(d).slider
animate: 'fast'
start: ->
sliding = true
allowEvents = false
true
stop: (event, ui)->
setMinMax sl
allowEvents = true
sliding = false
if !inside then hideSlider numberSpan
slide: slideFunc numberSpan
value: value
numberSpan.parentNode.insertBefore d, numberSpan
setMinMax sl, value
replacePresenter
numberSpan: numberSpan
hide: ->
d.remove()
isRelated: (node)-> (isOrContains d, node) || (isOrContains numberSpan, node)
d.focus()
psgn = (x)-> if x < 0 then -1 else 1
setMinMax = (sl, value)->
value = value || sl.slider("value")
min = 0
max = if 1 <= Math.abs(value) < 50 or value == 0 then 100 * psgn(value) else value * 2
step = (max - min) / 100
if Math.round(value) == value
step = Math.round(step)
step = Math.max(1, step - step % (max - min))
sl.slider "option", "min", min
sl.slider "option", "max", max
sl.slider "option", "step", step
getSlides = (parent)->
showHidden = $(document.body).is('.show-hidden')
$(parent ? '[maindoc]').find('.slideholder').filter (i, el)->
slides = $(el).find("[data-org-headline='1']")
if !showHidden then slides = slides.not('[data-property-hidden="true"]')
slides.length > 0
setCurrentSlide = (element, noscroll)->
element = $(element).closest '.slideholder'
for node in $('.currentSlide')
if node.shadowRoot then $(node).shadow().removeClass 'currentSlide'
$('.currentSlide').removeClass 'currentSlide'
element.addClass 'currentSlide'
if element.is('.firstSlide') then $("body").addClass 'firstSlide' else $("body").removeClass 'firstSlide'
if element.is('.lastSlide') then $("body").addClass 'lastSlide' else $("body").removeClass 'lastSlide'
# this is needed until there is support for :host (and/or ^ & ^^)
$(element).shadow().addClass 'currentSlide'
Leisure.actualSelectionUpdate()
if !noscroll then window.scrollTo 0, 0
firstSlide = -> setCurrentSlide getSlides().first()
lastSlide = -> setCurrentSlide getSlides().last()
slideIndex = (slides)->
slides = slides || getSlides()
slides.index slides.filter('.currentSlide').first()
nextSlide = ->
slides = getSlides()
if (i = slideIndex slides) > -1
setCurrentSlide slides[Math.min(i + 1, slides.length - 1)]
prevSlide = ->
slides = getSlides()
i = slideIndex slides
setCurrentSlide slides[Math.max(i - 1, 0)]
slideParent = (node)-> $(node).closest("[data-org-headline='1']")[0]
documentTop = (node)->
top = 0
while node
if node.tagName
top = top + node.offsetTop
node = node.offsetParent
else node = node.parentNode
top
slideBindings =
'PAGEUP': (e, parent, r)->
e.preventDefault()
prevSlide()
false
'PAGEDOWN': (e, parent, r)->
e.preventDefault()
nextSlide()
false
'S-PAGEUP': (e, parent, r)->
e.preventDefault()
firstSlide()
false
'S-PAGEDOWN': (e, parent, r)->
e.preventDefault()
lastSlide()
false
'C-PAGEUP': (e, parent, r)->
e.preventDefault()
firstSlide()
false
'C-PAGEDOWN': (e, parent, r)->
e.preventDefault()
lastSlide()
false
slideBindings.__proto__ = defaultBindings
toggleSlides = ->
slideMode = !slideMode
applySlides()
applySlides = ->
$('#prevSlide:not(.bound)').addClass('bound').bind('click', prevSlide);
$('#nextSlide:not(.bound)').addClass('bound').bind('click', nextSlide);
$('body').removeClass 'firstSlide'
$('body').removeClass 'lastSlide'
$('.firstSlide').removeClass 'firstSlide'
$('.lastSlide').removeClass 'lastSlide'
if slideMode
fancyOrg.bindings = slideBindings
s = getSlides()
s.first().addClass 'firstSlide'
s.last().addClass 'lastSlide'
#restorePosition null, ->
$('[data-org-html]').addClass 'slideHtml'
$('body').addClass 'slides'
firstSlide()
else
fancyOrg.bindings = defaultBindings
$('body').removeClass 'slides'
$('[data-org-html]').removeClass 'slideHtml'
theme = null
setTheme = (str)->
el = $('[data-shadowholder]').shadow().add('body')
if theme && theme != str then el.removeClass theme
theme = str
if str then el.addClass str
for t in $("style.theme")
$(t).prop 'disabled', true
$("style#" + theme).removeProp 'disabled'
dd = $("#themeSelect")
if dd then dd.val theme
define 'setTheme', (str)->
makeSyncMonad (env, cont)->
if str != theme then setTheme rz str
cont rz L_true
define 'toggleLeisureBar', makeSyncMonad (env, cont)->
console.log new Error "TOGGLE LEISURE BAR"
root.toggleLeisureBar()
cont rz L_true
define 'toggleSlides', makeSyncMonad (env, cont)->
toggleSlides()
cont rz L_true
slideOffset = (slide)->
if slide
a = []
a.push $("[data-org-headline='1']")...
a.indexOf slide ? $('.currentSlide')[0]
else -1
codeHolder = (el)-> if el?.getAttribute 'data-shared' then el else el?.parentElement
fixupViews = (target)->
if Leisure.noViewUpdate then return
if target
yn = 'data-yaml-name'
ynA = "[#{yn}]"
vl = 'data-view-link'
vlA = "[#{vl}]"
rendered = {}
for dataEl in $(target).add($(target).find(ynA)).filter(ynA)
rendered[$(dataEl).attr yn] = true
renderView dataEl
for link in $(target).add($(target).find(vlA)).filter(vlA)
dataName = $(link).attr vl
if !rendered[dataName] && data = getBlockNamed dataName
renderLink link, data
else
for dataEl in $('[data-yaml-name]')
renderView dataEl
for html in $('[data-html-view]')
renderHtmlView html
renderHtmlView = (html, data)->
if !html.leisureRendered && (txt = $(html).find("[data-content]").text()) && output = $(html).find('[data-org-html]')
if !data && name = html.getAttribute 'data-html-view' then data = getDataNamed name
if data && txt
try
comp = Handlebars.compile txt
html.leisureRendered = true
catch err
console.log err.stack
return
appendAndActivate output, nonOrg comp data.yaml
# el could be a parent fragment, a shared source block, or a source block in a fragment
renderView = (el, name)->
holder = codeHolder el
id = holder.id
data = getBlock id
if data?.yaml?.type
yn = 'data-yaml-name'
renderData data, $(holder).add($(holder).find("[#{yn}]")).filter("[#{yn}]").attr yn
else if name = name || el.getAttribute "data-yaml-name"
for html in $("[data-html-view='#{name}']")
renderHtmlView html, data
renderData = (data, linkName)->
if type = data?.yaml?.type
links = if name then $("[data-view-link='#{linkName}'][data-view-name='#{name}']") else $("[data-view-link='#{linkName}']")
id = data._id
links.attr 'data-view-id', id
try
oldChunk = Leisure.currentViewChunk
Leisure.currentViewChunk = data
for node in links
renderLink node, data
finally
Leisure.currentViewChunk = oldChunk
noRenderWhile = (links, func)->
addChangeContextWhile _.merge({}, root.changeContext.blockViews ? {}, blockViews: links), func
renderLink = (node, data)->
if node.lastRendered == getRenderCount() then return
node.lastRendered = getRenderCount()
if isPlainEditing(node) || root.changeContext.blockViews?.is(node) || root.changeContext.blockViews?.is($(node).children().filter('[data-view]')) then return
if name = node.getAttribute 'data-view-name'
viewKey = "#{data.yaml.type}/#{name}"
descriptor = "#{data._id}/#{name}"
else
viewKey = data.yaml.type
descriptor = data._id
if root.viewTypeData[viewKey] && markup = viewMarkup[viewKey]
markup data.yaml, $(node), false, data
else clearView node
$(node)
.attr 'data-view-descriptor', descriptor
.attr 'data-view-key', viewKey
.attr 'data-view-id', data._id
updateIndexViews = (index)->
for view in $("[data-org-index~='#{index}']").closest("[data-view]")
type = $(view).attr 'data-view-type'
if block = getBlock $(view).attr 'data-view-block'
viewMarkup[type] block.yaml, $(view), false, block, true, $(view).closest("[data-view-link]")
updateViews = (id, allowInplaceUpdate)->
if block = getBlock id
if block.language?.toLowerCase() == 'css'
$("##{id} style").html codeString block
else if allowInplaceUpdate
updateViewsInPlace block
else
for link in $("[data-view-ids~='#{id}']")
if !root.changeContext.blockViews?.is(link)
for view in $(link).find("[data-view-block='#{id}']")
if !root.changeContext.blockViews?.is(view)
type = $(view).attr 'data-view-type'
viewMarkup[type] block.yaml, $(view), false, block, true, link
updateViewsInPlace = (block)->
for view in $("[data-view-block='#{block._id}']")
type = $(view).attr 'data-view-type'
viewMarkup[type] block.yaml, $(view), false, block, true, $(view).closest("[data-view-link]")
viewBlock = (el)->
if id = $(el).closest('[data-view-block]').attr('data-view-block')
getBlock id
Leisure.bindWidgets = bindWidgets = (parent)->
link = Templating.currentViewLink
for input in $(parent).find 'input[data-value]'
do (input)->
input.setAttribute 'data-input-number', ++Templating.currentInputCount
blockParent = $(input).closest '[data-view-block]'
field = input.getAttribute 'data-value'
input.value = viewBlock(input)?.yaml?[field] ? ''
nextButton = input.getAttribute 'button'
input.onkeyup = (e)->
block = viewBlock(input)
data = block.yaml
setField data, field, input.value
noRenderWhile $(link), -> setData block._id, data
if nextButton && e.keyCode == 13
e.preventDefault()
$(rootNode(input).firstChild).find("##{nextButton}").click()
setField = (data, field, value)->
data[field] = if typeof value == 'number' then value
else if typeof value == 'string'
n = Number value
if String(n) == value.trim() then n
else value
else value
Handlebars.registerHelper 'values', (items..., options)-> items
Handlebars.registerHelper 'view', (item, name, options)->
if !options
options = name
name = null
data = if typeof item == 'string'
block = getBlock(item) || getBlockNamed(item)
block?.yaml
else if item?.yaml && item._id
block = item
item.yaml
else
block = null
item
if data?.type
descriptor = if name then "#{data.type}/#{name}" else "#{data.type}"
viewMarkup[descriptor]?(data, null, false, block) || ''
else ''
Handlebars.registerHelper 'deref', (item)->
if typeof item == 'string'
block = getBlockNamed item
block?.yaml
else if item.yaml && item._id
block = item
item.yaml
else
block = null
item
Handlebars.registerHelper 'find', (index, options)->
ret = "<span data-org-index='#{index}'></span>"
indexedCursor(root.currentDocument, index)?.forEach (data)-> if data then ret += options.fn data
ret
addViewId = ->
if Templating.currentViewData._id?
ids = {}
for id in Templating.currentViewLink.getAttribute('data-view-id').split ' '
ids[id] = true
ids[Templating.currentViewData._id] = true
result = []
for k of ids
result.push k
Templating.currentViewLink.setAttribute 'data-view-id', result.join ' '
changeInputText = (field, id)->
console.log "CHANGE DATA"
isHidden = (target)->
if target && !$(document.body).hasClass('show-hidden')
data = if isNode target then target.id else target
root.currentDocument.leisure.parentCache.isHidden data
isHiddenBlock = (block)->
if !$(document.body).hasClass('show-hidden')
root.currentDocument.leisure.parentCache.isHidden block
fancyOrg =
__proto__: orgNotebook
name: 'fancy'
opposite: plainOrg
markupOrg: markupOrg
markupOrgWithNode: markupOrgWithNode
bindContent: bindContent
isHiddenBlock: isHiddenBlock
reparse: (parent, text, target)->
if isHidden target then return
if isPlainEditing target
t = $(plainOrg.reparse parent, text, target)
if t.is("[data-org-headline='1']")
t.attr 'data-edit-mode', 'plain'
t.attr 'data-org-note', t.attr('data-property-note') || 'main'
createEditToggleButton t
@newNode t
fixupHtml t
else orgNotebook.reparse.apply this, arguments
installOrgDOM: (parent, orgNode, orgText, target)->
@parent = parent
restorePosition parent, =>
if !target
parent.setAttribute 'class', 'org-fancy'
parent.setAttribute 'maindoc', ''
hadTarget = target
target = orgNotebook.installOrgDOM parent, orgNode, orgText, target
fixupHtml target || parent, null
@newNode target
if !hadTarget
@applyShowHidden()
setTimeout (=>
redrawAllIssues()
), 1
$(document).tooltip()
newNode: (target)->
setTheme theme
nextNoteId = 0
fixupViews target
createNoteShadows()
executeSource: (parent, node, cont)->
node = $(node).closest('[data-org-type="source"]')[0]
if isPlainEditing node then plainOrg.executeSource arguments...
else
restorePosition null, =>
code = getCodeContainer node
shouldRedrawAst = false
if presenter?.astCode == code
pos = getTextPosition code, node, 0
if presenter.astCodeContains? pos
shouldRedrawAst = true
presenter = emptyPresenter
executeSource.call this, parent, node, this, (env)->
env.finishedComputation()
recreateAstButtons code
if shouldRedrawAst then redrawAst code, pos
cont?()
executeDef: fancyExecuteDef
createResults: createResults
bindings: defaultBindings
redrawIssue: (i)-> redrawIssue i
leisureButton: ->
restorePosition @parent, ->
toggleSlides()
if slideMode then setTimeout (-> if !getSelection().focusNode then $('[maindoc]').focus()), 1
else swapMarkup()
emptySlide: (id, slidePosition)->
"#{slideStart()}<hr class='#{if slidePosition == 'only' then 'first' else slidePosition}'><div id='#{id}'></div>#{slideEnd()}"
insertEmptySlide: (id, prevId)->
slide = $(@emptySlide id)
if (prev = $("##{prevId}").closest('.slideholder')).length then prev.after slide
else $("[maindoc] [data-org-headline='0']").append slide
slide.find("##{id}")[0]
defineView: (id)-> # define a view from a data block
if type = viewIdTypes[id]
createTemplateRenderer type, root.viewTypeData[type], false, (data, target, block, update)->
el = if update then target else viewRoots(target)
if target
el
.addClass(theme)
.addClass($('body').hasClass('bar_collapse') && 'bar_collapse')
.css('white-space', 'normal')
.css('user-select', 'none')
.css('-webkit-user-select', 'none')
.css('-moz-user-select', 'none')
el
.find('button')
.button()
el
.find('[title]')
.tooltip()
bindAllWidgets el
for view in el.add el.find '[data-view-type]'
type = view.getAttribute 'data-view-type'
block = getBlock view.getAttribute 'data-view-block'
for cid in controllerDescriptorIds[type] ? []
codeContexts[cid]?.initializeView? view, block.yaml, block._id
dataType = type.match /([^/]*)\/?(.*)?/
restorePosition null, ->
vBlock = getBlock id
for dataId of dataTypeIds[vBlock?.codeAttributes?.defview] ? {}
if block = getBlock dataId
nodes = $("[data-view-ids~='#{dataId}']")
if block.codeName?
for node in $("[data-view-link='#{block.codeName}']")
renderLink node, block
deleteView: (type)->
delete viewMarkup[type]
for node in $("[data-view-key='#{type}']")
clearView node
applyShowHidden: ->
for node in $('.slideholder')
if $(node).find("[data-org-headline='1']").not("[data-property-hidden='true']").length == 0
$(node).addClass('hidden-slide')
applySlides()
checkSourceMod: checkSourceMod
updateBlock: (block, allowInplaceUpdate)->
lang = block.language?.toLowerCase()
attr = block.codeAttributes
restorePosition null, ->
if lang in ['css', 'yaml']
updateViews block._id, allowInplaceUpdate
if !allowInplaceUpdate && index = block.codeAttributes?.index
updateIndexViews index.split(' ')[0]
else if lang == 'html' && attr?.defview
incRenderCount()
root.orgApi.defineView block._id
updateIndexViews: -> restorePosition null, -> updateIndexViews
updateAllBlocks: ->
restorePosition null, ->
console.log "UPDATE ALL"
fixupViews '[maindoc]'
updateObserver: (observerId, observerContext, yaml, block, type)->
args = arguments
restorePosition null, =>
orgNotebook.updateObserver.apply this, args
if observerContext.block.codeAttributes.view
displayCodeView findOrIs($("##{observerContext.block._id}"), '[data-code-view]')[0]
removeSlide: (id)->
el = $("##{id}")
holder = el.closest ".slideholder"
el.remove()
if holder.children().not('hr').length == 0 then holder.remove()
binding = false
bindAllWidgets = (els)->
if !binding
binding = true
try
for node in els
bindWidgets node
finally
binding = false
plainOrg.opposite = fancyOrg
# called on installing DOM and also on new notes
fixupHtml = (parent, note)->
for node in findOrIs findOrIs($(parent), "[data-lang='leisure']"), '[data-org-src]'
recreateAstButtons node
createValueSliders node, leisureNumberSlider
for node in findOrIs findOrIs($(parent), "[data-lang]:not([data-lang='leisure'])"), '[data-org-src]'
createValueSliders node, regularNumberSlider
createNoteShadows()
createEditToggleButton parent
#if !note
# $(parent).find("button.create_note").remove()
# $("<button class='create_note' contenteditable='false'><i class='fa fa-file-text-o'></i></button>")
# .insertBefore(findOrIs($(parent), '[data-org-headline="1"]').find('.maincontent'))
# .children().find(':first-child')
# .click (e)->
# e.preventDefault()
# #root.currentMode.createNotes()
for node in findOrIs $(parent), "[data-code-view]"
displayCodeView node
for node in findOrIs $(parent), '[data-org-comments]'
setShadowHtml node.firstElementChild, newCommentBox node.getAttribute('data-org-comments'), $(node.parentNode).find('.codeblock').attr 'id'
if parent.getAttribute('data-org-headline') == '0' then processHiddenNodes()
processHiddenNodes = ->
for name, doc of importedDocs
mapDocumentBlocks doc, (block)->
if block.language?.toLowerCase() == 'css' && isCurrent block
id = block._id
if !$("##{id}").length
$("[maindoc]").append $("<div id='#{id}'><style name='css'></style></div>")
updateViews id
if !(document.body.classList.contains 'show-hidden') && (parentCache = root.currentDocument?.leisure.parentCache)
mapDocumentBlocks root.currentDocument, (block)->
if parentCache.isHidden block
if block.language?.toLowerCase() == 'css'
id = block._id
if !$("##{id}").length
$("[maindoc]").append $("<div id='#{id}'><style name='css'></style></div>")
updateViews id
findSlideId = (name)->
if sl = $('[data-org-headline-text="Chats"]').prop 'id' then sl
else
for slide of root.currentDocument.leisure.parentCache.hidden
block = getBlock slide
if block.text.substring(1).trim() == name then return block
slide = null
mapDocumentBlocks root.currentDocument, (block)->
if !slide && block.type == 'headline' && block.level == 1 && block.text.substring(1).trim() == name then slide = block
slide
displayCodeView = (node)->
if node
if block = getBlock $(node).closest('[data-shared]')[0]?.id
clearView node
viewMarkup[node.getAttribute 'data-code-view']? block, $(node), false, block
#$(node).shadow().attr 'data-view-id', block._id
viewFor = (node)-> $("##{$(node).closest('[data-view-block]').attr 'data-view-block'}")
getMainContent = (headline)->
headline = findOrIs headline, '[data-org-headline="1"]'
c = headline.children '.maincontent'
if c.length > 0
headline.not(c.parent()).add(c)
else headline
createEditToggleButton = (doc)->
for node in getMainContent $(doc)
id = if $(node).is '.maincontent' then node.parentElement.id else node.id
button = $("<button class='toggle_edit' contenteditable='false' onclick='Leisure.toggleEdit(\"#{id}\")'><i class='fa fa-glass'></i></button>")
if $(node).is '.maincontent'
if !$(node).prev().is('.toggle_edit') then button.insertBefore(node)
else if !$(node).children().first().is('.toggle_edit') then $(node).prepend button
isPlainEditing = (node)-> $(slideParent(node)).is "[data-edit-mode='plain']"
toggleEdit = (id)->
restorePosition null, ->
console.log "toggle edit", id
node = $("##{id}").closest("[data-org-headline='1']")
id = node[0].id
parent = parentForNode node
if node.attr('data-edit-mode') == 'plain'
node.attr 'data-edit-mode', 'fancy'
mode = fancyOrg
else
node.attr 'data-edit-mode', 'plain'
mode = plainOrg
mode.reparse parent, orgForNode(node[0]), node[0]
node = $("##{id}")
node.attr 'data-edit-mode', mode.name
if mode == plainOrg
node.attr 'data-org-note', node.attr('data-property-note') || 'main'
if mode == root.plainOrg then createEditToggleButton node
addStyles = (name, string)->
styles = $ "<style id='styles-#{name}'>\n#{string}\n</style>"
if (old = $("#styles-#{name}")).length then old.replaceWith styles
else $('body').append styles
root.fancyOrg = fancyOrg
root.toggleComment = toggleComment
root.addComment = addComment
root.recreateAstButtons = recreateAstButtons
root.setTheme = setTheme
root.createTestCase = createTestCase
root.executeCode = executeCode
root.toggleDynamic = toggleDynamic
root.getDocRange = getDocRange
root.restoreDocRange = restoreDocRange
root.getDocumentOffset = getDocumentOffset
root.viewMarkup = viewMarkup
root.noViewUpdate = false
root.topNode = topNode
root.rootNode = rootNode
root.codeHolder = codeHolder
root.getBlockNamed = getBlockNamed
root.viewBlock = viewBlock
root.toggleEdit = toggleEdit
root.toggleSlides = toggleSlides
root.getDeepestActiveElement = getDeepestActiveElement
root.addViewId = addViewId
root.getDataNamed = getDataNamed
root.setDataNamed = setDataNamed
root.findLinks = findLinks
root.findViews = findViews
root.viewFor = viewFor
root.setCodeAttributes = setCodeAttributes
root.clearCodeAttributes = clearCodeAttributes
root.addStyles = addStyles
root.noRenderWhile = noRenderWhile
root.fancyEnv = orgEnv
root.unescapeString = unescapeString
root.findSlideId = findSlideId
| 175166 | {
Node,
resolve,
lazy,
defaultEnv,
} = root = module.exports = require '15-base'
rz = resolve
lz = lazy
{
TAB,
ENTER,
BS,
DEL,
} = require '21-browserSupport'
{
getType,
define,
makeSyncMonad,
} = require '16-ast'
{
runMonad,
isMonad,
escapePresentationHtml,
unescapePresentationHtml,
} = require '17-runtime'
{
parseOrgMode,
Headline,
headlineRE,
HL_TAGS,
Fragment,
Meat,
Keyword,
keywordRE,
KW_BOILERPLATE,
KW_NAME,
KW_INFO,
Source,
srcStartRE,
HTML,
Results,
AttrHtml,
resultsRE,
ListItem,
SimpleMarkup,
Link,
Drawer,
drawerRE,
parseTags,
matchLine,
} = require '11-org'
yaml = root.yaml
{
getCodeItems,
isCodeBlock,
isYaml,
lineCodeBlockType,
} = require '12-docOrg'
{
isCollapsed,
selectRange,
} = window.DOMCursor
{
handleDelete,
handleInsert,
domCursorForCaret,
textPositionForDomCursor,
SelectionDescriptor,
checkLast,
changeSavedSelectionOffset,
currentSelectionDescriptor,
parentForNode,
savePosition,
findOrIs,
orgNotebook,
parseOrgMode,
orgAttrs,
content,
contentSpan,
checkStart,
checkEnterReparse,
checkExtraNewline,
followingSpan,
currentLine,
checkSourceMod,
nextOrgId,
modifyingKey,
handleKeyup,
backspace,
getOrgParent,
getOrgType,
executeDef,
swapMarkup,
modifiers,
keyFuncs,
defaultBindings,
addKeyPress,
adjustSelection,
findKeyBinding,
setCurKeyBinding,
installEnvLang,
propsFor,
escapeAttr,
splitLines,
orgSrcAttrs,
baseEnv,
getNodeLang,
getNodeSource,
resultsType,
isDef,
getTextPosition,
findDomPosition,
nativeRange,
nodeBefore,
textNodeAfter,
textNodeBefore,
visibleTextNodeAfter,
getOrgText,
nonOrg,
errorDiv,
blockIdsForSelection,
PAGEUP,
PAGEDOWN,
HOME,
END,
markupData,
orgForNode,
plainOrg,
blockElementForNode,
executeSource,
redrawDoc,
isNode,
} = require '24-orgSupport'
{
redrawAllIssues,
createComment,
} = require '26-storage'
{
dataTypeIds,
edited,
pretty,
setData,
getBlock,
getBlockNamed,
getDataNamed,
setDataNamed,
addChangeContextWhile,
getSourceAttribute,
setSourceAttribute,
codeString,
controllerDescriptorIds,
codeContexts,
indexedCursor,
getRenderCount,
incRenderCount,
viewTypeData,
viewIdTypes,
mapDocumentBlocks,
importedDocs,
isCurrent,
} = require '23-collaborate'
{
nodeText,
createTemplateRenderer,
escapeHtml,
getDeepestActiveElement,
setShadowHtml,
clearView,
viewMarkup,
appendAndActivate,
viewRoots,
} = Templating # require '27-templating'
_ = require 'lodash.min'
fancyOrg = null
slideMode = false
lastOrgOffset = -1
curPos = -1
emptyPresenter =
hide: ->
isRelated: -> false
presenter = emptyPresenter
class FancySelectionDescriptor
constructor: (parent)->
sel = getSelection()
el = getDeepestActiveElement()
@parent = $(parent)[0] ? (slideParent sel.focusNode)
@focusNode = sel.focusNode
if inputNum = el?.getAttribute "data-input-number"
@linkParent = $(el).closest("[data-view-link]").attr("data-view-id")
@inputNum = inputNum
@inputSel = [el.selectionStart, el.selectionEnd]
@x = window.scrollX
@y = window.scrollY
if sel.type != 'None'
startNode = sel.getRangeAt(0).startContainer
[start, end, offset, note] = getDocRange()
@toString = -> "Selection(doc: #{start}, #{end})"
@restore = (delta, doc)->
if @linkParent && (input = $("[data-view-id='#{@linkParent}']").find("[data-input-number='#{@inputNum}']")).length > 0
input[0].focus()
[input[0].selectionStart, input[0].selectionEnd] = @inputSel
else
sel = getSelection()
if (sel.type != 'None' && sel.getRangeAt(0))?.startContainer != startNode
restoreDocRange doc, [start + delta, end + delta, offset, note]
window.scrollTo @x, @y
#[id, start, end, left, top] = pos = getSlidePosition sel.focusNode
#if id
# @toString = -> "Selection(doc: #{id}, start: #{start}, end: #{end}, left: #{left}, top: #{top})"
# @restore = -> setSlidePosition pos
#console.log "NEW SELECTION: #{this}"
restore: ->
toString: -> "Selection(none)"
isParentSelectionOf = (parent, child)-> parent?.parent?.contains child.parent
restoreStack = []
fancySaveSelection = root.saveSelection
root.restorePosition = restorePosition = (parent, block)->
savePosition fancySaveSelection, block
getSlidePosition = (node)->
if block = blockElementForNode node
{top, left} = block.getBoundingClientRect()
r = getSelection().getRangeAt 0
start = getTextPosition block, r.startContainer, r.startOffset
end = getTextPosition block, r.endContainer, r.endOffset
[block.id, start, end, left, top]
else []
setSlidePosition = ([id, start, end, left, top])->
block = $("##{id}")[0]
{curTop, curLeft} = block.getBoundingClientRect()
window.scrollBy curLeft - left, curTop - top
r1 = findDomPosition block, start, true
r2 = findDomPosition block, end, true
s = getSelection()
r = document.createRange()
r.startContainer = r1[0]
r.startOffset = r1[1]
r.endContainer = r2[0]
r.endOffset = r2[1]
selectRange r
# get a logical document range with an optional note
# [startPos, endPos, scrollOffset, noteId]
# if note is null, the positions are in the main doc
# otherwise, note is the id of a note
#
# Assumes the document has only two levels -- the main doc and notes
getDocRange = ->
s = getSelection()
r = s.getRangeAt 0
offset = getDocumentOffset r
if s.rangeCount == 1 && r.collapsed && r.startContainer.nodeType == 1 && shadow = r.startContainer.children[r.startOffset]?.shadowRoot
s = shadow.getSelection()
note = $(s.focusNode).closest('[data-note-origin]')?[0]
if note then [getTextPosition(note, s.anchorNode, s.anchorOffset), getTextPosition(note, s.extentNode, s.extentOffset), window.pageYOffset - offset, note.id]
else [null, null, null]
else
doc = topNode s.focusNode
[getTextPosition(doc, r.startContainer, r.startOffset), getTextPosition(doc, r.endContainer, r.endOffset), window.pageYOffset - offset]
restoreDocRange = (parent, [start, end, offset, noteId])->
if noteId
noteNode = $("[data-org-note-instances~='#{noteId}']")[0]
parent = $(noteNode).shadow().find("##{noteId}")[0]
[startContainer, startOffset] = findDomPosition parent, start, true
[endContainer, endOffset] = findDomPosition parent, Math.min(end, getOrgText(parent).length - 1), true
r = document.createRange()
r.setStart startContainer, startOffset
r.setEnd endContainer, endOffset
if noteId
offR = document.createRange()
offR.selectNode noteNode
window.scrollTo window.pageXOffset, offset + getDocumentOffset(offR)
s = noteNode.shadowRoot.getSelection()
else
window.scrollTo window.pageXOffset, offset + getDocumentOffset(r)
s = getSelection()
selectRange r
getDocumentOffset = (r)->
parent = parentForNode r.startContainer
c = (if r.startOffset == 0 then (textNodeBefore parent, r.startContainer) ? r.startContainer else r.startContainer)
while isCollapsed c
c = textNodeBefore parent, c
documentTop c
rootNode = (node)->
while node.parentNode
node = node.parentNode
node
topNode = (node)->
top = node
while node
if node.hasAttribute? 'data-org-headline' then top = node
node = node.parentNode
return top
replaceUnrelatedPresenter = (target, newPres)->
if result = !presenter || !presenter.isRelated target
replacePresenter newPres
result
replaceRelatedPresenter = (target, newPres)->
if result = (presenter && presenter.isRelated target)
replacePresenter newPres
result
replacePresenter = (pres)->
presenter?.hide()
presenter = pres || emptyPresenter
markupOrg = (text)->
[node, result] = markupOrgWithNode text
result
markupOrgWithNode = (text, note, replace)->
nodes = {}
if typeof text == 'string'
# ensure trailing newline -- contenteditable doesn't like it, otherwise
if text[text.length - 1] != '\n' then text = text + '\n'
org = parseOrgMode text
if isNode text then org = text
if org
[org, markupNewNode org, null, null, note, replace]
else
console.log "Attempt to display uknown object type: ", text
throw new Error "Attempt to display unknown type of object: #{text}"
markupNewNode = (org, middleOfLine, delay, note, replace)->
lastOrgOffset = -1
markupNode org, middleOfLine, delay, note, replace
getCodeAttribute = (node, attr)->
if (top = $(node).closest('[data-shared]'))[0]
getSourceAttribute top.find('[data-source-lead]').text(), attr
setCodeAttributes = (node, attrs...)->
if (top = $(node).closest('[data-shared]'))[0]
lead = top.find('[data-source-lead]')
oldTxt = txt = lead.text()
for [k, v] in L(attrs).chunk(2).toArray()
txt = setSourceAttribute txt, k, v
if txt != oldTxt
lead.text escapeHtml txt
edited top[0], true
clearCodeAttributes = (node, attrs...)->
if (top = $(node).closest('[data-shared]'))[0]
lead = top.find('[data-source-lead]')
oldTxt = txt = lead.text()
for attr in attrs
txt = setSourceAttribute txt, attr
if txt != oldTxt
lead.text escapeHtml txt
edited top[0], true
markupNode = (org, middleOfLine, delay, note, replace, inFragment)->
if (org.shared && isHidden org.nodeId) || org.offset <= lastOrgOffset then ''
else if org instanceof Results
pos = org.contentPos
text = org.text.substring pos
"<span #{orgAttrs org}><span data-org-type='text'>#{escapeHtml org.text.substring(0, pos)}</span>#{contentSpan text}"
else if org instanceof Fragment then markupFragment org, delay, note
else if org instanceof HTML then markupHtml org
else if org instanceof AttrHtml then markupAttr org
else if org instanceof Keyword
if org.name.match /^name$/i
intertext = ''
name = org
src = org.next
while src instanceof Meat && !(src instanceof Source)
intertext += src.text
src = src.next
if src instanceof Source then markupSource src, name, intertext, delay, inFragment
else defaultMarkup org
else if org instanceof Source then markupSource org, null, null, delay, inFragment
else defaultMarkup org
else if org instanceof Headline then markupHeadline org, delay, note, replace
else if org instanceof Drawer && org.name.toLowerCase() == 'properties' then markupProperties org, delay
else if org instanceof Drawer && org.name.toLowerCase() == 'data' then markupData org
else if org instanceof ListItem then markupListItem org, delay
else if org instanceof SimpleMarkup then markupSimple org
else if org instanceof Link then markupLink org
else if content(org.text).length then defaultMarkup org
else
tag = (if middleOfLine then 'span' else 'div')
"<#{tag} #{orgAttrs org}>#{meatText org.text}</#{tag}>"
meatText = (meat)->
result = if meat.match /^\n/
meat = meat.substring 1
"<span class='meat-break'>\n</span>"
else ""
paras = escapeHtml(meat).split /\n\n/
last = paras.pop()
result += _(paras).map((i)-> "<span class='meat-text#{checkBlankMeat i}'>#{i}\n</span>").join "<span class='meat-break'>\n</span>"
if result then result += "<span class='meat-break'>\n</span>"
if last
if last[last.length - 1] == '\n'
end = '\n'
last = last.substring 0, last.length - 1
if last then result += "<span class='meat-text#{checkBlankMeat last}'>#{last}</span>"
if end then result += "<span class='hidden'>\n</span><span data-nonorg contenteditable='false'>\n</span>"
result
checkBlankMeat = (hunk)-> if hunk in ['', '\n'] then " blank" else ""
isLeisure = (org)-> org instanceof Source && org.getLanguage().toLowerCase() == 'leisure'
isExecutable = (org)->
org instanceof Source && (org.getLanguage() in ['javascript', 'leisure'])
markupFragment = (org, delay, note)->
{first, name, source, last} = getCodeItems org.children[0]
if source
if first == name then first = first.next
if first in [org.children[0], org.children[1]] && !last.next
prelude = ''
while first != source
prelude += first.allText()
first = first.next
return "<span #{orgAttrs org}#{blockForLeisure source}>#{markupSource source, name, prelude, delay, true}</span>"
"<span #{orgAttrs org}>#{(markupNode child, false, delay, note, false, true for child in org.children).join ''}</span>"
blockForLeisure = (source)->
if source.getLanguage() == 'leisure' then " class='inline'" else ''
markupProperties = (org, delay)->"<span data-note-location class='hidden'>#{escapeHtml org.text}</span>"
lastAttr = null
markupAttr = (org)->
lastAttr = org
"<span class='hidden'>#{org.text}</span>"
markupLink = (org)->
if leisureMatch = org.isLeisure()
viewName = if leisureMatch[2] then " data-view-name='#{leisureMatch[2]}'" else ''
"<span data-view-link='#{leisureMatch[1]}'#{viewName}><span class='hidden'>#{org.allText()}</span></span>"
else if org.isImage()
title = (if desc = org.descriptionText() then " title='#{escapeAttr desc}'" else "")
"<span><img src='#{escapeAttr org.path}'#{title}><span class='hidden'>#{escapeHtml org.allText()}</span></span>"
else
guts = ''
for c in org.children
guts += markupNode c, true
if !guts then "<span class='hidden'>[[</span><a onclick='Leisure.followLink(event)' href='#{org.path}'>#{org.path}</a><span class='hidden'>]]</span>"
else "<span class='hidden'>[[#{org.path}][</span><a onclick='Leisure.followLink(event)' href='#{org.path}'>#{guts}</a><span class='hidden'>]]</span>"
root.followLink = (e)->
t = e.target
while t && t.nodeName != 'A'
t = t.parentNode
if t then window.open t.href, "links"
markupSimple = (org)->
guts = ''
for c in org.children
guts += markupNode c, true
text = switch org.markupType
when 'bold' then "<b>#{guts}</b>"
when 'italic' then "<i>#{guts}</i>"
when 'underline' then "<span style='text-decoration: underline'>#{guts}</span>"
when 'strikethrough' then "<span style='text-decoration: line-through'>#{guts}</span>"
when 'code' then "<code>#{guts}</code>"
when 'verbatim' then "<code>#{guts}</code>"
"<span class='hidden'>#{org.text[0]}</span>#{text}<span class='hidden'>#{org.text[0]}</span>"
hlStars = /^\*+ */
markupHeadline = (org, delay, note, replace)->
match = org.text.match headlineRE
start = "#{org.text.substring 0, org.text.length - (match?[HL_TAGS] ? '').length}".trim()
if org.text[org.text.length - 1] == '\n'
tags = escapeHtml org.text.substring start.length, org.text.length - 1
else
tags = escapeHtml org.text.substring start.length - 1
if starsM = start.match hlStars
stars = start.substring 0, starsM[0].length
start = start.substring stars.length
else stars = ''
properties = []
for k, v of org.properties
properties.push "#{k} = #{v}"
properties = if properties.length then "<span class='headline-properties' title='#{escapeAttr properties.join '<br>'}' data-nonorg='true'><i class='fa fa-wrench'></i></span>" else ''
optImport = if org.properties.import
imp = if root.currentDocument.demo then "tmp/#{importedDocs['demo/' + org.properties.import]._name}"
else new URI("x://h/#{root.currentDocument.leisure.name}", org.properties.import).path.substring 1
"<div class='import' data-nonorg='true' contenteditable='false'><span><a href='#load=/#{imp}' target='_blank'>#{org.properties.import}</a></span></div>"
else ''
editMode = if org.level == 1 then " data-edit-mode='fancy'" else ""
if org.level == 1 && !note && !org.properties?.note
if org.text.trim() != ''
"#{startNewSlide replace, org}<div #{orgAttrs org}#{editMode} data-org-headline-text='#{escapeAttr start}'#{noteAttrs org}><span class='maincontent'><span class='hidden'>#{stars}</span><span data-org-type='text'><div data-org-type='headline-content'><div class='textborder' contenteditable='false'></div><div class='headline-content'>#{escapeHtml start}<span class='tags'>#{properties}#{tags}</span></div></div><span class='meat-break'>\n</span></span>#{optImport}#{markupGuts org, checkStart start, org.text}</span></div>"
else "#{startNewSlide()}<div #{orgAttrs org}#{editMode}><span data-org-type='text'><span data-org-type='headline-content'><span class='hidden'>#{org.text}</span></span></span>#{optImport}#{markupGuts org, checkStart start, org.text}</div>"
else
slide = if org.text.trim() != ''
"<div #{orgAttrs org}#{editMode} data-org-headline-text='#{escapeAttr start}'#{noteAttrs org}><span class='hidden'>#{stars}</span><span data-org-type='text'><div data-org-type='headline-content'><div class='headline-content'>#{escapeHtml start}</div><span class='tags'>#{properties}#{tags}</span>\n</div></span>#{markupGuts org, checkStart start, org.text}</div>"
else "<div #{orgAttrs org}#{editMode}><span data-org-type='text'><span data-org-type='headline-content'><span class='hidden'>#{org.text}</span></span></span>#{markupGuts org, checkStart start, org.text}</div>"
floatize org, slide
#slide
#noteAttrs = (org)->
# if org.properties?.notes then "data-org-notes='#{org.properties.notes}'"
# else ''
nextNoteId = 0
noteAttrs = (org)->
if org.level != 1 then ''
else if org.properties?.note == 'sidebar' then " data-org-note='sidebar' data-org-noteid='#{nextNoteId++}'"
else if org.properties?.note?.match /^float / then " data-org-note='float' data-org-noteid='#{nextNoteId++}' data-org-floatval='#{org.properties.note}'"
else " data-org-note='main'"
floatize = (org, slide)->
if org.properties?.note?.match /^float /
"<div data-draggable data-float-holder='#{nextNoteId - 1}'><div data-resizable style='width: 600px; height: 600px; background: lightgray;'><h2 class='note_drag_handle' contenteditable='false'>YOUR NOTE</h2><div contenteditable='true'>#{slide}</div></div></div>"
else slide
updateNoteProperties = (span, index, txt) ->
old = getOrgText span
lines = old.split /\n/
s = lines[1].split /\s*,\s*/
if index != 0 then s[index] = txt else s[index] = ":notes: " + txt
lines[1] = s.join ', '
span.textContent = lines.join '\n'
saveNoteLocation = (target) ->
drag = target.closest("[data-draggable]")
resize = $(drag.children()[0])
orig_id = drag.attr 'data-note-origin'
orig = $("#" + orig_id)
span = orig.find("[data-note-location]")[0]
if span
index = drag.attr 'data-note-index'
#console.log "span: " + span + " => " + index
updateNoteProperties span, index, "float #{drag.css('top')} #{drag.css('left')} #{resize.width()}px #{resize.height()}px"
createNotes = (node)->
$(node).addClass 'herpderp'
for noteSpec in node.getAttribute('data-org-notes').split /\s*,\s*/
#console.log "NOTE FOR #{node.id}: #{noteSpec}"
noteId = "note-#{nextNoteId++}"
[org, html] = markupOrgWithNode getOrgText(node), true
newNote = $("<div class='sidebar_notes' data-note-origin='#{node.id}' id='#{noteId}' contenteditable='true'>#{html}</div>")[0]
switch (splitSpec = noteSpec.split(/\s+/))[0]
when 'sidebar'
if dest = $("[data-org-headline-text='#{splitSpec[1]}'] div.sidebar")[0]
if !dest.shadowRoot then setShadowHtml dest, "<div contenteditable='true'></div>"
$(dest).shadow().append newNote
when 'float'
parent = topNode node
dest = $(document.body).find('[data-org-floats]')[0]
if !dest then $(document.body).prepend dest = $("<div data-org-floats='true' contenteditable='true'></div>")[0]
inside = $('<div data-resizable style="width: 600px; height: 600px; background: black;"><h2 class="note_drag_handle" contenteditable="false">YOUR NOTE</h2><div></div></div>')
holder = $("<div data-draggable data-note-origin='#{node.id}' data-note-index='#{nextNoteId - 1}'></div>")
#console.log node
holder.append inside
dest.appendChild holder[0]
holder.draggable({handle: 'h2'})
inside.resizable()
holder.bind 'dragstop', (event) ->
saveNoteLocation $(event.target)
inside.bind 'resizestop', ->
saveNoteLocation $(event.target)
child = inside[0].children[1]
setShadowHtml child, "<div contenteditable='true' class='float_note'></div>"
$(child).shadow().append newNote
dest = child
orig = $("#" + node.id)[0]
[skip, top, left, width, height] = noteSpec.split /\s+/
holder.css({top: top, left: left})
inside.css({width: width, height: height})
saveNoteLocation holder
else continue
if dest
addWord dest, 'data-org-note-content', node.id
addWord dest, 'data-org-note-instances', noteId
fixupHtml newNote
addWord = (node, attr, value)->
vals = (node.getAttribute(attr) ? '').split ' '
vals = vals.filter (el) ->
el.length != 0
if !(value in vals) then vals.push value
node.setAttribute attr, vals.join ' '
editing = false
editedNote = (mainId, editedId)-> ->
if !editing
setTimeout (->
restorePosition $("##{editedId}")[0], ->
targets = $("##{mainId}")
main = targets[0]
for node in $("[data-org-note-content~='#{mainId}']")
targets = targets.add($(node).shadow().find "[data-note-origin='#{mainId}']")
origin = targets.filter "##{editedId}"
editing = true
try
t = targets.not("##{editedId}")
t.html origin.html()
for node in t
fixupHtml node, node != main
finally
setTimeout (-> editing = false), 1), 1
markupHtml = (org)->
if v = org.attributes()?.view
pre = org.text.substring 0, org.contentPos
post = org.text.substring org.contentPos + org.contentLength
"<span #{orgAttrs org} data-html-view='#{v}'><span contenteditable='false' data-org-html='true'></span><span class='hidden'>#{escapeHtml pre}</span><span class='hidden' data-content>#{escapeHtml org.content()}</span><span class='hidden'>#{escapeHtml post}</span><span></span></span>"
else
"<span #{orgAttrs org}><span contenteditable='false' data-nonorg='true' data-org-html='true'>#{nodeText(org.content())}</span><span class='hidden'>#{escapeHtml org.text}</span><span></span></span>"
chooseSourceMarkup = (org)->
if isYaml org then markupYaml
else if isExecutable org then markupLeisure
#else if org.lead()?.trim().toLowerCase() == 'html' then (org)-> defaultMarkup org, 'div', 'class', 'default-lang', 'data-lang', org.lead()?.trim()
else if org.info.match /^ *css\b/i then markupCSS
else markupCode
markupSource = (org, name, doctext, delay, inFragment)->
(chooseSourceMarkup org) org, name, doctext, delay, inFragment
findLinks = (name)->
if m = name.match /^([^/]*)\/(.*)$/ then $("[data-view-link='#{m[1]}'][data-view-name='#{m[2]}']") else $("[data-view-link='#{name}']")
findViews = (name)-> findLinks(name)
getSourceSegments = (name, org)->
{first, name, source, results, expected, last} = getCodeItems(name || org)
pos = source.contentPos
pre = ''
while first != source
pre += first.allText()
first = first.next
pre += source.text.substring 0, pos
post = ''
cur = source.next
while cur != last.next
post += cur.allText()
cur = cur.next
post = source.text.substring(pos + source.content.length) + post
[pre, source.content, post]
markupYaml = (org, name, doctext, delay, inFragment)->
[pre, src, post] = getSourceSegments name, org
{name, source, results, expected, last} = getCodeItems(name || org)
lastOrgOffset = last.offset
shared = (if org.shared then org else org.fragment)
yamlAttr = "data-lang='yaml'"
if shared
data = getBlock shared.nodeId
type = data.yaml?.type
if type
err = if !viewMarkup[type] then errorDiv "No value view type for data nodeId: #{shared.nodeId}" else ''
yamlAttr += " data-yaml-type='#{type}'"
err = ''
if name
n = escapeAttr name.info.trim()
yamlAttr += " data-org-codeblock='#{n}' data-yaml-name='#{n}'"
"<div #{orgAttrs source}#{yamlAttr}>#{err}<span class='Xhidden codeHeading'>#{escapeHtml pre}</span><span data-org-src data-contain>#{Highlighting.highlight 'yaml', source.content}</span><span class='Xhidden codeHeading'>#{escapeHtml post}</span></div>"
markupCode = (org, name, doctext, delay, inFragment)->
[pre, src, post] = getSourceSegments name, org
{name, source, results, expected, last} = getCodeItems(name || org)
lastOrgOffset = last.offset
lang = org.getLanguage() || ''
if name
n = escapeAttr name.info.trim()
addAttr = " data-org-codeblock='#{n}'"
else addAttr = ''
if (l = source.getLanguage()) #&& !inFragment
addAttr += " data-lang='#{l}' id='#{org.nodeId}'"
"<div class='default-lang' data-#{orgAttrs source}#{addAttr}><span class='Xhidden codeHeading'>#{escapeHtml pre}</span><span data-org-src data-contain>#{Highlighting.highlight lang, source.content}</span><span class='Xhidden codeHeading'>#{escapeHtml post}</span></div>"
markupCSS = (org, name, doctext, delay, inFragment)->
[pre, src, post] = getSourceSegments name, org
{name, source, results, expected, last} = getCodeItems(name || org)
lastOrgOffset = last.offset
lang = org.getLanguage() || ''
if name
n = escapeAttr name.info.trim()
addAttr = " data-org-codeblock='#{n}'"
styleName = " name='#{escapeAttr n}'"
else
addAttr = ''
styleName = ''
if (l = source.getLanguage()) #&& !inFragment
addAttr += " data-lang='#{l}' id='#{org.nodeId}'"
cssBlock = nonOrg("<style name='css'#{styleName}>#{src}</style>")[0].outerHTML
"<div class='default-lang' data-#{orgAttrs source}#{addAttr}><span class='Xhidden codeHeading'>#{escapeHtml pre}</span><span data-org-src data-contain>#{Highlighting.highlight lang, source.content}</span><span class='Xhidden codeHeading'>#{escapeHtml post}</span>#{cssBlock}</div>"
dragging = false
butLast = (str)-> str.substring 0, str.length - 1
markupLeisure = (org, name, doctext, delay, inFragment)->
attr = org.attributes()
lang = org.getLanguage() || ''
lastOrgOffset = org.offset
startHtml = "<div class='codeblock' contenteditable='false' data-lang='#{lang}' #{orgAttrs org}"
parts = parseSrcBlock org
if name then startHtml += " data-org-codeblock='#{escapeAttr name.info.trim()}'"
if view = attr?.view
return "#{startHtml} data-code-view='#{escapeAttr view.trim()}'>#{simpleLeisure org, doctext, attr, parts}</div>"
startHtml += "><div class='codeborder'></div>"
{lead, srcContent, trail, resText, intertext, resOrg} = parts
if name
codeName = "<div class='codename' contenteditable='true'><span class='hidden'>#{nameBoilerplate name}</span><div class='name'>#{escapeHtml butLast name.info}</div><span class='meat-break'>\n</span>#{meatText doctext}</div>"
else codeName = "<div class='codename' contenteditable='true'></div>"
wrapper = "<table class='codewrapper'><tr><td class='code-buttons'>"
if testCaseButton = toTestCaseButton org
wrapper += "<div>#{testCaseButton}</div>"
wrapper += "<div><button class='results-indicator' onclick='Leisure.executeCode(event)'><i class='fa fa-gear'></i><div></div></button></div>"
wrapper += "<div><button class='dyntoggle-button' onclick='Leisure.toggleDynamic(event)'><span class='dyntoggle'><i class='fa fa-link'></i><i class='fa fa-unlink'></i></span></button></div>"
if name then wrapper += "<div>#{commentButton name.info.trim()}</div>"
wrapper += "</td><td class='code-content'>"
wrapper += codeName
wrapper += "<div class='hidden' data-source-lead>#{escapeHtml lead}</div>"
wrapper += "<div #{orgSrcAttrs org} data-contain contenteditable='true'>#{escapeHtml srcContent}</div><span class='hidden' data-org-type='boundary'>#{escapeHtml trail}</span>"
wrapper += "<span class='hidden'>#{intertext}</span>" + htmlForResults resText, resOrg
wrapper += "</td></tr></table>"
top = name ? org
fluff = if top.prev instanceof Source || top.prev instanceof Results then "<div class='fluff' data-newline></div>" else ''
result = startHtml + wrapper + (if name then "</div>#{commentBlock name.info.trim()}" else "</div>")
inner = fluff + result
if view then inner += "</span>"
"<div></div>" + (if inFragment then inner
else '<div>' + inner + '</div>') + "<div></div>"
nameBoilerplate = (name)->
if nameM = name.text.match keywordRE then escapeHtml nameM[KW_BOILERPLATE]
parseSrcBlock = (org, name)->
result =
intertext: ''
lead: org.text.substring 0, org.contentPos
trail: org.text.substring org.contentPos + org.content.length
srcContent: org.content
if name
result.nameBoilerplate = nameBoilerplate name
result.name = name.info
node = org.next
intertext = ''
while node
if node instanceof Results
lastOrgOffset = node.offset
result.resBoilerplate = node.text.substring 0, node.contentPos
result.resText = node.text.substring node.contentPos
result.resOrg = node
result.intertext = intertext
break
else if node instanceof Drawer
if node.name.toLowerCase() == 'expected'
lastOrgOffset = node.offset
result.intertext = intertext + escapeHtml node.text
else break
else if node instanceof Headline || node instanceof Keyword
break
else intertext += escapeHtml node.text
node = node.next
result
editable = 'contenteditable="true"'
simpleLeisure = (org, doctext, attr, parts)->
html = sourceSpan 'name-boilerplate', parts.nameBoilerplate
html += sourceSpan 'name', parts.name
html += sourceSpan 'doctext', doctext, meatText
html += sourceSpan 'lead', parts.lead
html += "<div #{orgSrcAttrs org} data-contain data-source-content>#{escapeHtml parts.srcContent}</div>"
html += sourceSpan 'trail', parts.trail
html += sourceSpan 'intertext', parts.intertext
if parts.resText? then html += htmlForViewResults parts.resText, parts.resBoilerplate
html
sourceSpan = (type, content, process, attrs)->
if content
"<span#{if attrs then ' ' + attrs else ''} data-source-#{type}>#{(process ? escapeHtml) content}</span>"
else ''
updateChannels = (org)-> org instanceof Source && (org.info.match /:update *([^:]*)/)?[1]
testResult = (expected, actual)->
if actual == '' then 'unknown'
else if expected == actual then 'pass'
else 'fail'
root.toggleTestCase = (evt)->
node = codeBlockForNode evt.target
selectPrevious node
if node then replaceCodeBlock node, changeResultType getOrgText(node), (if node.getAttribute('data-org-results') == 'autotest' then 'dynamic' else 'static')
selectPrevious = (node)->
top = topNode node
pos = getTextPosition top, node, 0
r = nativeRange findDomPosition top, Math.max 0, pos - 1
selectRange r
replaceCodeBlock = (node, text)->
newNode = null
restorePosition null, ->
org = parseOrgMode text, 0, true
org.nodeId = $(node)[0].id
org.shared = 'code'
newNode = $(markupNewNode org, false, true)[0]
$(node).replaceWith(newNode)
edited newNode
fixupHtml blockElementForNode newNode
setTimeout (=>
nn = $(newNode)
(if nn.is('.codeblock') then nn else nn.find('.codeblock')).addClass 'ready'
for n in $(newNode).find('[data-org-comments]')
setShadowHtml n.firstElementChild, "<div class='#{theme ? ''}'>" + newCommentBox n.getAttribute('data-org-comments') + '</div>', codeBlockForNode(n.previousElementSibling).id
redrawAllIssues()), 1
newNode
markupListItem = (org, delay)->
if org.level == 0
start = !org.getPreviousListItem()
end = !org.getNextListItem()
else
start = (parent = org.getParent()) && parent == org.getPreviousListItem()
next = org.getNextListItem()
end = !next || next.level < org.level
"""#{if start then '<ul>' else ''}<li #{orgAttrs org} data-org-listlevel='#{
org.level
}'#{
if org.checked? then ' data-org-checked="' + org.checked + '"' else ''
}><span class='hidden'>#{
escapeHtml org.text.substring 0, org.contentOffset
}</span><span>#{markupListContents org.children}</span></li>#{
eatListItem org
}#{if end then '</ul>' else ''}"""
markupListContents = (children)-> (markupNode child, true for child in children).join ''
legalListContent = (org)->
org && (!(org instanceof Meat) || !org.inNewMeat()) && !(org instanceof Headline || org instanceof ListItem)
eatListItem = (org)->
item = org
result = ''
while legalListContent org = org.next
result += markupNode org
lastOrgOffset = Math.max(lastOrgOffset, org.offset)
result
unwrap = (node)->
parent = node.parentNode
if parent
while node.firstChild?
parent.insertBefore node.firstChild, node
parent.removeChild node
createValueSliders = (node, slideFunc)->
if !(top = $(node).closest('[data-org-src]')[0]) then return
$(node).find('.org-num').children().unwrap()
node.normalize()
createNextValueSliders node, slideFunc, node
chunkSize = 30
chunkDelay = 1000
createNextValueSliders = (node, slideFunc, cur)->
if (cur = visibleTextNodeAfter parentForNode(cur), cur) && node?.contains cur
createNextValueSlider node, slideFunc, cur
numPat = /[0-9][0-9.]*|\.[0-9.]+/
createNextValueSlider = (node, slideFunc, cur)->
setTimeout (->
done = false
if mnum = cur.data.match numPat
restorePosition top, ->
orig = cur
mid = cur.splitText mnum.index
cur = (if mid.length > mnum[0].length then mid.splitText mnum[0].length
else
done = true
mid)
numberSpan = $(mid).wrap("<span class='org-num'></span>").parent()[0]
do (n = numberSpan)-> n.onmousedown = (e)->
showSliderButton node, n, slideFunc
if !done
return createNextValueSlider node, slideFunc, cur
createNextValueSliders node, slideFunc, cur), 1
leisureNumberSlider = (numberSpan)->
orgParent = $(numberSpan).closest('[data-org-results]')[0]
orgType = orgParent.getAttribute 'data-org-results'
computing = false
pending = false
newValue = ->
computing = true
pending = false
doc = topNode orgParent
selection = new FancySelectionDescriptor doc
done = ->
selection.restore 0, doc
computing = false
if pending then newValue()
setTimeout (->
if orgType == 'dynamic' then root.orgApi.executeSource parent, numberSpan.parentNode, done
else if orgType == 'def' then root.orgApi.executeDef orgParent, done
else done()), 1
if orgType in ['dynamic', 'def']
(event, ui)->
numberSpan.innerHTML = String(ui.value)
if !computing then newValue()
else pending = true
else ->
regularNumberSlider = (numberSpan)->
Lodash.throttle ((event, ui)->
numberSpan.innerHTML = String(ui.value)
edited numberSpan), 20,
leading: true
trailing: true
lineStart = /^[^ ].*$/gm
recreateAstButtons = (node)->
if !(top = $(node).closest('.codeblock')[0]) then return
restorePosition top, ->
$(node).find('[data-ast-offset]').remove()
t = getOrgText node
while m = lineStart.exec t
if (tr = m[0].trim()) && tr[0] != '#'
[cur, offset] = findDomPosition node, m.index
if offset > 0 then cur = cur.splitText offset
div = document.createElement 'div'
div.setAttribute 'class', 'ast-button'
div.setAttribute 'contenteditable', 'false'
div.setAttribute 'data-ast-offset', m.index
do (d = div)-> d.onmousedown = (e)->
e.preventDefault()
e.stopPropagation()
showAst d
cur.parentNode.insertBefore div, cur
node.normalize()
newCodeContent = (name, content)->
parent = $("[data-org-codeblock='#{name}']")
if node = parent.find('[data-org-src]')[0]
node.innerHTML = escapeHtml content
recreateAstButtons node
createValueSliders node, leisureNumberSlider
define 'newCodeContent', (name)->(content)->
makeSyncMonad (env, cont)->
newCodeContent rz(name), rz(content)
cont rz L_true
isOrContains = (parent, node)->
n = parent.compareDocumentPosition(node)
(n & Element.DOCUMENT_POSITION_CONTAINED_BY) || n == 0
redrawAst = (code, pos)->
[button] = findDomPosition code, pos
while (button = nodeBefore button) != code && !$(button).is '.ast-button' then
console.log "redraw ast", button
showAst button, true
linePat = /\r?\n(?=[^ ]|$)/
showAst = (astButton, force)->
offset = Number(astButton.getAttribute 'data-ast-offset')
#if force || !replaceRelatedPresenter presenter.button, emptyPresenter
if force || !replaceRelatedPresenter astButton, emptyPresenter
$(astButton).children().remove()
text = getOrgText(astButton.parentNode).substring offset
text = text.substring 0, (if m = text.match linePat then m.index else text.length)
result = rz(L_newParseLine)(lz 0)(L_nil)(lz text)
runMonad result, baseEnv, (ast)->
if getType(ast) != 'parseErr'
console.log "SIMPLIFIED: #{show lz(runMonad rz(L_simplify) lz text)}"
try
astContent = nonOrg "<div class='#{theme ? ''} ast'>#{rz(L_wrappedTreeFor)(lz ast)(L_id)}</div>"
if theme then astContent.addClass theme
$(astButton).append astContent
replacePresenter
hide: -> astButton.firstChild?.remove()
isRelated: (node)-> isOrContains astButton, node
button: astButton
astCodeContains: (pos)-> 0 <= pos - offset < text.length
astCode: getCodeContainer astButton
catch err
console.log "Error showing AST: #{err.stack}"
show = (obj)-> rz(L_show)(lz obj)
commentButton = (name)->
"<button class='comment-button' onclick='Leisure.toggleComment(\"#{escapeAttr name}\", event)' contenteditable='false' data-org-commentcount='0'><i class='fa fa-comment'></i><span></span><div></div></button>"
toTestCaseButton = (org)->
if isDef org then ''
else "<button class='testcase-button' onclick='Leisure.createTestCase(event)' contenteditable='false' data-org-commentcount='0'><i class='fa fa-mail-reply'></i><div></div><span></span></button>"
codeBlockForNode = (node)->
node = $(node).closest '[data-org-type="source"]'
if node.is '[data-org-test]' then node[0] else node[0].parentNode
createTestCase = (evt)->
restorePosition null, ->
node = codeBlockForNode evt.target
selectPrevious node
attrs = ['view', 'testcase']
if !getCodeAttribute evt.target, 'observe' then attrs.push 'observe', '*'
setCodeAttributes evt.target, attrs...
node = $("##{node.id}")[0]
text = getOrgText node
rest = text
while match = rest.match drawerRE
if match[0].trim().toLowerCase() == ':expected:'
drawer = parseOrgMode(rest.substring(match.index), text.length - rest.length + match.index).children[0]
break
rest = rest.substring match.index + match[0].length
resultsText = (if drawer then text.substring drawer.offset + drawer.text.length else text)
if match = resultsRE.exec resultsText
results = parseOrgMode(resultsText.substring(match.index), text.length - resultsText.length + match.index).children[0]
if results.text.substring results.contentPos
newExpectation = ":EXPECTED:\n#{results.text.substring results.contentPos}:END:\n"
start = (if drawer then drawer else results).offset
end = (if drawer then drawer.offset + drawer.text.length else results.offset)
src = parseOrgMode(text).children[0]
pre = text.substring 0, start
#return replaceCodeBlock node, pre + newExpectation + text.substring end
return replaceCodeBlock $("##{node.id}"), pre + newExpectation + text.substring end
alert('You have to have results in order to make a test case')
newChangeResultType = (node, newType)->
org = src = orgForNode node
while src && !(src instanceof Source)
src = src.next
if src
if m = src.text.match /(:results *)([\w]*)/i
start = m.index + m[1].length
end = start + m[2].length
src.text = src.text.substring(0, start) + newType + src.text.substring(end)
else
pos = src.contentPos - 1
src.text = src.text.substring(0, pos) + " :results #{newType}" + src.text.substring pos
org
changeResultType = (text, newType)->
src = parseOrgMode(text).children[0]
while src && !(src instanceof Source)
src = src.next
if src
if m = src.text.match /(:results *)([\w]*)/i
start = src.offset + m.index + m[1].length
end = start + m[2].length
text.substring(0, start) + newType + text.substring(end)
else
pos = src.offset + src.contentPos - 1
text.substring(0, pos) + " :results #{newType}" + text.substring pos
else text
commentBlock = (name)->
"<div class='comments' data-org-comments='#{escapeAttr name}'><div></div></div>"
toggleComment = (name, evt)->
button = $(evt.target).closest('button')[0]
block = $("[data-org-comments='#{name}']")
console.log "comments clicked!"
if block.hasClass 'showcomments'
if !replaceRelatedPresenter button, null then block.removeClass 'showcomments'
else
block.addClass 'showcomments'
$("[data-org-codeblock='#{escapeAttr name}'] button.comment-button").removeClass 'new-comments'
replacePresenter
hide: -> block.removeClass 'showcomments'
isRelated: (target)->
button == $(target).closest('button')[0] || $(target).closest("[data-org-comments]").is(block)
addComment = (name, event)->
box = $(event.target.parentNode.querySelector('textarea'))
createComment name, box.val()
box.val ''
defaultMarkup = (org, tag, attrs...)->
tag = tag || 'span'
attrs = if attrs.length then " " + Lazy(attrs).chunk(2).map(([k, v])-> "#{k}='#{v}'").join(' ')
else ''
"<#{tag} #{orgAttrs org}#{attrs}>#{meatText org.text}</#{tag}>"
htmlForResults = (text, org)->
attr = if org?.shared then " id='#{org.nodeId}' data-shared='#{org.shared}'" else ''
bareResults = ''
for line in splitLines text ? ''
if line.match /^: / then bareResults += "<div class='resultsline'>#{unescapeString line.substring(2)}</div>"
"""
<div class='coderesults' data-org-type='results'#{attr}><span data-results-boilerplate class='hidden'>#+RESULTS:\n</span><div class='resultscontent'><div data-results-display data-nonorg>#{bareResults}</div><span data-results-content class='hidden'>#{escapeHtml text}</span></div></div>"""
htmlForViewResults = (text, boilerplate)->
html = sourceSpan 'results-boilerplate', boilerplate ? '#+RESULTS:\n'
html += "<div data-source-results class='resultscontent'><div data-results-display data-nonorg>"
for line in splitLines text
if line.match /^: / then html += "<div class='resultsline'>#{unescapeString line.substring(2)}</div>"
html += "</div><span data-results-content class='hidden'>#{text}</span></div>"
toggleDynamic = (event)->
block = codeBlockForNode event.target
bl = $(block)
resType = bl.attr('data-org-results') || bl.find('[data-org-results]').attr('data-org-results')
top = topNode block
newResType = if resType == 'dynamic' then 'static' else 'dynamic'
newNode = replaceCodeBlock block, changeResultType getOrgText(block), newResType
if newResType == 'dynamic' then executeSource top, $(newNode).find('[data-org-type="source"]')[0]
nonl = (txt)-> if txt[txt.length - 1] == '\n' then txt.substring 0, txt.length - 1 else txt
createResults = (srcNode)->
srcNode = $(srcNode).closest('.codeblock')
if created = (srcNode && !$(srcNode).find('[data-results-boilerplate]').length)
if $(srcNode).is('[data-code-view]')
$(srcNode).find('.codewrapper').append htmlForViewResults ''
else $(srcNode).find('.codewrapper').append htmlForResults ''
created
executeCode = (event)->
selectPrevious codeBlockForNode event.target
executeSource topNode(event.target), event.target, ->
#
# When to cancel line joins
# - BS at the start of a SRC block
# - DEL at the end of a SRC block
#
shouldCancelBS = (parent, r)-> atTextStart(r) && crossesHidden -1
atTextStart = (r)-> r.collapsed && (r.startContainer.nodeType == 1 || (r.startContainer.nodeType == 3 && r.startOffset == 0))
# returns:
# false if not at the end
# 1 if at the end
# 2 at an ending \n
atTextEnd = (r)-> r.collapsed && (r.startContainer.nodeType == 1 || (r.startContainer.nodeType == 3 &&
((r.startOffset == r.startContainer.length && 1) ||
(r.startOffset == r.startContainer.length - 1 &&
getOrgText(r.startContainer)[r.startOffset] == '\n' && 2))))
shouldCancelDEL = (parent, r)-> (atEnd = atTextEnd r) && crossesHidden atEnd + 1
matchLineAt = (parent, pos)->
text = getOrgText parent
start = text.substring(0, pos).lastIndexOf('\n')
end = text.indexOf '\n', start + 1
if end == -1 then end = text.length
matchLine text.substring start + 1, end
slideStart = (headline)-> "<div class='slideholder'#{headlineSlideProperties headline}>"
headlineSlideProperties = (headline)->
props = ''
if headline.level == 1
for k of headline?.properties ? {}
props += "data-slide-property-#{k}='#{headline.properties[k]}'"
if props then " " + props else ''
slideEnd = -> "</div>"
firstSlideFlag = false
startNewSlide = (replace, headline)->
if replace then ''
else if firstSlideFlag
firstSlideFlag = false
''
else "#{slideEnd()}#{slideStart headline}"
createNoteShadows = ->
for node in $('.slideholder')
setShadowHtml node, "<div class='page'><div class='border'></div><table class='pagecontent slideshadow'><tr class='slideshadowrow'><td class='slidemain'><content select='[data-org-note=\"main\"]'></content></td><td class='sidebarholder'><div class='sidebar'><div class='sidebarcontent'><content select='[data-org-note=\"sidebar\"]'></content></div></div></td></tr></table></div><content select='[data-org-note=\"skip\"],[data-float-holder]'></content>"
for node in $('[data-float-holder]')
holder = $(node)
inside = $(node.firstChild)
noteSpec = $(node).find('[data-org-floatval]').attr 'data-org-floatval'
holder.draggable handle: 'h2'
inside.resizable()
holder.bind 'dragstop', (event) -> saveNoteLocation $(event.target)
inside.bind 'resizestop', -> saveNoteLocation $(event.target)
[skip, top, left, width, height] = noteSpec.split /\s+/
window.setTimeout (->
holder.css top: top, left: left
inside.css width: width, height: height), 1
markupGuts = (org, start)->
if !org.children.length then ''
else
prev = if start then null else org
hline = 'first'
if org.level == 0 then firstSlideFlag = true
guts = ((for c in org.children
s = start
start = false
p = prev
prev = c
h = hline
if c instanceof Headline then hline = 'inner'
(hlineFor c, h) + markupNode(c, s)).join "") + (if org.level == 0 then "<hr class='last'>" else '')
if org.level == 0
"#{slideStart org.children[0]}#{guts}#{slideEnd()}"
else guts
hlineFor = (headline, hline)->
if !(headline instanceof Headline) || headline.level != 1 then ''
else "<hr class='#{hline}'>"
currentTextPosition = (parent, r)->
if curPos > -1 then curPos
else curPos = getTextPosition parent, r || getSelection().getRangeAt(0)
crossesHidden = (delta)->
r = getSelection().getRangeAt 0
!(0 <= r.startOffset < r.startContainer.length) && isCollapsed (if delta < 0 then textNodeBefore else textNodeAfter) parentForNode(r.startContainer), r.startContainer
bindContent = (div)->
div.addEventListener 'drop', (e)-> root.orgApi.handleDrop e
div.addEventListener 'mousedown', (e)->
if replaceUnrelatedPresenter e.target, emptyPresenter
setCurKeyBinding null
div.addEventListener 'keydown', handleKey div
div.addEventListener 'keyup', handleKeyup div
handleKey = (div)->(e)->
if !(e.target instanceof HTMLInputElement || e.target.getAttribute 'data-view-id')
root.modCancelled = false
curPos = -1
c = (e.charCode || e.keyCode || e.which)
if !addKeyPress e, c then return
s = getSelection()
r = s.rangeCount > 0 && s.getRangeAt(0)
root.currentBlockIds = blockIdsForSelection s, r
[bound, checkMod] = findKeyBinding e, div, r
if bound then root.modCancelled = !checkMod
else
root.modCancelled = false
if c == ENTER then handleInsert e, s, newLinesForNode r.startContainer
else if c == BS then fancyBackspace div, e, s, r
else if c == DEL then fancyDel div, e, s, r
else if modifyingKey c, e then handleInsert e, s
childIndex = (el)->
count = 0
while el = el.previousSibling
count++
count
newLinesForNode = (node)->
if $(node).closest('[data-shared]').attr('data-shared') in ['chunk','headline']
'\n\n'
else '\n'
whitespaceEnd = /(\n | )*(\n*)$/
fancyBackspace = (div, e, s, r)->
handleDelete e, s, false, (text, pos)->
if pos == 0 then false
else if $(s.anchorNode).closest('.code-content').length then true
else if text[pos - 1] in [' ', '\n']
fore = text.substring 0, pos
ws = (m = fore.match(whitespaceEnd))?[0] ? ''
nls = m?[2] ? ''
if nls.length > 3 then [pos - 2, pos]
else [pos - ws.length, pos]
else [pos - 1, pos]
isEmptyText = (text)-> text in ['\n', '\n\n']
fancyDel = (div, e, s, r)->
handleDelete e, s, true, (text, pos)->
if pos in [text.length, text.length - 1] then false
else if isEmptyText text then [0, '']
else if $(s.anchorNode).closest('.code-content').length then pos < text.length - 1
else if text[pos] != '\n' then [pos, pos + 1]
else if text[pos + 1] == '\n' then [pos, pos + 2]
else if text[pos - 1] == '\n' then [pos - 1, pos + 1]
else [pos, pos + 1]
beginsMeat = (s)->
n = s.anchorNode
s.anchorOffset == 0 &&
(isMeatText(n) || (n.nodeType == Node.TEXT_NODE && isMeatText n.parentNode))
endsMeat = (s)->
n = s.anchorNode
p = s.anchorOffset
(isMeatText(n) && n.textContent.match /^\s*\n/) ||
(n.nodeType == Node.TEXT_NODE && isMeatText(n.parentNode) && p == n.length - 1 && n.data[p] == '\n')
isMeatText = (n)-> n.nodeType == Node.ELEMENT_NODE && n.classList.contains 'meat-text'
isMeatBreak = (n)-> n.nodeType == Node.ELEMENT_NODE && n.classList.contains 'meat-break'
fancyCheckExtraNewline = (range, n, parent)->
if range.collapsed && n.nodeType == Node.TEXT_NODE && range.startOffset == n.length && getOrgText(n)[n.length - 1] != '\n' then checkLast n, parent
else if $(n).closest('[data-org-type=meat]').length
'\n\n'
else '\n'
cancelAndReselect = (event, selection, oldRange, currentRange)->
e.preventDefault()
root.modCancelled = true
if oldRange != currentRange
selectRange oldRange
null
getCodeContainer = (node)->
$(node).closest("[data-org-src]")[0] || $(node).find("[data-org-src]")[0]
needsNewline = (el)->
if !el then false
else if el.nodeType == 3 then needsNewline el.parentNode
else el.nodeType == 1 && $(el).is('[data-newline]')
bsWillDestroyParent = (r)->
if r.startContainer.nodeType == 3 && r.startOffset == 1 && r.startContainer.data.match /^.\n?$/
getOrgText(r.startContainer.parentNode) == r.startContainer.data
else false
allowEvents = true
executeSource = (parent, node, env, cont, skipTests)->
if typeof env == 'function' then [env, cont, skipTests] = [null, env, cont]
doc = topNode node
[srcNode, text] = getNodeSource node
if srcNode
createResults srcNode
if text.trim().length
lang = getNodeLang node
orgEnv(parent, srcNode).executeText text.trim(), propsFor(srcNode), (env)->
cont? env
if !skipTests then runAutotests doc
else
if r = $(srcNode).find('[data-results-content]').length then clearResults srcNode
cont?()
fancyExecuteDef = (node, cont)->
doc = topNode node
executeDef node, ->
cont?()
runAutotests doc
runAutotests = (doc)->
for n in $(doc).find("[data-org-results='autotest']").add($(doc).find("[data-org-update~='any']"))
runTest doc, n
runTest = (doc, node)-> executeSource doc, node, (if $(node).is("[data-org-results='autotest']") then (-> checkTestResults node)), true
checkTestResults = (node)->
node.setAttribute 'data-org-test', (if node.getAttribute('data-org-expected') == $(node).find('[data-results-content]').text() then 'pass' else 'fail')
processResults = (str, node, skipText)->
if !(node.hasAttribute 'data-no-results')
if resultsNode = $(node).find('[data-results-display]')[0]
if !skipText
$(node).find('[data-results-content]')[0]?.textContent += str
edited node
classes = 'resultsline'
if theme != null then classes = theme + ' ' + classes
if $("body").hasClass 'bar_collapse' then classes += ' bar_collapse'
for line in splitLines str
if line.match /^: / then resultsNode.innerHTML += "<div class='#{classes}'>#{unescapeString line.substring(2)}</div>"
else console.log str
charCodes =
"b": '\b'
"f": '\f'
"n": '\n'
"r": '\r'
"t": '\t'
"v": '\v'
"'": '\''
"\"": '\"'
"\\": '\\'
unescapeString = (str)-> str.replace /\\./g, (str)-> charCodes[str[1]] || str
redrawIssue = (issue)->
issueName = issue.leisureName
if (name = $("[data-org-comments='#{issueName}']")).length
count = issue.comments.length + 1
button = $("[data-org-codeblock='#{issueName}'] button.comment-button")
if button.attr('data-org-commentcount') != count
button.attr 'data-org-commentcount', count
button.addClass 'new-comments'
setShadowHtml button.find('span')[0], count
setShadowHtml name[0].firstChild, "<div class='#{theme ? ''}'>#{commentHtml issue, 'main'}#{(commentHtml c, 'added' for c in issue.comments).join ''}#{newCommentBox issueName, $(name[0].parentNode).find('.codeblock').attr 'id'}</div>"
commentHtml = (comment, type)->
"<div class='commentbox'><img src='http://gravatar.com/avatar/#{comment.user.gravatar_id}?s=48'><div class='#{type}'>#{comment.body}</div></div>"
newCommentBox = (name, codeId)->
"<div><textarea pseudo='x-new-comment'></textarea><br><button class='add_comment' onclick='Leisure.addComment(\"#{name}\", event)'>Add Comment</button></div>"
colonify = (str)-> ': ' + (str.replace /[\n\\]/g, (c)-> if c == '\n' then '\\n' else '\\\\') + '\n'
clearResults = (node)->
$(node).find('[data-results-display]').html ''
$(node).find('[data-results-content]').html ''
# like orgSupport's orgEnv, but wrap the leading ': ' in hidden spans
orgEnv = (parent, node)->
if id = $(node).closest('[data-shared]')[0]?.id
r = -> $("##{id}")[0]
env = if r?() && !r().hasAttribute 'data-no-results'
pendingResults = ''
__proto__: defaultEnv
readFile: (filename, cont)-> window.setTimeout (->$.get filename, (data)-> cont false, data), 1
write: (str)-> pendingResults += colonify String str
clear: ->
pendingResults = ''
clearResults r()
newCodeContent: (name, con)-> console.log "NEW CODE CONTENT: #{name}, #{con}"
finishedComputation: ->
clearResults r()
processResults pendingResults, r()
else
__proto__: defaultEnv
readFile: (filename, cont)-> window.setTimeout (->$.get filename, (data)-> cont false, data), 1
write: (str)-> console.log colonify String str
newCodeContent: (name, con)-> console.log "NEW CODE CONTENT: #{name}, #{con}"
finishedComputation: ->
installEnvLang node, env
et = env.executeText
env.executeText = (text, props, cont)->
et.call this, text, props, ->
env.finishedComputation()
cont? env
env
#################
# Value sliders
#################
hideSlider = (numberSpan)-> replaceRelatedPresenter numberSpan, emptyPresenter
showSliderButton = (parent, numberSpan, slideFunc)->
if hideSlider numberSpan then return
inside = false
sliding = false
d = $("<div style='z-index: 1; position: absolute; width: 200px; background: white; border: solid green 1px' slider contentEditable='false'></div>")[0]
d.style.top = "#{numberSpan.offsetTop + numberSpan.offsetHeight + 5}px"
d.style.minTop = '0px'
d.style.left = "#{Math.max(0, numberSpan.offsetLeft + numberSpan.offsetWidth/2 - 100)}px"
d.addEventListener 'mouseover', (e)->
if !inside then inside = true
d.addEventListener 'mouseout', (e)->
if e.toElement != d && !d.contains e.toElement
inside = false
if !sliding then hideSlider numberSpan
value = Number getOrgText numberSpan
min = if value < 0 then value * 2 else value / 2
max = if value == 0 then 10 else value * 2
sl = $(d).slider
animate: 'fast'
start: ->
sliding = true
allowEvents = false
true
stop: (event, ui)->
setMinMax sl
allowEvents = true
sliding = false
if !inside then hideSlider numberSpan
slide: slideFunc numberSpan
value: value
numberSpan.parentNode.insertBefore d, numberSpan
setMinMax sl, value
replacePresenter
numberSpan: numberSpan
hide: ->
d.remove()
isRelated: (node)-> (isOrContains d, node) || (isOrContains numberSpan, node)
d.focus()
psgn = (x)-> if x < 0 then -1 else 1
setMinMax = (sl, value)->
value = value || sl.slider("value")
min = 0
max = if 1 <= Math.abs(value) < 50 or value == 0 then 100 * psgn(value) else value * 2
step = (max - min) / 100
if Math.round(value) == value
step = Math.round(step)
step = Math.max(1, step - step % (max - min))
sl.slider "option", "min", min
sl.slider "option", "max", max
sl.slider "option", "step", step
getSlides = (parent)->
showHidden = $(document.body).is('.show-hidden')
$(parent ? '[maindoc]').find('.slideholder').filter (i, el)->
slides = $(el).find("[data-org-headline='1']")
if !showHidden then slides = slides.not('[data-property-hidden="true"]')
slides.length > 0
setCurrentSlide = (element, noscroll)->
element = $(element).closest '.slideholder'
for node in $('.currentSlide')
if node.shadowRoot then $(node).shadow().removeClass 'currentSlide'
$('.currentSlide').removeClass 'currentSlide'
element.addClass 'currentSlide'
if element.is('.firstSlide') then $("body").addClass 'firstSlide' else $("body").removeClass 'firstSlide'
if element.is('.lastSlide') then $("body").addClass 'lastSlide' else $("body").removeClass 'lastSlide'
# this is needed until there is support for :host (and/or ^ & ^^)
$(element).shadow().addClass 'currentSlide'
Leisure.actualSelectionUpdate()
if !noscroll then window.scrollTo 0, 0
firstSlide = -> setCurrentSlide getSlides().first()
lastSlide = -> setCurrentSlide getSlides().last()
slideIndex = (slides)->
slides = slides || getSlides()
slides.index slides.filter('.currentSlide').first()
nextSlide = ->
slides = getSlides()
if (i = slideIndex slides) > -1
setCurrentSlide slides[Math.min(i + 1, slides.length - 1)]
prevSlide = ->
slides = getSlides()
i = slideIndex slides
setCurrentSlide slides[Math.max(i - 1, 0)]
slideParent = (node)-> $(node).closest("[data-org-headline='1']")[0]
documentTop = (node)->
top = 0
while node
if node.tagName
top = top + node.offsetTop
node = node.offsetParent
else node = node.parentNode
top
slideBindings =
'PAGEUP': (e, parent, r)->
e.preventDefault()
prevSlide()
false
'PAGEDOWN': (e, parent, r)->
e.preventDefault()
nextSlide()
false
'S-PAGEUP': (e, parent, r)->
e.preventDefault()
firstSlide()
false
'S-PAGEDOWN': (e, parent, r)->
e.preventDefault()
lastSlide()
false
'C-PAGEUP': (e, parent, r)->
e.preventDefault()
firstSlide()
false
'C-PAGEDOWN': (e, parent, r)->
e.preventDefault()
lastSlide()
false
slideBindings.__proto__ = defaultBindings
toggleSlides = ->
slideMode = !slideMode
applySlides()
applySlides = ->
$('#prevSlide:not(.bound)').addClass('bound').bind('click', prevSlide);
$('#nextSlide:not(.bound)').addClass('bound').bind('click', nextSlide);
$('body').removeClass 'firstSlide'
$('body').removeClass 'lastSlide'
$('.firstSlide').removeClass 'firstSlide'
$('.lastSlide').removeClass 'lastSlide'
if slideMode
fancyOrg.bindings = slideBindings
s = getSlides()
s.first().addClass 'firstSlide'
s.last().addClass 'lastSlide'
#restorePosition null, ->
$('[data-org-html]').addClass 'slideHtml'
$('body').addClass 'slides'
firstSlide()
else
fancyOrg.bindings = defaultBindings
$('body').removeClass 'slides'
$('[data-org-html]').removeClass 'slideHtml'
theme = null
setTheme = (str)->
el = $('[data-shadowholder]').shadow().add('body')
if theme && theme != str then el.removeClass theme
theme = str
if str then el.addClass str
for t in $("style.theme")
$(t).prop 'disabled', true
$("style#" + theme).removeProp 'disabled'
dd = $("#themeSelect")
if dd then dd.val theme
define 'setTheme', (str)->
makeSyncMonad (env, cont)->
if str != theme then setTheme rz str
cont rz L_true
define 'toggleLeisureBar', makeSyncMonad (env, cont)->
console.log new Error "TOGGLE LEISURE BAR"
root.toggleLeisureBar()
cont rz L_true
define 'toggleSlides', makeSyncMonad (env, cont)->
toggleSlides()
cont rz L_true
slideOffset = (slide)->
if slide
a = []
a.push $("[data-org-headline='1']")...
a.indexOf slide ? $('.currentSlide')[0]
else -1
codeHolder = (el)-> if el?.getAttribute 'data-shared' then el else el?.parentElement
fixupViews = (target)->
if Leisure.noViewUpdate then return
if target
yn = 'data-yaml-name'
ynA = "[#{yn}]"
vl = 'data-view-link'
vlA = "[#{vl}]"
rendered = {}
for dataEl in $(target).add($(target).find(ynA)).filter(ynA)
rendered[$(dataEl).attr yn] = true
renderView dataEl
for link in $(target).add($(target).find(vlA)).filter(vlA)
dataName = $(link).attr vl
if !rendered[dataName] && data = getBlockNamed dataName
renderLink link, data
else
for dataEl in $('[data-yaml-name]')
renderView dataEl
for html in $('[data-html-view]')
renderHtmlView html
renderHtmlView = (html, data)->
if !html.leisureRendered && (txt = $(html).find("[data-content]").text()) && output = $(html).find('[data-org-html]')
if !data && name = html.getAttribute 'data-html-view' then data = getDataNamed name
if data && txt
try
comp = Handlebars.compile txt
html.leisureRendered = true
catch err
console.log err.stack
return
appendAndActivate output, nonOrg comp data.yaml
# el could be a parent fragment, a shared source block, or a source block in a fragment
renderView = (el, name)->
holder = codeHolder el
id = holder.id
data = getBlock id
if data?.yaml?.type
yn = 'data-yaml-name'
renderData data, $(holder).add($(holder).find("[#{yn}]")).filter("[#{yn}]").attr yn
else if name = name || el.getAttribute "data-yaml-name"
for html in $("[data-html-view='#{name}']")
renderHtmlView html, data
renderData = (data, linkName)->
if type = data?.yaml?.type
links = if name then $("[data-view-link='#{linkName}'][data-view-name='#{name}']") else $("[data-view-link='#{linkName}']")
id = data._id
links.attr 'data-view-id', id
try
oldChunk = Leisure.currentViewChunk
Leisure.currentViewChunk = data
for node in links
renderLink node, data
finally
Leisure.currentViewChunk = oldChunk
noRenderWhile = (links, func)->
addChangeContextWhile _.merge({}, root.changeContext.blockViews ? {}, blockViews: links), func
renderLink = (node, data)->
if node.lastRendered == getRenderCount() then return
node.lastRendered = getRenderCount()
if isPlainEditing(node) || root.changeContext.blockViews?.is(node) || root.changeContext.blockViews?.is($(node).children().filter('[data-view]')) then return
if name = node.getAttribute 'data-view-name'
viewKey = <KEY>
descriptor = "#{data._id}/#{name}"
else
viewKey = data.<KEY>
descriptor = data._id
if root.viewTypeData[viewKey] && markup = viewMarkup[viewKey]
markup data.yaml, $(node), false, data
else clearView node
$(node)
.attr 'data-view-descriptor', descriptor
.attr 'data-view-key', viewKey
.attr 'data-view-id', data._id
updateIndexViews = (index)->
for view in $("[data-org-index~='#{index}']").closest("[data-view]")
type = $(view).attr 'data-view-type'
if block = getBlock $(view).attr 'data-view-block'
viewMarkup[type] block.yaml, $(view), false, block, true, $(view).closest("[data-view-link]")
updateViews = (id, allowInplaceUpdate)->
if block = getBlock id
if block.language?.toLowerCase() == 'css'
$("##{id} style").html codeString block
else if allowInplaceUpdate
updateViewsInPlace block
else
for link in $("[data-view-ids~='#{id}']")
if !root.changeContext.blockViews?.is(link)
for view in $(link).find("[data-view-block='#{id}']")
if !root.changeContext.blockViews?.is(view)
type = $(view).attr 'data-view-type'
viewMarkup[type] block.yaml, $(view), false, block, true, link
updateViewsInPlace = (block)->
for view in $("[data-view-block='#{block._id}']")
type = $(view).attr 'data-view-type'
viewMarkup[type] block.yaml, $(view), false, block, true, $(view).closest("[data-view-link]")
viewBlock = (el)->
if id = $(el).closest('[data-view-block]').attr('data-view-block')
getBlock id
Leisure.bindWidgets = bindWidgets = (parent)->
link = Templating.currentViewLink
for input in $(parent).find 'input[data-value]'
do (input)->
input.setAttribute 'data-input-number', ++Templating.currentInputCount
blockParent = $(input).closest '[data-view-block]'
field = input.getAttribute 'data-value'
input.value = viewBlock(input)?.yaml?[field] ? ''
nextButton = input.getAttribute 'button'
input.onkeyup = (e)->
block = viewBlock(input)
data = block.yaml
setField data, field, input.value
noRenderWhile $(link), -> setData block._id, data
if nextButton && e.keyCode == 13
e.preventDefault()
$(rootNode(input).firstChild).find("##{nextButton}").click()
setField = (data, field, value)->
data[field] = if typeof value == 'number' then value
else if typeof value == 'string'
n = Number value
if String(n) == value.trim() then n
else value
else value
Handlebars.registerHelper 'values', (items..., options)-> items
Handlebars.registerHelper 'view', (item, name, options)->
if !options
options = name
name = null
data = if typeof item == 'string'
block = getBlock(item) || getBlockNamed(item)
block?.yaml
else if item?.yaml && item._id
block = item
item.yaml
else
block = null
item
if data?.type
descriptor = if name then "#{data.type}/#{name}" else "#{data.type}"
viewMarkup[descriptor]?(data, null, false, block) || ''
else ''
Handlebars.registerHelper 'deref', (item)->
if typeof item == 'string'
block = getBlockNamed item
block?.yaml
else if item.yaml && item._id
block = item
item.yaml
else
block = null
item
Handlebars.registerHelper 'find', (index, options)->
ret = "<span data-org-index='#{index}'></span>"
indexedCursor(root.currentDocument, index)?.forEach (data)-> if data then ret += options.fn data
ret
addViewId = ->
if Templating.currentViewData._id?
ids = {}
for id in Templating.currentViewLink.getAttribute('data-view-id').split ' '
ids[id] = true
ids[Templating.currentViewData._id] = true
result = []
for k of ids
result.push k
Templating.currentViewLink.setAttribute 'data-view-id', result.join ' '
changeInputText = (field, id)->
console.log "CHANGE DATA"
isHidden = (target)->
if target && !$(document.body).hasClass('show-hidden')
data = if isNode target then target.id else target
root.currentDocument.leisure.parentCache.isHidden data
isHiddenBlock = (block)->
if !$(document.body).hasClass('show-hidden')
root.currentDocument.leisure.parentCache.isHidden block
fancyOrg =
__proto__: orgNotebook
name: 'fancy'
opposite: plainOrg
markupOrg: markupOrg
markupOrgWithNode: markupOrgWithNode
bindContent: bindContent
isHiddenBlock: isHiddenBlock
reparse: (parent, text, target)->
if isHidden target then return
if isPlainEditing target
t = $(plainOrg.reparse parent, text, target)
if t.is("[data-org-headline='1']")
t.attr 'data-edit-mode', 'plain'
t.attr 'data-org-note', t.attr('data-property-note') || 'main'
createEditToggleButton t
@newNode t
fixupHtml t
else orgNotebook.reparse.apply this, arguments
installOrgDOM: (parent, orgNode, orgText, target)->
@parent = parent
restorePosition parent, =>
if !target
parent.setAttribute 'class', 'org-fancy'
parent.setAttribute 'maindoc', ''
hadTarget = target
target = orgNotebook.installOrgDOM parent, orgNode, orgText, target
fixupHtml target || parent, null
@newNode target
if !hadTarget
@applyShowHidden()
setTimeout (=>
redrawAllIssues()
), 1
$(document).tooltip()
newNode: (target)->
setTheme theme
nextNoteId = 0
fixupViews target
createNoteShadows()
executeSource: (parent, node, cont)->
node = $(node).closest('[data-org-type="source"]')[0]
if isPlainEditing node then plainOrg.executeSource arguments...
else
restorePosition null, =>
code = getCodeContainer node
shouldRedrawAst = false
if presenter?.astCode == code
pos = getTextPosition code, node, 0
if presenter.astCodeContains? pos
shouldRedrawAst = true
presenter = emptyPresenter
executeSource.call this, parent, node, this, (env)->
env.finishedComputation()
recreateAstButtons code
if shouldRedrawAst then redrawAst code, pos
cont?()
executeDef: fancyExecuteDef
createResults: createResults
bindings: defaultBindings
redrawIssue: (i)-> redrawIssue i
leisureButton: ->
restorePosition @parent, ->
toggleSlides()
if slideMode then setTimeout (-> if !getSelection().focusNode then $('[maindoc]').focus()), 1
else swapMarkup()
emptySlide: (id, slidePosition)->
"#{slideStart()}<hr class='#{if slidePosition == 'only' then 'first' else slidePosition}'><div id='#{id}'></div>#{slideEnd()}"
insertEmptySlide: (id, prevId)->
slide = $(@emptySlide id)
if (prev = $("##{prevId}").closest('.slideholder')).length then prev.after slide
else $("[maindoc] [data-org-headline='0']").append slide
slide.find("##{id}")[0]
defineView: (id)-> # define a view from a data block
if type = viewIdTypes[id]
createTemplateRenderer type, root.viewTypeData[type], false, (data, target, block, update)->
el = if update then target else viewRoots(target)
if target
el
.addClass(theme)
.addClass($('body').hasClass('bar_collapse') && 'bar_collapse')
.css('white-space', 'normal')
.css('user-select', 'none')
.css('-webkit-user-select', 'none')
.css('-moz-user-select', 'none')
el
.find('button')
.button()
el
.find('[title]')
.tooltip()
bindAllWidgets el
for view in el.add el.find '[data-view-type]'
type = view.getAttribute 'data-view-type'
block = getBlock view.getAttribute 'data-view-block'
for cid in controllerDescriptorIds[type] ? []
codeContexts[cid]?.initializeView? view, block.yaml, block._id
dataType = type.match /([^/]*)\/?(.*)?/
restorePosition null, ->
vBlock = getBlock id
for dataId of dataTypeIds[vBlock?.codeAttributes?.defview] ? {}
if block = getBlock dataId
nodes = $("[data-view-ids~='#{dataId}']")
if block.codeName?
for node in $("[data-view-link='#{block.codeName}']")
renderLink node, block
deleteView: (type)->
delete viewMarkup[type]
for node in $("[data-view-key='#{type}']")
clearView node
applyShowHidden: ->
for node in $('.slideholder')
if $(node).find("[data-org-headline='1']").not("[data-property-hidden='true']").length == 0
$(node).addClass('hidden-slide')
applySlides()
checkSourceMod: checkSourceMod
updateBlock: (block, allowInplaceUpdate)->
lang = block.language?.toLowerCase()
attr = block.codeAttributes
restorePosition null, ->
if lang in ['css', 'yaml']
updateViews block._id, allowInplaceUpdate
if !allowInplaceUpdate && index = block.codeAttributes?.index
updateIndexViews index.split(' ')[0]
else if lang == 'html' && attr?.defview
incRenderCount()
root.orgApi.defineView block._id
updateIndexViews: -> restorePosition null, -> updateIndexViews
updateAllBlocks: ->
restorePosition null, ->
console.log "UPDATE ALL"
fixupViews '[maindoc]'
updateObserver: (observerId, observerContext, yaml, block, type)->
args = arguments
restorePosition null, =>
orgNotebook.updateObserver.apply this, args
if observerContext.block.codeAttributes.view
displayCodeView findOrIs($("##{observerContext.block._id}"), '[data-code-view]')[0]
removeSlide: (id)->
el = $("##{id}")
holder = el.closest ".slideholder"
el.remove()
if holder.children().not('hr').length == 0 then holder.remove()
binding = false
bindAllWidgets = (els)->
if !binding
binding = true
try
for node in els
bindWidgets node
finally
binding = false
plainOrg.opposite = fancyOrg
# called on installing DOM and also on new notes
fixupHtml = (parent, note)->
for node in findOrIs findOrIs($(parent), "[data-lang='leisure']"), '[data-org-src]'
recreateAstButtons node
createValueSliders node, leisureNumberSlider
for node in findOrIs findOrIs($(parent), "[data-lang]:not([data-lang='leisure'])"), '[data-org-src]'
createValueSliders node, regularNumberSlider
createNoteShadows()
createEditToggleButton parent
#if !note
# $(parent).find("button.create_note").remove()
# $("<button class='create_note' contenteditable='false'><i class='fa fa-file-text-o'></i></button>")
# .insertBefore(findOrIs($(parent), '[data-org-headline="1"]').find('.maincontent'))
# .children().find(':first-child')
# .click (e)->
# e.preventDefault()
# #root.currentMode.createNotes()
for node in findOrIs $(parent), "[data-code-view]"
displayCodeView node
for node in findOrIs $(parent), '[data-org-comments]'
setShadowHtml node.firstElementChild, newCommentBox node.getAttribute('data-org-comments'), $(node.parentNode).find('.codeblock').attr 'id'
if parent.getAttribute('data-org-headline') == '0' then processHiddenNodes()
processHiddenNodes = ->
for name, doc of importedDocs
mapDocumentBlocks doc, (block)->
if block.language?.toLowerCase() == 'css' && isCurrent block
id = block._id
if !$("##{id}").length
$("[maindoc]").append $("<div id='#{id}'><style name='css'></style></div>")
updateViews id
if !(document.body.classList.contains 'show-hidden') && (parentCache = root.currentDocument?.leisure.parentCache)
mapDocumentBlocks root.currentDocument, (block)->
if parentCache.isHidden block
if block.language?.toLowerCase() == 'css'
id = block._id
if !$("##{id}").length
$("[maindoc]").append $("<div id='#{id}'><style name='css'></style></div>")
updateViews id
findSlideId = (name)->
if sl = $('[data-org-headline-text="Chats"]').prop 'id' then sl
else
for slide of root.currentDocument.leisure.parentCache.hidden
block = getBlock slide
if block.text.substring(1).trim() == name then return block
slide = null
mapDocumentBlocks root.currentDocument, (block)->
if !slide && block.type == 'headline' && block.level == 1 && block.text.substring(1).trim() == name then slide = block
slide
displayCodeView = (node)->
if node
if block = getBlock $(node).closest('[data-shared]')[0]?.id
clearView node
viewMarkup[node.getAttribute 'data-code-view']? block, $(node), false, block
#$(node).shadow().attr 'data-view-id', block._id
viewFor = (node)-> $("##{$(node).closest('[data-view-block]').attr 'data-view-block'}")
getMainContent = (headline)->
headline = findOrIs headline, '[data-org-headline="1"]'
c = headline.children '.maincontent'
if c.length > 0
headline.not(c.parent()).add(c)
else headline
createEditToggleButton = (doc)->
for node in getMainContent $(doc)
id = if $(node).is '.maincontent' then node.parentElement.id else node.id
button = $("<button class='toggle_edit' contenteditable='false' onclick='Leisure.toggleEdit(\"#{id}\")'><i class='fa fa-glass'></i></button>")
if $(node).is '.maincontent'
if !$(node).prev().is('.toggle_edit') then button.insertBefore(node)
else if !$(node).children().first().is('.toggle_edit') then $(node).prepend button
isPlainEditing = (node)-> $(slideParent(node)).is "[data-edit-mode='plain']"
toggleEdit = (id)->
restorePosition null, ->
console.log "toggle edit", id
node = $("##{id}").closest("[data-org-headline='1']")
id = node[0].id
parent = parentForNode node
if node.attr('data-edit-mode') == 'plain'
node.attr 'data-edit-mode', 'fancy'
mode = fancyOrg
else
node.attr 'data-edit-mode', 'plain'
mode = plainOrg
mode.reparse parent, orgForNode(node[0]), node[0]
node = $("##{id}")
node.attr 'data-edit-mode', mode.name
if mode == plainOrg
node.attr 'data-org-note', node.attr('data-property-note') || 'main'
if mode == root.plainOrg then createEditToggleButton node
addStyles = (name, string)->
styles = $ "<style id='styles-#{name}'>\n#{string}\n</style>"
if (old = $("#styles-#{name}")).length then old.replaceWith styles
else $('body').append styles
root.fancyOrg = fancyOrg
root.toggleComment = toggleComment
root.addComment = addComment
root.recreateAstButtons = recreateAstButtons
root.setTheme = setTheme
root.createTestCase = createTestCase
root.executeCode = executeCode
root.toggleDynamic = toggleDynamic
root.getDocRange = getDocRange
root.restoreDocRange = restoreDocRange
root.getDocumentOffset = getDocumentOffset
root.viewMarkup = viewMarkup
root.noViewUpdate = false
root.topNode = topNode
root.rootNode = rootNode
root.codeHolder = codeHolder
root.getBlockNamed = getBlockNamed
root.viewBlock = viewBlock
root.toggleEdit = toggleEdit
root.toggleSlides = toggleSlides
root.getDeepestActiveElement = getDeepestActiveElement
root.addViewId = addViewId
root.getDataNamed = getDataNamed
root.setDataNamed = setDataNamed
root.findLinks = findLinks
root.findViews = findViews
root.viewFor = viewFor
root.setCodeAttributes = setCodeAttributes
root.clearCodeAttributes = clearCodeAttributes
root.addStyles = addStyles
root.noRenderWhile = noRenderWhile
root.fancyEnv = orgEnv
root.unescapeString = unescapeString
root.findSlideId = findSlideId
| true | {
Node,
resolve,
lazy,
defaultEnv,
} = root = module.exports = require '15-base'
rz = resolve
lz = lazy
{
TAB,
ENTER,
BS,
DEL,
} = require '21-browserSupport'
{
getType,
define,
makeSyncMonad,
} = require '16-ast'
{
runMonad,
isMonad,
escapePresentationHtml,
unescapePresentationHtml,
} = require '17-runtime'
{
parseOrgMode,
Headline,
headlineRE,
HL_TAGS,
Fragment,
Meat,
Keyword,
keywordRE,
KW_BOILERPLATE,
KW_NAME,
KW_INFO,
Source,
srcStartRE,
HTML,
Results,
AttrHtml,
resultsRE,
ListItem,
SimpleMarkup,
Link,
Drawer,
drawerRE,
parseTags,
matchLine,
} = require '11-org'
yaml = root.yaml
{
getCodeItems,
isCodeBlock,
isYaml,
lineCodeBlockType,
} = require '12-docOrg'
{
isCollapsed,
selectRange,
} = window.DOMCursor
{
handleDelete,
handleInsert,
domCursorForCaret,
textPositionForDomCursor,
SelectionDescriptor,
checkLast,
changeSavedSelectionOffset,
currentSelectionDescriptor,
parentForNode,
savePosition,
findOrIs,
orgNotebook,
parseOrgMode,
orgAttrs,
content,
contentSpan,
checkStart,
checkEnterReparse,
checkExtraNewline,
followingSpan,
currentLine,
checkSourceMod,
nextOrgId,
modifyingKey,
handleKeyup,
backspace,
getOrgParent,
getOrgType,
executeDef,
swapMarkup,
modifiers,
keyFuncs,
defaultBindings,
addKeyPress,
adjustSelection,
findKeyBinding,
setCurKeyBinding,
installEnvLang,
propsFor,
escapeAttr,
splitLines,
orgSrcAttrs,
baseEnv,
getNodeLang,
getNodeSource,
resultsType,
isDef,
getTextPosition,
findDomPosition,
nativeRange,
nodeBefore,
textNodeAfter,
textNodeBefore,
visibleTextNodeAfter,
getOrgText,
nonOrg,
errorDiv,
blockIdsForSelection,
PAGEUP,
PAGEDOWN,
HOME,
END,
markupData,
orgForNode,
plainOrg,
blockElementForNode,
executeSource,
redrawDoc,
isNode,
} = require '24-orgSupport'
{
redrawAllIssues,
createComment,
} = require '26-storage'
{
dataTypeIds,
edited,
pretty,
setData,
getBlock,
getBlockNamed,
getDataNamed,
setDataNamed,
addChangeContextWhile,
getSourceAttribute,
setSourceAttribute,
codeString,
controllerDescriptorIds,
codeContexts,
indexedCursor,
getRenderCount,
incRenderCount,
viewTypeData,
viewIdTypes,
mapDocumentBlocks,
importedDocs,
isCurrent,
} = require '23-collaborate'
{
nodeText,
createTemplateRenderer,
escapeHtml,
getDeepestActiveElement,
setShadowHtml,
clearView,
viewMarkup,
appendAndActivate,
viewRoots,
} = Templating # require '27-templating'
_ = require 'lodash.min'
fancyOrg = null
slideMode = false
lastOrgOffset = -1
curPos = -1
emptyPresenter =
hide: ->
isRelated: -> false
presenter = emptyPresenter
class FancySelectionDescriptor
constructor: (parent)->
sel = getSelection()
el = getDeepestActiveElement()
@parent = $(parent)[0] ? (slideParent sel.focusNode)
@focusNode = sel.focusNode
if inputNum = el?.getAttribute "data-input-number"
@linkParent = $(el).closest("[data-view-link]").attr("data-view-id")
@inputNum = inputNum
@inputSel = [el.selectionStart, el.selectionEnd]
@x = window.scrollX
@y = window.scrollY
if sel.type != 'None'
startNode = sel.getRangeAt(0).startContainer
[start, end, offset, note] = getDocRange()
@toString = -> "Selection(doc: #{start}, #{end})"
@restore = (delta, doc)->
if @linkParent && (input = $("[data-view-id='#{@linkParent}']").find("[data-input-number='#{@inputNum}']")).length > 0
input[0].focus()
[input[0].selectionStart, input[0].selectionEnd] = @inputSel
else
sel = getSelection()
if (sel.type != 'None' && sel.getRangeAt(0))?.startContainer != startNode
restoreDocRange doc, [start + delta, end + delta, offset, note]
window.scrollTo @x, @y
#[id, start, end, left, top] = pos = getSlidePosition sel.focusNode
#if id
# @toString = -> "Selection(doc: #{id}, start: #{start}, end: #{end}, left: #{left}, top: #{top})"
# @restore = -> setSlidePosition pos
#console.log "NEW SELECTION: #{this}"
restore: ->
toString: -> "Selection(none)"
isParentSelectionOf = (parent, child)-> parent?.parent?.contains child.parent
restoreStack = []
fancySaveSelection = root.saveSelection
root.restorePosition = restorePosition = (parent, block)->
savePosition fancySaveSelection, block
getSlidePosition = (node)->
if block = blockElementForNode node
{top, left} = block.getBoundingClientRect()
r = getSelection().getRangeAt 0
start = getTextPosition block, r.startContainer, r.startOffset
end = getTextPosition block, r.endContainer, r.endOffset
[block.id, start, end, left, top]
else []
setSlidePosition = ([id, start, end, left, top])->
block = $("##{id}")[0]
{curTop, curLeft} = block.getBoundingClientRect()
window.scrollBy curLeft - left, curTop - top
r1 = findDomPosition block, start, true
r2 = findDomPosition block, end, true
s = getSelection()
r = document.createRange()
r.startContainer = r1[0]
r.startOffset = r1[1]
r.endContainer = r2[0]
r.endOffset = r2[1]
selectRange r
# get a logical document range with an optional note
# [startPos, endPos, scrollOffset, noteId]
# if note is null, the positions are in the main doc
# otherwise, note is the id of a note
#
# Assumes the document has only two levels -- the main doc and notes
getDocRange = ->
s = getSelection()
r = s.getRangeAt 0
offset = getDocumentOffset r
if s.rangeCount == 1 && r.collapsed && r.startContainer.nodeType == 1 && shadow = r.startContainer.children[r.startOffset]?.shadowRoot
s = shadow.getSelection()
note = $(s.focusNode).closest('[data-note-origin]')?[0]
if note then [getTextPosition(note, s.anchorNode, s.anchorOffset), getTextPosition(note, s.extentNode, s.extentOffset), window.pageYOffset - offset, note.id]
else [null, null, null]
else
doc = topNode s.focusNode
[getTextPosition(doc, r.startContainer, r.startOffset), getTextPosition(doc, r.endContainer, r.endOffset), window.pageYOffset - offset]
restoreDocRange = (parent, [start, end, offset, noteId])->
if noteId
noteNode = $("[data-org-note-instances~='#{noteId}']")[0]
parent = $(noteNode).shadow().find("##{noteId}")[0]
[startContainer, startOffset] = findDomPosition parent, start, true
[endContainer, endOffset] = findDomPosition parent, Math.min(end, getOrgText(parent).length - 1), true
r = document.createRange()
r.setStart startContainer, startOffset
r.setEnd endContainer, endOffset
if noteId
offR = document.createRange()
offR.selectNode noteNode
window.scrollTo window.pageXOffset, offset + getDocumentOffset(offR)
s = noteNode.shadowRoot.getSelection()
else
window.scrollTo window.pageXOffset, offset + getDocumentOffset(r)
s = getSelection()
selectRange r
getDocumentOffset = (r)->
parent = parentForNode r.startContainer
c = (if r.startOffset == 0 then (textNodeBefore parent, r.startContainer) ? r.startContainer else r.startContainer)
while isCollapsed c
c = textNodeBefore parent, c
documentTop c
rootNode = (node)->
while node.parentNode
node = node.parentNode
node
topNode = (node)->
top = node
while node
if node.hasAttribute? 'data-org-headline' then top = node
node = node.parentNode
return top
replaceUnrelatedPresenter = (target, newPres)->
if result = !presenter || !presenter.isRelated target
replacePresenter newPres
result
replaceRelatedPresenter = (target, newPres)->
if result = (presenter && presenter.isRelated target)
replacePresenter newPres
result
replacePresenter = (pres)->
presenter?.hide()
presenter = pres || emptyPresenter
markupOrg = (text)->
[node, result] = markupOrgWithNode text
result
markupOrgWithNode = (text, note, replace)->
nodes = {}
if typeof text == 'string'
# ensure trailing newline -- contenteditable doesn't like it, otherwise
if text[text.length - 1] != '\n' then text = text + '\n'
org = parseOrgMode text
if isNode text then org = text
if org
[org, markupNewNode org, null, null, note, replace]
else
console.log "Attempt to display uknown object type: ", text
throw new Error "Attempt to display unknown type of object: #{text}"
markupNewNode = (org, middleOfLine, delay, note, replace)->
lastOrgOffset = -1
markupNode org, middleOfLine, delay, note, replace
getCodeAttribute = (node, attr)->
if (top = $(node).closest('[data-shared]'))[0]
getSourceAttribute top.find('[data-source-lead]').text(), attr
setCodeAttributes = (node, attrs...)->
if (top = $(node).closest('[data-shared]'))[0]
lead = top.find('[data-source-lead]')
oldTxt = txt = lead.text()
for [k, v] in L(attrs).chunk(2).toArray()
txt = setSourceAttribute txt, k, v
if txt != oldTxt
lead.text escapeHtml txt
edited top[0], true
clearCodeAttributes = (node, attrs...)->
if (top = $(node).closest('[data-shared]'))[0]
lead = top.find('[data-source-lead]')
oldTxt = txt = lead.text()
for attr in attrs
txt = setSourceAttribute txt, attr
if txt != oldTxt
lead.text escapeHtml txt
edited top[0], true
markupNode = (org, middleOfLine, delay, note, replace, inFragment)->
if (org.shared && isHidden org.nodeId) || org.offset <= lastOrgOffset then ''
else if org instanceof Results
pos = org.contentPos
text = org.text.substring pos
"<span #{orgAttrs org}><span data-org-type='text'>#{escapeHtml org.text.substring(0, pos)}</span>#{contentSpan text}"
else if org instanceof Fragment then markupFragment org, delay, note
else if org instanceof HTML then markupHtml org
else if org instanceof AttrHtml then markupAttr org
else if org instanceof Keyword
if org.name.match /^name$/i
intertext = ''
name = org
src = org.next
while src instanceof Meat && !(src instanceof Source)
intertext += src.text
src = src.next
if src instanceof Source then markupSource src, name, intertext, delay, inFragment
else defaultMarkup org
else if org instanceof Source then markupSource org, null, null, delay, inFragment
else defaultMarkup org
else if org instanceof Headline then markupHeadline org, delay, note, replace
else if org instanceof Drawer && org.name.toLowerCase() == 'properties' then markupProperties org, delay
else if org instanceof Drawer && org.name.toLowerCase() == 'data' then markupData org
else if org instanceof ListItem then markupListItem org, delay
else if org instanceof SimpleMarkup then markupSimple org
else if org instanceof Link then markupLink org
else if content(org.text).length then defaultMarkup org
else
tag = (if middleOfLine then 'span' else 'div')
"<#{tag} #{orgAttrs org}>#{meatText org.text}</#{tag}>"
meatText = (meat)->
result = if meat.match /^\n/
meat = meat.substring 1
"<span class='meat-break'>\n</span>"
else ""
paras = escapeHtml(meat).split /\n\n/
last = paras.pop()
result += _(paras).map((i)-> "<span class='meat-text#{checkBlankMeat i}'>#{i}\n</span>").join "<span class='meat-break'>\n</span>"
if result then result += "<span class='meat-break'>\n</span>"
if last
if last[last.length - 1] == '\n'
end = '\n'
last = last.substring 0, last.length - 1
if last then result += "<span class='meat-text#{checkBlankMeat last}'>#{last}</span>"
if end then result += "<span class='hidden'>\n</span><span data-nonorg contenteditable='false'>\n</span>"
result
checkBlankMeat = (hunk)-> if hunk in ['', '\n'] then " blank" else ""
isLeisure = (org)-> org instanceof Source && org.getLanguage().toLowerCase() == 'leisure'
isExecutable = (org)->
org instanceof Source && (org.getLanguage() in ['javascript', 'leisure'])
markupFragment = (org, delay, note)->
{first, name, source, last} = getCodeItems org.children[0]
if source
if first == name then first = first.next
if first in [org.children[0], org.children[1]] && !last.next
prelude = ''
while first != source
prelude += first.allText()
first = first.next
return "<span #{orgAttrs org}#{blockForLeisure source}>#{markupSource source, name, prelude, delay, true}</span>"
"<span #{orgAttrs org}>#{(markupNode child, false, delay, note, false, true for child in org.children).join ''}</span>"
blockForLeisure = (source)->
if source.getLanguage() == 'leisure' then " class='inline'" else ''
markupProperties = (org, delay)->"<span data-note-location class='hidden'>#{escapeHtml org.text}</span>"
lastAttr = null
markupAttr = (org)->
lastAttr = org
"<span class='hidden'>#{org.text}</span>"
markupLink = (org)->
if leisureMatch = org.isLeisure()
viewName = if leisureMatch[2] then " data-view-name='#{leisureMatch[2]}'" else ''
"<span data-view-link='#{leisureMatch[1]}'#{viewName}><span class='hidden'>#{org.allText()}</span></span>"
else if org.isImage()
title = (if desc = org.descriptionText() then " title='#{escapeAttr desc}'" else "")
"<span><img src='#{escapeAttr org.path}'#{title}><span class='hidden'>#{escapeHtml org.allText()}</span></span>"
else
guts = ''
for c in org.children
guts += markupNode c, true
if !guts then "<span class='hidden'>[[</span><a onclick='Leisure.followLink(event)' href='#{org.path}'>#{org.path}</a><span class='hidden'>]]</span>"
else "<span class='hidden'>[[#{org.path}][</span><a onclick='Leisure.followLink(event)' href='#{org.path}'>#{guts}</a><span class='hidden'>]]</span>"
root.followLink = (e)->
t = e.target
while t && t.nodeName != 'A'
t = t.parentNode
if t then window.open t.href, "links"
markupSimple = (org)->
guts = ''
for c in org.children
guts += markupNode c, true
text = switch org.markupType
when 'bold' then "<b>#{guts}</b>"
when 'italic' then "<i>#{guts}</i>"
when 'underline' then "<span style='text-decoration: underline'>#{guts}</span>"
when 'strikethrough' then "<span style='text-decoration: line-through'>#{guts}</span>"
when 'code' then "<code>#{guts}</code>"
when 'verbatim' then "<code>#{guts}</code>"
"<span class='hidden'>#{org.text[0]}</span>#{text}<span class='hidden'>#{org.text[0]}</span>"
hlStars = /^\*+ */
markupHeadline = (org, delay, note, replace)->
match = org.text.match headlineRE
start = "#{org.text.substring 0, org.text.length - (match?[HL_TAGS] ? '').length}".trim()
if org.text[org.text.length - 1] == '\n'
tags = escapeHtml org.text.substring start.length, org.text.length - 1
else
tags = escapeHtml org.text.substring start.length - 1
if starsM = start.match hlStars
stars = start.substring 0, starsM[0].length
start = start.substring stars.length
else stars = ''
properties = []
for k, v of org.properties
properties.push "#{k} = #{v}"
properties = if properties.length then "<span class='headline-properties' title='#{escapeAttr properties.join '<br>'}' data-nonorg='true'><i class='fa fa-wrench'></i></span>" else ''
optImport = if org.properties.import
imp = if root.currentDocument.demo then "tmp/#{importedDocs['demo/' + org.properties.import]._name}"
else new URI("x://h/#{root.currentDocument.leisure.name}", org.properties.import).path.substring 1
"<div class='import' data-nonorg='true' contenteditable='false'><span><a href='#load=/#{imp}' target='_blank'>#{org.properties.import}</a></span></div>"
else ''
editMode = if org.level == 1 then " data-edit-mode='fancy'" else ""
if org.level == 1 && !note && !org.properties?.note
if org.text.trim() != ''
"#{startNewSlide replace, org}<div #{orgAttrs org}#{editMode} data-org-headline-text='#{escapeAttr start}'#{noteAttrs org}><span class='maincontent'><span class='hidden'>#{stars}</span><span data-org-type='text'><div data-org-type='headline-content'><div class='textborder' contenteditable='false'></div><div class='headline-content'>#{escapeHtml start}<span class='tags'>#{properties}#{tags}</span></div></div><span class='meat-break'>\n</span></span>#{optImport}#{markupGuts org, checkStart start, org.text}</span></div>"
else "#{startNewSlide()}<div #{orgAttrs org}#{editMode}><span data-org-type='text'><span data-org-type='headline-content'><span class='hidden'>#{org.text}</span></span></span>#{optImport}#{markupGuts org, checkStart start, org.text}</div>"
else
slide = if org.text.trim() != ''
"<div #{orgAttrs org}#{editMode} data-org-headline-text='#{escapeAttr start}'#{noteAttrs org}><span class='hidden'>#{stars}</span><span data-org-type='text'><div data-org-type='headline-content'><div class='headline-content'>#{escapeHtml start}</div><span class='tags'>#{properties}#{tags}</span>\n</div></span>#{markupGuts org, checkStart start, org.text}</div>"
else "<div #{orgAttrs org}#{editMode}><span data-org-type='text'><span data-org-type='headline-content'><span class='hidden'>#{org.text}</span></span></span>#{markupGuts org, checkStart start, org.text}</div>"
floatize org, slide
#slide
#noteAttrs = (org)->
# if org.properties?.notes then "data-org-notes='#{org.properties.notes}'"
# else ''
nextNoteId = 0
noteAttrs = (org)->
if org.level != 1 then ''
else if org.properties?.note == 'sidebar' then " data-org-note='sidebar' data-org-noteid='#{nextNoteId++}'"
else if org.properties?.note?.match /^float / then " data-org-note='float' data-org-noteid='#{nextNoteId++}' data-org-floatval='#{org.properties.note}'"
else " data-org-note='main'"
floatize = (org, slide)->
if org.properties?.note?.match /^float /
"<div data-draggable data-float-holder='#{nextNoteId - 1}'><div data-resizable style='width: 600px; height: 600px; background: lightgray;'><h2 class='note_drag_handle' contenteditable='false'>YOUR NOTE</h2><div contenteditable='true'>#{slide}</div></div></div>"
else slide
updateNoteProperties = (span, index, txt) ->
old = getOrgText span
lines = old.split /\n/
s = lines[1].split /\s*,\s*/
if index != 0 then s[index] = txt else s[index] = ":notes: " + txt
lines[1] = s.join ', '
span.textContent = lines.join '\n'
saveNoteLocation = (target) ->
drag = target.closest("[data-draggable]")
resize = $(drag.children()[0])
orig_id = drag.attr 'data-note-origin'
orig = $("#" + orig_id)
span = orig.find("[data-note-location]")[0]
if span
index = drag.attr 'data-note-index'
#console.log "span: " + span + " => " + index
updateNoteProperties span, index, "float #{drag.css('top')} #{drag.css('left')} #{resize.width()}px #{resize.height()}px"
createNotes = (node)->
$(node).addClass 'herpderp'
for noteSpec in node.getAttribute('data-org-notes').split /\s*,\s*/
#console.log "NOTE FOR #{node.id}: #{noteSpec}"
noteId = "note-#{nextNoteId++}"
[org, html] = markupOrgWithNode getOrgText(node), true
newNote = $("<div class='sidebar_notes' data-note-origin='#{node.id}' id='#{noteId}' contenteditable='true'>#{html}</div>")[0]
switch (splitSpec = noteSpec.split(/\s+/))[0]
when 'sidebar'
if dest = $("[data-org-headline-text='#{splitSpec[1]}'] div.sidebar")[0]
if !dest.shadowRoot then setShadowHtml dest, "<div contenteditable='true'></div>"
$(dest).shadow().append newNote
when 'float'
parent = topNode node
dest = $(document.body).find('[data-org-floats]')[0]
if !dest then $(document.body).prepend dest = $("<div data-org-floats='true' contenteditable='true'></div>")[0]
inside = $('<div data-resizable style="width: 600px; height: 600px; background: black;"><h2 class="note_drag_handle" contenteditable="false">YOUR NOTE</h2><div></div></div>')
holder = $("<div data-draggable data-note-origin='#{node.id}' data-note-index='#{nextNoteId - 1}'></div>")
#console.log node
holder.append inside
dest.appendChild holder[0]
holder.draggable({handle: 'h2'})
inside.resizable()
holder.bind 'dragstop', (event) ->
saveNoteLocation $(event.target)
inside.bind 'resizestop', ->
saveNoteLocation $(event.target)
child = inside[0].children[1]
setShadowHtml child, "<div contenteditable='true' class='float_note'></div>"
$(child).shadow().append newNote
dest = child
orig = $("#" + node.id)[0]
[skip, top, left, width, height] = noteSpec.split /\s+/
holder.css({top: top, left: left})
inside.css({width: width, height: height})
saveNoteLocation holder
else continue
if dest
addWord dest, 'data-org-note-content', node.id
addWord dest, 'data-org-note-instances', noteId
fixupHtml newNote
addWord = (node, attr, value)->
vals = (node.getAttribute(attr) ? '').split ' '
vals = vals.filter (el) ->
el.length != 0
if !(value in vals) then vals.push value
node.setAttribute attr, vals.join ' '
editing = false
editedNote = (mainId, editedId)-> ->
if !editing
setTimeout (->
restorePosition $("##{editedId}")[0], ->
targets = $("##{mainId}")
main = targets[0]
for node in $("[data-org-note-content~='#{mainId}']")
targets = targets.add($(node).shadow().find "[data-note-origin='#{mainId}']")
origin = targets.filter "##{editedId}"
editing = true
try
t = targets.not("##{editedId}")
t.html origin.html()
for node in t
fixupHtml node, node != main
finally
setTimeout (-> editing = false), 1), 1
markupHtml = (org)->
if v = org.attributes()?.view
pre = org.text.substring 0, org.contentPos
post = org.text.substring org.contentPos + org.contentLength
"<span #{orgAttrs org} data-html-view='#{v}'><span contenteditable='false' data-org-html='true'></span><span class='hidden'>#{escapeHtml pre}</span><span class='hidden' data-content>#{escapeHtml org.content()}</span><span class='hidden'>#{escapeHtml post}</span><span></span></span>"
else
"<span #{orgAttrs org}><span contenteditable='false' data-nonorg='true' data-org-html='true'>#{nodeText(org.content())}</span><span class='hidden'>#{escapeHtml org.text}</span><span></span></span>"
chooseSourceMarkup = (org)->
if isYaml org then markupYaml
else if isExecutable org then markupLeisure
#else if org.lead()?.trim().toLowerCase() == 'html' then (org)-> defaultMarkup org, 'div', 'class', 'default-lang', 'data-lang', org.lead()?.trim()
else if org.info.match /^ *css\b/i then markupCSS
else markupCode
markupSource = (org, name, doctext, delay, inFragment)->
(chooseSourceMarkup org) org, name, doctext, delay, inFragment
findLinks = (name)->
if m = name.match /^([^/]*)\/(.*)$/ then $("[data-view-link='#{m[1]}'][data-view-name='#{m[2]}']") else $("[data-view-link='#{name}']")
findViews = (name)-> findLinks(name)
getSourceSegments = (name, org)->
{first, name, source, results, expected, last} = getCodeItems(name || org)
pos = source.contentPos
pre = ''
while first != source
pre += first.allText()
first = first.next
pre += source.text.substring 0, pos
post = ''
cur = source.next
while cur != last.next
post += cur.allText()
cur = cur.next
post = source.text.substring(pos + source.content.length) + post
[pre, source.content, post]
markupYaml = (org, name, doctext, delay, inFragment)->
[pre, src, post] = getSourceSegments name, org
{name, source, results, expected, last} = getCodeItems(name || org)
lastOrgOffset = last.offset
shared = (if org.shared then org else org.fragment)
yamlAttr = "data-lang='yaml'"
if shared
data = getBlock shared.nodeId
type = data.yaml?.type
if type
err = if !viewMarkup[type] then errorDiv "No value view type for data nodeId: #{shared.nodeId}" else ''
yamlAttr += " data-yaml-type='#{type}'"
err = ''
if name
n = escapeAttr name.info.trim()
yamlAttr += " data-org-codeblock='#{n}' data-yaml-name='#{n}'"
"<div #{orgAttrs source}#{yamlAttr}>#{err}<span class='Xhidden codeHeading'>#{escapeHtml pre}</span><span data-org-src data-contain>#{Highlighting.highlight 'yaml', source.content}</span><span class='Xhidden codeHeading'>#{escapeHtml post}</span></div>"
markupCode = (org, name, doctext, delay, inFragment)->
[pre, src, post] = getSourceSegments name, org
{name, source, results, expected, last} = getCodeItems(name || org)
lastOrgOffset = last.offset
lang = org.getLanguage() || ''
if name
n = escapeAttr name.info.trim()
addAttr = " data-org-codeblock='#{n}'"
else addAttr = ''
if (l = source.getLanguage()) #&& !inFragment
addAttr += " data-lang='#{l}' id='#{org.nodeId}'"
"<div class='default-lang' data-#{orgAttrs source}#{addAttr}><span class='Xhidden codeHeading'>#{escapeHtml pre}</span><span data-org-src data-contain>#{Highlighting.highlight lang, source.content}</span><span class='Xhidden codeHeading'>#{escapeHtml post}</span></div>"
markupCSS = (org, name, doctext, delay, inFragment)->
[pre, src, post] = getSourceSegments name, org
{name, source, results, expected, last} = getCodeItems(name || org)
lastOrgOffset = last.offset
lang = org.getLanguage() || ''
if name
n = escapeAttr name.info.trim()
addAttr = " data-org-codeblock='#{n}'"
styleName = " name='#{escapeAttr n}'"
else
addAttr = ''
styleName = ''
if (l = source.getLanguage()) #&& !inFragment
addAttr += " data-lang='#{l}' id='#{org.nodeId}'"
cssBlock = nonOrg("<style name='css'#{styleName}>#{src}</style>")[0].outerHTML
"<div class='default-lang' data-#{orgAttrs source}#{addAttr}><span class='Xhidden codeHeading'>#{escapeHtml pre}</span><span data-org-src data-contain>#{Highlighting.highlight lang, source.content}</span><span class='Xhidden codeHeading'>#{escapeHtml post}</span>#{cssBlock}</div>"
dragging = false
butLast = (str)-> str.substring 0, str.length - 1
markupLeisure = (org, name, doctext, delay, inFragment)->
attr = org.attributes()
lang = org.getLanguage() || ''
lastOrgOffset = org.offset
startHtml = "<div class='codeblock' contenteditable='false' data-lang='#{lang}' #{orgAttrs org}"
parts = parseSrcBlock org
if name then startHtml += " data-org-codeblock='#{escapeAttr name.info.trim()}'"
if view = attr?.view
return "#{startHtml} data-code-view='#{escapeAttr view.trim()}'>#{simpleLeisure org, doctext, attr, parts}</div>"
startHtml += "><div class='codeborder'></div>"
{lead, srcContent, trail, resText, intertext, resOrg} = parts
if name
codeName = "<div class='codename' contenteditable='true'><span class='hidden'>#{nameBoilerplate name}</span><div class='name'>#{escapeHtml butLast name.info}</div><span class='meat-break'>\n</span>#{meatText doctext}</div>"
else codeName = "<div class='codename' contenteditable='true'></div>"
wrapper = "<table class='codewrapper'><tr><td class='code-buttons'>"
if testCaseButton = toTestCaseButton org
wrapper += "<div>#{testCaseButton}</div>"
wrapper += "<div><button class='results-indicator' onclick='Leisure.executeCode(event)'><i class='fa fa-gear'></i><div></div></button></div>"
wrapper += "<div><button class='dyntoggle-button' onclick='Leisure.toggleDynamic(event)'><span class='dyntoggle'><i class='fa fa-link'></i><i class='fa fa-unlink'></i></span></button></div>"
if name then wrapper += "<div>#{commentButton name.info.trim()}</div>"
wrapper += "</td><td class='code-content'>"
wrapper += codeName
wrapper += "<div class='hidden' data-source-lead>#{escapeHtml lead}</div>"
wrapper += "<div #{orgSrcAttrs org} data-contain contenteditable='true'>#{escapeHtml srcContent}</div><span class='hidden' data-org-type='boundary'>#{escapeHtml trail}</span>"
wrapper += "<span class='hidden'>#{intertext}</span>" + htmlForResults resText, resOrg
wrapper += "</td></tr></table>"
top = name ? org
fluff = if top.prev instanceof Source || top.prev instanceof Results then "<div class='fluff' data-newline></div>" else ''
result = startHtml + wrapper + (if name then "</div>#{commentBlock name.info.trim()}" else "</div>")
inner = fluff + result
if view then inner += "</span>"
"<div></div>" + (if inFragment then inner
else '<div>' + inner + '</div>') + "<div></div>"
nameBoilerplate = (name)->
if nameM = name.text.match keywordRE then escapeHtml nameM[KW_BOILERPLATE]
parseSrcBlock = (org, name)->
result =
intertext: ''
lead: org.text.substring 0, org.contentPos
trail: org.text.substring org.contentPos + org.content.length
srcContent: org.content
if name
result.nameBoilerplate = nameBoilerplate name
result.name = name.info
node = org.next
intertext = ''
while node
if node instanceof Results
lastOrgOffset = node.offset
result.resBoilerplate = node.text.substring 0, node.contentPos
result.resText = node.text.substring node.contentPos
result.resOrg = node
result.intertext = intertext
break
else if node instanceof Drawer
if node.name.toLowerCase() == 'expected'
lastOrgOffset = node.offset
result.intertext = intertext + escapeHtml node.text
else break
else if node instanceof Headline || node instanceof Keyword
break
else intertext += escapeHtml node.text
node = node.next
result
editable = 'contenteditable="true"'
simpleLeisure = (org, doctext, attr, parts)->
html = sourceSpan 'name-boilerplate', parts.nameBoilerplate
html += sourceSpan 'name', parts.name
html += sourceSpan 'doctext', doctext, meatText
html += sourceSpan 'lead', parts.lead
html += "<div #{orgSrcAttrs org} data-contain data-source-content>#{escapeHtml parts.srcContent}</div>"
html += sourceSpan 'trail', parts.trail
html += sourceSpan 'intertext', parts.intertext
if parts.resText? then html += htmlForViewResults parts.resText, parts.resBoilerplate
html
sourceSpan = (type, content, process, attrs)->
if content
"<span#{if attrs then ' ' + attrs else ''} data-source-#{type}>#{(process ? escapeHtml) content}</span>"
else ''
updateChannels = (org)-> org instanceof Source && (org.info.match /:update *([^:]*)/)?[1]
testResult = (expected, actual)->
if actual == '' then 'unknown'
else if expected == actual then 'pass'
else 'fail'
root.toggleTestCase = (evt)->
node = codeBlockForNode evt.target
selectPrevious node
if node then replaceCodeBlock node, changeResultType getOrgText(node), (if node.getAttribute('data-org-results') == 'autotest' then 'dynamic' else 'static')
selectPrevious = (node)->
top = topNode node
pos = getTextPosition top, node, 0
r = nativeRange findDomPosition top, Math.max 0, pos - 1
selectRange r
replaceCodeBlock = (node, text)->
newNode = null
restorePosition null, ->
org = parseOrgMode text, 0, true
org.nodeId = $(node)[0].id
org.shared = 'code'
newNode = $(markupNewNode org, false, true)[0]
$(node).replaceWith(newNode)
edited newNode
fixupHtml blockElementForNode newNode
setTimeout (=>
nn = $(newNode)
(if nn.is('.codeblock') then nn else nn.find('.codeblock')).addClass 'ready'
for n in $(newNode).find('[data-org-comments]')
setShadowHtml n.firstElementChild, "<div class='#{theme ? ''}'>" + newCommentBox n.getAttribute('data-org-comments') + '</div>', codeBlockForNode(n.previousElementSibling).id
redrawAllIssues()), 1
newNode
markupListItem = (org, delay)->
if org.level == 0
start = !org.getPreviousListItem()
end = !org.getNextListItem()
else
start = (parent = org.getParent()) && parent == org.getPreviousListItem()
next = org.getNextListItem()
end = !next || next.level < org.level
"""#{if start then '<ul>' else ''}<li #{orgAttrs org} data-org-listlevel='#{
org.level
}'#{
if org.checked? then ' data-org-checked="' + org.checked + '"' else ''
}><span class='hidden'>#{
escapeHtml org.text.substring 0, org.contentOffset
}</span><span>#{markupListContents org.children}</span></li>#{
eatListItem org
}#{if end then '</ul>' else ''}"""
markupListContents = (children)-> (markupNode child, true for child in children).join ''
legalListContent = (org)->
org && (!(org instanceof Meat) || !org.inNewMeat()) && !(org instanceof Headline || org instanceof ListItem)
eatListItem = (org)->
item = org
result = ''
while legalListContent org = org.next
result += markupNode org
lastOrgOffset = Math.max(lastOrgOffset, org.offset)
result
unwrap = (node)->
parent = node.parentNode
if parent
while node.firstChild?
parent.insertBefore node.firstChild, node
parent.removeChild node
createValueSliders = (node, slideFunc)->
if !(top = $(node).closest('[data-org-src]')[0]) then return
$(node).find('.org-num').children().unwrap()
node.normalize()
createNextValueSliders node, slideFunc, node
chunkSize = 30
chunkDelay = 1000
createNextValueSliders = (node, slideFunc, cur)->
if (cur = visibleTextNodeAfter parentForNode(cur), cur) && node?.contains cur
createNextValueSlider node, slideFunc, cur
numPat = /[0-9][0-9.]*|\.[0-9.]+/
createNextValueSlider = (node, slideFunc, cur)->
setTimeout (->
done = false
if mnum = cur.data.match numPat
restorePosition top, ->
orig = cur
mid = cur.splitText mnum.index
cur = (if mid.length > mnum[0].length then mid.splitText mnum[0].length
else
done = true
mid)
numberSpan = $(mid).wrap("<span class='org-num'></span>").parent()[0]
do (n = numberSpan)-> n.onmousedown = (e)->
showSliderButton node, n, slideFunc
if !done
return createNextValueSlider node, slideFunc, cur
createNextValueSliders node, slideFunc, cur), 1
leisureNumberSlider = (numberSpan)->
orgParent = $(numberSpan).closest('[data-org-results]')[0]
orgType = orgParent.getAttribute 'data-org-results'
computing = false
pending = false
newValue = ->
computing = true
pending = false
doc = topNode orgParent
selection = new FancySelectionDescriptor doc
done = ->
selection.restore 0, doc
computing = false
if pending then newValue()
setTimeout (->
if orgType == 'dynamic' then root.orgApi.executeSource parent, numberSpan.parentNode, done
else if orgType == 'def' then root.orgApi.executeDef orgParent, done
else done()), 1
if orgType in ['dynamic', 'def']
(event, ui)->
numberSpan.innerHTML = String(ui.value)
if !computing then newValue()
else pending = true
else ->
regularNumberSlider = (numberSpan)->
Lodash.throttle ((event, ui)->
numberSpan.innerHTML = String(ui.value)
edited numberSpan), 20,
leading: true
trailing: true
lineStart = /^[^ ].*$/gm
recreateAstButtons = (node)->
if !(top = $(node).closest('.codeblock')[0]) then return
restorePosition top, ->
$(node).find('[data-ast-offset]').remove()
t = getOrgText node
while m = lineStart.exec t
if (tr = m[0].trim()) && tr[0] != '#'
[cur, offset] = findDomPosition node, m.index
if offset > 0 then cur = cur.splitText offset
div = document.createElement 'div'
div.setAttribute 'class', 'ast-button'
div.setAttribute 'contenteditable', 'false'
div.setAttribute 'data-ast-offset', m.index
do (d = div)-> d.onmousedown = (e)->
e.preventDefault()
e.stopPropagation()
showAst d
cur.parentNode.insertBefore div, cur
node.normalize()
newCodeContent = (name, content)->
parent = $("[data-org-codeblock='#{name}']")
if node = parent.find('[data-org-src]')[0]
node.innerHTML = escapeHtml content
recreateAstButtons node
createValueSliders node, leisureNumberSlider
define 'newCodeContent', (name)->(content)->
makeSyncMonad (env, cont)->
newCodeContent rz(name), rz(content)
cont rz L_true
isOrContains = (parent, node)->
n = parent.compareDocumentPosition(node)
(n & Element.DOCUMENT_POSITION_CONTAINED_BY) || n == 0
redrawAst = (code, pos)->
[button] = findDomPosition code, pos
while (button = nodeBefore button) != code && !$(button).is '.ast-button' then
console.log "redraw ast", button
showAst button, true
linePat = /\r?\n(?=[^ ]|$)/
showAst = (astButton, force)->
offset = Number(astButton.getAttribute 'data-ast-offset')
#if force || !replaceRelatedPresenter presenter.button, emptyPresenter
if force || !replaceRelatedPresenter astButton, emptyPresenter
$(astButton).children().remove()
text = getOrgText(astButton.parentNode).substring offset
text = text.substring 0, (if m = text.match linePat then m.index else text.length)
result = rz(L_newParseLine)(lz 0)(L_nil)(lz text)
runMonad result, baseEnv, (ast)->
if getType(ast) != 'parseErr'
console.log "SIMPLIFIED: #{show lz(runMonad rz(L_simplify) lz text)}"
try
astContent = nonOrg "<div class='#{theme ? ''} ast'>#{rz(L_wrappedTreeFor)(lz ast)(L_id)}</div>"
if theme then astContent.addClass theme
$(astButton).append astContent
replacePresenter
hide: -> astButton.firstChild?.remove()
isRelated: (node)-> isOrContains astButton, node
button: astButton
astCodeContains: (pos)-> 0 <= pos - offset < text.length
astCode: getCodeContainer astButton
catch err
console.log "Error showing AST: #{err.stack}"
show = (obj)-> rz(L_show)(lz obj)
commentButton = (name)->
"<button class='comment-button' onclick='Leisure.toggleComment(\"#{escapeAttr name}\", event)' contenteditable='false' data-org-commentcount='0'><i class='fa fa-comment'></i><span></span><div></div></button>"
toTestCaseButton = (org)->
if isDef org then ''
else "<button class='testcase-button' onclick='Leisure.createTestCase(event)' contenteditable='false' data-org-commentcount='0'><i class='fa fa-mail-reply'></i><div></div><span></span></button>"
codeBlockForNode = (node)->
node = $(node).closest '[data-org-type="source"]'
if node.is '[data-org-test]' then node[0] else node[0].parentNode
createTestCase = (evt)->
restorePosition null, ->
node = codeBlockForNode evt.target
selectPrevious node
attrs = ['view', 'testcase']
if !getCodeAttribute evt.target, 'observe' then attrs.push 'observe', '*'
setCodeAttributes evt.target, attrs...
node = $("##{node.id}")[0]
text = getOrgText node
rest = text
while match = rest.match drawerRE
if match[0].trim().toLowerCase() == ':expected:'
drawer = parseOrgMode(rest.substring(match.index), text.length - rest.length + match.index).children[0]
break
rest = rest.substring match.index + match[0].length
resultsText = (if drawer then text.substring drawer.offset + drawer.text.length else text)
if match = resultsRE.exec resultsText
results = parseOrgMode(resultsText.substring(match.index), text.length - resultsText.length + match.index).children[0]
if results.text.substring results.contentPos
newExpectation = ":EXPECTED:\n#{results.text.substring results.contentPos}:END:\n"
start = (if drawer then drawer else results).offset
end = (if drawer then drawer.offset + drawer.text.length else results.offset)
src = parseOrgMode(text).children[0]
pre = text.substring 0, start
#return replaceCodeBlock node, pre + newExpectation + text.substring end
return replaceCodeBlock $("##{node.id}"), pre + newExpectation + text.substring end
alert('You have to have results in order to make a test case')
newChangeResultType = (node, newType)->
org = src = orgForNode node
while src && !(src instanceof Source)
src = src.next
if src
if m = src.text.match /(:results *)([\w]*)/i
start = m.index + m[1].length
end = start + m[2].length
src.text = src.text.substring(0, start) + newType + src.text.substring(end)
else
pos = src.contentPos - 1
src.text = src.text.substring(0, pos) + " :results #{newType}" + src.text.substring pos
org
changeResultType = (text, newType)->
src = parseOrgMode(text).children[0]
while src && !(src instanceof Source)
src = src.next
if src
if m = src.text.match /(:results *)([\w]*)/i
start = src.offset + m.index + m[1].length
end = start + m[2].length
text.substring(0, start) + newType + text.substring(end)
else
pos = src.offset + src.contentPos - 1
text.substring(0, pos) + " :results #{newType}" + text.substring pos
else text
commentBlock = (name)->
"<div class='comments' data-org-comments='#{escapeAttr name}'><div></div></div>"
toggleComment = (name, evt)->
button = $(evt.target).closest('button')[0]
block = $("[data-org-comments='#{name}']")
console.log "comments clicked!"
if block.hasClass 'showcomments'
if !replaceRelatedPresenter button, null then block.removeClass 'showcomments'
else
block.addClass 'showcomments'
$("[data-org-codeblock='#{escapeAttr name}'] button.comment-button").removeClass 'new-comments'
replacePresenter
hide: -> block.removeClass 'showcomments'
isRelated: (target)->
button == $(target).closest('button')[0] || $(target).closest("[data-org-comments]").is(block)
addComment = (name, event)->
box = $(event.target.parentNode.querySelector('textarea'))
createComment name, box.val()
box.val ''
defaultMarkup = (org, tag, attrs...)->
tag = tag || 'span'
attrs = if attrs.length then " " + Lazy(attrs).chunk(2).map(([k, v])-> "#{k}='#{v}'").join(' ')
else ''
"<#{tag} #{orgAttrs org}#{attrs}>#{meatText org.text}</#{tag}>"
htmlForResults = (text, org)->
attr = if org?.shared then " id='#{org.nodeId}' data-shared='#{org.shared}'" else ''
bareResults = ''
for line in splitLines text ? ''
if line.match /^: / then bareResults += "<div class='resultsline'>#{unescapeString line.substring(2)}</div>"
"""
<div class='coderesults' data-org-type='results'#{attr}><span data-results-boilerplate class='hidden'>#+RESULTS:\n</span><div class='resultscontent'><div data-results-display data-nonorg>#{bareResults}</div><span data-results-content class='hidden'>#{escapeHtml text}</span></div></div>"""
htmlForViewResults = (text, boilerplate)->
html = sourceSpan 'results-boilerplate', boilerplate ? '#+RESULTS:\n'
html += "<div data-source-results class='resultscontent'><div data-results-display data-nonorg>"
for line in splitLines text
if line.match /^: / then html += "<div class='resultsline'>#{unescapeString line.substring(2)}</div>"
html += "</div><span data-results-content class='hidden'>#{text}</span></div>"
toggleDynamic = (event)->
block = codeBlockForNode event.target
bl = $(block)
resType = bl.attr('data-org-results') || bl.find('[data-org-results]').attr('data-org-results')
top = topNode block
newResType = if resType == 'dynamic' then 'static' else 'dynamic'
newNode = replaceCodeBlock block, changeResultType getOrgText(block), newResType
if newResType == 'dynamic' then executeSource top, $(newNode).find('[data-org-type="source"]')[0]
nonl = (txt)-> if txt[txt.length - 1] == '\n' then txt.substring 0, txt.length - 1 else txt
createResults = (srcNode)->
srcNode = $(srcNode).closest('.codeblock')
if created = (srcNode && !$(srcNode).find('[data-results-boilerplate]').length)
if $(srcNode).is('[data-code-view]')
$(srcNode).find('.codewrapper').append htmlForViewResults ''
else $(srcNode).find('.codewrapper').append htmlForResults ''
created
executeCode = (event)->
selectPrevious codeBlockForNode event.target
executeSource topNode(event.target), event.target, ->
#
# When to cancel line joins
# - BS at the start of a SRC block
# - DEL at the end of a SRC block
#
shouldCancelBS = (parent, r)-> atTextStart(r) && crossesHidden -1
atTextStart = (r)-> r.collapsed && (r.startContainer.nodeType == 1 || (r.startContainer.nodeType == 3 && r.startOffset == 0))
# returns:
# false if not at the end
# 1 if at the end
# 2 at an ending \n
atTextEnd = (r)-> r.collapsed && (r.startContainer.nodeType == 1 || (r.startContainer.nodeType == 3 &&
((r.startOffset == r.startContainer.length && 1) ||
(r.startOffset == r.startContainer.length - 1 &&
getOrgText(r.startContainer)[r.startOffset] == '\n' && 2))))
shouldCancelDEL = (parent, r)-> (atEnd = atTextEnd r) && crossesHidden atEnd + 1
matchLineAt = (parent, pos)->
text = getOrgText parent
start = text.substring(0, pos).lastIndexOf('\n')
end = text.indexOf '\n', start + 1
if end == -1 then end = text.length
matchLine text.substring start + 1, end
slideStart = (headline)-> "<div class='slideholder'#{headlineSlideProperties headline}>"
headlineSlideProperties = (headline)->
props = ''
if headline.level == 1
for k of headline?.properties ? {}
props += "data-slide-property-#{k}='#{headline.properties[k]}'"
if props then " " + props else ''
slideEnd = -> "</div>"
firstSlideFlag = false
startNewSlide = (replace, headline)->
if replace then ''
else if firstSlideFlag
firstSlideFlag = false
''
else "#{slideEnd()}#{slideStart headline}"
createNoteShadows = ->
for node in $('.slideholder')
setShadowHtml node, "<div class='page'><div class='border'></div><table class='pagecontent slideshadow'><tr class='slideshadowrow'><td class='slidemain'><content select='[data-org-note=\"main\"]'></content></td><td class='sidebarholder'><div class='sidebar'><div class='sidebarcontent'><content select='[data-org-note=\"sidebar\"]'></content></div></div></td></tr></table></div><content select='[data-org-note=\"skip\"],[data-float-holder]'></content>"
for node in $('[data-float-holder]')
holder = $(node)
inside = $(node.firstChild)
noteSpec = $(node).find('[data-org-floatval]').attr 'data-org-floatval'
holder.draggable handle: 'h2'
inside.resizable()
holder.bind 'dragstop', (event) -> saveNoteLocation $(event.target)
inside.bind 'resizestop', -> saveNoteLocation $(event.target)
[skip, top, left, width, height] = noteSpec.split /\s+/
window.setTimeout (->
holder.css top: top, left: left
inside.css width: width, height: height), 1
markupGuts = (org, start)->
if !org.children.length then ''
else
prev = if start then null else org
hline = 'first'
if org.level == 0 then firstSlideFlag = true
guts = ((for c in org.children
s = start
start = false
p = prev
prev = c
h = hline
if c instanceof Headline then hline = 'inner'
(hlineFor c, h) + markupNode(c, s)).join "") + (if org.level == 0 then "<hr class='last'>" else '')
if org.level == 0
"#{slideStart org.children[0]}#{guts}#{slideEnd()}"
else guts
hlineFor = (headline, hline)->
if !(headline instanceof Headline) || headline.level != 1 then ''
else "<hr class='#{hline}'>"
currentTextPosition = (parent, r)->
if curPos > -1 then curPos
else curPos = getTextPosition parent, r || getSelection().getRangeAt(0)
crossesHidden = (delta)->
r = getSelection().getRangeAt 0
!(0 <= r.startOffset < r.startContainer.length) && isCollapsed (if delta < 0 then textNodeBefore else textNodeAfter) parentForNode(r.startContainer), r.startContainer
bindContent = (div)->
div.addEventListener 'drop', (e)-> root.orgApi.handleDrop e
div.addEventListener 'mousedown', (e)->
if replaceUnrelatedPresenter e.target, emptyPresenter
setCurKeyBinding null
div.addEventListener 'keydown', handleKey div
div.addEventListener 'keyup', handleKeyup div
handleKey = (div)->(e)->
if !(e.target instanceof HTMLInputElement || e.target.getAttribute 'data-view-id')
root.modCancelled = false
curPos = -1
c = (e.charCode || e.keyCode || e.which)
if !addKeyPress e, c then return
s = getSelection()
r = s.rangeCount > 0 && s.getRangeAt(0)
root.currentBlockIds = blockIdsForSelection s, r
[bound, checkMod] = findKeyBinding e, div, r
if bound then root.modCancelled = !checkMod
else
root.modCancelled = false
if c == ENTER then handleInsert e, s, newLinesForNode r.startContainer
else if c == BS then fancyBackspace div, e, s, r
else if c == DEL then fancyDel div, e, s, r
else if modifyingKey c, e then handleInsert e, s
childIndex = (el)->
count = 0
while el = el.previousSibling
count++
count
newLinesForNode = (node)->
if $(node).closest('[data-shared]').attr('data-shared') in ['chunk','headline']
'\n\n'
else '\n'
whitespaceEnd = /(\n | )*(\n*)$/
fancyBackspace = (div, e, s, r)->
handleDelete e, s, false, (text, pos)->
if pos == 0 then false
else if $(s.anchorNode).closest('.code-content').length then true
else if text[pos - 1] in [' ', '\n']
fore = text.substring 0, pos
ws = (m = fore.match(whitespaceEnd))?[0] ? ''
nls = m?[2] ? ''
if nls.length > 3 then [pos - 2, pos]
else [pos - ws.length, pos]
else [pos - 1, pos]
isEmptyText = (text)-> text in ['\n', '\n\n']
fancyDel = (div, e, s, r)->
handleDelete e, s, true, (text, pos)->
if pos in [text.length, text.length - 1] then false
else if isEmptyText text then [0, '']
else if $(s.anchorNode).closest('.code-content').length then pos < text.length - 1
else if text[pos] != '\n' then [pos, pos + 1]
else if text[pos + 1] == '\n' then [pos, pos + 2]
else if text[pos - 1] == '\n' then [pos - 1, pos + 1]
else [pos, pos + 1]
beginsMeat = (s)->
n = s.anchorNode
s.anchorOffset == 0 &&
(isMeatText(n) || (n.nodeType == Node.TEXT_NODE && isMeatText n.parentNode))
endsMeat = (s)->
n = s.anchorNode
p = s.anchorOffset
(isMeatText(n) && n.textContent.match /^\s*\n/) ||
(n.nodeType == Node.TEXT_NODE && isMeatText(n.parentNode) && p == n.length - 1 && n.data[p] == '\n')
isMeatText = (n)-> n.nodeType == Node.ELEMENT_NODE && n.classList.contains 'meat-text'
isMeatBreak = (n)-> n.nodeType == Node.ELEMENT_NODE && n.classList.contains 'meat-break'
fancyCheckExtraNewline = (range, n, parent)->
if range.collapsed && n.nodeType == Node.TEXT_NODE && range.startOffset == n.length && getOrgText(n)[n.length - 1] != '\n' then checkLast n, parent
else if $(n).closest('[data-org-type=meat]').length
'\n\n'
else '\n'
cancelAndReselect = (event, selection, oldRange, currentRange)->
e.preventDefault()
root.modCancelled = true
if oldRange != currentRange
selectRange oldRange
null
getCodeContainer = (node)->
$(node).closest("[data-org-src]")[0] || $(node).find("[data-org-src]")[0]
needsNewline = (el)->
if !el then false
else if el.nodeType == 3 then needsNewline el.parentNode
else el.nodeType == 1 && $(el).is('[data-newline]')
bsWillDestroyParent = (r)->
if r.startContainer.nodeType == 3 && r.startOffset == 1 && r.startContainer.data.match /^.\n?$/
getOrgText(r.startContainer.parentNode) == r.startContainer.data
else false
allowEvents = true
executeSource = (parent, node, env, cont, skipTests)->
if typeof env == 'function' then [env, cont, skipTests] = [null, env, cont]
doc = topNode node
[srcNode, text] = getNodeSource node
if srcNode
createResults srcNode
if text.trim().length
lang = getNodeLang node
orgEnv(parent, srcNode).executeText text.trim(), propsFor(srcNode), (env)->
cont? env
if !skipTests then runAutotests doc
else
if r = $(srcNode).find('[data-results-content]').length then clearResults srcNode
cont?()
fancyExecuteDef = (node, cont)->
doc = topNode node
executeDef node, ->
cont?()
runAutotests doc
runAutotests = (doc)->
for n in $(doc).find("[data-org-results='autotest']").add($(doc).find("[data-org-update~='any']"))
runTest doc, n
runTest = (doc, node)-> executeSource doc, node, (if $(node).is("[data-org-results='autotest']") then (-> checkTestResults node)), true
checkTestResults = (node)->
node.setAttribute 'data-org-test', (if node.getAttribute('data-org-expected') == $(node).find('[data-results-content]').text() then 'pass' else 'fail')
processResults = (str, node, skipText)->
if !(node.hasAttribute 'data-no-results')
if resultsNode = $(node).find('[data-results-display]')[0]
if !skipText
$(node).find('[data-results-content]')[0]?.textContent += str
edited node
classes = 'resultsline'
if theme != null then classes = theme + ' ' + classes
if $("body").hasClass 'bar_collapse' then classes += ' bar_collapse'
for line in splitLines str
if line.match /^: / then resultsNode.innerHTML += "<div class='#{classes}'>#{unescapeString line.substring(2)}</div>"
else console.log str
charCodes =
"b": '\b'
"f": '\f'
"n": '\n'
"r": '\r'
"t": '\t'
"v": '\v'
"'": '\''
"\"": '\"'
"\\": '\\'
unescapeString = (str)-> str.replace /\\./g, (str)-> charCodes[str[1]] || str
redrawIssue = (issue)->
issueName = issue.leisureName
if (name = $("[data-org-comments='#{issueName}']")).length
count = issue.comments.length + 1
button = $("[data-org-codeblock='#{issueName}'] button.comment-button")
if button.attr('data-org-commentcount') != count
button.attr 'data-org-commentcount', count
button.addClass 'new-comments'
setShadowHtml button.find('span')[0], count
setShadowHtml name[0].firstChild, "<div class='#{theme ? ''}'>#{commentHtml issue, 'main'}#{(commentHtml c, 'added' for c in issue.comments).join ''}#{newCommentBox issueName, $(name[0].parentNode).find('.codeblock').attr 'id'}</div>"
commentHtml = (comment, type)->
"<div class='commentbox'><img src='http://gravatar.com/avatar/#{comment.user.gravatar_id}?s=48'><div class='#{type}'>#{comment.body}</div></div>"
newCommentBox = (name, codeId)->
"<div><textarea pseudo='x-new-comment'></textarea><br><button class='add_comment' onclick='Leisure.addComment(\"#{name}\", event)'>Add Comment</button></div>"
colonify = (str)-> ': ' + (str.replace /[\n\\]/g, (c)-> if c == '\n' then '\\n' else '\\\\') + '\n'
clearResults = (node)->
$(node).find('[data-results-display]').html ''
$(node).find('[data-results-content]').html ''
# like orgSupport's orgEnv, but wrap the leading ': ' in hidden spans
orgEnv = (parent, node)->
if id = $(node).closest('[data-shared]')[0]?.id
r = -> $("##{id}")[0]
env = if r?() && !r().hasAttribute 'data-no-results'
pendingResults = ''
__proto__: defaultEnv
readFile: (filename, cont)-> window.setTimeout (->$.get filename, (data)-> cont false, data), 1
write: (str)-> pendingResults += colonify String str
clear: ->
pendingResults = ''
clearResults r()
newCodeContent: (name, con)-> console.log "NEW CODE CONTENT: #{name}, #{con}"
finishedComputation: ->
clearResults r()
processResults pendingResults, r()
else
__proto__: defaultEnv
readFile: (filename, cont)-> window.setTimeout (->$.get filename, (data)-> cont false, data), 1
write: (str)-> console.log colonify String str
newCodeContent: (name, con)-> console.log "NEW CODE CONTENT: #{name}, #{con}"
finishedComputation: ->
installEnvLang node, env
et = env.executeText
env.executeText = (text, props, cont)->
et.call this, text, props, ->
env.finishedComputation()
cont? env
env
#################
# Value sliders
#################
hideSlider = (numberSpan)-> replaceRelatedPresenter numberSpan, emptyPresenter
showSliderButton = (parent, numberSpan, slideFunc)->
if hideSlider numberSpan then return
inside = false
sliding = false
d = $("<div style='z-index: 1; position: absolute; width: 200px; background: white; border: solid green 1px' slider contentEditable='false'></div>")[0]
d.style.top = "#{numberSpan.offsetTop + numberSpan.offsetHeight + 5}px"
d.style.minTop = '0px'
d.style.left = "#{Math.max(0, numberSpan.offsetLeft + numberSpan.offsetWidth/2 - 100)}px"
d.addEventListener 'mouseover', (e)->
if !inside then inside = true
d.addEventListener 'mouseout', (e)->
if e.toElement != d && !d.contains e.toElement
inside = false
if !sliding then hideSlider numberSpan
value = Number getOrgText numberSpan
min = if value < 0 then value * 2 else value / 2
max = if value == 0 then 10 else value * 2
sl = $(d).slider
animate: 'fast'
start: ->
sliding = true
allowEvents = false
true
stop: (event, ui)->
setMinMax sl
allowEvents = true
sliding = false
if !inside then hideSlider numberSpan
slide: slideFunc numberSpan
value: value
numberSpan.parentNode.insertBefore d, numberSpan
setMinMax sl, value
replacePresenter
numberSpan: numberSpan
hide: ->
d.remove()
isRelated: (node)-> (isOrContains d, node) || (isOrContains numberSpan, node)
d.focus()
psgn = (x)-> if x < 0 then -1 else 1
setMinMax = (sl, value)->
value = value || sl.slider("value")
min = 0
max = if 1 <= Math.abs(value) < 50 or value == 0 then 100 * psgn(value) else value * 2
step = (max - min) / 100
if Math.round(value) == value
step = Math.round(step)
step = Math.max(1, step - step % (max - min))
sl.slider "option", "min", min
sl.slider "option", "max", max
sl.slider "option", "step", step
getSlides = (parent)->
showHidden = $(document.body).is('.show-hidden')
$(parent ? '[maindoc]').find('.slideholder').filter (i, el)->
slides = $(el).find("[data-org-headline='1']")
if !showHidden then slides = slides.not('[data-property-hidden="true"]')
slides.length > 0
setCurrentSlide = (element, noscroll)->
element = $(element).closest '.slideholder'
for node in $('.currentSlide')
if node.shadowRoot then $(node).shadow().removeClass 'currentSlide'
$('.currentSlide').removeClass 'currentSlide'
element.addClass 'currentSlide'
if element.is('.firstSlide') then $("body").addClass 'firstSlide' else $("body").removeClass 'firstSlide'
if element.is('.lastSlide') then $("body").addClass 'lastSlide' else $("body").removeClass 'lastSlide'
# this is needed until there is support for :host (and/or ^ & ^^)
$(element).shadow().addClass 'currentSlide'
Leisure.actualSelectionUpdate()
if !noscroll then window.scrollTo 0, 0
firstSlide = -> setCurrentSlide getSlides().first()
lastSlide = -> setCurrentSlide getSlides().last()
slideIndex = (slides)->
slides = slides || getSlides()
slides.index slides.filter('.currentSlide').first()
nextSlide = ->
slides = getSlides()
if (i = slideIndex slides) > -1
setCurrentSlide slides[Math.min(i + 1, slides.length - 1)]
prevSlide = ->
slides = getSlides()
i = slideIndex slides
setCurrentSlide slides[Math.max(i - 1, 0)]
slideParent = (node)-> $(node).closest("[data-org-headline='1']")[0]
documentTop = (node)->
top = 0
while node
if node.tagName
top = top + node.offsetTop
node = node.offsetParent
else node = node.parentNode
top
slideBindings =
'PAGEUP': (e, parent, r)->
e.preventDefault()
prevSlide()
false
'PAGEDOWN': (e, parent, r)->
e.preventDefault()
nextSlide()
false
'S-PAGEUP': (e, parent, r)->
e.preventDefault()
firstSlide()
false
'S-PAGEDOWN': (e, parent, r)->
e.preventDefault()
lastSlide()
false
'C-PAGEUP': (e, parent, r)->
e.preventDefault()
firstSlide()
false
'C-PAGEDOWN': (e, parent, r)->
e.preventDefault()
lastSlide()
false
slideBindings.__proto__ = defaultBindings
toggleSlides = ->
slideMode = !slideMode
applySlides()
applySlides = ->
$('#prevSlide:not(.bound)').addClass('bound').bind('click', prevSlide);
$('#nextSlide:not(.bound)').addClass('bound').bind('click', nextSlide);
$('body').removeClass 'firstSlide'
$('body').removeClass 'lastSlide'
$('.firstSlide').removeClass 'firstSlide'
$('.lastSlide').removeClass 'lastSlide'
if slideMode
fancyOrg.bindings = slideBindings
s = getSlides()
s.first().addClass 'firstSlide'
s.last().addClass 'lastSlide'
#restorePosition null, ->
$('[data-org-html]').addClass 'slideHtml'
$('body').addClass 'slides'
firstSlide()
else
fancyOrg.bindings = defaultBindings
$('body').removeClass 'slides'
$('[data-org-html]').removeClass 'slideHtml'
theme = null
setTheme = (str)->
el = $('[data-shadowholder]').shadow().add('body')
if theme && theme != str then el.removeClass theme
theme = str
if str then el.addClass str
for t in $("style.theme")
$(t).prop 'disabled', true
$("style#" + theme).removeProp 'disabled'
dd = $("#themeSelect")
if dd then dd.val theme
define 'setTheme', (str)->
makeSyncMonad (env, cont)->
if str != theme then setTheme rz str
cont rz L_true
define 'toggleLeisureBar', makeSyncMonad (env, cont)->
console.log new Error "TOGGLE LEISURE BAR"
root.toggleLeisureBar()
cont rz L_true
define 'toggleSlides', makeSyncMonad (env, cont)->
toggleSlides()
cont rz L_true
slideOffset = (slide)->
if slide
a = []
a.push $("[data-org-headline='1']")...
a.indexOf slide ? $('.currentSlide')[0]
else -1
codeHolder = (el)-> if el?.getAttribute 'data-shared' then el else el?.parentElement
fixupViews = (target)->
if Leisure.noViewUpdate then return
if target
yn = 'data-yaml-name'
ynA = "[#{yn}]"
vl = 'data-view-link'
vlA = "[#{vl}]"
rendered = {}
for dataEl in $(target).add($(target).find(ynA)).filter(ynA)
rendered[$(dataEl).attr yn] = true
renderView dataEl
for link in $(target).add($(target).find(vlA)).filter(vlA)
dataName = $(link).attr vl
if !rendered[dataName] && data = getBlockNamed dataName
renderLink link, data
else
for dataEl in $('[data-yaml-name]')
renderView dataEl
for html in $('[data-html-view]')
renderHtmlView html
renderHtmlView = (html, data)->
if !html.leisureRendered && (txt = $(html).find("[data-content]").text()) && output = $(html).find('[data-org-html]')
if !data && name = html.getAttribute 'data-html-view' then data = getDataNamed name
if data && txt
try
comp = Handlebars.compile txt
html.leisureRendered = true
catch err
console.log err.stack
return
appendAndActivate output, nonOrg comp data.yaml
# el could be a parent fragment, a shared source block, or a source block in a fragment
renderView = (el, name)->
holder = codeHolder el
id = holder.id
data = getBlock id
if data?.yaml?.type
yn = 'data-yaml-name'
renderData data, $(holder).add($(holder).find("[#{yn}]")).filter("[#{yn}]").attr yn
else if name = name || el.getAttribute "data-yaml-name"
for html in $("[data-html-view='#{name}']")
renderHtmlView html, data
renderData = (data, linkName)->
if type = data?.yaml?.type
links = if name then $("[data-view-link='#{linkName}'][data-view-name='#{name}']") else $("[data-view-link='#{linkName}']")
id = data._id
links.attr 'data-view-id', id
try
oldChunk = Leisure.currentViewChunk
Leisure.currentViewChunk = data
for node in links
renderLink node, data
finally
Leisure.currentViewChunk = oldChunk
noRenderWhile = (links, func)->
addChangeContextWhile _.merge({}, root.changeContext.blockViews ? {}, blockViews: links), func
renderLink = (node, data)->
if node.lastRendered == getRenderCount() then return
node.lastRendered = getRenderCount()
if isPlainEditing(node) || root.changeContext.blockViews?.is(node) || root.changeContext.blockViews?.is($(node).children().filter('[data-view]')) then return
if name = node.getAttribute 'data-view-name'
viewKey = PI:KEY:<KEY>END_PI
descriptor = "#{data._id}/#{name}"
else
viewKey = data.PI:KEY:<KEY>END_PI
descriptor = data._id
if root.viewTypeData[viewKey] && markup = viewMarkup[viewKey]
markup data.yaml, $(node), false, data
else clearView node
$(node)
.attr 'data-view-descriptor', descriptor
.attr 'data-view-key', viewKey
.attr 'data-view-id', data._id
updateIndexViews = (index)->
for view in $("[data-org-index~='#{index}']").closest("[data-view]")
type = $(view).attr 'data-view-type'
if block = getBlock $(view).attr 'data-view-block'
viewMarkup[type] block.yaml, $(view), false, block, true, $(view).closest("[data-view-link]")
updateViews = (id, allowInplaceUpdate)->
if block = getBlock id
if block.language?.toLowerCase() == 'css'
$("##{id} style").html codeString block
else if allowInplaceUpdate
updateViewsInPlace block
else
for link in $("[data-view-ids~='#{id}']")
if !root.changeContext.blockViews?.is(link)
for view in $(link).find("[data-view-block='#{id}']")
if !root.changeContext.blockViews?.is(view)
type = $(view).attr 'data-view-type'
viewMarkup[type] block.yaml, $(view), false, block, true, link
updateViewsInPlace = (block)->
for view in $("[data-view-block='#{block._id}']")
type = $(view).attr 'data-view-type'
viewMarkup[type] block.yaml, $(view), false, block, true, $(view).closest("[data-view-link]")
viewBlock = (el)->
if id = $(el).closest('[data-view-block]').attr('data-view-block')
getBlock id
Leisure.bindWidgets = bindWidgets = (parent)->
link = Templating.currentViewLink
for input in $(parent).find 'input[data-value]'
do (input)->
input.setAttribute 'data-input-number', ++Templating.currentInputCount
blockParent = $(input).closest '[data-view-block]'
field = input.getAttribute 'data-value'
input.value = viewBlock(input)?.yaml?[field] ? ''
nextButton = input.getAttribute 'button'
input.onkeyup = (e)->
block = viewBlock(input)
data = block.yaml
setField data, field, input.value
noRenderWhile $(link), -> setData block._id, data
if nextButton && e.keyCode == 13
e.preventDefault()
$(rootNode(input).firstChild).find("##{nextButton}").click()
setField = (data, field, value)->
data[field] = if typeof value == 'number' then value
else if typeof value == 'string'
n = Number value
if String(n) == value.trim() then n
else value
else value
Handlebars.registerHelper 'values', (items..., options)-> items
Handlebars.registerHelper 'view', (item, name, options)->
if !options
options = name
name = null
data = if typeof item == 'string'
block = getBlock(item) || getBlockNamed(item)
block?.yaml
else if item?.yaml && item._id
block = item
item.yaml
else
block = null
item
if data?.type
descriptor = if name then "#{data.type}/#{name}" else "#{data.type}"
viewMarkup[descriptor]?(data, null, false, block) || ''
else ''
Handlebars.registerHelper 'deref', (item)->
if typeof item == 'string'
block = getBlockNamed item
block?.yaml
else if item.yaml && item._id
block = item
item.yaml
else
block = null
item
Handlebars.registerHelper 'find', (index, options)->
ret = "<span data-org-index='#{index}'></span>"
indexedCursor(root.currentDocument, index)?.forEach (data)-> if data then ret += options.fn data
ret
addViewId = ->
if Templating.currentViewData._id?
ids = {}
for id in Templating.currentViewLink.getAttribute('data-view-id').split ' '
ids[id] = true
ids[Templating.currentViewData._id] = true
result = []
for k of ids
result.push k
Templating.currentViewLink.setAttribute 'data-view-id', result.join ' '
changeInputText = (field, id)->
console.log "CHANGE DATA"
isHidden = (target)->
if target && !$(document.body).hasClass('show-hidden')
data = if isNode target then target.id else target
root.currentDocument.leisure.parentCache.isHidden data
isHiddenBlock = (block)->
if !$(document.body).hasClass('show-hidden')
root.currentDocument.leisure.parentCache.isHidden block
fancyOrg =
__proto__: orgNotebook
name: 'fancy'
opposite: plainOrg
markupOrg: markupOrg
markupOrgWithNode: markupOrgWithNode
bindContent: bindContent
isHiddenBlock: isHiddenBlock
reparse: (parent, text, target)->
if isHidden target then return
if isPlainEditing target
t = $(plainOrg.reparse parent, text, target)
if t.is("[data-org-headline='1']")
t.attr 'data-edit-mode', 'plain'
t.attr 'data-org-note', t.attr('data-property-note') || 'main'
createEditToggleButton t
@newNode t
fixupHtml t
else orgNotebook.reparse.apply this, arguments
installOrgDOM: (parent, orgNode, orgText, target)->
@parent = parent
restorePosition parent, =>
if !target
parent.setAttribute 'class', 'org-fancy'
parent.setAttribute 'maindoc', ''
hadTarget = target
target = orgNotebook.installOrgDOM parent, orgNode, orgText, target
fixupHtml target || parent, null
@newNode target
if !hadTarget
@applyShowHidden()
setTimeout (=>
redrawAllIssues()
), 1
$(document).tooltip()
newNode: (target)->
setTheme theme
nextNoteId = 0
fixupViews target
createNoteShadows()
executeSource: (parent, node, cont)->
node = $(node).closest('[data-org-type="source"]')[0]
if isPlainEditing node then plainOrg.executeSource arguments...
else
restorePosition null, =>
code = getCodeContainer node
shouldRedrawAst = false
if presenter?.astCode == code
pos = getTextPosition code, node, 0
if presenter.astCodeContains? pos
shouldRedrawAst = true
presenter = emptyPresenter
executeSource.call this, parent, node, this, (env)->
env.finishedComputation()
recreateAstButtons code
if shouldRedrawAst then redrawAst code, pos
cont?()
executeDef: fancyExecuteDef
createResults: createResults
bindings: defaultBindings
redrawIssue: (i)-> redrawIssue i
leisureButton: ->
restorePosition @parent, ->
toggleSlides()
if slideMode then setTimeout (-> if !getSelection().focusNode then $('[maindoc]').focus()), 1
else swapMarkup()
emptySlide: (id, slidePosition)->
"#{slideStart()}<hr class='#{if slidePosition == 'only' then 'first' else slidePosition}'><div id='#{id}'></div>#{slideEnd()}"
insertEmptySlide: (id, prevId)->
slide = $(@emptySlide id)
if (prev = $("##{prevId}").closest('.slideholder')).length then prev.after slide
else $("[maindoc] [data-org-headline='0']").append slide
slide.find("##{id}")[0]
defineView: (id)-> # define a view from a data block
if type = viewIdTypes[id]
createTemplateRenderer type, root.viewTypeData[type], false, (data, target, block, update)->
el = if update then target else viewRoots(target)
if target
el
.addClass(theme)
.addClass($('body').hasClass('bar_collapse') && 'bar_collapse')
.css('white-space', 'normal')
.css('user-select', 'none')
.css('-webkit-user-select', 'none')
.css('-moz-user-select', 'none')
el
.find('button')
.button()
el
.find('[title]')
.tooltip()
bindAllWidgets el
for view in el.add el.find '[data-view-type]'
type = view.getAttribute 'data-view-type'
block = getBlock view.getAttribute 'data-view-block'
for cid in controllerDescriptorIds[type] ? []
codeContexts[cid]?.initializeView? view, block.yaml, block._id
dataType = type.match /([^/]*)\/?(.*)?/
restorePosition null, ->
vBlock = getBlock id
for dataId of dataTypeIds[vBlock?.codeAttributes?.defview] ? {}
if block = getBlock dataId
nodes = $("[data-view-ids~='#{dataId}']")
if block.codeName?
for node in $("[data-view-link='#{block.codeName}']")
renderLink node, block
deleteView: (type)->
delete viewMarkup[type]
for node in $("[data-view-key='#{type}']")
clearView node
applyShowHidden: ->
for node in $('.slideholder')
if $(node).find("[data-org-headline='1']").not("[data-property-hidden='true']").length == 0
$(node).addClass('hidden-slide')
applySlides()
checkSourceMod: checkSourceMod
updateBlock: (block, allowInplaceUpdate)->
lang = block.language?.toLowerCase()
attr = block.codeAttributes
restorePosition null, ->
if lang in ['css', 'yaml']
updateViews block._id, allowInplaceUpdate
if !allowInplaceUpdate && index = block.codeAttributes?.index
updateIndexViews index.split(' ')[0]
else if lang == 'html' && attr?.defview
incRenderCount()
root.orgApi.defineView block._id
updateIndexViews: -> restorePosition null, -> updateIndexViews
updateAllBlocks: ->
restorePosition null, ->
console.log "UPDATE ALL"
fixupViews '[maindoc]'
updateObserver: (observerId, observerContext, yaml, block, type)->
args = arguments
restorePosition null, =>
orgNotebook.updateObserver.apply this, args
if observerContext.block.codeAttributes.view
displayCodeView findOrIs($("##{observerContext.block._id}"), '[data-code-view]')[0]
removeSlide: (id)->
el = $("##{id}")
holder = el.closest ".slideholder"
el.remove()
if holder.children().not('hr').length == 0 then holder.remove()
binding = false
bindAllWidgets = (els)->
if !binding
binding = true
try
for node in els
bindWidgets node
finally
binding = false
plainOrg.opposite = fancyOrg
# called on installing DOM and also on new notes
fixupHtml = (parent, note)->
for node in findOrIs findOrIs($(parent), "[data-lang='leisure']"), '[data-org-src]'
recreateAstButtons node
createValueSliders node, leisureNumberSlider
for node in findOrIs findOrIs($(parent), "[data-lang]:not([data-lang='leisure'])"), '[data-org-src]'
createValueSliders node, regularNumberSlider
createNoteShadows()
createEditToggleButton parent
#if !note
# $(parent).find("button.create_note").remove()
# $("<button class='create_note' contenteditable='false'><i class='fa fa-file-text-o'></i></button>")
# .insertBefore(findOrIs($(parent), '[data-org-headline="1"]').find('.maincontent'))
# .children().find(':first-child')
# .click (e)->
# e.preventDefault()
# #root.currentMode.createNotes()
for node in findOrIs $(parent), "[data-code-view]"
displayCodeView node
for node in findOrIs $(parent), '[data-org-comments]'
setShadowHtml node.firstElementChild, newCommentBox node.getAttribute('data-org-comments'), $(node.parentNode).find('.codeblock').attr 'id'
if parent.getAttribute('data-org-headline') == '0' then processHiddenNodes()
processHiddenNodes = ->
for name, doc of importedDocs
mapDocumentBlocks doc, (block)->
if block.language?.toLowerCase() == 'css' && isCurrent block
id = block._id
if !$("##{id}").length
$("[maindoc]").append $("<div id='#{id}'><style name='css'></style></div>")
updateViews id
if !(document.body.classList.contains 'show-hidden') && (parentCache = root.currentDocument?.leisure.parentCache)
mapDocumentBlocks root.currentDocument, (block)->
if parentCache.isHidden block
if block.language?.toLowerCase() == 'css'
id = block._id
if !$("##{id}").length
$("[maindoc]").append $("<div id='#{id}'><style name='css'></style></div>")
updateViews id
findSlideId = (name)->
if sl = $('[data-org-headline-text="Chats"]').prop 'id' then sl
else
for slide of root.currentDocument.leisure.parentCache.hidden
block = getBlock slide
if block.text.substring(1).trim() == name then return block
slide = null
mapDocumentBlocks root.currentDocument, (block)->
if !slide && block.type == 'headline' && block.level == 1 && block.text.substring(1).trim() == name then slide = block
slide
displayCodeView = (node)->
if node
if block = getBlock $(node).closest('[data-shared]')[0]?.id
clearView node
viewMarkup[node.getAttribute 'data-code-view']? block, $(node), false, block
#$(node).shadow().attr 'data-view-id', block._id
viewFor = (node)-> $("##{$(node).closest('[data-view-block]').attr 'data-view-block'}")
getMainContent = (headline)->
headline = findOrIs headline, '[data-org-headline="1"]'
c = headline.children '.maincontent'
if c.length > 0
headline.not(c.parent()).add(c)
else headline
createEditToggleButton = (doc)->
for node in getMainContent $(doc)
id = if $(node).is '.maincontent' then node.parentElement.id else node.id
button = $("<button class='toggle_edit' contenteditable='false' onclick='Leisure.toggleEdit(\"#{id}\")'><i class='fa fa-glass'></i></button>")
if $(node).is '.maincontent'
if !$(node).prev().is('.toggle_edit') then button.insertBefore(node)
else if !$(node).children().first().is('.toggle_edit') then $(node).prepend button
isPlainEditing = (node)-> $(slideParent(node)).is "[data-edit-mode='plain']"
toggleEdit = (id)->
restorePosition null, ->
console.log "toggle edit", id
node = $("##{id}").closest("[data-org-headline='1']")
id = node[0].id
parent = parentForNode node
if node.attr('data-edit-mode') == 'plain'
node.attr 'data-edit-mode', 'fancy'
mode = fancyOrg
else
node.attr 'data-edit-mode', 'plain'
mode = plainOrg
mode.reparse parent, orgForNode(node[0]), node[0]
node = $("##{id}")
node.attr 'data-edit-mode', mode.name
if mode == plainOrg
node.attr 'data-org-note', node.attr('data-property-note') || 'main'
if mode == root.plainOrg then createEditToggleButton node
addStyles = (name, string)->
styles = $ "<style id='styles-#{name}'>\n#{string}\n</style>"
if (old = $("#styles-#{name}")).length then old.replaceWith styles
else $('body').append styles
root.fancyOrg = fancyOrg
root.toggleComment = toggleComment
root.addComment = addComment
root.recreateAstButtons = recreateAstButtons
root.setTheme = setTheme
root.createTestCase = createTestCase
root.executeCode = executeCode
root.toggleDynamic = toggleDynamic
root.getDocRange = getDocRange
root.restoreDocRange = restoreDocRange
root.getDocumentOffset = getDocumentOffset
root.viewMarkup = viewMarkup
root.noViewUpdate = false
root.topNode = topNode
root.rootNode = rootNode
root.codeHolder = codeHolder
root.getBlockNamed = getBlockNamed
root.viewBlock = viewBlock
root.toggleEdit = toggleEdit
root.toggleSlides = toggleSlides
root.getDeepestActiveElement = getDeepestActiveElement
root.addViewId = addViewId
root.getDataNamed = getDataNamed
root.setDataNamed = setDataNamed
root.findLinks = findLinks
root.findViews = findViews
root.viewFor = viewFor
root.setCodeAttributes = setCodeAttributes
root.clearCodeAttributes = clearCodeAttributes
root.addStyles = addStyles
root.noRenderWhile = noRenderWhile
root.fancyEnv = orgEnv
root.unescapeString = unescapeString
root.findSlideId = findSlideId
|
[
{
"context": "TA: 222\n AUTHENTICATED: 281\n PASSWORD_REQUIRED: 381\n ARTICLE_NOT_FOUND: 430\n TOO_MANY_CONNECTIONS: ",
"end": 6008,
"score": 0.9905228614807129,
"start": 6005,
"tag": "PASSWORD",
"value": "381"
}
] | src/connection.coffee | andykant/nzb | 1 | Events = require 'events'
tls = require 'tls'
net = require 'net'
util = require 'util'
buffertools = require 'buffertools'
class Connection extends Events.EventEmitter
constructor: (@options) ->
@options or= {}
@data = []
log: (message) ->
# util.log @options.host + ':' + @options.port + '#' + (@options.number or 0) + ' - ' + message
# connect to the server
connect: ->
return @socket if @socket or @connecting
# updates the state of the connection to ready for requests
ready = =>
@ready = yes
@log 'ready'
@emit 'ready'
# wires up socket listeners and helpers
listen = (socket) =>
# override the write method so that we can log requests
socket.write = (request) =>
logged = request.substr(0, request.length - 2)
logged = logged.split(' ').slice(0, 2).join(' ') + ' ********' if logged.match(/^AUTHINFO/)
@log 'REQUEST: ' + logged
socket.__proto__.write.call(socket, request + BREAK)
# track when the server connects
socket.on 'connect', =>
@connected = yes
@log 'connect'
# handle data responses
socket.on 'data', (data) =>
response = @parse data
@log 'response: ' + response.code + ' - ' + response.message if response.code?
# check for receiving data first since they don't include a response code past the first buffer
if (response.code is Codes.RECEIVING_DATA or @receiving) and response.data
# append the data
if response.code is Codes.RECEIVING_DATA
@data = [response.data]
@receiving = yes
else
@data.push response.data
# check for the end of the file
if EOF.test response.data
@receiving = no
# make references in case these properties get overwritten
group = @selectedGroup
message = @message
data = buffertools.concat.apply(buffertools, @data)
callback = @callback
@emit 'segment', group, message, data
callback data if callback
# successfully connected to the server
else if response.code in Codes.CONNECTED
# need to authenticate if credentials were included
if @options.username
@authenticate()
else
ready()
# authenticated the user, but still need a password
else if @authenticating and response.code is Codes.PASSWORD_REQUIRED
@authenticate()
# successfully authenticated the user (and password if applicable)
else if response.code is Codes.AUTHENTICATED
@authenticating = no
@authenticated = yes
ready()
# handle a list of capabilities (mainly for debugging)
else if response.code is Codes.CAPABILITIES
@log 'capabilities: \r\n' + response.data.join(BREAK)
@emit 'capabilities', response.data
# group successfully selected (needed to retrieve body content)
else if response.code is Codes.GROUP_SELECTED
@selectedGroup = @selectingGroup
@selectingGroup = null
# now that the group was selected, re-attempt the message retrieval
@get @selectedGroup, @message, @callback if @message
socket.on 'end', =>
@log 'end'
@disconnect()
socket.on 'error', (exception) =>
@log 'error: ' + exception.message
@disconnect()
socket.on 'close', =>
@log 'close'
@disconnect()
# open the connection
@connecting = yes
@log 'open'
if @options.secure
@socket = listen tls.connect(@options.port, @options.host, =>
# emulate the connect/error events that an insecure socket would emit
if @socket.authorized
@socket.emit 'connect'
else
@socket.emit 'error', { message: 'Unauthorized' }
)
else
@socket = listen net.createConnection(@options.port, @options.host)
return @socket
# authenticate with the username/password
authenticate: ->
return if not @connected or @authenticated or not @options.username
if not @authenticating
@authenticating = yes
@socket.write('AUTHINFO USER ' + @options.username)
else
@authenticating = no
@socket.write('AUTHINFO PASS ' + @options.password)
# retrieve the capabilities for the active session (mainly for debugging sessions)
capabilities: ->
return if not @ready
@socket.write('CAPABILITIES')
# select a newsgroup
group: (group)->
return if not @ready
@selectedGroup = null
@socket.write('GROUP ' + group)
# retrieve an article
get: (group, message, callback) ->
return if not @ready
@message = message
@callback = callback or null
if not @group or @selectedGroup isnt group
@selectingGroup = group
@group group
else
@socket.write('BODY ' + @message)
# parse a socket data response
parse: (data) ->
lines = data.toString().split(LINE)
match = lines[0].match(RESPONSE)
code = match and parseInt(match[1], 10)
return {
code: code
data: ((code is Codes.RECEIVING_DATA or @receiving) and data) or (match and lines.slice(1)) or data.toString()
message: match and match[2]
}
# disconnect and clean up
disconnect: ->
@ready = no
@connecting = no
@connected = no
@authenticating = no
@authenticated = no
@receiving = no
@selectedGroup = null
@message = null
@callback = null
@data = []
@socket.destroy() if @socket
@socket = null
# expressions used for parsing responses
RESPONSE = /^(\d+)\s(.+?)$/
LINE = /[\r\n]+/
REST_OF_DATA = /[\r\n]+([\s\S]*)$/
EOF = /[\r\n]*\.[\r\n]+$/
BREAK = '\r\n'
# response codes
Codes =
CAPABILITIES: 101
CONNECTED: [200, 201]
GROUP_SELECTED: 211
RECEIVING_DATA: 222
AUTHENTICATED: 281
PASSWORD_REQUIRED: 381
ARTICLE_NOT_FOUND: 430
TOO_MANY_CONNECTIONS: 502
# convert a buffer to an array
bufferToArray = (buffer) ->
arr = new Array(buffer.length)
for i in [0..buffer.length - 1]
arr[i] = buffer[i]
return arr
exports.Connection = Connection
| 217883 | Events = require 'events'
tls = require 'tls'
net = require 'net'
util = require 'util'
buffertools = require 'buffertools'
class Connection extends Events.EventEmitter
constructor: (@options) ->
@options or= {}
@data = []
log: (message) ->
# util.log @options.host + ':' + @options.port + '#' + (@options.number or 0) + ' - ' + message
# connect to the server
connect: ->
return @socket if @socket or @connecting
# updates the state of the connection to ready for requests
ready = =>
@ready = yes
@log 'ready'
@emit 'ready'
# wires up socket listeners and helpers
listen = (socket) =>
# override the write method so that we can log requests
socket.write = (request) =>
logged = request.substr(0, request.length - 2)
logged = logged.split(' ').slice(0, 2).join(' ') + ' ********' if logged.match(/^AUTHINFO/)
@log 'REQUEST: ' + logged
socket.__proto__.write.call(socket, request + BREAK)
# track when the server connects
socket.on 'connect', =>
@connected = yes
@log 'connect'
# handle data responses
socket.on 'data', (data) =>
response = @parse data
@log 'response: ' + response.code + ' - ' + response.message if response.code?
# check for receiving data first since they don't include a response code past the first buffer
if (response.code is Codes.RECEIVING_DATA or @receiving) and response.data
# append the data
if response.code is Codes.RECEIVING_DATA
@data = [response.data]
@receiving = yes
else
@data.push response.data
# check for the end of the file
if EOF.test response.data
@receiving = no
# make references in case these properties get overwritten
group = @selectedGroup
message = @message
data = buffertools.concat.apply(buffertools, @data)
callback = @callback
@emit 'segment', group, message, data
callback data if callback
# successfully connected to the server
else if response.code in Codes.CONNECTED
# need to authenticate if credentials were included
if @options.username
@authenticate()
else
ready()
# authenticated the user, but still need a password
else if @authenticating and response.code is Codes.PASSWORD_REQUIRED
@authenticate()
# successfully authenticated the user (and password if applicable)
else if response.code is Codes.AUTHENTICATED
@authenticating = no
@authenticated = yes
ready()
# handle a list of capabilities (mainly for debugging)
else if response.code is Codes.CAPABILITIES
@log 'capabilities: \r\n' + response.data.join(BREAK)
@emit 'capabilities', response.data
# group successfully selected (needed to retrieve body content)
else if response.code is Codes.GROUP_SELECTED
@selectedGroup = @selectingGroup
@selectingGroup = null
# now that the group was selected, re-attempt the message retrieval
@get @selectedGroup, @message, @callback if @message
socket.on 'end', =>
@log 'end'
@disconnect()
socket.on 'error', (exception) =>
@log 'error: ' + exception.message
@disconnect()
socket.on 'close', =>
@log 'close'
@disconnect()
# open the connection
@connecting = yes
@log 'open'
if @options.secure
@socket = listen tls.connect(@options.port, @options.host, =>
# emulate the connect/error events that an insecure socket would emit
if @socket.authorized
@socket.emit 'connect'
else
@socket.emit 'error', { message: 'Unauthorized' }
)
else
@socket = listen net.createConnection(@options.port, @options.host)
return @socket
# authenticate with the username/password
authenticate: ->
return if not @connected or @authenticated or not @options.username
if not @authenticating
@authenticating = yes
@socket.write('AUTHINFO USER ' + @options.username)
else
@authenticating = no
@socket.write('AUTHINFO PASS ' + @options.password)
# retrieve the capabilities for the active session (mainly for debugging sessions)
capabilities: ->
return if not @ready
@socket.write('CAPABILITIES')
# select a newsgroup
group: (group)->
return if not @ready
@selectedGroup = null
@socket.write('GROUP ' + group)
# retrieve an article
get: (group, message, callback) ->
return if not @ready
@message = message
@callback = callback or null
if not @group or @selectedGroup isnt group
@selectingGroup = group
@group group
else
@socket.write('BODY ' + @message)
# parse a socket data response
parse: (data) ->
lines = data.toString().split(LINE)
match = lines[0].match(RESPONSE)
code = match and parseInt(match[1], 10)
return {
code: code
data: ((code is Codes.RECEIVING_DATA or @receiving) and data) or (match and lines.slice(1)) or data.toString()
message: match and match[2]
}
# disconnect and clean up
disconnect: ->
@ready = no
@connecting = no
@connected = no
@authenticating = no
@authenticated = no
@receiving = no
@selectedGroup = null
@message = null
@callback = null
@data = []
@socket.destroy() if @socket
@socket = null
# expressions used for parsing responses
RESPONSE = /^(\d+)\s(.+?)$/
LINE = /[\r\n]+/
REST_OF_DATA = /[\r\n]+([\s\S]*)$/
EOF = /[\r\n]*\.[\r\n]+$/
BREAK = '\r\n'
# response codes
Codes =
CAPABILITIES: 101
CONNECTED: [200, 201]
GROUP_SELECTED: 211
RECEIVING_DATA: 222
AUTHENTICATED: 281
PASSWORD_REQUIRED: <PASSWORD>
ARTICLE_NOT_FOUND: 430
TOO_MANY_CONNECTIONS: 502
# convert a buffer to an array
bufferToArray = (buffer) ->
arr = new Array(buffer.length)
for i in [0..buffer.length - 1]
arr[i] = buffer[i]
return arr
exports.Connection = Connection
| true | Events = require 'events'
tls = require 'tls'
net = require 'net'
util = require 'util'
buffertools = require 'buffertools'
class Connection extends Events.EventEmitter
constructor: (@options) ->
@options or= {}
@data = []
log: (message) ->
# util.log @options.host + ':' + @options.port + '#' + (@options.number or 0) + ' - ' + message
# connect to the server
connect: ->
return @socket if @socket or @connecting
# updates the state of the connection to ready for requests
ready = =>
@ready = yes
@log 'ready'
@emit 'ready'
# wires up socket listeners and helpers
listen = (socket) =>
# override the write method so that we can log requests
socket.write = (request) =>
logged = request.substr(0, request.length - 2)
logged = logged.split(' ').slice(0, 2).join(' ') + ' ********' if logged.match(/^AUTHINFO/)
@log 'REQUEST: ' + logged
socket.__proto__.write.call(socket, request + BREAK)
# track when the server connects
socket.on 'connect', =>
@connected = yes
@log 'connect'
# handle data responses
socket.on 'data', (data) =>
response = @parse data
@log 'response: ' + response.code + ' - ' + response.message if response.code?
# check for receiving data first since they don't include a response code past the first buffer
if (response.code is Codes.RECEIVING_DATA or @receiving) and response.data
# append the data
if response.code is Codes.RECEIVING_DATA
@data = [response.data]
@receiving = yes
else
@data.push response.data
# check for the end of the file
if EOF.test response.data
@receiving = no
# make references in case these properties get overwritten
group = @selectedGroup
message = @message
data = buffertools.concat.apply(buffertools, @data)
callback = @callback
@emit 'segment', group, message, data
callback data if callback
# successfully connected to the server
else if response.code in Codes.CONNECTED
# need to authenticate if credentials were included
if @options.username
@authenticate()
else
ready()
# authenticated the user, but still need a password
else if @authenticating and response.code is Codes.PASSWORD_REQUIRED
@authenticate()
# successfully authenticated the user (and password if applicable)
else if response.code is Codes.AUTHENTICATED
@authenticating = no
@authenticated = yes
ready()
# handle a list of capabilities (mainly for debugging)
else if response.code is Codes.CAPABILITIES
@log 'capabilities: \r\n' + response.data.join(BREAK)
@emit 'capabilities', response.data
# group successfully selected (needed to retrieve body content)
else if response.code is Codes.GROUP_SELECTED
@selectedGroup = @selectingGroup
@selectingGroup = null
# now that the group was selected, re-attempt the message retrieval
@get @selectedGroup, @message, @callback if @message
socket.on 'end', =>
@log 'end'
@disconnect()
socket.on 'error', (exception) =>
@log 'error: ' + exception.message
@disconnect()
socket.on 'close', =>
@log 'close'
@disconnect()
# open the connection
@connecting = yes
@log 'open'
if @options.secure
@socket = listen tls.connect(@options.port, @options.host, =>
# emulate the connect/error events that an insecure socket would emit
if @socket.authorized
@socket.emit 'connect'
else
@socket.emit 'error', { message: 'Unauthorized' }
)
else
@socket = listen net.createConnection(@options.port, @options.host)
return @socket
# authenticate with the username/password
authenticate: ->
return if not @connected or @authenticated or not @options.username
if not @authenticating
@authenticating = yes
@socket.write('AUTHINFO USER ' + @options.username)
else
@authenticating = no
@socket.write('AUTHINFO PASS ' + @options.password)
# retrieve the capabilities for the active session (mainly for debugging sessions)
capabilities: ->
return if not @ready
@socket.write('CAPABILITIES')
# select a newsgroup
group: (group)->
return if not @ready
@selectedGroup = null
@socket.write('GROUP ' + group)
# retrieve an article
get: (group, message, callback) ->
return if not @ready
@message = message
@callback = callback or null
if not @group or @selectedGroup isnt group
@selectingGroup = group
@group group
else
@socket.write('BODY ' + @message)
# parse a socket data response
parse: (data) ->
lines = data.toString().split(LINE)
match = lines[0].match(RESPONSE)
code = match and parseInt(match[1], 10)
return {
code: code
data: ((code is Codes.RECEIVING_DATA or @receiving) and data) or (match and lines.slice(1)) or data.toString()
message: match and match[2]
}
# disconnect and clean up
disconnect: ->
@ready = no
@connecting = no
@connected = no
@authenticating = no
@authenticated = no
@receiving = no
@selectedGroup = null
@message = null
@callback = null
@data = []
@socket.destroy() if @socket
@socket = null
# expressions used for parsing responses
RESPONSE = /^(\d+)\s(.+?)$/
LINE = /[\r\n]+/
REST_OF_DATA = /[\r\n]+([\s\S]*)$/
EOF = /[\r\n]*\.[\r\n]+$/
BREAK = '\r\n'
# response codes
Codes =
CAPABILITIES: 101
CONNECTED: [200, 201]
GROUP_SELECTED: 211
RECEIVING_DATA: 222
AUTHENTICATED: 281
PASSWORD_REQUIRED: PI:PASSWORD:<PASSWORD>END_PI
ARTICLE_NOT_FOUND: 430
TOO_MANY_CONNECTIONS: 502
# convert a buffer to an array
bufferToArray = (buffer) ->
arr = new Array(buffer.length)
for i in [0..buffer.length - 1]
arr[i] = buffer[i]
return arr
exports.Connection = Connection
|
[
{
"context": "a simple document', (done) ->\n# doc = {name: 'Meow', field: 'Mixer'}\n# wongo.prune(doc, schema.f",
"end": 461,
"score": 0.8182539939880371,
"start": 457,
"tag": "NAME",
"value": "Meow"
},
{
"context": "to prune an array', (done) ->\n# doc = {name: 'Meow', field: 'Mixer', fieldArray: [], array: ['meow',",
"end": 681,
"score": 0.865424394607544,
"start": 677,
"tag": "NAME",
"value": "Meow"
},
{
"context": "rune subdocuments', (done) ->\n# doc = {name: 'Meow', subdoc: {name: 'Happy', field: 'remmmy'}}\n# ",
"end": 1064,
"score": 0.8706052303314209,
"start": 1060,
"tag": "NAME",
"value": "Meow"
},
{
"context": "ne) ->\n# doc = {name: 'Meow', subdoc: {name: 'Happy', field: 'remmmy'}}\n# wongo.prune(doc, schema",
"end": 1088,
"score": 0.8298919796943665,
"start": 1083,
"tag": "NAME",
"value": "Happy"
},
{
"context": " sub-subdocuments', (done) ->\n# doc = {name: 'Meow', subdoc: {name: 'Happy', subdoc: {name: 'Wally',",
"end": 1370,
"score": 0.8913099765777588,
"start": 1366,
"tag": "NAME",
"value": "Meow"
},
{
"context": "ne) ->\n# doc = {name: 'Meow', subdoc: {name: 'Happy', subdoc: {name: 'Wally', field: 'Chese'}}}\n# ",
"end": 1394,
"score": 0.9892860054969788,
"start": 1389,
"tag": "NAME",
"value": "Happy"
},
{
"context": ": 'Meow', subdoc: {name: 'Happy', subdoc: {name: 'Wally', field: 'Chese'}}}\n# wongo.prune(doc, schema",
"end": 1418,
"score": 0.9960078001022339,
"start": 1413,
"tag": "NAME",
"value": "Wally"
},
{
"context": ": {name: 'Happy', subdoc: {name: 'Wally', field: 'Chese'}}}\n# wongo.prune(doc, schema.fields)\n# a",
"end": 1434,
"score": 0.8275748491287231,
"start": 1429,
"tag": "NAME",
"value": "Chese"
},
{
"context": "doc, schema.fields)\n# assert.equal(doc.name, 'Meow')\n# assert.equal(doc.subdoc.subdoc.name, 'Wal",
"end": 1511,
"score": 0.902504026889801,
"start": 1507,
"tag": "NAME",
"value": "Meow"
},
{
"context": "eow')\n# assert.equal(doc.subdoc.subdoc.name, 'Wally')\n# assert.ok(not doc.subdoc.subdoc.field)\n# ",
"end": 1563,
"score": 0.9959801435470581,
"start": 1558,
"tag": "NAME",
"value": "Wally"
},
{
"context": "ubdocument arrays', (done) ->\n# doc = {name: 'Meow', subdoc: {subdoc: {array: ['Wally'], field: ['me",
"end": 1720,
"score": 0.9688923358917236,
"start": 1716,
"tag": "NAME",
"value": "Meow"
},
{
"context": " doc = {name: 'Meow', subdoc: {subdoc: {array: ['Wally'], field: ['meowpants']}}}\n# wongo.prune(doc,",
"end": 1755,
"score": 0.9806106090545654,
"start": 1750,
"tag": "NAME",
"value": "Wally"
},
{
"context": "doc, schema.fields)\n# assert.equal(doc.name, 'Meow')\n# assert.equal(doc.subdoc.subdoc.array[0], ",
"end": 1855,
"score": 0.9024171829223633,
"start": 1851,
"tag": "NAME",
"value": "Meow"
},
{
"context": ")\n# assert.equal(doc.subdoc.subdoc.array[0], 'Wally')\n# assert.ok(not doc.subdoc.subdoc.field)\n# ",
"end": 1911,
"score": 0.9925433397293091,
"start": 1906,
"tag": "NAME",
"value": "Wally"
},
{
"context": "b document fields', (done) ->\n# doc = {name: 'Meow', arrayObj: [{name: 'meowpants', field: 'wall'}]}",
"end": 2073,
"score": 0.9391575455665588,
"start": 2069,
"tag": "NAME",
"value": "Meow"
},
{
"context": " ->\n# doc = {name: 'Meow', arrayObj: [{name: 'meowpants', field: 'wall'}]}\n# wongo.prune(doc, sc",
"end": 2099,
"score": 0.5595164895057678,
"start": 2095,
"tag": "NAME",
"value": "meow"
},
{
"context": " doc = {name: 'Meow', arrayObj: [{name: 'meowpants', field: 'wall'}]}\n# wongo.prune(doc, schema.",
"end": 2104,
"score": 0.5734843015670776,
"start": 2100,
"tag": "NAME",
"value": "ants"
},
{
"context": "doc, schema.fields)\n# assert.equal(doc.name, 'Meow')\n# assert.equal(doc.arrayObj[0].name, 'meowp",
"end": 2196,
"score": 0.8839954137802124,
"start": 2192,
"tag": "NAME",
"value": "Meow"
}
] | test/prune.test.coffee | wookets/wongo | 0 | # assert = require 'assert'
# wongo = require '../lib/wongo'
#
#
# wongo.schema 'MockPrune',
# fields:
# name: String
# array: [String]
# arrayObj: [
# name: String
# ]
# subdoc:
# name: String
# subdoc:
# name: String
# array: [String]
#
# describe 'Wongo Prune', ->
# schema = wongo.schema('MockPrune')
#
# it 'should be able to prune a simple document', (done) ->
# doc = {name: 'Meow', field: 'Mixer'}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.ok(not doc.field)
# done()
#
# it 'should be able to prune an array', (done) ->
# doc = {name: 'Meow', field: 'Mixer', fieldArray: [], array: ['meow', 'woof']}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.ok(not doc.field)
# assert.ok(not doc.fieldArray)
# assert.equal(doc.array[0], 'meow')
# assert.equal(doc.array[1], 'woof')
# done()
#
# it 'should be able to prune subdocuments', (done) ->
# doc = {name: 'Meow', subdoc: {name: 'Happy', field: 'remmmy'}}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.equal(doc.subdoc.name, 'Happy')
# assert.ok(not doc.subdoc.field)
# done()
#
# it 'should be able to prune sub-subdocuments', (done) ->
# doc = {name: 'Meow', subdoc: {name: 'Happy', subdoc: {name: 'Wally', field: 'Chese'}}}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.equal(doc.subdoc.subdoc.name, 'Wally')
# assert.ok(not doc.subdoc.subdoc.field)
# done()
#
# it 'should be able to prune sub-subdocument arrays', (done) ->
# doc = {name: 'Meow', subdoc: {subdoc: {array: ['Wally'], field: ['meowpants']}}}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.equal(doc.subdoc.subdoc.array[0], 'Wally')
# assert.ok(not doc.subdoc.subdoc.field)
# done()
#
# it 'should be able to prune arrayed sub document fields', (done) ->
# doc = {name: 'Meow', arrayObj: [{name: 'meowpants', field: 'wall'}]}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.equal(doc.arrayObj[0].name, 'meowpants')
# assert.ok(not doc.arrayObj[0].field)
# done() | 131788 | # assert = require 'assert'
# wongo = require '../lib/wongo'
#
#
# wongo.schema 'MockPrune',
# fields:
# name: String
# array: [String]
# arrayObj: [
# name: String
# ]
# subdoc:
# name: String
# subdoc:
# name: String
# array: [String]
#
# describe 'Wongo Prune', ->
# schema = wongo.schema('MockPrune')
#
# it 'should be able to prune a simple document', (done) ->
# doc = {name: '<NAME>', field: 'Mixer'}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.ok(not doc.field)
# done()
#
# it 'should be able to prune an array', (done) ->
# doc = {name: '<NAME>', field: 'Mixer', fieldArray: [], array: ['meow', 'woof']}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.ok(not doc.field)
# assert.ok(not doc.fieldArray)
# assert.equal(doc.array[0], 'meow')
# assert.equal(doc.array[1], 'woof')
# done()
#
# it 'should be able to prune subdocuments', (done) ->
# doc = {name: '<NAME>', subdoc: {name: '<NAME>', field: 'remmmy'}}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.equal(doc.subdoc.name, 'Happy')
# assert.ok(not doc.subdoc.field)
# done()
#
# it 'should be able to prune sub-subdocuments', (done) ->
# doc = {name: '<NAME>', subdoc: {name: '<NAME>', subdoc: {name: '<NAME>', field: '<NAME>'}}}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, '<NAME>')
# assert.equal(doc.subdoc.subdoc.name, '<NAME>')
# assert.ok(not doc.subdoc.subdoc.field)
# done()
#
# it 'should be able to prune sub-subdocument arrays', (done) ->
# doc = {name: '<NAME>', subdoc: {subdoc: {array: ['<NAME>'], field: ['meowpants']}}}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, '<NAME>')
# assert.equal(doc.subdoc.subdoc.array[0], '<NAME>')
# assert.ok(not doc.subdoc.subdoc.field)
# done()
#
# it 'should be able to prune arrayed sub document fields', (done) ->
# doc = {name: '<NAME>', arrayObj: [{name: '<NAME>p<NAME>', field: 'wall'}]}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, '<NAME>')
# assert.equal(doc.arrayObj[0].name, 'meowpants')
# assert.ok(not doc.arrayObj[0].field)
# done() | true | # assert = require 'assert'
# wongo = require '../lib/wongo'
#
#
# wongo.schema 'MockPrune',
# fields:
# name: String
# array: [String]
# arrayObj: [
# name: String
# ]
# subdoc:
# name: String
# subdoc:
# name: String
# array: [String]
#
# describe 'Wongo Prune', ->
# schema = wongo.schema('MockPrune')
#
# it 'should be able to prune a simple document', (done) ->
# doc = {name: 'PI:NAME:<NAME>END_PI', field: 'Mixer'}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.ok(not doc.field)
# done()
#
# it 'should be able to prune an array', (done) ->
# doc = {name: 'PI:NAME:<NAME>END_PI', field: 'Mixer', fieldArray: [], array: ['meow', 'woof']}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.ok(not doc.field)
# assert.ok(not doc.fieldArray)
# assert.equal(doc.array[0], 'meow')
# assert.equal(doc.array[1], 'woof')
# done()
#
# it 'should be able to prune subdocuments', (done) ->
# doc = {name: 'PI:NAME:<NAME>END_PI', subdoc: {name: 'PI:NAME:<NAME>END_PI', field: 'remmmy'}}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'Meow')
# assert.equal(doc.subdoc.name, 'Happy')
# assert.ok(not doc.subdoc.field)
# done()
#
# it 'should be able to prune sub-subdocuments', (done) ->
# doc = {name: 'PI:NAME:<NAME>END_PI', subdoc: {name: 'PI:NAME:<NAME>END_PI', subdoc: {name: 'PI:NAME:<NAME>END_PI', field: 'PI:NAME:<NAME>END_PI'}}}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'PI:NAME:<NAME>END_PI')
# assert.equal(doc.subdoc.subdoc.name, 'PI:NAME:<NAME>END_PI')
# assert.ok(not doc.subdoc.subdoc.field)
# done()
#
# it 'should be able to prune sub-subdocument arrays', (done) ->
# doc = {name: 'PI:NAME:<NAME>END_PI', subdoc: {subdoc: {array: ['PI:NAME:<NAME>END_PI'], field: ['meowpants']}}}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'PI:NAME:<NAME>END_PI')
# assert.equal(doc.subdoc.subdoc.array[0], 'PI:NAME:<NAME>END_PI')
# assert.ok(not doc.subdoc.subdoc.field)
# done()
#
# it 'should be able to prune arrayed sub document fields', (done) ->
# doc = {name: 'PI:NAME:<NAME>END_PI', arrayObj: [{name: 'PI:NAME:<NAME>END_PIpPI:NAME:<NAME>END_PI', field: 'wall'}]}
# wongo.prune(doc, schema.fields)
# assert.equal(doc.name, 'PI:NAME:<NAME>END_PI')
# assert.equal(doc.arrayObj[0].name, 'meowpants')
# assert.ok(not doc.arrayObj[0].field)
# done() |
[
{
"context": " <tr>\n <th>Name</th>\n <th>Twin</th>\n <th>Details</th>\n </tr>\n",
"end": 2549,
"score": 0.9266858696937561,
"start": 2548,
"tag": "NAME",
"value": "T"
}
] | app/classifier/tasks/survey/editor-help.cjsx | tlalka/Panoptes-Front-End | 0 | React = require 'react'
module.exports =
choices: <div className="content-container">
<p>User-identifiable <strong>choices</strong>, with these headers:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Name</th>
<th>Description</th>
<th>Images</th>
<th>No questions</th>
</tr>
<tr className="form-label">
<td>The label for the choice</td>
<td>A short description of the choice</td>
<td>Representative images of the choice, <code>;</code>-separated</td>
<td>Y or N for whether you want "sub-questions" to appear</td>
</tr>
<tr>
<td>Shark</td>
<td>A shark is a big gray ocean monster with fins and teeth.</td>
<td>shark.jpg</td>
<td>Y</td>
</tr>
<tr>
<td>Dolphin</td>
<td>Dolphins are intelligent marine mammals who solve crimes.</td>
<td>dolphin.jpg; flipper.jpg</td>
<td>N</td>
</tr>
</tbody>
</table>
</div>
images: <div className="content-container">
Pick some <strong>images</strong>. Make sure they have the exact same names as the ones in your other files.
</div>
characteristics: <div className="content-container">
<p><strong>Characteristics</strong> of those choices that the user can filter through. Note that the values in Name have to match the values in choices.csv exactly. Format like this:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Name</th>
<th>Color=Orange; orange.png</th>
<th>Color=Gray; gray.png</th>
<th>Teeth=Dull; dull.png</th>
<th>Teeth=Pointy; pointy.png</th>
</tr>
<tr className="form-label">
<td>Choice name</td>
<td colSpan="4"><code>Characteristic</code>=<code>value</code>; <code>icon filename</code>, with each row marked <code>Y</code> or <code>N</code> for that choice</td>
</tr>
<tr>
<td>Shark</td>
<td>N</td>
<td>Y</td>
<td>N</td>
<td>Y</td>
</tr>
<tr>
<td>Dolphin</td>
<td>Y</td>
<td>Y</td>
<td>Y</td>
<td>N</td>
</tr>
</tbody>
</table>
</div>
confusions: <div className="content-container">
<p>Commonly <strong>confused pairs</strong> of choices:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Name</th>
<th>Twin</th>
<th>Details</th>
</tr>
<tr className="form-label">
<td>The name of the choice to show this pairing for</td>
<td>The name of the similar choice</td>
<td>A short explanation of how to tell the difference</td>
</tr>
<tr>
<td>Shark</td>
<td>Dolphin</td>
<td>A dolphin is shaped like a shark, but its tail is horizontal and it’s less terrifying.</td>
</tr>
</tbody>
</table>
</div>
questions: <div className="content-container">
<p><strong>Questions</strong> to ask about each identification:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Question</th>
<th>Multiple</th>
<th>Required</th>
<th>Answers</th>
<th>Include</th>
<th>Exclude</th>
</tr>
<tr className="form-label">
<td>The question to ask</td>
<td>Can the user select multiple answers? <code>Y</code> or <code>N</code></td>
<td>Is an answer required? <code>Y</code> or <code>N</code></td>
<td>The answers separated with <code>;</code></td>
<td>Choices to ask this question for (leave blank for all by default).</td>
<td>Choices to not ask this question for.</td>
</tr>
<tr>
<td>Is this an example question?</td>
<td>Y</td>
<td>N</td>
<td>Yes; No; Maybe</td>
<td> </td>
<td>Dolphin</td>
</tr>
</tbody>
</table>
</div>
| 161680 | React = require 'react'
module.exports =
choices: <div className="content-container">
<p>User-identifiable <strong>choices</strong>, with these headers:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Name</th>
<th>Description</th>
<th>Images</th>
<th>No questions</th>
</tr>
<tr className="form-label">
<td>The label for the choice</td>
<td>A short description of the choice</td>
<td>Representative images of the choice, <code>;</code>-separated</td>
<td>Y or N for whether you want "sub-questions" to appear</td>
</tr>
<tr>
<td>Shark</td>
<td>A shark is a big gray ocean monster with fins and teeth.</td>
<td>shark.jpg</td>
<td>Y</td>
</tr>
<tr>
<td>Dolphin</td>
<td>Dolphins are intelligent marine mammals who solve crimes.</td>
<td>dolphin.jpg; flipper.jpg</td>
<td>N</td>
</tr>
</tbody>
</table>
</div>
images: <div className="content-container">
Pick some <strong>images</strong>. Make sure they have the exact same names as the ones in your other files.
</div>
characteristics: <div className="content-container">
<p><strong>Characteristics</strong> of those choices that the user can filter through. Note that the values in Name have to match the values in choices.csv exactly. Format like this:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Name</th>
<th>Color=Orange; orange.png</th>
<th>Color=Gray; gray.png</th>
<th>Teeth=Dull; dull.png</th>
<th>Teeth=Pointy; pointy.png</th>
</tr>
<tr className="form-label">
<td>Choice name</td>
<td colSpan="4"><code>Characteristic</code>=<code>value</code>; <code>icon filename</code>, with each row marked <code>Y</code> or <code>N</code> for that choice</td>
</tr>
<tr>
<td>Shark</td>
<td>N</td>
<td>Y</td>
<td>N</td>
<td>Y</td>
</tr>
<tr>
<td>Dolphin</td>
<td>Y</td>
<td>Y</td>
<td>Y</td>
<td>N</td>
</tr>
</tbody>
</table>
</div>
confusions: <div className="content-container">
<p>Commonly <strong>confused pairs</strong> of choices:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Name</th>
<th><NAME>win</th>
<th>Details</th>
</tr>
<tr className="form-label">
<td>The name of the choice to show this pairing for</td>
<td>The name of the similar choice</td>
<td>A short explanation of how to tell the difference</td>
</tr>
<tr>
<td>Shark</td>
<td>Dolphin</td>
<td>A dolphin is shaped like a shark, but its tail is horizontal and it’s less terrifying.</td>
</tr>
</tbody>
</table>
</div>
questions: <div className="content-container">
<p><strong>Questions</strong> to ask about each identification:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Question</th>
<th>Multiple</th>
<th>Required</th>
<th>Answers</th>
<th>Include</th>
<th>Exclude</th>
</tr>
<tr className="form-label">
<td>The question to ask</td>
<td>Can the user select multiple answers? <code>Y</code> or <code>N</code></td>
<td>Is an answer required? <code>Y</code> or <code>N</code></td>
<td>The answers separated with <code>;</code></td>
<td>Choices to ask this question for (leave blank for all by default).</td>
<td>Choices to not ask this question for.</td>
</tr>
<tr>
<td>Is this an example question?</td>
<td>Y</td>
<td>N</td>
<td>Yes; No; Maybe</td>
<td> </td>
<td>Dolphin</td>
</tr>
</tbody>
</table>
</div>
| true | React = require 'react'
module.exports =
choices: <div className="content-container">
<p>User-identifiable <strong>choices</strong>, with these headers:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Name</th>
<th>Description</th>
<th>Images</th>
<th>No questions</th>
</tr>
<tr className="form-label">
<td>The label for the choice</td>
<td>A short description of the choice</td>
<td>Representative images of the choice, <code>;</code>-separated</td>
<td>Y or N for whether you want "sub-questions" to appear</td>
</tr>
<tr>
<td>Shark</td>
<td>A shark is a big gray ocean monster with fins and teeth.</td>
<td>shark.jpg</td>
<td>Y</td>
</tr>
<tr>
<td>Dolphin</td>
<td>Dolphins are intelligent marine mammals who solve crimes.</td>
<td>dolphin.jpg; flipper.jpg</td>
<td>N</td>
</tr>
</tbody>
</table>
</div>
images: <div className="content-container">
Pick some <strong>images</strong>. Make sure they have the exact same names as the ones in your other files.
</div>
characteristics: <div className="content-container">
<p><strong>Characteristics</strong> of those choices that the user can filter through. Note that the values in Name have to match the values in choices.csv exactly. Format like this:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Name</th>
<th>Color=Orange; orange.png</th>
<th>Color=Gray; gray.png</th>
<th>Teeth=Dull; dull.png</th>
<th>Teeth=Pointy; pointy.png</th>
</tr>
<tr className="form-label">
<td>Choice name</td>
<td colSpan="4"><code>Characteristic</code>=<code>value</code>; <code>icon filename</code>, with each row marked <code>Y</code> or <code>N</code> for that choice</td>
</tr>
<tr>
<td>Shark</td>
<td>N</td>
<td>Y</td>
<td>N</td>
<td>Y</td>
</tr>
<tr>
<td>Dolphin</td>
<td>Y</td>
<td>Y</td>
<td>Y</td>
<td>N</td>
</tr>
</tbody>
</table>
</div>
confusions: <div className="content-container">
<p>Commonly <strong>confused pairs</strong> of choices:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Name</th>
<th>PI:NAME:<NAME>END_PIwin</th>
<th>Details</th>
</tr>
<tr className="form-label">
<td>The name of the choice to show this pairing for</td>
<td>The name of the similar choice</td>
<td>A short explanation of how to tell the difference</td>
</tr>
<tr>
<td>Shark</td>
<td>Dolphin</td>
<td>A dolphin is shaped like a shark, but its tail is horizontal and it’s less terrifying.</td>
</tr>
</tbody>
</table>
</div>
questions: <div className="content-container">
<p><strong>Questions</strong> to ask about each identification:</p>
<table className="standard-table">
<tbody>
<tr>
<th>Question</th>
<th>Multiple</th>
<th>Required</th>
<th>Answers</th>
<th>Include</th>
<th>Exclude</th>
</tr>
<tr className="form-label">
<td>The question to ask</td>
<td>Can the user select multiple answers? <code>Y</code> or <code>N</code></td>
<td>Is an answer required? <code>Y</code> or <code>N</code></td>
<td>The answers separated with <code>;</code></td>
<td>Choices to ask this question for (leave blank for all by default).</td>
<td>Choices to not ask this question for.</td>
</tr>
<tr>
<td>Is this an example question?</td>
<td>Y</td>
<td>N</td>
<td>Yes; No; Maybe</td>
<td> </td>
<td>Dolphin</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"context": "ne )->\n\n\t\t\tquery =\n\t\t\t\ttoken:\n\t\t\t\t\t\"startsWith\": \"desfire-801e\"\n\t\t\topt =\n\t\t\t\tlimit: 0\n\t\t\t\t_customQueryF",
"end": 6886,
"score": 0.6305949687957764,
"start": 6883,
"tag": "USERNAME",
"value": "des"
},
{
"context": ")->\n\n\t\t\tquery =\n\t\t\t\ttoken:\n\t\t\t\t\t\"startsWith\": \"desfire-801e\"\n\t\t\topt =\n\t\t\t\tlimit: 0\n\t\t\t\t_customQueryFilter:\n\t\t",
"end": 6895,
"score": 0.673326313495636,
"start": 6886,
"tag": "PASSWORD",
"value": "fire-801e"
},
{
"context": "ne )->\n\n\t\t\tquery =\n\t\t\t\ttoken:\n\t\t\t\t\t\"startsWith\": \"desfire-801e\"\n\n\t\t\t\n\t\t\topt =\n\t\t\t\tlimit: 0\n\t\t\t\tjoins:\n\t\t\t\t\t\"user",
"end": 7860,
"score": 0.9917669296264648,
"start": 7848,
"tag": "PASSWORD",
"value": "desfire-801e"
},
{
"context": "->\n\t\t\tts = 1381322463000\n\t\t\tquery =\n\t\t\t\tuser_id: \"swDqh\"\n\t\t\t\t_t: { \">\": ts }\n\n\t\t\topt =\n\t\t\t\tlimit: 3\n\t\t\t\n\t",
"end": 11822,
"score": 0.8667969107627869,
"start": 11817,
"tag": "USERNAME",
"value": "swDqh"
},
{
"context": " string-id\", ( done )->\n\t\t\tdata =\n\t\t\t\tfirstname: \"Test\"\n\t\t\t\tlastname: \"Test\"\n\t\t\t\tgender: true\n\t\t\t\trole: ",
"end": 12235,
"score": 0.5903874635696411,
"start": 12231,
"tag": "NAME",
"value": "Test"
},
{
"context": "->\n\t\t\tdata =\n\t\t\t\tfirstname: \"Test\"\n\t\t\t\tlastname: \"Test\"\n\t\t\t\tgender: true\n\t\t\t\trole: \"USER\"\n\t\t\t\temail: \"te",
"end": 12256,
"score": 0.9222444295883179,
"start": 12252,
"tag": "NAME",
"value": "Test"
},
{
"context": "USER\"\n\t\t\t\temail: \"test.#{_utils.randomString( 5 )}@test.de\"\n\t\t\t\t_t: 0\n\n\t\t\ttableU.set( data, ( err, item )->\n",
"end": 12344,
"score": 0.8779003620147705,
"start": 12336,
"tag": "EMAIL",
"value": "@test.de"
},
{
"context": ">\n\t\t\tdata =\n\t\t\t\tfirstname: \"Test2\"\n\t\t\t\tlastname: \"Test\"\n\t\t\t\tgender: true\n\t\t\t\trole: \"USER\"\n\t\t\t\temail: \"te",
"end": 12993,
"score": 0.9386326670646667,
"start": 12989,
"tag": "NAME",
"value": "Test"
},
{
"context": "USER\"\n\t\t\t\temail: \"test.#{_utils.randomString( 5 )}@test.de\"\n\t\t\t\t_t: 0\n\n\t\t\ttableU.set( data, ( err, item )->\n",
"end": 13081,
"score": 0.9845811128616333,
"start": 13073,
"tag": "EMAIL",
"value": "@test.de"
},
{
"context": " test case\", ( done )->\n\t\t\tdata =\n\t\t\t\tfirstname: \"Test3\"\n\t\t\t\tlastname: \"Test\"\n\t\t\t\tgender: false\n\t\t\t\trole:",
"end": 13686,
"score": 0.8138779401779175,
"start": 13681,
"tag": "NAME",
"value": "Test3"
},
{
"context": ">\n\t\t\tdata =\n\t\t\t\tfirstname: \"Test3\"\n\t\t\t\tlastname: \"Test\"\n\t\t\t\tgender: false\n\t\t\t\trole: \"USER\"\n\t\t\t\temail: \"t",
"end": 13707,
"score": 0.7729424238204956,
"start": 13703,
"tag": "NAME",
"value": "Test"
},
{
"context": "USER\"\n\t\t\t\temail: \"test.#{_utils.randomString( 5 )}@test.de\"\n\t\t\t\t_t: 0\n\n\t\t\ttableU.set( data, ( err, item )->\n",
"end": 13796,
"score": 0.968903660774231,
"start": 13788,
"tag": "EMAIL",
"value": "@test.de"
},
{
"context": "should.have.property('firstname').and.equal( \"Test3\" )\n\t\t\t\titem.should.have.property('lastname').and.",
"end": 13993,
"score": 0.6332867741584778,
"start": 13992,
"tag": "NAME",
"value": "3"
},
{
"context": " test case\", ( done )->\n\t\t\tdata =\n\t\t\t\tfirstname: \"Test4\"\n\t\t\t\tlastname: \"Test\"\n\t\t\t\tgender: true\n\t\t\t\trole: ",
"end": 14403,
"score": 0.9441094398498535,
"start": 14398,
"tag": "NAME",
"value": "Test4"
},
{
"context": ">\n\t\t\tdata =\n\t\t\t\tfirstname: \"Test4\"\n\t\t\t\tlastname: \"Test\"\n\t\t\t\tgender: true\n\t\t\t\trole: \"USER\"\n\t\t\t\temail: \"te",
"end": 14424,
"score": 0.8885923624038696,
"start": 14420,
"tag": "NAME",
"value": "Test"
},
{
"context": "USER\"\n\t\t\t\temail: \"test.#{_utils.randomString( 5 )}@test.de\"\n\t\t\t\t_t: 0\n\n\t\t\ttableU.set( data, ( err, item )->\n",
"end": 14512,
"score": 0.9775205254554749,
"start": 14504,
"tag": "EMAIL",
"value": "@test.de"
},
{
"context": "should.have.property('firstname').and.equal( \"Test4\" )\n\t\t\t\titem.should.have.property('lastname').and.",
"end": 14709,
"score": 0.6278719305992126,
"start": 14708,
"tag": "NAME",
"value": "4"
},
{
"context": "item.should.have.property('lastname').and.equal( \"Test\" )\n\t\t\t\titem.should.have.property('gender').and.eq",
"end": 14771,
"score": 0.996407687664032,
"start": 14767,
"tag": "NAME",
"value": "Test"
},
{
"context": "String( 5 )\n\t\t\tdata =\n\t\t\t\tid: _id\n\t\t\t\tfirstname: \"Test\"\n\t\t\t\tlastname: \"Test\"\n\t\t\t\tgender: true\n\t\t\t\trole: ",
"end": 16083,
"score": 0.9971895813941956,
"start": 16079,
"tag": "NAME",
"value": "Test"
},
{
"context": "\n\t\t\t\tid: _id\n\t\t\t\tfirstname: \"Test\"\n\t\t\t\tlastname: \"Test\"\n\t\t\t\tgender: true\n\t\t\t\trole: \"USER\"\n\t\t\t\t_t: 0\n\t\t\tt",
"end": 16104,
"score": 0.9972260594367981,
"start": 16100,
"tag": "NAME",
"value": "Test"
},
{
"context": "\n\t\t\tdata =\n\t\t\t\tlastname: \"Update2\"\n\t\t\t\tpassword: \"test\"\n\t\t\t\t_t: _saveUserT\n\n\t\t\ttableU.set( _saveUserId, ",
"end": 17656,
"score": 0.9995618462562561,
"start": 17652,
"tag": "PASSWORD",
"value": "test"
},
{
"context": "m.should.have.property('password').and.containEql( \"$2a$10$\" )\n\n\t\t\t\titem.should.have.property('_u').and.equal(",
"end": 17880,
"score": 0.9991455078125,
"start": 17873,
"tag": "PASSWORD",
"value": "\"$2a$10"
},
{
"context": ")->\n\t\t\tdata =\n\t\t\t\tlastname: \"Update7\"\n\t\t\t\temail: \"testmilon@test.de\"\n\t\t\t\t_t: _saveUserT\n\n\t\t\ttableU.set( _saveUserId, ",
"end": 22338,
"score": 0.9999216198921204,
"start": 22321,
"tag": "EMAIL",
"value": "testmilon@test.de"
},
{
"context": "d.exist( err.value )\n\t\t\t\terr.value.should.equal( \"testmilon@test.de\" )\n\t\t\t\t\n\t\t\t\tdone()\n\t\t\t\treturn\n\t\t\t, {} )\n\t\t\treturn",
"end": 22669,
"score": 0.9999199509620667,
"start": 22652,
"tag": "EMAIL",
"value": "testmilon@test.de"
},
{
"context": "LE.COUNT\", ( done )->\n\t\t\tfilter =\n\t\t\t\tfirstname: \"Maxi\"\n\t\t\t\trole: \"TRAINER\"\n\t\t\ttableU.count( filter, ( e",
"end": 25673,
"score": 0.9996746778488159,
"start": 25669,
"tag": "NAME",
"value": "Maxi"
},
{
"context": "NT empty\", ( done )->\n\t\t\tfilter =\n\t\t\t\tfirstname: \"Maxi\"\n\t\t\t\trole: \"INVALIDROLE\"\n\t\t\ttableU.count( filter,",
"end": 25928,
"score": 0.9996719360351562,
"start": 25924,
"tag": "NAME",
"value": "Maxi"
}
] | _src/test/general.coffee | mpneuried/pg-factory | 0 | _CONFIG = require './config'
PgFactory = require( "../." )
_map = require( "lodash/map" )
_difference = require( "lodash/difference" )
should = require('should')
moment = require('moment')
_startTime = Date.now() - 1000 * 60
_utils = require( "../lib/utils" )
DBFactory = null
cbMulti = ( count, cb )->
return ->
count--
if count is 0
cb()
return
console.log "\nCONFIG:\n", _CONFIG.pg
describe "----- Postgres Factory TESTS -----", ->
before ( done )->
done()
return
describe 'Initialization', ->
it "1. init factory", ( done )->
DBFactory = new PgFactory( _CONFIG.pg, _CONFIG.tables )
done()
return
describe 'Factory Tests', ->
it "2. List the existing tables", ( done )->
DBFactory.list ( err, tables )->
throw err if err
tables.should.eql( Object.keys( _CONFIG.tables ) )
done()
return
it "3. Get a table", ( done )->
_cnf = _CONFIG.tables[ _CONFIG.test.singleCreateTableTest ]
_tbl = DBFactory.get( _CONFIG.test.singleCreateTableTest )
_tbl.should.exist
_tbl?.name?.should.eql( _cnf.name )
done()
return
it "4. Try to get a not existend table", ( done )->
_tbl = DBFactory.get( "notexistend" )
should.not.exist( _tbl )
done()
return
it "5. has for existend table", ( done )->
_has = DBFactory.has( _CONFIG.test.singleCreateTableTest )
_has.should.be.true
done()
return
it "6. has for not existend table", ( done )->
_has = DBFactory.has( "notexistend" )
_has.should.be.false
done()
return
return
describe 'Table Tests', ->
tableU = null # user
tableT = null # tokens
tableC = null # contracts
fieldsTest = [ "id", "firstname" ]
allFields = Object.keys( _CONFIG.tables[ _CONFIG.test.getTest.tbl ].fields )
_saveUserId = null
_saveUserT = 0
_testUsers = []
it "7. get test table `#{_CONFIG.test.getTest.tbl}`", ( done )->
tableU = DBFactory.get( _CONFIG.test.getTest.tbl )
tableU?.name?.should.eql( _CONFIG.test.getTest.tbl )
done()
return
it "8. get test table `#{_CONFIG.test.tokenTable}`", ( done )->
tableT = DBFactory.get( _CONFIG.test.tokenTable )
tableT?.name?.should.eql( _CONFIG.test.tokenTable )
done()
return
it "9. get test table `#{_CONFIG.test.contractsTable}`", ( done )->
tableC = DBFactory.get( _CONFIG.test.contractsTable )
tableC?.name?.should.eql( _CONFIG.test.contractsTable )
done()
return
it "10. TABLE.GET", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get _id, ( err, item )->
throw err if err
should.exist( item.id )
item.id.should.equal( _id )
done()
return
return
it "11. TABLE.GET fields as array", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,fieldsTest).should.have.length(0)
done()
return
, fields: fieldsTest )
return
it "12. TABLE.GET fields as string", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,fieldsTest).should.have.length(0)
done()
return
, fields: fieldsTest.join( ", " ) )
return
it "13. TABLE.GET fields as set", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,fieldsTest).should.have.length(0)
done()
return
, fields: "set:test" )
return
it "14. TABLE.GET fields `all`", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,allFields).should.have.length(0)
done()
return
, fields: "all" )
return
it "15. TABLE.GET fields `*`", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,allFields).should.have.length(0)
done()
return
, fields: "all" )
return
it "16. TABLE.GET fields `idonly`", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,[ "id" ]).should.have.length(0)
done()
return
, fields: "idonly" )
return
it "17. TABLE.GET fields by filter function", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,[ "id", "_t", "_u" ]).should.have.length(0)
done()
return
, fields: ( (fld)->
fld.name.length <= 2 ) )
return
it "18. TABLE.MGET", ( done )->
_ids = JSON.parse( JSON.stringify( _CONFIG.test.mgetTest.id ) )
tableU.mget _ids, ( err, items )->
throw err if err
items.should.have.length(2)
_difference(_CONFIG.test.mgetTest.id,_map( items, "id" ) ).should.have.length(0)
done()
return
return
it "19. TABLE.MGET empty", ( done )->
tableU.mget [], ( err, items )->
throw err if err
items.should.have.length(0)
done()
return
return
it "20. TABLE.FIND all", ( done )->
@timeout( 6000 )
tableU.find {}, ( err, items )->
throw err if err
items.should.have.length( _CONFIG.tables.Users.limit)
done()
return
return
it "21. TABLE.FIND query", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
tableU.find query, ( err, items )->
throw err if err
items.should.have.length( 6 )
done()
return
return
it "22. TABLE.FIND with limit", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
query.limit = 1
tableU.find( query, ( err, items )->
throw err if err
items.should.have.length(1)
done()
return
, {} )
return
it "23. TABLE.FIND with limit by option", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
tableU.find( query, ( err, items )->
throw err if err
items.should.have.length(1)
done()
return
, { limit: 1 } )
return
it "24. TABLE.FIND with `idonly`", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
tableU.find( query, ( err, items )->
throw err if err
items.should.be.an.instanceOf(Array)
for id in items
id.should.be.a.String
done()
return
, { fields: "idonly" } )
return
it "25. TABLE.FIND studio tokens with subquery", ( done )->
query =
token:
"startsWith": "desfire-801e"
opt =
limit: 0
_customQueryFilter:
"user_id":
sub:
table: "contracts"
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-TOKENS SUB", items.length
done()
return
, opt )
return
it "26. TABLE.FIND studio users with subquery", ( done )->
query =
"id":
sub:
table: "contracts"
field: "user_id"
filter:
studio_id: 1
contracttype: 1
opt =
limit: 0
tableU.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-USR SUB", items.length
done()
return
, opt )
return
it "27. TABLE.FIND studio tokens with TABLE.JOIN", ( done )->
query =
token:
"startsWith": "desfire-801e"
opt =
limit: 0
joins:
"user_id":
type: "inner"
table: "Contracts"
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-TOKENS JOIN", items.length
done()
return
, opt )
return
it "28. TABLE.FIND studio users with TABLE.JOIN with table instance", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
table: tableC
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-USR JOIN", items.length
done()
return
, opt )
return
it "29. TABLE.JOIN without table", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
#table: tableC
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "missing-join-table" )
done()
return
, opt )
return
it "30. TABLE.JOIN without field", ( done )->
query =
studio_id: 1
contracttype: 1
opt =
fields: "*"
limit: 0
joins:
"user_id":
type: "left outer"
table: tableU
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
done()
return
, opt )
return
it "31. TABLE.JOIN with invalid field", ( done )->
query = {}
opt =
limit: 0
joins:
"_id":
table: tableC
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-field" )
done()
return
, opt )
return
it "32. TABLE.JOIN with invalid foreign field", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
table: tableC
field: "_user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-foreignfield" )
done()
return
, opt )
return
it "33. TABLE.JOIN with invalid table", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
table: "_Contracts"
field: "_user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-table" )
done()
return
, opt )
return
it "34. TABLE.JOIN with invalid type", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
type: "foo"
table: tableC
field: "_user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-type" )
done()
return
, opt )
return
###
it "35. TABLE.FIND with option `_customQueryFilter`", ( done )->
query = _CONFIG.test.findTest.q
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "deprecated-option" )
done()
return
, { _customQueryFilter: "id = 'abcde'" } )
return
###
it "36. TABLE.FIND with invalid filter", ( done )->
tableU.find "wrong", ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-filter" )
done()
return
return
it "37. TABLE.FIND with complex filter", ( done )->
ts = 1381322463000
query =
user_id: "swDqh"
_t: { ">": ts }
opt =
limit: 3
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
items.should.have.property( "length" ).and.be.below(4)
for item in items
item._t.should.be.above( ts )
done()
return
, opt )
return
it "38. TABLE.INSERT string-id", ( done )->
data =
firstname: "Test"
lastname: "Test"
gender: true
role: "USER"
email: "test.#{_utils.randomString( 5 )}@test.de"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_saveUserId = item.id
_saveUserT = item._t
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "39. TABLE.INSERT second test case", ( done )->
data =
firstname: "Test2"
lastname: "Test"
gender: true
role: "USER"
email: "test.#{_utils.randomString( 5 )}@test.de"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_testUsers.push item
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test2" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "40. TABLE.INSERT third test case", ( done )->
data =
firstname: "Test3"
lastname: "Test"
gender: false
role: "USER"
email: "test.#{_utils.randomString( 5 )}@test.de"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_testUsers.push item
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test3" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( false )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "41. TABLE.INSERT fourth test case", ( done )->
data =
firstname: "Test4"
lastname: "Test"
gender: true
role: "USER"
email: "test.#{_utils.randomString( 5 )}@test.de"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_testUsers.push item
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test4" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "42. TABLE.INSERT with createId function", ( done )->
_tbl = DBFactory.get( "Apikeys" )
data =
studio_id: 1
jsonOptions: {}
_tbl.set( data, ( err, item )->
throw err if err
item.should.have.property('apikey').and.match( /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}/ )
item.should.have.property('studio_id').and.equal( 1 )
done()
return
, {} )
return
it "43. TABLE.INSERT autoincrement-id", ( done )->
data = JSON.parse( JSON.stringify( _CONFIG.test.insertTestToken ) )
tableT.set( data, ( err, item )->
throw err if err
item.should.have.property('id')
item.should.have.property('user_id')
item.should.have.property('studio_id')
item.should.have.property('token')
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "44. TABLE.INSERT predefined string-id", ( done )->
_id = _utils.randomString( 5 )
data =
id: _id
firstname: "Test"
lastname: "Test"
gender: true
role: "USER"
_t: 0
tableU.set( data, ( err, item )->
# special case. A predefined is could allready exist
if err?.code is "ER_DUP_ENTRY"
done()
return
throw err if err
item.should.have.property('id').and.equal(_id)
item.should.have.property('firstname').and.equal( "Test" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.within( _startTime, +Infinity )
item.should.have.property('_u')
done()
return
, {} )
return
it "45. TABLE.INSERT existing predefined string-id", ( done )->
data =
id: _CONFIG.test.getTest.id
firstname: "Test"
lastname: "Test"
gender: true
role: "USER"
_t: 0
tableU.set( data, ( err, item )->
should.exist( err )
err.code.should.equal( "ER_DUP_ENTRY" )
done()
return
, {} )
return
it "46. TABLE.UPDATE", ( done )->
data =
lastname: "Update1"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update1" )
item.should.have.property('_u').and.equal( 1 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "47. TABLE.UPDATE with crypting passowrd", ( done )->
data =
lastname: "Update2"
password: "test"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update2" )
item.should.have.property('password').and.containEql( "$2a$10$" )
item.should.have.property('_u').and.equal( 2 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "48. TABLE.UPDATE with event check", ( done )->
data =
lastname: "Update3"
birthday: new Date( 1950,5,15 )
image: "testimage.jpg"
role: "TRAINER"
_t: _saveUserT
_done = cbMulti 5, ->
tableU.removeListener( "lastname.userchanged", fnEvnt1 )
tableU.removeListener( "birthday.userchanged", fnEvnt2 )
tableU.removeListener( "image.userchanged", fnEvnt3 )
tableU.removeListener( "set", fnEvnt4 )
done()
return
fnEvnt1 = ( oldValue, newValue, id )->
id.should.equal( _saveUserId )
oldValue.should.equal( "Update2" )
newValue.should.equal( "Update3" )
_done()
return
tableU.on "lastname.userchanged", fnEvnt1
fnEvnt2 = ( oldValue, newValue, id )->
id.should.equal( _saveUserId )
should.not.exist( oldValue )
newValue.toUTCString().should.equal(new Date( 1950,5,15 ).toUTCString())
_done()
return
tableU.on "birthday.userchanged", fnEvnt2
fnEvnt3 = ( oldValue, newValue, id )->
id.should.equal( _saveUserId )
should.not.exist( oldValue )
newValue.should.equal( "testimage.jpg" )
_done()
return
tableU.on "image.userchanged", fnEvnt3
fnEvnt4 = ( err, item )->
item.should.have.property('lastname').and.equal( "Update3" )
item.should.have.property('role').and.equal( "TRAINER" )
item.should.have.property('_u').and.equal( 3 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_done()
return
tableU.on "set", fnEvnt4
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update3" )
item.should.have.property('role').and.equal( "TRAINER" )
item.should.have.property('_u').and.equal( 3 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
_done()
return
, {} )
return
it "49. TABLE.UPDATE with invalid role", ( done )->
data =
lastname: "Update4"
role: "MILON"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "value-not-allowed" )
done()
return
, {} )
return
it "50. TABLE.UPDATE with with json object", ( done )->
data =
lastname: "Update5"
jsonSettings:
a: 123
b: 456
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update5" )
item.should.have.property('jsonSettings').and.eql
a: 123
b: 456
item.should.have.property('_u').and.equal( 4 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "51. TABLE.UPDATE with wrong `_t` check", ( done )->
data =
lastname: "Update6"
_t: _startTime
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "validation-notequal" )
should.exist( err.field )
err.field.should.equal( "_t" )
should.exist( err.value )
err.value.should.equal( _startTime )
should.exist( err.curr )
err.curr.should.equal( _saveUserT )
done()
return
, {} )
return
it "52. TABLE.UPDATE without `_t", ( done )->
data =
lastname: "Update7b"
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "validation-notequal-required" )
should.exist( err.field )
err.field.should.equal( "_t" )
done()
return
, {} )
return
it "53. TABLE.UPDATE try a manual of `_u`", ( done )->
data =
lastname: "Update7"
_u: 99
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update7" )
item.should.have.property('_u').and.equal( 5 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "54. TABLE.UPDATE with existing `mail`", ( done )->
data =
lastname: "Update7"
email: "testmilon@test.de"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "validation-already-existend" )
should.exist( err.field )
err.field.should.equal( "email" )
should.exist( err.value )
err.value.should.equal( "testmilon@test.de" )
done()
return
, {} )
return
it "55. TABLE.UPDATE date fields as `Date`", ( done )->
_date = new Date()
data =
lastname: "Update8"
lastlogin: _date
deletedate: _date
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( Math.round( _date.getTime() / 1000 ) )
item.should.have.property('deletedate').and.equal( _date.getTime() )
item.should.have.property('lastname').and.equal( "Update8" )
item.should.have.property('_u').and.equal( 6 )
_saveUserT = item._t
done()
return
, {} )
return
it "56. TABLE.UPDATE date fields as `Number` in ms", ( done )->
_date = new Date().getTime()
data =
lastname: "Update9"
lastlogin: _date
deletedate: _date
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( Math.round( _date / 1000 ) )
item.should.have.property('deletedate').and.equal( _date )
item.should.have.property('lastname').and.equal( "Update9" )
item.should.have.property('_u').and.equal( 7 )
_saveUserT = item._t
done()
return
, {} )
return
it "57. TABLE.UPDATE date fields as `Number` in s", ( done )->
_date = Math.round( new Date().getTime() / 1000 )
data =
lastname: "Update10"
lastlogin: _date
deletedate: _date
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( _date )
item.should.have.property('deletedate').and.equal( _date * 1000 )
item.should.have.property('lastname').and.equal( "Update10" )
item.should.have.property('_u').and.equal( 8 )
_saveUserT = item._t
done()
return
, {} )
return
it "58. TABLE.UPDATE date fields as `String`", ( done )->
_date = moment( moment().format( "YYYY-MM-DD HH:mm" ), "YYYY-MM-DD HH:mm" )
data =
lastname: "Update11"
lastlogin: _date.format( "YYYY-MM-DD HH:mm" )
deletedate: _date.format( "YYYY-MM-DD HH:mm" )
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( _date.unix() )
item.should.have.property('deletedate').and.equal( _date.valueOf() )
item.should.have.property('lastname').and.equal( "Update11" )
item.should.have.property('_u').and.equal( 9 )
_saveUserT = item._t
done()
return
, {} )
return
it "59. TABLE.HAS", ( done )->
tableU.has( _saveUserId, ( err, existend )->
throw err if err
existend.should.be.ok
done()
return
, {} )
return
it "60. TABLE.HAS not existend", ( done )->
tableU.has( "notexist", ( err, existend )->
throw err if err
existend.should.not.be.ok
done()
return
, {} )
return
it "61. TABLE.COUNT", ( done )->
filter =
firstname: "Maxi"
role: "TRAINER"
tableU.count( filter, ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 6 )
done()
return
, {} )
return
it "62. TABLE.COUNT empty", ( done )->
filter =
firstname: "Maxi"
role: "INVALIDROLE"
tableU.count( filter, ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 0 )
done()
return
, {} )
return
it "63. TABLE.INCREMENT", ( done )->
tableU.increment( _saveUserId, "plansversion", ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 1 )
done()
return
, {} )
return
it "64. TABLE.INCREMENT second increment", ( done )->
tableU.increment( _saveUserId, "plansversion", ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 2 )
done()
return
, {} )
return
it "65. TABLE.INCREMENT unknown field", ( done )->
tableU.increment( _saveUserId, "unknown", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-field" )
should.exist( err.field )
err.field.should.equal( "unknown" )
done()
return
, {} )
return
it "66. TABLE.INCREMENT unknown id", ( done )->
tableU.increment( "unknown", "plansversion", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "67. TABLE.DECREMENT", ( done )->
tableU.decrement( _saveUserId, "plansversion", ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 1 )
done()
return
, {} )
return
it "68. TABLE.INCREMENT unknown field", ( done )->
tableU.decrement( _saveUserId, "unknown", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-field" )
should.exist( err.field )
err.field.should.equal( "unknown" )
done()
return
, {} )
return
it "69. TABLE.INCREMENT unknown id", ( done )->
tableU.decrement( "unknown", "plansversion", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "70. TABLE.DEL", ( done )->
_usr = _testUsers[ 0 ]
tableU.del( _usr.id, ( err, item )->
throw err if err
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test2" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_u')
done()
return
, {} )
return
it "71. TABLE.GET deleted", ( done )->
_usr = _testUsers[ 0 ]
tableU.get( _usr.id, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "72. TABLE.DEL deleted", ( done )->
_usr = _testUsers[ 0 ]
tableU.del( _usr.id, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "73. TABLE.MDEL invalid filter", ( done )->
_usrA = _testUsers[ 1 ]
_usrB = _testUsers[ 2 ]
ids = [ _usrA.id, _usrB.id ]
tableU.mdel( user_id: ids, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "no-filter" )
done()
return
, {} )
return
it "74. TABLE.MDEL", ( done )->
_usrA = _testUsers[ 1 ]
_usrB = _testUsers[ 2 ]
ids = [ _usrA.id, _usrB.id ]
tableU.mdel( id: ids, ( err, items )->
throw err if err
_difference(ids,_map( items, "id" ) ).should.have.length(0)
done()
return
, {} )
return
it "75. TABLE.GET", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get _testUsers[ 1 ].id, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
return
| 149988 | _CONFIG = require './config'
PgFactory = require( "../." )
_map = require( "lodash/map" )
_difference = require( "lodash/difference" )
should = require('should')
moment = require('moment')
_startTime = Date.now() - 1000 * 60
_utils = require( "../lib/utils" )
DBFactory = null
cbMulti = ( count, cb )->
return ->
count--
if count is 0
cb()
return
console.log "\nCONFIG:\n", _CONFIG.pg
describe "----- Postgres Factory TESTS -----", ->
before ( done )->
done()
return
describe 'Initialization', ->
it "1. init factory", ( done )->
DBFactory = new PgFactory( _CONFIG.pg, _CONFIG.tables )
done()
return
describe 'Factory Tests', ->
it "2. List the existing tables", ( done )->
DBFactory.list ( err, tables )->
throw err if err
tables.should.eql( Object.keys( _CONFIG.tables ) )
done()
return
it "3. Get a table", ( done )->
_cnf = _CONFIG.tables[ _CONFIG.test.singleCreateTableTest ]
_tbl = DBFactory.get( _CONFIG.test.singleCreateTableTest )
_tbl.should.exist
_tbl?.name?.should.eql( _cnf.name )
done()
return
it "4. Try to get a not existend table", ( done )->
_tbl = DBFactory.get( "notexistend" )
should.not.exist( _tbl )
done()
return
it "5. has for existend table", ( done )->
_has = DBFactory.has( _CONFIG.test.singleCreateTableTest )
_has.should.be.true
done()
return
it "6. has for not existend table", ( done )->
_has = DBFactory.has( "notexistend" )
_has.should.be.false
done()
return
return
describe 'Table Tests', ->
tableU = null # user
tableT = null # tokens
tableC = null # contracts
fieldsTest = [ "id", "firstname" ]
allFields = Object.keys( _CONFIG.tables[ _CONFIG.test.getTest.tbl ].fields )
_saveUserId = null
_saveUserT = 0
_testUsers = []
it "7. get test table `#{_CONFIG.test.getTest.tbl}`", ( done )->
tableU = DBFactory.get( _CONFIG.test.getTest.tbl )
tableU?.name?.should.eql( _CONFIG.test.getTest.tbl )
done()
return
it "8. get test table `#{_CONFIG.test.tokenTable}`", ( done )->
tableT = DBFactory.get( _CONFIG.test.tokenTable )
tableT?.name?.should.eql( _CONFIG.test.tokenTable )
done()
return
it "9. get test table `#{_CONFIG.test.contractsTable}`", ( done )->
tableC = DBFactory.get( _CONFIG.test.contractsTable )
tableC?.name?.should.eql( _CONFIG.test.contractsTable )
done()
return
it "10. TABLE.GET", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get _id, ( err, item )->
throw err if err
should.exist( item.id )
item.id.should.equal( _id )
done()
return
return
it "11. TABLE.GET fields as array", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,fieldsTest).should.have.length(0)
done()
return
, fields: fieldsTest )
return
it "12. TABLE.GET fields as string", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,fieldsTest).should.have.length(0)
done()
return
, fields: fieldsTest.join( ", " ) )
return
it "13. TABLE.GET fields as set", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,fieldsTest).should.have.length(0)
done()
return
, fields: "set:test" )
return
it "14. TABLE.GET fields `all`", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,allFields).should.have.length(0)
done()
return
, fields: "all" )
return
it "15. TABLE.GET fields `*`", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,allFields).should.have.length(0)
done()
return
, fields: "all" )
return
it "16. TABLE.GET fields `idonly`", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,[ "id" ]).should.have.length(0)
done()
return
, fields: "idonly" )
return
it "17. TABLE.GET fields by filter function", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,[ "id", "_t", "_u" ]).should.have.length(0)
done()
return
, fields: ( (fld)->
fld.name.length <= 2 ) )
return
it "18. TABLE.MGET", ( done )->
_ids = JSON.parse( JSON.stringify( _CONFIG.test.mgetTest.id ) )
tableU.mget _ids, ( err, items )->
throw err if err
items.should.have.length(2)
_difference(_CONFIG.test.mgetTest.id,_map( items, "id" ) ).should.have.length(0)
done()
return
return
it "19. TABLE.MGET empty", ( done )->
tableU.mget [], ( err, items )->
throw err if err
items.should.have.length(0)
done()
return
return
it "20. TABLE.FIND all", ( done )->
@timeout( 6000 )
tableU.find {}, ( err, items )->
throw err if err
items.should.have.length( _CONFIG.tables.Users.limit)
done()
return
return
it "21. TABLE.FIND query", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
tableU.find query, ( err, items )->
throw err if err
items.should.have.length( 6 )
done()
return
return
it "22. TABLE.FIND with limit", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
query.limit = 1
tableU.find( query, ( err, items )->
throw err if err
items.should.have.length(1)
done()
return
, {} )
return
it "23. TABLE.FIND with limit by option", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
tableU.find( query, ( err, items )->
throw err if err
items.should.have.length(1)
done()
return
, { limit: 1 } )
return
it "24. TABLE.FIND with `idonly`", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
tableU.find( query, ( err, items )->
throw err if err
items.should.be.an.instanceOf(Array)
for id in items
id.should.be.a.String
done()
return
, { fields: "idonly" } )
return
it "25. TABLE.FIND studio tokens with subquery", ( done )->
query =
token:
"startsWith": "des<PASSWORD>"
opt =
limit: 0
_customQueryFilter:
"user_id":
sub:
table: "contracts"
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-TOKENS SUB", items.length
done()
return
, opt )
return
it "26. TABLE.FIND studio users with subquery", ( done )->
query =
"id":
sub:
table: "contracts"
field: "user_id"
filter:
studio_id: 1
contracttype: 1
opt =
limit: 0
tableU.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-USR SUB", items.length
done()
return
, opt )
return
it "27. TABLE.FIND studio tokens with TABLE.JOIN", ( done )->
query =
token:
"startsWith": "<PASSWORD>"
opt =
limit: 0
joins:
"user_id":
type: "inner"
table: "Contracts"
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-TOKENS JOIN", items.length
done()
return
, opt )
return
it "28. TABLE.FIND studio users with TABLE.JOIN with table instance", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
table: tableC
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-USR JOIN", items.length
done()
return
, opt )
return
it "29. TABLE.JOIN without table", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
#table: tableC
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "missing-join-table" )
done()
return
, opt )
return
it "30. TABLE.JOIN without field", ( done )->
query =
studio_id: 1
contracttype: 1
opt =
fields: "*"
limit: 0
joins:
"user_id":
type: "left outer"
table: tableU
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
done()
return
, opt )
return
it "31. TABLE.JOIN with invalid field", ( done )->
query = {}
opt =
limit: 0
joins:
"_id":
table: tableC
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-field" )
done()
return
, opt )
return
it "32. TABLE.JOIN with invalid foreign field", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
table: tableC
field: "_user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-foreignfield" )
done()
return
, opt )
return
it "33. TABLE.JOIN with invalid table", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
table: "_Contracts"
field: "_user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-table" )
done()
return
, opt )
return
it "34. TABLE.JOIN with invalid type", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
type: "foo"
table: tableC
field: "_user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-type" )
done()
return
, opt )
return
###
it "35. TABLE.FIND with option `_customQueryFilter`", ( done )->
query = _CONFIG.test.findTest.q
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "deprecated-option" )
done()
return
, { _customQueryFilter: "id = 'abcde'" } )
return
###
it "36. TABLE.FIND with invalid filter", ( done )->
tableU.find "wrong", ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-filter" )
done()
return
return
it "37. TABLE.FIND with complex filter", ( done )->
ts = 1381322463000
query =
user_id: "swDqh"
_t: { ">": ts }
opt =
limit: 3
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
items.should.have.property( "length" ).and.be.below(4)
for item in items
item._t.should.be.above( ts )
done()
return
, opt )
return
it "38. TABLE.INSERT string-id", ( done )->
data =
firstname: "<NAME>"
lastname: "<NAME>"
gender: true
role: "USER"
email: "test.#{_utils.randomString( 5 )}<EMAIL>"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_saveUserId = item.id
_saveUserT = item._t
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "39. TABLE.INSERT second test case", ( done )->
data =
firstname: "Test2"
lastname: "<NAME>"
gender: true
role: "USER"
email: "test.#{_utils.randomString( 5 )}<EMAIL>"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_testUsers.push item
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test2" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "40. TABLE.INSERT third test case", ( done )->
data =
firstname: "<NAME>"
lastname: "<NAME>"
gender: false
role: "USER"
email: "test.#{_utils.randomString( 5 )}<EMAIL>"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_testUsers.push item
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test<NAME>" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( false )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "41. TABLE.INSERT fourth test case", ( done )->
data =
firstname: "<NAME>"
lastname: "<NAME>"
gender: true
role: "USER"
email: "test.#{_utils.randomString( 5 )}<EMAIL>"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_testUsers.push item
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test<NAME>" )
item.should.have.property('lastname').and.equal( "<NAME>" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "42. TABLE.INSERT with createId function", ( done )->
_tbl = DBFactory.get( "Apikeys" )
data =
studio_id: 1
jsonOptions: {}
_tbl.set( data, ( err, item )->
throw err if err
item.should.have.property('apikey').and.match( /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}/ )
item.should.have.property('studio_id').and.equal( 1 )
done()
return
, {} )
return
it "43. TABLE.INSERT autoincrement-id", ( done )->
data = JSON.parse( JSON.stringify( _CONFIG.test.insertTestToken ) )
tableT.set( data, ( err, item )->
throw err if err
item.should.have.property('id')
item.should.have.property('user_id')
item.should.have.property('studio_id')
item.should.have.property('token')
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "44. TABLE.INSERT predefined string-id", ( done )->
_id = _utils.randomString( 5 )
data =
id: _id
firstname: "<NAME>"
lastname: "<NAME>"
gender: true
role: "USER"
_t: 0
tableU.set( data, ( err, item )->
# special case. A predefined is could allready exist
if err?.code is "ER_DUP_ENTRY"
done()
return
throw err if err
item.should.have.property('id').and.equal(_id)
item.should.have.property('firstname').and.equal( "Test" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.within( _startTime, +Infinity )
item.should.have.property('_u')
done()
return
, {} )
return
it "45. TABLE.INSERT existing predefined string-id", ( done )->
data =
id: _CONFIG.test.getTest.id
firstname: "Test"
lastname: "Test"
gender: true
role: "USER"
_t: 0
tableU.set( data, ( err, item )->
should.exist( err )
err.code.should.equal( "ER_DUP_ENTRY" )
done()
return
, {} )
return
it "46. TABLE.UPDATE", ( done )->
data =
lastname: "Update1"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update1" )
item.should.have.property('_u').and.equal( 1 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "47. TABLE.UPDATE with crypting passowrd", ( done )->
data =
lastname: "Update2"
password: "<PASSWORD>"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update2" )
item.should.have.property('password').and.containEql( <PASSWORD>$" )
item.should.have.property('_u').and.equal( 2 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "48. TABLE.UPDATE with event check", ( done )->
data =
lastname: "Update3"
birthday: new Date( 1950,5,15 )
image: "testimage.jpg"
role: "TRAINER"
_t: _saveUserT
_done = cbMulti 5, ->
tableU.removeListener( "lastname.userchanged", fnEvnt1 )
tableU.removeListener( "birthday.userchanged", fnEvnt2 )
tableU.removeListener( "image.userchanged", fnEvnt3 )
tableU.removeListener( "set", fnEvnt4 )
done()
return
fnEvnt1 = ( oldValue, newValue, id )->
id.should.equal( _saveUserId )
oldValue.should.equal( "Update2" )
newValue.should.equal( "Update3" )
_done()
return
tableU.on "lastname.userchanged", fnEvnt1
fnEvnt2 = ( oldValue, newValue, id )->
id.should.equal( _saveUserId )
should.not.exist( oldValue )
newValue.toUTCString().should.equal(new Date( 1950,5,15 ).toUTCString())
_done()
return
tableU.on "birthday.userchanged", fnEvnt2
fnEvnt3 = ( oldValue, newValue, id )->
id.should.equal( _saveUserId )
should.not.exist( oldValue )
newValue.should.equal( "testimage.jpg" )
_done()
return
tableU.on "image.userchanged", fnEvnt3
fnEvnt4 = ( err, item )->
item.should.have.property('lastname').and.equal( "Update3" )
item.should.have.property('role').and.equal( "TRAINER" )
item.should.have.property('_u').and.equal( 3 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_done()
return
tableU.on "set", fnEvnt4
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update3" )
item.should.have.property('role').and.equal( "TRAINER" )
item.should.have.property('_u').and.equal( 3 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
_done()
return
, {} )
return
it "49. TABLE.UPDATE with invalid role", ( done )->
data =
lastname: "Update4"
role: "MILON"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "value-not-allowed" )
done()
return
, {} )
return
it "50. TABLE.UPDATE with with json object", ( done )->
data =
lastname: "Update5"
jsonSettings:
a: 123
b: 456
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update5" )
item.should.have.property('jsonSettings').and.eql
a: 123
b: 456
item.should.have.property('_u').and.equal( 4 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "51. TABLE.UPDATE with wrong `_t` check", ( done )->
data =
lastname: "Update6"
_t: _startTime
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "validation-notequal" )
should.exist( err.field )
err.field.should.equal( "_t" )
should.exist( err.value )
err.value.should.equal( _startTime )
should.exist( err.curr )
err.curr.should.equal( _saveUserT )
done()
return
, {} )
return
it "52. TABLE.UPDATE without `_t", ( done )->
data =
lastname: "Update7b"
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "validation-notequal-required" )
should.exist( err.field )
err.field.should.equal( "_t" )
done()
return
, {} )
return
it "53. TABLE.UPDATE try a manual of `_u`", ( done )->
data =
lastname: "Update7"
_u: 99
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update7" )
item.should.have.property('_u').and.equal( 5 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "54. TABLE.UPDATE with existing `mail`", ( done )->
data =
lastname: "Update7"
email: "<EMAIL>"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "validation-already-existend" )
should.exist( err.field )
err.field.should.equal( "email" )
should.exist( err.value )
err.value.should.equal( "<EMAIL>" )
done()
return
, {} )
return
it "55. TABLE.UPDATE date fields as `Date`", ( done )->
_date = new Date()
data =
lastname: "Update8"
lastlogin: _date
deletedate: _date
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( Math.round( _date.getTime() / 1000 ) )
item.should.have.property('deletedate').and.equal( _date.getTime() )
item.should.have.property('lastname').and.equal( "Update8" )
item.should.have.property('_u').and.equal( 6 )
_saveUserT = item._t
done()
return
, {} )
return
it "56. TABLE.UPDATE date fields as `Number` in ms", ( done )->
_date = new Date().getTime()
data =
lastname: "Update9"
lastlogin: _date
deletedate: _date
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( Math.round( _date / 1000 ) )
item.should.have.property('deletedate').and.equal( _date )
item.should.have.property('lastname').and.equal( "Update9" )
item.should.have.property('_u').and.equal( 7 )
_saveUserT = item._t
done()
return
, {} )
return
it "57. TABLE.UPDATE date fields as `Number` in s", ( done )->
_date = Math.round( new Date().getTime() / 1000 )
data =
lastname: "Update10"
lastlogin: _date
deletedate: _date
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( _date )
item.should.have.property('deletedate').and.equal( _date * 1000 )
item.should.have.property('lastname').and.equal( "Update10" )
item.should.have.property('_u').and.equal( 8 )
_saveUserT = item._t
done()
return
, {} )
return
it "58. TABLE.UPDATE date fields as `String`", ( done )->
_date = moment( moment().format( "YYYY-MM-DD HH:mm" ), "YYYY-MM-DD HH:mm" )
data =
lastname: "Update11"
lastlogin: _date.format( "YYYY-MM-DD HH:mm" )
deletedate: _date.format( "YYYY-MM-DD HH:mm" )
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( _date.unix() )
item.should.have.property('deletedate').and.equal( _date.valueOf() )
item.should.have.property('lastname').and.equal( "Update11" )
item.should.have.property('_u').and.equal( 9 )
_saveUserT = item._t
done()
return
, {} )
return
it "59. TABLE.HAS", ( done )->
tableU.has( _saveUserId, ( err, existend )->
throw err if err
existend.should.be.ok
done()
return
, {} )
return
it "60. TABLE.HAS not existend", ( done )->
tableU.has( "notexist", ( err, existend )->
throw err if err
existend.should.not.be.ok
done()
return
, {} )
return
it "61. TABLE.COUNT", ( done )->
filter =
firstname: "<NAME>"
role: "TRAINER"
tableU.count( filter, ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 6 )
done()
return
, {} )
return
it "62. TABLE.COUNT empty", ( done )->
filter =
firstname: "<NAME>"
role: "INVALIDROLE"
tableU.count( filter, ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 0 )
done()
return
, {} )
return
it "63. TABLE.INCREMENT", ( done )->
tableU.increment( _saveUserId, "plansversion", ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 1 )
done()
return
, {} )
return
it "64. TABLE.INCREMENT second increment", ( done )->
tableU.increment( _saveUserId, "plansversion", ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 2 )
done()
return
, {} )
return
it "65. TABLE.INCREMENT unknown field", ( done )->
tableU.increment( _saveUserId, "unknown", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-field" )
should.exist( err.field )
err.field.should.equal( "unknown" )
done()
return
, {} )
return
it "66. TABLE.INCREMENT unknown id", ( done )->
tableU.increment( "unknown", "plansversion", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "67. TABLE.DECREMENT", ( done )->
tableU.decrement( _saveUserId, "plansversion", ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 1 )
done()
return
, {} )
return
it "68. TABLE.INCREMENT unknown field", ( done )->
tableU.decrement( _saveUserId, "unknown", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-field" )
should.exist( err.field )
err.field.should.equal( "unknown" )
done()
return
, {} )
return
it "69. TABLE.INCREMENT unknown id", ( done )->
tableU.decrement( "unknown", "plansversion", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "70. TABLE.DEL", ( done )->
_usr = _testUsers[ 0 ]
tableU.del( _usr.id, ( err, item )->
throw err if err
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test2" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_u')
done()
return
, {} )
return
it "71. TABLE.GET deleted", ( done )->
_usr = _testUsers[ 0 ]
tableU.get( _usr.id, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "72. TABLE.DEL deleted", ( done )->
_usr = _testUsers[ 0 ]
tableU.del( _usr.id, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "73. TABLE.MDEL invalid filter", ( done )->
_usrA = _testUsers[ 1 ]
_usrB = _testUsers[ 2 ]
ids = [ _usrA.id, _usrB.id ]
tableU.mdel( user_id: ids, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "no-filter" )
done()
return
, {} )
return
it "74. TABLE.MDEL", ( done )->
_usrA = _testUsers[ 1 ]
_usrB = _testUsers[ 2 ]
ids = [ _usrA.id, _usrB.id ]
tableU.mdel( id: ids, ( err, items )->
throw err if err
_difference(ids,_map( items, "id" ) ).should.have.length(0)
done()
return
, {} )
return
it "75. TABLE.GET", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get _testUsers[ 1 ].id, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
return
| true | _CONFIG = require './config'
PgFactory = require( "../." )
_map = require( "lodash/map" )
_difference = require( "lodash/difference" )
should = require('should')
moment = require('moment')
_startTime = Date.now() - 1000 * 60
_utils = require( "../lib/utils" )
DBFactory = null
cbMulti = ( count, cb )->
return ->
count--
if count is 0
cb()
return
console.log "\nCONFIG:\n", _CONFIG.pg
describe "----- Postgres Factory TESTS -----", ->
before ( done )->
done()
return
describe 'Initialization', ->
it "1. init factory", ( done )->
DBFactory = new PgFactory( _CONFIG.pg, _CONFIG.tables )
done()
return
describe 'Factory Tests', ->
it "2. List the existing tables", ( done )->
DBFactory.list ( err, tables )->
throw err if err
tables.should.eql( Object.keys( _CONFIG.tables ) )
done()
return
it "3. Get a table", ( done )->
_cnf = _CONFIG.tables[ _CONFIG.test.singleCreateTableTest ]
_tbl = DBFactory.get( _CONFIG.test.singleCreateTableTest )
_tbl.should.exist
_tbl?.name?.should.eql( _cnf.name )
done()
return
it "4. Try to get a not existend table", ( done )->
_tbl = DBFactory.get( "notexistend" )
should.not.exist( _tbl )
done()
return
it "5. has for existend table", ( done )->
_has = DBFactory.has( _CONFIG.test.singleCreateTableTest )
_has.should.be.true
done()
return
it "6. has for not existend table", ( done )->
_has = DBFactory.has( "notexistend" )
_has.should.be.false
done()
return
return
describe 'Table Tests', ->
tableU = null # user
tableT = null # tokens
tableC = null # contracts
fieldsTest = [ "id", "firstname" ]
allFields = Object.keys( _CONFIG.tables[ _CONFIG.test.getTest.tbl ].fields )
_saveUserId = null
_saveUserT = 0
_testUsers = []
it "7. get test table `#{_CONFIG.test.getTest.tbl}`", ( done )->
tableU = DBFactory.get( _CONFIG.test.getTest.tbl )
tableU?.name?.should.eql( _CONFIG.test.getTest.tbl )
done()
return
it "8. get test table `#{_CONFIG.test.tokenTable}`", ( done )->
tableT = DBFactory.get( _CONFIG.test.tokenTable )
tableT?.name?.should.eql( _CONFIG.test.tokenTable )
done()
return
it "9. get test table `#{_CONFIG.test.contractsTable}`", ( done )->
tableC = DBFactory.get( _CONFIG.test.contractsTable )
tableC?.name?.should.eql( _CONFIG.test.contractsTable )
done()
return
it "10. TABLE.GET", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get _id, ( err, item )->
throw err if err
should.exist( item.id )
item.id.should.equal( _id )
done()
return
return
it "11. TABLE.GET fields as array", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,fieldsTest).should.have.length(0)
done()
return
, fields: fieldsTest )
return
it "12. TABLE.GET fields as string", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,fieldsTest).should.have.length(0)
done()
return
, fields: fieldsTest.join( ", " ) )
return
it "13. TABLE.GET fields as set", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,fieldsTest).should.have.length(0)
done()
return
, fields: "set:test" )
return
it "14. TABLE.GET fields `all`", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,allFields).should.have.length(0)
done()
return
, fields: "all" )
return
it "15. TABLE.GET fields `*`", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,allFields).should.have.length(0)
done()
return
, fields: "all" )
return
it "16. TABLE.GET fields `idonly`", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,[ "id" ]).should.have.length(0)
done()
return
, fields: "idonly" )
return
it "17. TABLE.GET fields by filter function", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get( _id, ( err, item )->
throw err if err
should.exist( item.id )
_keys = Object.keys( item )
_difference(_keys,[ "id", "_t", "_u" ]).should.have.length(0)
done()
return
, fields: ( (fld)->
fld.name.length <= 2 ) )
return
it "18. TABLE.MGET", ( done )->
_ids = JSON.parse( JSON.stringify( _CONFIG.test.mgetTest.id ) )
tableU.mget _ids, ( err, items )->
throw err if err
items.should.have.length(2)
_difference(_CONFIG.test.mgetTest.id,_map( items, "id" ) ).should.have.length(0)
done()
return
return
it "19. TABLE.MGET empty", ( done )->
tableU.mget [], ( err, items )->
throw err if err
items.should.have.length(0)
done()
return
return
it "20. TABLE.FIND all", ( done )->
@timeout( 6000 )
tableU.find {}, ( err, items )->
throw err if err
items.should.have.length( _CONFIG.tables.Users.limit)
done()
return
return
it "21. TABLE.FIND query", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
tableU.find query, ( err, items )->
throw err if err
items.should.have.length( 6 )
done()
return
return
it "22. TABLE.FIND with limit", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
query.limit = 1
tableU.find( query, ( err, items )->
throw err if err
items.should.have.length(1)
done()
return
, {} )
return
it "23. TABLE.FIND with limit by option", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
tableU.find( query, ( err, items )->
throw err if err
items.should.have.length(1)
done()
return
, { limit: 1 } )
return
it "24. TABLE.FIND with `idonly`", ( done )->
@timeout( 6000 )
query = JSON.parse( JSON.stringify( _CONFIG.test.findTest.q ) )
tableU.find( query, ( err, items )->
throw err if err
items.should.be.an.instanceOf(Array)
for id in items
id.should.be.a.String
done()
return
, { fields: "idonly" } )
return
it "25. TABLE.FIND studio tokens with subquery", ( done )->
query =
token:
"startsWith": "desPI:PASSWORD:<PASSWORD>END_PI"
opt =
limit: 0
_customQueryFilter:
"user_id":
sub:
table: "contracts"
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-TOKENS SUB", items.length
done()
return
, opt )
return
it "26. TABLE.FIND studio users with subquery", ( done )->
query =
"id":
sub:
table: "contracts"
field: "user_id"
filter:
studio_id: 1
contracttype: 1
opt =
limit: 0
tableU.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-USR SUB", items.length
done()
return
, opt )
return
it "27. TABLE.FIND studio tokens with TABLE.JOIN", ( done )->
query =
token:
"startsWith": "PI:PASSWORD:<PASSWORD>END_PI"
opt =
limit: 0
joins:
"user_id":
type: "inner"
table: "Contracts"
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-TOKENS JOIN", items.length
done()
return
, opt )
return
it "28. TABLE.FIND studio users with TABLE.JOIN with table instance", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
table: tableC
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
#console.log "ITEMS STD-USR JOIN", items.length
done()
return
, opt )
return
it "29. TABLE.JOIN without table", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
#table: tableC
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "missing-join-table" )
done()
return
, opt )
return
it "30. TABLE.JOIN without field", ( done )->
query =
studio_id: 1
contracttype: 1
opt =
fields: "*"
limit: 0
joins:
"user_id":
type: "left outer"
table: tableU
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
done()
return
, opt )
return
it "31. TABLE.JOIN with invalid field", ( done )->
query = {}
opt =
limit: 0
joins:
"_id":
table: tableC
field: "user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-field" )
done()
return
, opt )
return
it "32. TABLE.JOIN with invalid foreign field", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
table: tableC
field: "_user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-foreignfield" )
done()
return
, opt )
return
it "33. TABLE.JOIN with invalid table", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
table: "_Contracts"
field: "_user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-table" )
done()
return
, opt )
return
it "34. TABLE.JOIN with invalid type", ( done )->
query = {}
opt =
limit: 0
joins:
"id":
type: "foo"
table: tableC
field: "_user_id"
filter:
studio_id: 1
contracttype: 1
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-join-type" )
done()
return
, opt )
return
###
it "35. TABLE.FIND with option `_customQueryFilter`", ( done )->
query = _CONFIG.test.findTest.q
tableU.find( query, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "deprecated-option" )
done()
return
, { _customQueryFilter: "id = 'abcde'" } )
return
###
it "36. TABLE.FIND with invalid filter", ( done )->
tableU.find "wrong", ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-filter" )
done()
return
return
it "37. TABLE.FIND with complex filter", ( done )->
ts = 1381322463000
query =
user_id: "swDqh"
_t: { ">": ts }
opt =
limit: 3
tableT.find( query, ( err, items )->
throw err if err
items.should.have.property( "length" ).and.be.above(1)
items.should.have.property( "length" ).and.be.below(4)
for item in items
item._t.should.be.above( ts )
done()
return
, opt )
return
it "38. TABLE.INSERT string-id", ( done )->
data =
firstname: "PI:NAME:<NAME>END_PI"
lastname: "PI:NAME:<NAME>END_PI"
gender: true
role: "USER"
email: "test.#{_utils.randomString( 5 )}PI:EMAIL:<EMAIL>END_PI"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_saveUserId = item.id
_saveUserT = item._t
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "39. TABLE.INSERT second test case", ( done )->
data =
firstname: "Test2"
lastname: "PI:NAME:<NAME>END_PI"
gender: true
role: "USER"
email: "test.#{_utils.randomString( 5 )}PI:EMAIL:<EMAIL>END_PI"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_testUsers.push item
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test2" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "40. TABLE.INSERT third test case", ( done )->
data =
firstname: "PI:NAME:<NAME>END_PI"
lastname: "PI:NAME:<NAME>END_PI"
gender: false
role: "USER"
email: "test.#{_utils.randomString( 5 )}PI:EMAIL:<EMAIL>END_PI"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_testUsers.push item
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "TestPI:NAME:<NAME>END_PI" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( false )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "41. TABLE.INSERT fourth test case", ( done )->
data =
firstname: "PI:NAME:<NAME>END_PI"
lastname: "PI:NAME:<NAME>END_PI"
gender: true
role: "USER"
email: "test.#{_utils.randomString( 5 )}PI:EMAIL:<EMAIL>END_PI"
_t: 0
tableU.set( data, ( err, item )->
throw err if err
_testUsers.push item
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "TestPI:NAME:<NAME>END_PI" )
item.should.have.property('lastname').and.equal( "PI:NAME:<NAME>END_PI" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "42. TABLE.INSERT with createId function", ( done )->
_tbl = DBFactory.get( "Apikeys" )
data =
studio_id: 1
jsonOptions: {}
_tbl.set( data, ( err, item )->
throw err if err
item.should.have.property('apikey').and.match( /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}/ )
item.should.have.property('studio_id').and.equal( 1 )
done()
return
, {} )
return
it "43. TABLE.INSERT autoincrement-id", ( done )->
data = JSON.parse( JSON.stringify( _CONFIG.test.insertTestToken ) )
tableT.set( data, ( err, item )->
throw err if err
item.should.have.property('id')
item.should.have.property('user_id')
item.should.have.property('studio_id')
item.should.have.property('token')
item.should.have.property('_t').and.be.above( _startTime )
item.should.have.property('_u')
done()
return
, {} )
return
it "44. TABLE.INSERT predefined string-id", ( done )->
_id = _utils.randomString( 5 )
data =
id: _id
firstname: "PI:NAME:<NAME>END_PI"
lastname: "PI:NAME:<NAME>END_PI"
gender: true
role: "USER"
_t: 0
tableU.set( data, ( err, item )->
# special case. A predefined is could allready exist
if err?.code is "ER_DUP_ENTRY"
done()
return
throw err if err
item.should.have.property('id').and.equal(_id)
item.should.have.property('firstname').and.equal( "Test" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_t').and.be.within( _startTime, +Infinity )
item.should.have.property('_u')
done()
return
, {} )
return
it "45. TABLE.INSERT existing predefined string-id", ( done )->
data =
id: _CONFIG.test.getTest.id
firstname: "Test"
lastname: "Test"
gender: true
role: "USER"
_t: 0
tableU.set( data, ( err, item )->
should.exist( err )
err.code.should.equal( "ER_DUP_ENTRY" )
done()
return
, {} )
return
it "46. TABLE.UPDATE", ( done )->
data =
lastname: "Update1"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update1" )
item.should.have.property('_u').and.equal( 1 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "47. TABLE.UPDATE with crypting passowrd", ( done )->
data =
lastname: "Update2"
password: "PI:PASSWORD:<PASSWORD>END_PI"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update2" )
item.should.have.property('password').and.containEql( PI:PASSWORD:<PASSWORD>END_PI$" )
item.should.have.property('_u').and.equal( 2 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "48. TABLE.UPDATE with event check", ( done )->
data =
lastname: "Update3"
birthday: new Date( 1950,5,15 )
image: "testimage.jpg"
role: "TRAINER"
_t: _saveUserT
_done = cbMulti 5, ->
tableU.removeListener( "lastname.userchanged", fnEvnt1 )
tableU.removeListener( "birthday.userchanged", fnEvnt2 )
tableU.removeListener( "image.userchanged", fnEvnt3 )
tableU.removeListener( "set", fnEvnt4 )
done()
return
fnEvnt1 = ( oldValue, newValue, id )->
id.should.equal( _saveUserId )
oldValue.should.equal( "Update2" )
newValue.should.equal( "Update3" )
_done()
return
tableU.on "lastname.userchanged", fnEvnt1
fnEvnt2 = ( oldValue, newValue, id )->
id.should.equal( _saveUserId )
should.not.exist( oldValue )
newValue.toUTCString().should.equal(new Date( 1950,5,15 ).toUTCString())
_done()
return
tableU.on "birthday.userchanged", fnEvnt2
fnEvnt3 = ( oldValue, newValue, id )->
id.should.equal( _saveUserId )
should.not.exist( oldValue )
newValue.should.equal( "testimage.jpg" )
_done()
return
tableU.on "image.userchanged", fnEvnt3
fnEvnt4 = ( err, item )->
item.should.have.property('lastname').and.equal( "Update3" )
item.should.have.property('role').and.equal( "TRAINER" )
item.should.have.property('_u').and.equal( 3 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_done()
return
tableU.on "set", fnEvnt4
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update3" )
item.should.have.property('role').and.equal( "TRAINER" )
item.should.have.property('_u').and.equal( 3 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
_done()
return
, {} )
return
it "49. TABLE.UPDATE with invalid role", ( done )->
data =
lastname: "Update4"
role: "MILON"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "value-not-allowed" )
done()
return
, {} )
return
it "50. TABLE.UPDATE with with json object", ( done )->
data =
lastname: "Update5"
jsonSettings:
a: 123
b: 456
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update5" )
item.should.have.property('jsonSettings').and.eql
a: 123
b: 456
item.should.have.property('_u').and.equal( 4 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "51. TABLE.UPDATE with wrong `_t` check", ( done )->
data =
lastname: "Update6"
_t: _startTime
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "validation-notequal" )
should.exist( err.field )
err.field.should.equal( "_t" )
should.exist( err.value )
err.value.should.equal( _startTime )
should.exist( err.curr )
err.curr.should.equal( _saveUserT )
done()
return
, {} )
return
it "52. TABLE.UPDATE without `_t", ( done )->
data =
lastname: "Update7b"
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "validation-notequal-required" )
should.exist( err.field )
err.field.should.equal( "_t" )
done()
return
, {} )
return
it "53. TABLE.UPDATE try a manual of `_u`", ( done )->
data =
lastname: "Update7"
_u: 99
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastname').and.equal( "Update7" )
item.should.have.property('_u').and.equal( 5 )
item.should.have.property('_t').and.be.within( _saveUserT, +Infinity )
_saveUserT = item._t
done()
return
, {} )
return
it "54. TABLE.UPDATE with existing `mail`", ( done )->
data =
lastname: "Update7"
email: "PI:EMAIL:<EMAIL>END_PI"
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "validation-already-existend" )
should.exist( err.field )
err.field.should.equal( "email" )
should.exist( err.value )
err.value.should.equal( "PI:EMAIL:<EMAIL>END_PI" )
done()
return
, {} )
return
it "55. TABLE.UPDATE date fields as `Date`", ( done )->
_date = new Date()
data =
lastname: "Update8"
lastlogin: _date
deletedate: _date
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( Math.round( _date.getTime() / 1000 ) )
item.should.have.property('deletedate').and.equal( _date.getTime() )
item.should.have.property('lastname').and.equal( "Update8" )
item.should.have.property('_u').and.equal( 6 )
_saveUserT = item._t
done()
return
, {} )
return
it "56. TABLE.UPDATE date fields as `Number` in ms", ( done )->
_date = new Date().getTime()
data =
lastname: "Update9"
lastlogin: _date
deletedate: _date
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( Math.round( _date / 1000 ) )
item.should.have.property('deletedate').and.equal( _date )
item.should.have.property('lastname').and.equal( "Update9" )
item.should.have.property('_u').and.equal( 7 )
_saveUserT = item._t
done()
return
, {} )
return
it "57. TABLE.UPDATE date fields as `Number` in s", ( done )->
_date = Math.round( new Date().getTime() / 1000 )
data =
lastname: "Update10"
lastlogin: _date
deletedate: _date
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( _date )
item.should.have.property('deletedate').and.equal( _date * 1000 )
item.should.have.property('lastname').and.equal( "Update10" )
item.should.have.property('_u').and.equal( 8 )
_saveUserT = item._t
done()
return
, {} )
return
it "58. TABLE.UPDATE date fields as `String`", ( done )->
_date = moment( moment().format( "YYYY-MM-DD HH:mm" ), "YYYY-MM-DD HH:mm" )
data =
lastname: "Update11"
lastlogin: _date.format( "YYYY-MM-DD HH:mm" )
deletedate: _date.format( "YYYY-MM-DD HH:mm" )
_t: _saveUserT
tableU.set( _saveUserId, data, ( err, item )->
throw err if err
item.should.have.property('lastlogin').and.equal( _date.unix() )
item.should.have.property('deletedate').and.equal( _date.valueOf() )
item.should.have.property('lastname').and.equal( "Update11" )
item.should.have.property('_u').and.equal( 9 )
_saveUserT = item._t
done()
return
, {} )
return
it "59. TABLE.HAS", ( done )->
tableU.has( _saveUserId, ( err, existend )->
throw err if err
existend.should.be.ok
done()
return
, {} )
return
it "60. TABLE.HAS not existend", ( done )->
tableU.has( "notexist", ( err, existend )->
throw err if err
existend.should.not.be.ok
done()
return
, {} )
return
it "61. TABLE.COUNT", ( done )->
filter =
firstname: "PI:NAME:<NAME>END_PI"
role: "TRAINER"
tableU.count( filter, ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 6 )
done()
return
, {} )
return
it "62. TABLE.COUNT empty", ( done )->
filter =
firstname: "PI:NAME:<NAME>END_PI"
role: "INVALIDROLE"
tableU.count( filter, ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 0 )
done()
return
, {} )
return
it "63. TABLE.INCREMENT", ( done )->
tableU.increment( _saveUserId, "plansversion", ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 1 )
done()
return
, {} )
return
it "64. TABLE.INCREMENT second increment", ( done )->
tableU.increment( _saveUserId, "plansversion", ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 2 )
done()
return
, {} )
return
it "65. TABLE.INCREMENT unknown field", ( done )->
tableU.increment( _saveUserId, "unknown", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-field" )
should.exist( err.field )
err.field.should.equal( "unknown" )
done()
return
, {} )
return
it "66. TABLE.INCREMENT unknown id", ( done )->
tableU.increment( "unknown", "plansversion", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "67. TABLE.DECREMENT", ( done )->
tableU.decrement( _saveUserId, "plansversion", ( err, count )->
throw err if err
should.exist( count )
count.should.equal( 1 )
done()
return
, {} )
return
it "68. TABLE.INCREMENT unknown field", ( done )->
tableU.decrement( _saveUserId, "unknown", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "invalid-field" )
should.exist( err.field )
err.field.should.equal( "unknown" )
done()
return
, {} )
return
it "69. TABLE.INCREMENT unknown id", ( done )->
tableU.decrement( "unknown", "plansversion", ( err, count )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "70. TABLE.DEL", ( done )->
_usr = _testUsers[ 0 ]
tableU.del( _usr.id, ( err, item )->
throw err if err
item.should.have.property('id')
item.should.have.property('firstname').and.equal( "Test2" )
item.should.have.property('lastname').and.equal( "Test" )
item.should.have.property('gender').and.equal( true )
item.should.have.property('role').and.equal( "USER" )
item.should.have.property('_u')
done()
return
, {} )
return
it "71. TABLE.GET deleted", ( done )->
_usr = _testUsers[ 0 ]
tableU.get( _usr.id, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "72. TABLE.DEL deleted", ( done )->
_usr = _testUsers[ 0 ]
tableU.del( _usr.id, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
, {} )
return
it "73. TABLE.MDEL invalid filter", ( done )->
_usrA = _testUsers[ 1 ]
_usrB = _testUsers[ 2 ]
ids = [ _usrA.id, _usrB.id ]
tableU.mdel( user_id: ids, ( err, items )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "no-filter" )
done()
return
, {} )
return
it "74. TABLE.MDEL", ( done )->
_usrA = _testUsers[ 1 ]
_usrB = _testUsers[ 2 ]
ids = [ _usrA.id, _usrB.id ]
tableU.mdel( id: ids, ( err, items )->
throw err if err
_difference(ids,_map( items, "id" ) ).should.have.length(0)
done()
return
, {} )
return
it "75. TABLE.GET", ( done )->
_id = _CONFIG.test.getTest.id
tableU.get _testUsers[ 1 ].id, ( err, item )->
should.exist( err )
should.exist( err.name )
err.name.should.equal( "not-found" )
done()
return
return
|
[
{
"context": "###\n backbone-orm.js 0.5.12\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm\n Lice",
"end": 58,
"score": 0.9753897190093994,
"start": 50,
"tag": "NAME",
"value": "Vidigami"
},
{
"context": " Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm\n License: MIT (http://www.opensourc",
"end": 88,
"score": 0.9997197985649109,
"start": 80,
"tag": "USERNAME",
"value": "vidigami"
}
] | src/extensions/collection.coffee | michaelBenin/backbone-orm | 1 | ###
backbone-orm.js 0.5.12
Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Backbone.js, Underscore.js, and Moment.js.
###
_ = require 'underscore'
Backbone = require 'backbone'
Utils = require '../utils'
collection_type = Backbone.Collection
overrides =
fetch: (options) ->
# callback signature
if _.isFunction(callback = arguments[arguments.length-1])
switch arguments.length
when 1 then options = Utils.wrapOptions({}, callback)
when 2 then options = Utils.wrapOptions(options, callback)
return collection_type::_orm_original_fns.fetch.call(@, Utils.wrapOptions(options, (err, model, resp, options) =>
return options.error?(@, resp, options) if err
options.success?(model, resp, options)
))
_prepareModel: (attrs, options) ->
if not Utils.isModel(attrs) and (id = Utils.dataId(attrs))
is_new = !!@model.cache.get(id) if @model.cache
model = Utils.updateOrNew(attrs, @model)
if is_new and not model._validate(attrs, options)
this.trigger('invalid', @, attrs, options)
return false
return model
return collection_type::_orm_original_fns._prepareModel.call(@, attrs, options)
if not collection_type::_orm_original_fns
collection_type::_orm_original_fns = {}
for key, fn of overrides
collection_type::_orm_original_fns[key] = collection_type::[key]
collection_type::[key] = fn
| 93811 | ###
backbone-orm.js 0.5.12
Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-orm
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Backbone.js, Underscore.js, and Moment.js.
###
_ = require 'underscore'
Backbone = require 'backbone'
Utils = require '../utils'
collection_type = Backbone.Collection
overrides =
fetch: (options) ->
# callback signature
if _.isFunction(callback = arguments[arguments.length-1])
switch arguments.length
when 1 then options = Utils.wrapOptions({}, callback)
when 2 then options = Utils.wrapOptions(options, callback)
return collection_type::_orm_original_fns.fetch.call(@, Utils.wrapOptions(options, (err, model, resp, options) =>
return options.error?(@, resp, options) if err
options.success?(model, resp, options)
))
_prepareModel: (attrs, options) ->
if not Utils.isModel(attrs) and (id = Utils.dataId(attrs))
is_new = !!@model.cache.get(id) if @model.cache
model = Utils.updateOrNew(attrs, @model)
if is_new and not model._validate(attrs, options)
this.trigger('invalid', @, attrs, options)
return false
return model
return collection_type::_orm_original_fns._prepareModel.call(@, attrs, options)
if not collection_type::_orm_original_fns
collection_type::_orm_original_fns = {}
for key, fn of overrides
collection_type::_orm_original_fns[key] = collection_type::[key]
collection_type::[key] = fn
| true | ###
backbone-orm.js 0.5.12
Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-orm
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Backbone.js, Underscore.js, and Moment.js.
###
_ = require 'underscore'
Backbone = require 'backbone'
Utils = require '../utils'
collection_type = Backbone.Collection
overrides =
fetch: (options) ->
# callback signature
if _.isFunction(callback = arguments[arguments.length-1])
switch arguments.length
when 1 then options = Utils.wrapOptions({}, callback)
when 2 then options = Utils.wrapOptions(options, callback)
return collection_type::_orm_original_fns.fetch.call(@, Utils.wrapOptions(options, (err, model, resp, options) =>
return options.error?(@, resp, options) if err
options.success?(model, resp, options)
))
_prepareModel: (attrs, options) ->
if not Utils.isModel(attrs) and (id = Utils.dataId(attrs))
is_new = !!@model.cache.get(id) if @model.cache
model = Utils.updateOrNew(attrs, @model)
if is_new and not model._validate(attrs, options)
this.trigger('invalid', @, attrs, options)
return false
return model
return collection_type::_orm_original_fns._prepareModel.call(@, attrs, options)
if not collection_type::_orm_original_fns
collection_type::_orm_original_fns = {}
for key, fn of overrides
collection_type::_orm_original_fns[key] = collection_type::[key]
collection_type::[key] = fn
|
[
{
"context": "\nnikita = require '@nikitajs/core/lib'\n{tags, config} = require '../test'\nthey",
"end": 28,
"score": 0.7480289936065674,
"start": 26,
"tag": "USERNAME",
"value": "js"
},
{
"context": "lder/id_rsa\"\n bits: 2048\n comment: 'nikita'\n $status.should.be.true()\n {$status} =",
"end": 408,
"score": 0.9468900561332703,
"start": 402,
"tag": "NAME",
"value": "nikita"
},
{
"context": "lder/id_rsa\"\n bits: 2048\n comment: 'nikita'\n $status.should.be.false()\n\n \n",
"end": 568,
"score": 0.9294010400772095,
"start": 562,
"tag": "NAME",
"value": "nikita"
}
] | packages/tools/test/ssh/keygen.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
nikita = require '@nikitajs/core/lib'
{tags, config} = require '../test'
they = require('mocha-they')(config)
return unless tags.posix
describe 'tools.ssh.keygen', ->
they 'a new key', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
{$status} = await @tools.ssh.keygen
target: "#{tmpdir}/folder/id_rsa"
bits: 2048
comment: 'nikita'
$status.should.be.true()
{$status} = await @tools.ssh.keygen
target: "#{tmpdir}/folder/id_rsa"
bits: 2048
comment: 'nikita'
$status.should.be.false()
| 84508 |
nikita = require '@nikitajs/core/lib'
{tags, config} = require '../test'
they = require('mocha-they')(config)
return unless tags.posix
describe 'tools.ssh.keygen', ->
they 'a new key', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
{$status} = await @tools.ssh.keygen
target: "#{tmpdir}/folder/id_rsa"
bits: 2048
comment: '<NAME>'
$status.should.be.true()
{$status} = await @tools.ssh.keygen
target: "#{tmpdir}/folder/id_rsa"
bits: 2048
comment: '<NAME>'
$status.should.be.false()
| true |
nikita = require '@nikitajs/core/lib'
{tags, config} = require '../test'
they = require('mocha-they')(config)
return unless tags.posix
describe 'tools.ssh.keygen', ->
they 'a new key', ({ssh}) ->
nikita
$ssh: ssh
$tmpdir: true
, ({metadata: {tmpdir}}) ->
{$status} = await @tools.ssh.keygen
target: "#{tmpdir}/folder/id_rsa"
bits: 2048
comment: 'PI:NAME:<NAME>END_PI'
$status.should.be.true()
{$status} = await @tools.ssh.keygen
target: "#{tmpdir}/folder/id_rsa"
bits: 2048
comment: 'PI:NAME:<NAME>END_PI'
$status.should.be.false()
|
[
{
"context": " email is confirmed', ->\n @values.email = 'bob@example.com'\n @userEdit.validate(@values).email_confir",
"end": 543,
"score": 0.9999205470085144,
"start": 528,
"tag": "EMAIL",
"value": "bob@example.com"
},
{
"context": "tion_emtpy\n\n @values.email_confirmation = 'bob.mckenzie@example.com'\n @userEdit.validate(@values).email_confir",
"end": 725,
"score": 0.9998698234558105,
"start": 701,
"tag": "EMAIL",
"value": "bob.mckenzie@example.com"
},
{
"context": "nfirmation\n\n @values.email_confirmation = 'bob@example.com'\n _.isUndefined(@userEdit.validate(@values",
"end": 892,
"score": 0.9999184608459473,
"start": 877,
"tag": "EMAIL",
"value": "bob@example.com"
}
] | src/mobile/apps/user/test/models/user_edit.test.coffee | trkaplan/force | 1 | _ = require 'underscore'
Backbone = require 'backbone'
UserEdit = require '../../models/user_edit.coffee'
fabricate = require('antigravity').fabricate
sinon = require 'sinon'
describe 'UserEdit', ->
beforeEach ->
@userEdit = new UserEdit fabricate 'user'
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
describe "#validate (client validation)", ->
beforeEach ->
@values = {}
describe 'email', ->
it 'ensures that the email is confirmed', ->
@values.email = 'bob@example.com'
@userEdit.validate(@values).email_confirmation.should.equal @userEdit.errorMessages.email_confirmation_emtpy
@values.email_confirmation = 'bob.mckenzie@example.com'
@userEdit.validate(@values).email_confirmation.should.equal @userEdit.errorMessages.email_confirmation
@values.email_confirmation = 'bob@example.com'
_.isUndefined(@userEdit.validate(@values)).should.be.true()
it 'does not validate if the email is unchanged', ->
@values.email = @userEdit.get 'email'
_.isUndefined(@userEdit.validate(@values)).should.be.true()
describe 'name', ->
it 'is required', ->
@values.name = ' '
@userEdit.validate(@values).name.should.equal @userEdit.errorMessages.name_empty
@values.name = @userEdit.get 'name'
_.isUndefined(@userEdit.validate(@values)).should.be.true()
describe '#refresh', ->
it 'makes a client request to /user/refresh', ->
@userEdit.refresh()
Backbone.sync.args[0][2].url.should.equal '/user/refresh'
| 187864 | _ = require 'underscore'
Backbone = require 'backbone'
UserEdit = require '../../models/user_edit.coffee'
fabricate = require('antigravity').fabricate
sinon = require 'sinon'
describe 'UserEdit', ->
beforeEach ->
@userEdit = new UserEdit fabricate 'user'
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
describe "#validate (client validation)", ->
beforeEach ->
@values = {}
describe 'email', ->
it 'ensures that the email is confirmed', ->
@values.email = '<EMAIL>'
@userEdit.validate(@values).email_confirmation.should.equal @userEdit.errorMessages.email_confirmation_emtpy
@values.email_confirmation = '<EMAIL>'
@userEdit.validate(@values).email_confirmation.should.equal @userEdit.errorMessages.email_confirmation
@values.email_confirmation = '<EMAIL>'
_.isUndefined(@userEdit.validate(@values)).should.be.true()
it 'does not validate if the email is unchanged', ->
@values.email = @userEdit.get 'email'
_.isUndefined(@userEdit.validate(@values)).should.be.true()
describe 'name', ->
it 'is required', ->
@values.name = ' '
@userEdit.validate(@values).name.should.equal @userEdit.errorMessages.name_empty
@values.name = @userEdit.get 'name'
_.isUndefined(@userEdit.validate(@values)).should.be.true()
describe '#refresh', ->
it 'makes a client request to /user/refresh', ->
@userEdit.refresh()
Backbone.sync.args[0][2].url.should.equal '/user/refresh'
| true | _ = require 'underscore'
Backbone = require 'backbone'
UserEdit = require '../../models/user_edit.coffee'
fabricate = require('antigravity').fabricate
sinon = require 'sinon'
describe 'UserEdit', ->
beforeEach ->
@userEdit = new UserEdit fabricate 'user'
sinon.stub Backbone, 'sync'
afterEach ->
Backbone.sync.restore()
describe "#validate (client validation)", ->
beforeEach ->
@values = {}
describe 'email', ->
it 'ensures that the email is confirmed', ->
@values.email = 'PI:EMAIL:<EMAIL>END_PI'
@userEdit.validate(@values).email_confirmation.should.equal @userEdit.errorMessages.email_confirmation_emtpy
@values.email_confirmation = 'PI:EMAIL:<EMAIL>END_PI'
@userEdit.validate(@values).email_confirmation.should.equal @userEdit.errorMessages.email_confirmation
@values.email_confirmation = 'PI:EMAIL:<EMAIL>END_PI'
_.isUndefined(@userEdit.validate(@values)).should.be.true()
it 'does not validate if the email is unchanged', ->
@values.email = @userEdit.get 'email'
_.isUndefined(@userEdit.validate(@values)).should.be.true()
describe 'name', ->
it 'is required', ->
@values.name = ' '
@userEdit.validate(@values).name.should.equal @userEdit.errorMessages.name_empty
@values.name = @userEdit.get 'name'
_.isUndefined(@userEdit.validate(@values)).should.be.true()
describe '#refresh', ->
it 'makes a client request to /user/refresh', ->
@userEdit.refresh()
Backbone.sync.args[0][2].url.should.equal '/user/refresh'
|
[
{
"context": "vgMgr, 'Hue' )\n\n @quadrants = [\n { name1:\"Red\", key: '0', color:\"hsl( 0,100%,50%)\", be",
"end": 266,
"score": 0.9251652359962463,
"start": 263,
"tag": "NAME",
"value": "Red"
},
{
"context": " 0,100%,50%)\", beg:-15, end: 15 }\n { name1:\"Orange\", key: '30', color:\"hsl( 30,100%,50%)\", beg: ",
"end": 354,
"score": 0.9183318018913269,
"start": 348,
"tag": "NAME",
"value": "Orange"
},
{
"context": "-15, end: 15 }\n { name1:\"Orange\", key: '30', color:\"hsl( 30,100%,50%)\", beg: 15, end: 45 }\n ",
"end": 369,
"score": 0.9825876355171204,
"start": 368,
"tag": "KEY",
"value": "0"
},
{
"context": " 30,100%,50%)\", beg: 15, end: 45 }\n { name1:\"Yellow\", key: '60', color:\"hsl( 60,100%,50%)\", beg: ",
"end": 439,
"score": 0.9514822363853455,
"start": 433,
"tag": "NAME",
"value": "Yellow"
},
{
"context": ": 15, end: 45 }\n { name1:\"Yellow\", key: '60', color:\"hsl( 60,100%,50%)\", beg: 45, end: 75 }\n ",
"end": 454,
"score": 0.7885485887527466,
"start": 452,
"tag": "KEY",
"value": "60"
},
{
"context": " 60,100%,50%)\", beg: 45, end: 75 }\n { name1:\"Lime\", key: '90', color:\"hsl( 90,100%,50%)\", beg",
"end": 522,
"score": 0.9913312196731567,
"start": 518,
"tag": "NAME",
"value": "Lime"
},
{
"context": " 45, end: 75 }\n { name1:\"Lime\", key: '90', color:\"hsl( 90,100%,50%)\", beg: 75, end:105 }\n ",
"end": 539,
"score": 0.9735375642776489,
"start": 538,
"tag": "KEY",
"value": "0"
},
{
"context": " 90,100%,50%)\", beg: 75, end:105 }\n { name1:\"Green\", key:'120', color:\"hsl(120,100%,50%)\", beg:",
"end": 608,
"score": 0.9844526648521423,
"start": 603,
"tag": "NAME",
"value": "Green"
},
{
"context": ": 75, end:105 }\n { name1:\"Green\", key:'120', color:\"hsl(120,100%,50%)\", beg:105, end:135 }\n ",
"end": 624,
"score": 0.9888446927070618,
"start": 622,
"tag": "KEY",
"value": "20"
},
{
"context": "120,100%,50%)\", beg:105, end:135 }\n { name1:\"Teal\", key:'150', color:\"hsl(150,100%,50%)\", beg",
"end": 692,
"score": 0.9782584309577942,
"start": 688,
"tag": "NAME",
"value": "Teal"
},
{
"context": ":105, end:135 }\n { name1:\"Teal\", key:'150', color:\"hsl(150,100%,50%)\", beg:135, end:165 }\n ",
"end": 709,
"score": 0.9860376119613647,
"start": 707,
"tag": "KEY",
"value": "50"
},
{
"context": "150,100%,50%)\", beg:135, end:165 }\n { name1:\"Cyan\", key:'180', color:\"hsl(180,100%,50%)\", beg",
"end": 777,
"score": 0.9942328929901123,
"start": 773,
"tag": "NAME",
"value": "Cyan"
},
{
"context": ":135, end:165 }\n { name1:\"Cyan\", key:'180', color:\"hsl(180,100%,50%)\", beg:165, end:195 }\n ",
"end": 794,
"score": 0.9886573553085327,
"start": 792,
"tag": "KEY",
"value": "80"
},
{
"context": "180,100%,50%)\", beg:165, end:195 }\n { name1:\"Azure\", key:'210', color:\"hsl(210,100%,50%)\", beg:",
"end": 863,
"score": 0.8545324802398682,
"start": 858,
"tag": "NAME",
"value": "Azure"
},
{
"context": "g:165, end:195 }\n { name1:\"Azure\", key:'210', color:\"hsl(210,100%,50%)\", beg:195, end:225 }\n ",
"end": 879,
"score": 0.8884420990943909,
"start": 876,
"tag": "KEY",
"value": "210"
},
{
"context": "210,100%,50%)\", beg:195, end:225 }\n { name1:\"Blue\", key:'240', color:\"hsl(240,100%,50%)\", beg",
"end": 947,
"score": 0.9231424927711487,
"start": 943,
"tag": "NAME",
"value": "Blue"
},
{
"context": "g:195, end:225 }\n { name1:\"Blue\", key:'240', color:\"hsl(240,100%,50%)\", beg:225, end:255 }\n ",
"end": 964,
"score": 0.8348743915557861,
"start": 961,
"tag": "KEY",
"value": "240"
},
{
"context": "240,100%,50%)\", beg:225, end:255 }\n { name1:\"Violet\", key:'270', color:\"hsl(270,100%,50%)\", beg:2",
"end": 1034,
"score": 0.9883331656455994,
"start": 1028,
"tag": "NAME",
"value": "Violet"
},
{
"context": ":225, end:255 }\n { name1:\"Violet\", key:'270', color:\"hsl(270,100%,50%)\", beg:255, end:285 }\n ",
"end": 1049,
"score": 0.9881536960601807,
"start": 1047,
"tag": "KEY",
"value": "70"
},
{
"context": "270,100%,50%)\", beg:255, end:285 }\n { name1:\"Magenta\", key:'300', color:\"hsl(300,100%,50%)\", ",
"end": 1114,
"score": 0.561180830001831,
"start": 1113,
"tag": "NAME",
"value": "M"
},
{
"context": ":255, end:285 }\n { name1:\"Magenta\", key:'300', color:\"hsl(300,100%,50%)\", beg:285, end:315 }\n ",
"end": 1134,
"score": 0.5710569024085999,
"start": 1132,
"tag": "KEY",
"value": "00"
},
{
"context": ":285, end:315 }\n { name1:\"Pink\", key:'330', color:\"hsl(330,100%,50%)\", beg:315, end:345 } ]",
"end": 1219,
"score": 0.5648852586746216,
"start": 1217,
"tag": "KEY",
"value": "30"
},
{
"context": "tte:Palettes.browns, name1:\"Brown\", key: '20', beg: 15, end: 25 }\n { palette:Palettes.tan",
"end": 1437,
"score": 0.5759962201118469,
"start": 1436,
"tag": "KEY",
"value": "0"
},
{
"context": "tte:Palettes.oranges, name1:\"Orange\", key: '40', beg: 35, end: 45 }\n { palette:Palettes.yel",
"end": 1607,
"score": 0.6976016163825989,
"start": 1606,
"tag": "KEY",
"value": "0"
},
{
"context": "tte:Palettes.yellows, name1:\"Yellow\", key: '60', beg: 45, end: 75 }\n { palette:Palettes.lim",
"end": 1692,
"score": 0.692982017993927,
"start": 1691,
"tag": "KEY",
"value": "0"
},
{
"context": "d: 75 }\n { palette:Palettes.limes, name1:\"Lime\", key: '90', beg: 75, end:105 }\n { ",
"end": 1757,
"score": 0.5987327098846436,
"start": 1756,
"tag": "NAME",
"value": "L"
},
{
"context": "tte:Palettes.limes, name1:\"Lime\", key: '90', beg: 75, end:105 }\n { palette:Palettes.gre",
"end": 1777,
"score": 0.5337072610855103,
"start": 1776,
"tag": "KEY",
"value": "0"
},
{
"context": "ette:Palettes.greens, name1:\"Green\", key:'120', beg:105, end:135 }\n { palette:Palettes.tea",
"end": 1862,
"score": 0.6890996694564819,
"start": 1860,
"tag": "KEY",
"value": "20"
},
{
"context": "ette:Palettes.teals, name1:\"Teal\", key:'150', beg:135, end:165 }\n { palette:Palettes.cya",
"end": 1947,
"score": 0.881081759929657,
"start": 1945,
"tag": "KEY",
"value": "50"
},
{
"context": "ette:Palettes.cyans, name1:\"Cyan\", key:'180', beg:165, end:195 }\n { palette:Palettes.azu",
"end": 2032,
"score": 0.9076423048973083,
"start": 2030,
"tag": "KEY",
"value": "80"
},
{
"context": "ette:Palettes.azures, name1:\"Azure\", key:'210', beg:195, end:225 }\n { palette:Palettes.blu",
"end": 2117,
"score": 0.9267544746398926,
"start": 2115,
"tag": "KEY",
"value": "10"
},
{
"context": "ette:Palettes.blues, name1:\"Blue\", key:'240', beg:225, end:255 }\n { palette:Palettes.vio",
"end": 2202,
"score": 0.8853412866592407,
"start": 2200,
"tag": "KEY",
"value": "40"
},
{
"context": ":255 }\n { palette:Palettes.violets, name1:\"Violet\", key:'270', beg:255, end:285 }\n { pa",
"end": 2269,
"score": 0.63090580701828,
"start": 2267,
"tag": "NAME",
"value": "io"
},
{
"context": "ette:Palettes.violets, name1:\"Violet\", key:'270', beg:255, end:285 }\n { palette:Palettes.mag",
"end": 2287,
"score": 0.9758520126342773,
"start": 2285,
"tag": "KEY",
"value": "70"
},
{
"context": "ette:Palettes.magentas, name1:\"Magenta\", key:'300', beg:285, end:315 }\n { palette:Palettes.pin",
"end": 2372,
"score": 0.95569908618927,
"start": 2370,
"tag": "KEY",
"value": "00"
},
{
"context": "ette:Palettes.pinks, name1:\"Pink\", key:'330', beg:315, end:330 }\n { palette:Palettes.gra",
"end": 2457,
"score": 0.9284926652908325,
"start": 2455,
"tag": "KEY",
"value": "30"
},
{
"context": "ette:Palettes.grays, name1:\"Gray\", key:'345', beg:330, end:345 } ]\n\n @assoc = @assocQuad(",
"end": 2542,
"score": 0.9153625965118408,
"start": 2540,
"tag": "KEY",
"value": "45"
},
{
"context": " for hue in [0...360] by inc\n a.push( { name1:@name1(hue), color:\"hsla(#{hue},100%,50%,1.0)\", beg:hue-",
"end": 2926,
"score": 0.9984858632087708,
"start": 2920,
"tag": "USERNAME",
"value": "@name1"
}
] | src/augm/show/Hue.coffee | axiom6/aug | 0 |
import {vis} from '../../../lib/pub/draw/Vis.js'
import Palettes from '../../../lib/pub/draw/Palettes.js'
import Radar from './Radar.js'
class Hue extends Radar
constructor:( svgMgr ) ->
super( svgMgr, 'Hue' )
@quadrants = [
{ name1:"Red", key: '0', color:"hsl( 0,100%,50%)", beg:-15, end: 15 }
{ name1:"Orange", key: '30', color:"hsl( 30,100%,50%)", beg: 15, end: 45 }
{ name1:"Yellow", key: '60', color:"hsl( 60,100%,50%)", beg: 45, end: 75 }
{ name1:"Lime", key: '90', color:"hsl( 90,100%,50%)", beg: 75, end:105 }
{ name1:"Green", key:'120', color:"hsl(120,100%,50%)", beg:105, end:135 }
{ name1:"Teal", key:'150', color:"hsl(150,100%,50%)", beg:135, end:165 }
{ name1:"Cyan", key:'180', color:"hsl(180,100%,50%)", beg:165, end:195 }
{ name1:"Azure", key:'210', color:"hsl(210,100%,50%)", beg:195, end:225 }
{ name1:"Blue", key:'240', color:"hsl(240,100%,50%)", beg:225, end:255 }
{ name1:"Violet", key:'270', color:"hsl(270,100%,50%)", beg:255, end:285 }
{ name1:"Magenta", key:'300', color:"hsl(300,100%,50%)", beg:285, end:315 }
{ name1:"Pink", key:'330', color:"hsl(330,100%,50%)", beg:315, end:345 } ]
@palettes = [
{ palette:Palettes.reds, name1:"Red", key: '0', beg:-15, end: 15 }
{ palette:Palettes.browns, name1:"Brown", key: '20', beg: 15, end: 25 }
{ palette:Palettes.tans, name1:"Tan", key: '30', beg: 25, end: 35 }
{ palette:Palettes.oranges, name1:"Orange", key: '40', beg: 35, end: 45 }
{ palette:Palettes.yellows, name1:"Yellow", key: '60', beg: 45, end: 75 }
{ palette:Palettes.limes, name1:"Lime", key: '90', beg: 75, end:105 }
{ palette:Palettes.greens, name1:"Green", key:'120', beg:105, end:135 }
{ palette:Palettes.teals, name1:"Teal", key:'150', beg:135, end:165 }
{ palette:Palettes.cyans, name1:"Cyan", key:'180', beg:165, end:195 }
{ palette:Palettes.azures, name1:"Azure", key:'210', beg:195, end:225 }
{ palette:Palettes.blues, name1:"Blue", key:'240', beg:225, end:255 }
{ palette:Palettes.violets, name1:"Violet", key:'270', beg:255, end:285 }
{ palette:Palettes.magentas, name1:"Magenta", key:'300', beg:285, end:315 }
{ palette:Palettes.pinks, name1:"Pink", key:'330', beg:315, end:330 }
{ palette:Palettes.grays, name1:"Gray", key:'345', beg:330, end:345 } ]
@assoc = @assocQuad(@quadrants)
@wheelReady()
wheelReady:() ->
@graph = @svgMgr.svg
dr = ( @r100 - @r40 ) / 30
@quads( @hueQuads(10), @r80, @r100 )
@hsvWedges( 5, dr, @r40, @r100 )
@paletteWedges( 5, dr, @r40, @r100 )
return
hueQuads:(inc) ->
a = []
for hue in [0...360] by inc
a.push( { name1:@name1(hue), color:"hsla(#{hue},100%,50%,1.0)", beg:hue-inc/2, end:hue+inc/2 } )
a
###
hueWedges:( dh, dr, r1, r2 ) ->
g = @g.selectAll("g").append("svg:g")
for hue in [0...360] by dh
for r in [r1...r2] by dr
lite = 80 - (r-r1) / (r2-r1) * 50
@wedge( "hsla(#{hue},100%,#{lite}%,1.0)", g, r, r+dr, hue-dh/2, hue+dh/2 )
@grid(dh)
return
###
hsvWedges:( dh, dr, r1, r2 ) ->
g = @g.selectAll("g").append("svg:g")
for hue in [0...360] by dh
for r in [r1...r2] by dr
sat = 0.3 + (r-r1) / (r2-r1) * 0.7
@wedge( vis.hex( [hue,sat*100,100] ), g, r, r+dr, hue-dh/2, hue+dh/2 )
@grid( dh, dr, -dh/2, 360-dh/2 )
return
paletteWedges:( dh, dr, r1, r2 ) ->
vis.noop(r2)
g = @g.selectAll("g").append("svg:g")
for palette in @palettes
r = r1
for c in palette.palette
@wedge( c.hex, g, r, r+dr, palette.beg, palette.end )
r += dr
return
name1:(hue) ->
qa = @assoc[hue.toString()]
if qa? then qa.name1 else null
assocQuad:(quadrants) ->
assoc = []
for q in quadrants
assoc[q.key] = q
assoc
export default Hue | 154493 |
import {vis} from '../../../lib/pub/draw/Vis.js'
import Palettes from '../../../lib/pub/draw/Palettes.js'
import Radar from './Radar.js'
class Hue extends Radar
constructor:( svgMgr ) ->
super( svgMgr, 'Hue' )
@quadrants = [
{ name1:"<NAME>", key: '0', color:"hsl( 0,100%,50%)", beg:-15, end: 15 }
{ name1:"<NAME>", key: '3<KEY>', color:"hsl( 30,100%,50%)", beg: 15, end: 45 }
{ name1:"<NAME>", key: '<KEY>', color:"hsl( 60,100%,50%)", beg: 45, end: 75 }
{ name1:"<NAME>", key: '9<KEY>', color:"hsl( 90,100%,50%)", beg: 75, end:105 }
{ name1:"<NAME>", key:'1<KEY>', color:"hsl(120,100%,50%)", beg:105, end:135 }
{ name1:"<NAME>", key:'1<KEY>', color:"hsl(150,100%,50%)", beg:135, end:165 }
{ name1:"<NAME>", key:'1<KEY>', color:"hsl(180,100%,50%)", beg:165, end:195 }
{ name1:"<NAME>", key:'<KEY>', color:"hsl(210,100%,50%)", beg:195, end:225 }
{ name1:"<NAME>", key:'<KEY>', color:"hsl(240,100%,50%)", beg:225, end:255 }
{ name1:"<NAME>", key:'2<KEY>', color:"hsl(270,100%,50%)", beg:255, end:285 }
{ name1:"<NAME>agenta", key:'3<KEY>', color:"hsl(300,100%,50%)", beg:285, end:315 }
{ name1:"Pink", key:'3<KEY>', color:"hsl(330,100%,50%)", beg:315, end:345 } ]
@palettes = [
{ palette:Palettes.reds, name1:"Red", key: '0', beg:-15, end: 15 }
{ palette:Palettes.browns, name1:"Brown", key: '2<KEY>', beg: 15, end: 25 }
{ palette:Palettes.tans, name1:"Tan", key: '30', beg: 25, end: 35 }
{ palette:Palettes.oranges, name1:"Orange", key: '4<KEY>', beg: 35, end: 45 }
{ palette:Palettes.yellows, name1:"Yellow", key: '6<KEY>', beg: 45, end: 75 }
{ palette:Palettes.limes, name1:"<NAME>ime", key: '9<KEY>', beg: 75, end:105 }
{ palette:Palettes.greens, name1:"Green", key:'1<KEY>', beg:105, end:135 }
{ palette:Palettes.teals, name1:"Teal", key:'1<KEY>', beg:135, end:165 }
{ palette:Palettes.cyans, name1:"Cyan", key:'1<KEY>', beg:165, end:195 }
{ palette:Palettes.azures, name1:"Azure", key:'2<KEY>', beg:195, end:225 }
{ palette:Palettes.blues, name1:"Blue", key:'2<KEY>', beg:225, end:255 }
{ palette:Palettes.violets, name1:"V<NAME>let", key:'2<KEY>', beg:255, end:285 }
{ palette:Palettes.magentas, name1:"Magenta", key:'3<KEY>', beg:285, end:315 }
{ palette:Palettes.pinks, name1:"Pink", key:'3<KEY>', beg:315, end:330 }
{ palette:Palettes.grays, name1:"Gray", key:'3<KEY>', beg:330, end:345 } ]
@assoc = @assocQuad(@quadrants)
@wheelReady()
wheelReady:() ->
@graph = @svgMgr.svg
dr = ( @r100 - @r40 ) / 30
@quads( @hueQuads(10), @r80, @r100 )
@hsvWedges( 5, dr, @r40, @r100 )
@paletteWedges( 5, dr, @r40, @r100 )
return
hueQuads:(inc) ->
a = []
for hue in [0...360] by inc
a.push( { name1:@name1(hue), color:"hsla(#{hue},100%,50%,1.0)", beg:hue-inc/2, end:hue+inc/2 } )
a
###
hueWedges:( dh, dr, r1, r2 ) ->
g = @g.selectAll("g").append("svg:g")
for hue in [0...360] by dh
for r in [r1...r2] by dr
lite = 80 - (r-r1) / (r2-r1) * 50
@wedge( "hsla(#{hue},100%,#{lite}%,1.0)", g, r, r+dr, hue-dh/2, hue+dh/2 )
@grid(dh)
return
###
hsvWedges:( dh, dr, r1, r2 ) ->
g = @g.selectAll("g").append("svg:g")
for hue in [0...360] by dh
for r in [r1...r2] by dr
sat = 0.3 + (r-r1) / (r2-r1) * 0.7
@wedge( vis.hex( [hue,sat*100,100] ), g, r, r+dr, hue-dh/2, hue+dh/2 )
@grid( dh, dr, -dh/2, 360-dh/2 )
return
paletteWedges:( dh, dr, r1, r2 ) ->
vis.noop(r2)
g = @g.selectAll("g").append("svg:g")
for palette in @palettes
r = r1
for c in palette.palette
@wedge( c.hex, g, r, r+dr, palette.beg, palette.end )
r += dr
return
name1:(hue) ->
qa = @assoc[hue.toString()]
if qa? then qa.name1 else null
assocQuad:(quadrants) ->
assoc = []
for q in quadrants
assoc[q.key] = q
assoc
export default Hue | true |
import {vis} from '../../../lib/pub/draw/Vis.js'
import Palettes from '../../../lib/pub/draw/Palettes.js'
import Radar from './Radar.js'
class Hue extends Radar
constructor:( svgMgr ) ->
super( svgMgr, 'Hue' )
@quadrants = [
{ name1:"PI:NAME:<NAME>END_PI", key: '0', color:"hsl( 0,100%,50%)", beg:-15, end: 15 }
{ name1:"PI:NAME:<NAME>END_PI", key: '3PI:KEY:<KEY>END_PI', color:"hsl( 30,100%,50%)", beg: 15, end: 45 }
{ name1:"PI:NAME:<NAME>END_PI", key: 'PI:KEY:<KEY>END_PI', color:"hsl( 60,100%,50%)", beg: 45, end: 75 }
{ name1:"PI:NAME:<NAME>END_PI", key: '9PI:KEY:<KEY>END_PI', color:"hsl( 90,100%,50%)", beg: 75, end:105 }
{ name1:"PI:NAME:<NAME>END_PI", key:'1PI:KEY:<KEY>END_PI', color:"hsl(120,100%,50%)", beg:105, end:135 }
{ name1:"PI:NAME:<NAME>END_PI", key:'1PI:KEY:<KEY>END_PI', color:"hsl(150,100%,50%)", beg:135, end:165 }
{ name1:"PI:NAME:<NAME>END_PI", key:'1PI:KEY:<KEY>END_PI', color:"hsl(180,100%,50%)", beg:165, end:195 }
{ name1:"PI:NAME:<NAME>END_PI", key:'PI:KEY:<KEY>END_PI', color:"hsl(210,100%,50%)", beg:195, end:225 }
{ name1:"PI:NAME:<NAME>END_PI", key:'PI:KEY:<KEY>END_PI', color:"hsl(240,100%,50%)", beg:225, end:255 }
{ name1:"PI:NAME:<NAME>END_PI", key:'2PI:KEY:<KEY>END_PI', color:"hsl(270,100%,50%)", beg:255, end:285 }
{ name1:"PI:NAME:<NAME>END_PIagenta", key:'3PI:KEY:<KEY>END_PI', color:"hsl(300,100%,50%)", beg:285, end:315 }
{ name1:"Pink", key:'3PI:KEY:<KEY>END_PI', color:"hsl(330,100%,50%)", beg:315, end:345 } ]
@palettes = [
{ palette:Palettes.reds, name1:"Red", key: '0', beg:-15, end: 15 }
{ palette:Palettes.browns, name1:"Brown", key: '2PI:KEY:<KEY>END_PI', beg: 15, end: 25 }
{ palette:Palettes.tans, name1:"Tan", key: '30', beg: 25, end: 35 }
{ palette:Palettes.oranges, name1:"Orange", key: '4PI:KEY:<KEY>END_PI', beg: 35, end: 45 }
{ palette:Palettes.yellows, name1:"Yellow", key: '6PI:KEY:<KEY>END_PI', beg: 45, end: 75 }
{ palette:Palettes.limes, name1:"PI:NAME:<NAME>END_PIime", key: '9PI:KEY:<KEY>END_PI', beg: 75, end:105 }
{ palette:Palettes.greens, name1:"Green", key:'1PI:KEY:<KEY>END_PI', beg:105, end:135 }
{ palette:Palettes.teals, name1:"Teal", key:'1PI:KEY:<KEY>END_PI', beg:135, end:165 }
{ palette:Palettes.cyans, name1:"Cyan", key:'1PI:KEY:<KEY>END_PI', beg:165, end:195 }
{ palette:Palettes.azures, name1:"Azure", key:'2PI:KEY:<KEY>END_PI', beg:195, end:225 }
{ palette:Palettes.blues, name1:"Blue", key:'2PI:KEY:<KEY>END_PI', beg:225, end:255 }
{ palette:Palettes.violets, name1:"VPI:NAME:<NAME>END_PIlet", key:'2PI:KEY:<KEY>END_PI', beg:255, end:285 }
{ palette:Palettes.magentas, name1:"Magenta", key:'3PI:KEY:<KEY>END_PI', beg:285, end:315 }
{ palette:Palettes.pinks, name1:"Pink", key:'3PI:KEY:<KEY>END_PI', beg:315, end:330 }
{ palette:Palettes.grays, name1:"Gray", key:'3PI:KEY:<KEY>END_PI', beg:330, end:345 } ]
@assoc = @assocQuad(@quadrants)
@wheelReady()
wheelReady:() ->
@graph = @svgMgr.svg
dr = ( @r100 - @r40 ) / 30
@quads( @hueQuads(10), @r80, @r100 )
@hsvWedges( 5, dr, @r40, @r100 )
@paletteWedges( 5, dr, @r40, @r100 )
return
hueQuads:(inc) ->
a = []
for hue in [0...360] by inc
a.push( { name1:@name1(hue), color:"hsla(#{hue},100%,50%,1.0)", beg:hue-inc/2, end:hue+inc/2 } )
a
###
hueWedges:( dh, dr, r1, r2 ) ->
g = @g.selectAll("g").append("svg:g")
for hue in [0...360] by dh
for r in [r1...r2] by dr
lite = 80 - (r-r1) / (r2-r1) * 50
@wedge( "hsla(#{hue},100%,#{lite}%,1.0)", g, r, r+dr, hue-dh/2, hue+dh/2 )
@grid(dh)
return
###
hsvWedges:( dh, dr, r1, r2 ) ->
g = @g.selectAll("g").append("svg:g")
for hue in [0...360] by dh
for r in [r1...r2] by dr
sat = 0.3 + (r-r1) / (r2-r1) * 0.7
@wedge( vis.hex( [hue,sat*100,100] ), g, r, r+dr, hue-dh/2, hue+dh/2 )
@grid( dh, dr, -dh/2, 360-dh/2 )
return
paletteWedges:( dh, dr, r1, r2 ) ->
vis.noop(r2)
g = @g.selectAll("g").append("svg:g")
for palette in @palettes
r = r1
for c in palette.palette
@wedge( c.hex, g, r, r+dr, palette.beg, palette.end )
r += dr
return
name1:(hue) ->
qa = @assoc[hue.toString()]
if qa? then qa.name1 else null
assocQuad:(quadrants) ->
assoc = []
for q in quadrants
assoc[q.key] = q
assoc
export default Hue |
[
{
"context": "layer\n rico: ->\n if @neighbor(0,1).key == 'rico'\n blank\n else\n <symbol viewBox=\"0 0 ",
"end": 5504,
"score": 0.9052903652191162,
"start": 5503,
"tag": "KEY",
"value": "o"
},
{
"context": "bel == 'DCi+1,2j' and @neighbor(+4,0).key == 'c:DCi+1,2j+1'\n offsetX = -10\n else if label == 'DCi+1",
"end": 5938,
"score": 0.762549877166748,
"start": 5935,
"tag": "KEY",
"value": "i+1"
},
{
"context": "= 'DCi+1,2j' and @neighbor(+4,0).key == 'c:DCi+1,2j+1'\n offsetX = -10\n else if label == 'DCi+1,2j+1",
"end": 5943,
"score": 0.6866510510444641,
"start": 5940,
"tag": "KEY",
"value": "j+1"
},
{
"context": "label == 'DCi+1,2j+1' and @neighbor(-4,0).key == 'c:DCi+1,2j'\n offsetX = +10\n else if label in ['",
"end": 6024,
"score": 0.6274970173835754,
"start": 6023,
"tag": "KEY",
"value": "c"
},
{
"context": "bel == 'DCi+1,2j+1' and @neighbor(-4,0).key == 'c:DCi+1,2j'\n offsetX = +10\n else if label in ['VBa','VBb",
"end": 6033,
"score": 0.9113863706588745,
"start": 6025,
"tag": "KEY",
"value": "DCi+1,2j"
},
{
"context": "bel in ['VBa','VBb'] and @neighbor(+2,0).key in ['c:VAa','c:VAb']\n offsetX = -18\n else if label in ['",
"end": 6120,
"score": 0.8001019954681396,
"start": 6115,
"tag": "KEY",
"value": "c:VAa"
},
{
"context": "VBa','VBb'] and @neighbor(+2,0).key in ['c:VAa','c:VAb']\n offsetX = -18\n else if label in ['VAa','VA",
"end": 6128,
"score": 0.802351176738739,
"start": 6125,
"tag": "KEY",
"value": "VAb"
},
{
"context": "bel in ['VAa','VAb'] and @neighbor(-2,0).key in ['c:VBa','c:VBb']\n offsetX = +18\n else if label in ['",
"end": 6216,
"score": 0.9878422021865845,
"start": 6211,
"tag": "KEY",
"value": "c:VBa"
},
{
"context": "'VAa','VAb'] and @neighbor(-2,0).key in ['c:VBa','c:VBb']\n offsetX = +18\n else if label in ['PDC', 'P",
"end": 6224,
"score": 0.9799409508705139,
"start": 6219,
"tag": "KEY",
"value": "c:VBb"
},
{
"context": "l in ['PDC', 'PB11'] and @neighbor(-1,-1).key == 'c:VB_local2'\n offsetX = +20\n offsetY = +3\n else if lab",
"end": 6320,
"score": 0.9546217918395996,
"start": 6309,
"tag": "KEY",
"value": "c:VB_local2"
},
{
"context": "bel in ['VAB_local'] and @neighbor(+1,0).key in ['c:PAa', 'c:PAb']\n offsetX = -10\n else if label in [",
"end": 6424,
"score": 0.9512327909469604,
"start": 6419,
"tag": "KEY",
"value": "c:PAa"
},
{
"context": "VAB_local'] and @neighbor(+1,0).key in ['c:PAa', 'c:PAb']\n offsetX = -10\n else if label in ['PAa', 'P",
"end": 6433,
"score": 0.9571288824081421,
"start": 6428,
"tag": "KEY",
"value": "c:PAb"
},
{
"context": "bel in ['PAa', 'PAb'] and @neighbor(-1,0).key == 'c:VAB_local'\n offsetX = +27\n text = label\n if text of na",
"end": 6527,
"score": 0.9705471992492676,
"start": 6516,
"tag": "KEY",
"value": "c:VAB_local"
}
] | svgtiler/recursed.coffee | edemaine/recursed-xls2lua | 6 | # Mapping of internal room names to LaTeX label.
# I'm guessing that A_01 and B_10 will be the reference "room i,j"
#
# In order of appearance
nameMap =
# start room
"A00" : "A_{0,0}"
"global_lock" : "\\text{GL}" # "\\gl{}" # too big
# DC gadget needs to be re-done in small_examples to match binary tree version
"VDCi" : "V_{DC_i}"
"PDCi+1" : "P_{DC_{i+1}}"
"DCi+1,2j" : "DC_{i+1,2j}"
"DCi+1,2j+1" : "DC_{i+1,2j+1}"
# Aij rooms
"VA01" : "V_{A_{i,j}}"
"PB00" : "P_{A_{i,j+1}}"
"BC00" : "A_{i,j+1}"
"PAB_local" : "\\phs{}"
"PBb" : "P_{s(A_{i,j}),b}"
"VAb" : "V_{s(A_{i,j}),a}"
"VBb" : "V_{s(A_{i,j}),b}"
# Bij^C
"VB10" : "V_{B_{i,j}}"
"PB_local1" : "P_{B^{(J)}}"
"BJ10" : "B^{(J)}_{i,j}"
"PB11" : "P_{B_{i,j+1}}"
"VB_local2" : "V_{B^{(C)}}"
"BC11" : "B^{(C)}_{i,j+1}"
# Bij^J
"VB_local1" : "V_{B^{(J)}}"
"PB_local2" : "P_{B^{(C)}}"
"VBsb" : "V_{s(B_{i,j}),b}"
"PAb" : "P_{s(B_{i,j}),a}"
"VAB_local" : "\\vhs{}"
# stop
"VAx0" : "V_{A_{x,0}}"
"A10" : "A_{1,0}"
"Mx" : "M_x"
sprite = (x) -> "../sprites/#{x}.png"
area = 'city'
blank =
<rect width="16" height="16" fill="black" stroke="black" stroke-width="0.01"/>
#blank = <>
# <rect width="16" height="16" fill="black"/>
# <line x1="16" x2="16" y2="16" stroke="black" stroke-width="0.1"/>
# <line y1="16" y2="16" x2="16" stroke="black" stroke-width="0.1"/>
#</>
# Based on svgtiler's Symbol.imageRendering
rendering =
"image-rendering": "optimizeSpeed"
style: "image-rendering:pixelated"
mapping =
'':
<symbol viewBox="0 0 16 16" style="overflow: visible" z-index="-1">
{blank}
</symbol>
">":
<symbol viewBox="0 0 16 16" style="overflow: visible">
{blank}
<line x1="3" x2="9.5" y1="8" y2="8" stroke="white" stroke-width="2"/>
<path d="M 9,5 L 13,8 L 9,11 Z" fill="white"/>
</symbol>
solid: solid =
<symbol viewBox="0 0 16 16" style="overflow: visible">
<image {...rendering} xlink:href={sprite "solid_#{area}"} width="16" height="16"/>
</symbol>
s: solid
ledge: ledge =
<symbol viewBox="0 0 16 16" style="overflow: visible">
{blank}
<image {...rendering} xlink:href={sprite "ledge_#{area}"} width="16" height="16"/>
</symbol>
"-": ledge
crystal: crystal =
<symbol viewBox="0 0 16 16" overflowBox="-16 -24 48 64" style="overflow: visible">
{blank}
<image {...rendering} xlink:href={sprite "crystal"} x="-16" y="-24" width="48" height="64"/>
</symbol>
goal: crystal
ring: ring =
<symbol viewBox="0 0 16 16" style="overflow: visible">
{blank}
<image {...rendering} xlink:href={sprite "ring"} width="16" height="16"/>
</symbol>
r: ring
block: block =
<symbol viewBox="0 0 16 16" overflowBox="-2 0 22 16" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite "block"} x="-2" width="20" height="16"/>
</symbol>
b: block
"!b": green_block =
<symbol viewBox="0 0 16 16" overflowBox="-16 -22 45 38" style="overflow: visible; z-index: 20">
{blank}
<image {...rendering} xlink:href={sprite "green_block"} x="-16" y="-22" width="45" height="38"/>
</symbol>
"!block": green_block
key: key =
<symbol viewBox="0 0 16 16" overflowBox="-2 0 22 16" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite "key"} x="-2" width="22" height="16"/>
</symbol>
k: key
"!key": green_key =
<symbol viewBox="0 0 16 16" overflowBox="-17 -12 41 28" style="overflow: visible; z-index: 20">
{blank}
<image {...rendering} xlink:href={sprite "green_key"} x="-17" y="-12" width="41" height="28"/>
</symbol>
"!k": green_key
chest: chest =
<symbol viewBox="0 0 16 16" overflowBox="-2 -11 24 27" style="overflow: visible; z-index: 12">
{blank}
<image {...rendering} xlink:href={sprite 'chest'} x="-2" y="-11" width="24" height="27"/>
</symbol>
c: chest
yield: y =
<symbol viewBox="0 0 16 16" overflowBox="-16 -16 48 48" style="overflow: visible; z-index: 30">
{blank}
<image {...rendering} xlink:href={sprite 'green_flame'} x="-16" y="-16" width="48" height="48"/>
</symbol>
y: y
jar: jar =
<symbol viewBox="0 0 16 16" overflowBox="-3 3 23 13" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite 'jar'} x="-3" y="3" width="23" height="13"/>
</symbol>
j: jar
door: door = ->
if @neighbor(0,1).key in ['d', '!d', 'door', '!door']
blank
else
<symbol viewBox="0 0 16 16" overflowBox="0 -32 16 48" style="overflow: visible; z-index: 10">
<image {...rendering} xlink:href={sprite 'lock'} y="-32" width="16" height="48"/>
</symbol>
d: door
"!door": green_door = ->
if @neighbor(0,1).key in ['d', '!d', 'door', '!door']
blank
else
<symbol viewBox="0 0 16 16" overflowBox="-16 -54 47 70" style="overflow: visible; z-index: 20">
<image {...rendering} xlink:href={sprite 'green_lock'} x="-16" y="-54" width="47" height="70"/>
</symbol>
"!d": green_door
player: player = ->
if @neighbor(0,1).key in ['p', 'player']
blank
else
<symbol viewBox="0 0 16 16" overflowBox="-16 -20 48 52" style="overflow: visible; z-index: 30">
{blank}
<image {...rendering} xlink:href={sprite 'red_flame'} x="-16" y="-20" width="48" height="52"/>
</symbol>
p: player
rico: ->
if @neighbor(0,1).key == 'rico'
blank
else
<symbol viewBox="0 0 16 16" overflowBox="0 -8 16 24" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite 'player'} y="-8" width="16" height="24"/>
</symbol>
addText = (container, label) -> ->
if typeof container == 'function'
container = container.call @
offsetX = offsetY = 0
if label == 'DCi+1,2j' and @neighbor(+4,0).key == 'c:DCi+1,2j+1'
offsetX = -10
else if label == 'DCi+1,2j+1' and @neighbor(-4,0).key == 'c:DCi+1,2j'
offsetX = +10
else if label in ['VBa','VBb'] and @neighbor(+2,0).key in ['c:VAa','c:VAb']
offsetX = -18
else if label in ['VAa','VAb'] and @neighbor(-2,0).key in ['c:VBa','c:VBb']
offsetX = +18
else if label in ['PDC', 'PB11'] and @neighbor(-1,-1).key == 'c:VB_local2'
offsetX = +20
offsetY = +3
else if label in ['VAB_local'] and @neighbor(+1,0).key in ['c:PAa', 'c:PAb']
offsetX = -10
else if label in ['PAa', 'PAb'] and @neighbor(-1,0).key == 'c:VAB_local'
offsetX = +27
text = label
if text of nameMap
text = nameMap[text]
text = "$#{text}$" # math mode
text = "\\bf\\boldmath\\contour{black}{#{text}}" # readable
text = <text x={8 + offsetX} y={-1 + offsetY} text-anchor="middle" fill="white">{text}</text>
if container.type != 'symbol'
<symbol viewBox="0 0 16 16" style="overflow: visible">
{container}
{text}
</symbol>
else
preact.cloneElement container, {},
preact.toChildArray(container.props.children).concat [text]
(key) ->
key = key.replace /:sounds\/[^]*/, '' # ignore sound files as labels
if key of mapping
mapping[key]
else
[before, after] = key.split ':'
if before of mapping
addText mapping[before], after
| 214603 | # Mapping of internal room names to LaTeX label.
# I'm guessing that A_01 and B_10 will be the reference "room i,j"
#
# In order of appearance
nameMap =
# start room
"A00" : "A_{0,0}"
"global_lock" : "\\text{GL}" # "\\gl{}" # too big
# DC gadget needs to be re-done in small_examples to match binary tree version
"VDCi" : "V_{DC_i}"
"PDCi+1" : "P_{DC_{i+1}}"
"DCi+1,2j" : "DC_{i+1,2j}"
"DCi+1,2j+1" : "DC_{i+1,2j+1}"
# Aij rooms
"VA01" : "V_{A_{i,j}}"
"PB00" : "P_{A_{i,j+1}}"
"BC00" : "A_{i,j+1}"
"PAB_local" : "\\phs{}"
"PBb" : "P_{s(A_{i,j}),b}"
"VAb" : "V_{s(A_{i,j}),a}"
"VBb" : "V_{s(A_{i,j}),b}"
# Bij^C
"VB10" : "V_{B_{i,j}}"
"PB_local1" : "P_{B^{(J)}}"
"BJ10" : "B^{(J)}_{i,j}"
"PB11" : "P_{B_{i,j+1}}"
"VB_local2" : "V_{B^{(C)}}"
"BC11" : "B^{(C)}_{i,j+1}"
# Bij^J
"VB_local1" : "V_{B^{(J)}}"
"PB_local2" : "P_{B^{(C)}}"
"VBsb" : "V_{s(B_{i,j}),b}"
"PAb" : "P_{s(B_{i,j}),a}"
"VAB_local" : "\\vhs{}"
# stop
"VAx0" : "V_{A_{x,0}}"
"A10" : "A_{1,0}"
"Mx" : "M_x"
sprite = (x) -> "../sprites/#{x}.png"
area = 'city'
blank =
<rect width="16" height="16" fill="black" stroke="black" stroke-width="0.01"/>
#blank = <>
# <rect width="16" height="16" fill="black"/>
# <line x1="16" x2="16" y2="16" stroke="black" stroke-width="0.1"/>
# <line y1="16" y2="16" x2="16" stroke="black" stroke-width="0.1"/>
#</>
# Based on svgtiler's Symbol.imageRendering
rendering =
"image-rendering": "optimizeSpeed"
style: "image-rendering:pixelated"
mapping =
'':
<symbol viewBox="0 0 16 16" style="overflow: visible" z-index="-1">
{blank}
</symbol>
">":
<symbol viewBox="0 0 16 16" style="overflow: visible">
{blank}
<line x1="3" x2="9.5" y1="8" y2="8" stroke="white" stroke-width="2"/>
<path d="M 9,5 L 13,8 L 9,11 Z" fill="white"/>
</symbol>
solid: solid =
<symbol viewBox="0 0 16 16" style="overflow: visible">
<image {...rendering} xlink:href={sprite "solid_#{area}"} width="16" height="16"/>
</symbol>
s: solid
ledge: ledge =
<symbol viewBox="0 0 16 16" style="overflow: visible">
{blank}
<image {...rendering} xlink:href={sprite "ledge_#{area}"} width="16" height="16"/>
</symbol>
"-": ledge
crystal: crystal =
<symbol viewBox="0 0 16 16" overflowBox="-16 -24 48 64" style="overflow: visible">
{blank}
<image {...rendering} xlink:href={sprite "crystal"} x="-16" y="-24" width="48" height="64"/>
</symbol>
goal: crystal
ring: ring =
<symbol viewBox="0 0 16 16" style="overflow: visible">
{blank}
<image {...rendering} xlink:href={sprite "ring"} width="16" height="16"/>
</symbol>
r: ring
block: block =
<symbol viewBox="0 0 16 16" overflowBox="-2 0 22 16" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite "block"} x="-2" width="20" height="16"/>
</symbol>
b: block
"!b": green_block =
<symbol viewBox="0 0 16 16" overflowBox="-16 -22 45 38" style="overflow: visible; z-index: 20">
{blank}
<image {...rendering} xlink:href={sprite "green_block"} x="-16" y="-22" width="45" height="38"/>
</symbol>
"!block": green_block
key: key =
<symbol viewBox="0 0 16 16" overflowBox="-2 0 22 16" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite "key"} x="-2" width="22" height="16"/>
</symbol>
k: key
"!key": green_key =
<symbol viewBox="0 0 16 16" overflowBox="-17 -12 41 28" style="overflow: visible; z-index: 20">
{blank}
<image {...rendering} xlink:href={sprite "green_key"} x="-17" y="-12" width="41" height="28"/>
</symbol>
"!k": green_key
chest: chest =
<symbol viewBox="0 0 16 16" overflowBox="-2 -11 24 27" style="overflow: visible; z-index: 12">
{blank}
<image {...rendering} xlink:href={sprite 'chest'} x="-2" y="-11" width="24" height="27"/>
</symbol>
c: chest
yield: y =
<symbol viewBox="0 0 16 16" overflowBox="-16 -16 48 48" style="overflow: visible; z-index: 30">
{blank}
<image {...rendering} xlink:href={sprite 'green_flame'} x="-16" y="-16" width="48" height="48"/>
</symbol>
y: y
jar: jar =
<symbol viewBox="0 0 16 16" overflowBox="-3 3 23 13" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite 'jar'} x="-3" y="3" width="23" height="13"/>
</symbol>
j: jar
door: door = ->
if @neighbor(0,1).key in ['d', '!d', 'door', '!door']
blank
else
<symbol viewBox="0 0 16 16" overflowBox="0 -32 16 48" style="overflow: visible; z-index: 10">
<image {...rendering} xlink:href={sprite 'lock'} y="-32" width="16" height="48"/>
</symbol>
d: door
"!door": green_door = ->
if @neighbor(0,1).key in ['d', '!d', 'door', '!door']
blank
else
<symbol viewBox="0 0 16 16" overflowBox="-16 -54 47 70" style="overflow: visible; z-index: 20">
<image {...rendering} xlink:href={sprite 'green_lock'} x="-16" y="-54" width="47" height="70"/>
</symbol>
"!d": green_door
player: player = ->
if @neighbor(0,1).key in ['p', 'player']
blank
else
<symbol viewBox="0 0 16 16" overflowBox="-16 -20 48 52" style="overflow: visible; z-index: 30">
{blank}
<image {...rendering} xlink:href={sprite 'red_flame'} x="-16" y="-20" width="48" height="52"/>
</symbol>
p: player
rico: ->
if @neighbor(0,1).key == 'ric<KEY>'
blank
else
<symbol viewBox="0 0 16 16" overflowBox="0 -8 16 24" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite 'player'} y="-8" width="16" height="24"/>
</symbol>
addText = (container, label) -> ->
if typeof container == 'function'
container = container.call @
offsetX = offsetY = 0
if label == 'DCi+1,2j' and @neighbor(+4,0).key == 'c:DC<KEY>,2<KEY>'
offsetX = -10
else if label == 'DCi+1,2j+1' and @neighbor(-4,0).key == '<KEY>:<KEY>'
offsetX = +10
else if label in ['VBa','VBb'] and @neighbor(+2,0).key in ['<KEY>','c:<KEY>']
offsetX = -18
else if label in ['VAa','VAb'] and @neighbor(-2,0).key in ['<KEY>','<KEY>']
offsetX = +18
else if label in ['PDC', 'PB11'] and @neighbor(-1,-1).key == '<KEY>'
offsetX = +20
offsetY = +3
else if label in ['VAB_local'] and @neighbor(+1,0).key in ['<KEY>', '<KEY>']
offsetX = -10
else if label in ['PAa', 'PAb'] and @neighbor(-1,0).key == '<KEY>'
offsetX = +27
text = label
if text of nameMap
text = nameMap[text]
text = "$#{text}$" # math mode
text = "\\bf\\boldmath\\contour{black}{#{text}}" # readable
text = <text x={8 + offsetX} y={-1 + offsetY} text-anchor="middle" fill="white">{text}</text>
if container.type != 'symbol'
<symbol viewBox="0 0 16 16" style="overflow: visible">
{container}
{text}
</symbol>
else
preact.cloneElement container, {},
preact.toChildArray(container.props.children).concat [text]
(key) ->
key = key.replace /:sounds\/[^]*/, '' # ignore sound files as labels
if key of mapping
mapping[key]
else
[before, after] = key.split ':'
if before of mapping
addText mapping[before], after
| true | # Mapping of internal room names to LaTeX label.
# I'm guessing that A_01 and B_10 will be the reference "room i,j"
#
# In order of appearance
nameMap =
# start room
"A00" : "A_{0,0}"
"global_lock" : "\\text{GL}" # "\\gl{}" # too big
# DC gadget needs to be re-done in small_examples to match binary tree version
"VDCi" : "V_{DC_i}"
"PDCi+1" : "P_{DC_{i+1}}"
"DCi+1,2j" : "DC_{i+1,2j}"
"DCi+1,2j+1" : "DC_{i+1,2j+1}"
# Aij rooms
"VA01" : "V_{A_{i,j}}"
"PB00" : "P_{A_{i,j+1}}"
"BC00" : "A_{i,j+1}"
"PAB_local" : "\\phs{}"
"PBb" : "P_{s(A_{i,j}),b}"
"VAb" : "V_{s(A_{i,j}),a}"
"VBb" : "V_{s(A_{i,j}),b}"
# Bij^C
"VB10" : "V_{B_{i,j}}"
"PB_local1" : "P_{B^{(J)}}"
"BJ10" : "B^{(J)}_{i,j}"
"PB11" : "P_{B_{i,j+1}}"
"VB_local2" : "V_{B^{(C)}}"
"BC11" : "B^{(C)}_{i,j+1}"
# Bij^J
"VB_local1" : "V_{B^{(J)}}"
"PB_local2" : "P_{B^{(C)}}"
"VBsb" : "V_{s(B_{i,j}),b}"
"PAb" : "P_{s(B_{i,j}),a}"
"VAB_local" : "\\vhs{}"
# stop
"VAx0" : "V_{A_{x,0}}"
"A10" : "A_{1,0}"
"Mx" : "M_x"
sprite = (x) -> "../sprites/#{x}.png"
area = 'city'
blank =
<rect width="16" height="16" fill="black" stroke="black" stroke-width="0.01"/>
#blank = <>
# <rect width="16" height="16" fill="black"/>
# <line x1="16" x2="16" y2="16" stroke="black" stroke-width="0.1"/>
# <line y1="16" y2="16" x2="16" stroke="black" stroke-width="0.1"/>
#</>
# Based on svgtiler's Symbol.imageRendering
rendering =
"image-rendering": "optimizeSpeed"
style: "image-rendering:pixelated"
mapping =
'':
<symbol viewBox="0 0 16 16" style="overflow: visible" z-index="-1">
{blank}
</symbol>
">":
<symbol viewBox="0 0 16 16" style="overflow: visible">
{blank}
<line x1="3" x2="9.5" y1="8" y2="8" stroke="white" stroke-width="2"/>
<path d="M 9,5 L 13,8 L 9,11 Z" fill="white"/>
</symbol>
solid: solid =
<symbol viewBox="0 0 16 16" style="overflow: visible">
<image {...rendering} xlink:href={sprite "solid_#{area}"} width="16" height="16"/>
</symbol>
s: solid
ledge: ledge =
<symbol viewBox="0 0 16 16" style="overflow: visible">
{blank}
<image {...rendering} xlink:href={sprite "ledge_#{area}"} width="16" height="16"/>
</symbol>
"-": ledge
crystal: crystal =
<symbol viewBox="0 0 16 16" overflowBox="-16 -24 48 64" style="overflow: visible">
{blank}
<image {...rendering} xlink:href={sprite "crystal"} x="-16" y="-24" width="48" height="64"/>
</symbol>
goal: crystal
ring: ring =
<symbol viewBox="0 0 16 16" style="overflow: visible">
{blank}
<image {...rendering} xlink:href={sprite "ring"} width="16" height="16"/>
</symbol>
r: ring
block: block =
<symbol viewBox="0 0 16 16" overflowBox="-2 0 22 16" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite "block"} x="-2" width="20" height="16"/>
</symbol>
b: block
"!b": green_block =
<symbol viewBox="0 0 16 16" overflowBox="-16 -22 45 38" style="overflow: visible; z-index: 20">
{blank}
<image {...rendering} xlink:href={sprite "green_block"} x="-16" y="-22" width="45" height="38"/>
</symbol>
"!block": green_block
key: key =
<symbol viewBox="0 0 16 16" overflowBox="-2 0 22 16" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite "key"} x="-2" width="22" height="16"/>
</symbol>
k: key
"!key": green_key =
<symbol viewBox="0 0 16 16" overflowBox="-17 -12 41 28" style="overflow: visible; z-index: 20">
{blank}
<image {...rendering} xlink:href={sprite "green_key"} x="-17" y="-12" width="41" height="28"/>
</symbol>
"!k": green_key
chest: chest =
<symbol viewBox="0 0 16 16" overflowBox="-2 -11 24 27" style="overflow: visible; z-index: 12">
{blank}
<image {...rendering} xlink:href={sprite 'chest'} x="-2" y="-11" width="24" height="27"/>
</symbol>
c: chest
yield: y =
<symbol viewBox="0 0 16 16" overflowBox="-16 -16 48 48" style="overflow: visible; z-index: 30">
{blank}
<image {...rendering} xlink:href={sprite 'green_flame'} x="-16" y="-16" width="48" height="48"/>
</symbol>
y: y
jar: jar =
<symbol viewBox="0 0 16 16" overflowBox="-3 3 23 13" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite 'jar'} x="-3" y="3" width="23" height="13"/>
</symbol>
j: jar
door: door = ->
if @neighbor(0,1).key in ['d', '!d', 'door', '!door']
blank
else
<symbol viewBox="0 0 16 16" overflowBox="0 -32 16 48" style="overflow: visible; z-index: 10">
<image {...rendering} xlink:href={sprite 'lock'} y="-32" width="16" height="48"/>
</symbol>
d: door
"!door": green_door = ->
if @neighbor(0,1).key in ['d', '!d', 'door', '!door']
blank
else
<symbol viewBox="0 0 16 16" overflowBox="-16 -54 47 70" style="overflow: visible; z-index: 20">
<image {...rendering} xlink:href={sprite 'green_lock'} x="-16" y="-54" width="47" height="70"/>
</symbol>
"!d": green_door
player: player = ->
if @neighbor(0,1).key in ['p', 'player']
blank
else
<symbol viewBox="0 0 16 16" overflowBox="-16 -20 48 52" style="overflow: visible; z-index: 30">
{blank}
<image {...rendering} xlink:href={sprite 'red_flame'} x="-16" y="-20" width="48" height="52"/>
</symbol>
p: player
rico: ->
if @neighbor(0,1).key == 'ricPI:KEY:<KEY>END_PI'
blank
else
<symbol viewBox="0 0 16 16" overflowBox="0 -8 16 24" style="overflow: visible; z-index: 10">
{blank}
<image {...rendering} xlink:href={sprite 'player'} y="-8" width="16" height="24"/>
</symbol>
addText = (container, label) -> ->
if typeof container == 'function'
container = container.call @
offsetX = offsetY = 0
if label == 'DCi+1,2j' and @neighbor(+4,0).key == 'c:DCPI:KEY:<KEY>END_PI,2PI:KEY:<KEY>END_PI'
offsetX = -10
else if label == 'DCi+1,2j+1' and @neighbor(-4,0).key == 'PI:KEY:<KEY>END_PI:PI:KEY:<KEY>END_PI'
offsetX = +10
else if label in ['VBa','VBb'] and @neighbor(+2,0).key in ['PI:KEY:<KEY>END_PI','c:PI:KEY:<KEY>END_PI']
offsetX = -18
else if label in ['VAa','VAb'] and @neighbor(-2,0).key in ['PI:KEY:<KEY>END_PI','PI:KEY:<KEY>END_PI']
offsetX = +18
else if label in ['PDC', 'PB11'] and @neighbor(-1,-1).key == 'PI:KEY:<KEY>END_PI'
offsetX = +20
offsetY = +3
else if label in ['VAB_local'] and @neighbor(+1,0).key in ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI']
offsetX = -10
else if label in ['PAa', 'PAb'] and @neighbor(-1,0).key == 'PI:KEY:<KEY>END_PI'
offsetX = +27
text = label
if text of nameMap
text = nameMap[text]
text = "$#{text}$" # math mode
text = "\\bf\\boldmath\\contour{black}{#{text}}" # readable
text = <text x={8 + offsetX} y={-1 + offsetY} text-anchor="middle" fill="white">{text}</text>
if container.type != 'symbol'
<symbol viewBox="0 0 16 16" style="overflow: visible">
{container}
{text}
</symbol>
else
preact.cloneElement container, {},
preact.toChildArray(container.props.children).concat [text]
(key) ->
key = key.replace /:sounds\/[^]*/, '' # ignore sound files as labels
if key of mapping
mapping[key]
else
[before, after] = key.split ':'
if before of mapping
addText mapping[before], after
|
[
{
"context": " `Title` AS `title`, `Password` AS `password`,\n `IrcChannel` AS `irc_cha",
"end": 11617,
"score": 0.9914433360099792,
"start": 11609,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "nelData.title)},\n `Password`=#{@_toQuery(channelData.password)},\n ",
"end": 20214,
"score": 0.6484739184379578,
"start": 20210,
"tag": "PASSWORD",
"value": "@_to"
}
] | src/server/datasources/ds.default.coffee | Atanamo/IRC-Gateway | 0 |
## Include libraries
Q = require 'q'
crypto = require 'crypto'
## Include app modules
config = require '../config'
log = require '../logger'
## Include data classes
MysqlDatabaseHandler = require '../databasehandlers/dbh.mysql'
AbstractDatasource = require './ds.abstract'
## Default abstraction of data managing methods.
## See `AbstractDatasource` for more.
##
## Uses the MySQL database handler by default.
##
## Structure:
## * Client identity (with example implementations)
## * Game-specific queries (with example implementations)
## * Server management
## * Channel management
##
class DefaultDatasource extends AbstractDatasource
# @override
_createHandler: ->
return new MysqlDatabaseHandler(config, log)
#
# Client identity (with example implementations)
#
# Returns the saved identification data for the given player in the given game.
# @param idUser [int] The id of the player's account or game identity/character as given by a client on logon.
# @param idGame [int] The id of the player's game world as given by a client on logon.
# @return [promise] A promise, resolving to a data map with keys
# `id` (The id of the player for the chat),
# `idGame` (Should equal given idGame),
# `idUser` (The id of the player's account),
# `name` (The player's name for the chat),
# `title` (An optional more detail name for the chat, will default to the name),
# `gameTitle` (The full name of the player's game world),
# `gameTag` (An optional shortened version of the name of the player's game world, will default to the full name),
# `token` (The security token for the player).
# If the read data set is empty, the promise is rejected.
getClientIdentityData: (idUser, idGame) ->
##
# Note: This is an example implementation - overwrite it for your own game API
##
# Read (meta) data of given game
promise = @_getGameData(idGame)
# Read data of given player in given game
promise = promise.then (gameData) =>
sql = "
SELECT `Ch`.`ID` AS `character_id`,
`Ch`.`Name` AS `character_name`,
`Ch`.`Class` AS `class_name`,
#{@_toQuery(gameData.game_title)} AS `game_title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.PLAYER_GAMES}` AS `PG`
JOIN `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAME_PLAYER_IDENTITIES}` AS `Ch`
ON `Ch`.`ID`=`PG`.`CharacterID`
WHERE `PG`.`GameID`=#{@_toQuery(idGame)}
AND `PG`.`UserID`=#{@_toQuery(idUser)}
"
return @_readSimpleData(sql, true)
# Build final result
promise = promise.then (playerData) =>
return {
id: playerData.character_id
idGame: idGame
idUser: idUser
name: playerData.character_name
title: "#{playerData.character_name} - #{playerData.class_name}"
gameTitle: playerData.game_title
gameTag: @_getShortenedGameTitle(playerData.game_title)
token: @_getSecurityToken(idUser, playerData)
}
return promise
# Returns the current security token for the given player.
# This token must be sent on auth request by the client.
_getSecurityToken: (idUser, playerData) ->
return @_getHashValue("#{config.CLIENT_AUTH_SECRET}_#{idUser}")
# Returns the md5 hash of the given string
_getHashValue: (original_val) ->
hashingStream = crypto.createHash('md5')
hashingStream.update(original_val);
return hashingStream.digest('hex')
# Returns the first part of the given game title (split by underscore, hyphen or space)
_getShortenedGameTitle: (fullGameTitle) ->
shortTitle = String(fullGameTitle)
shortTitle = shortTitle.replace(/[_- ](.+)/, '')
return shortTitle
#
# Game-specific queries (with example implementations)
#
# Helper query - Returns the data for the given game world.
# @param idGame [int] The id of the game world.
# @return [promise] A promise, resolving to a data map with keys
# `game_id` (Should equal idGame),
# `database_id` (The id of the database, which stores the game tables) and
# `game_title` (The display name of the game world - is allowed to contain spaces, etc.).
# If the read data set is empty, the promise is rejected.
_getGameData: (idGame) ->
##
# Note: This is an example implementation - overwrite it for your own requirements
##
sql = "
SELECT `ID` AS `game_id`, `ServerID` AS `database_id`, `Name` AS `game_title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `ID`=#{@_toQuery(idGame)}
"
return @_readSimpleData(sql, true)
# Returns the status information for each of the given list of game worlds.
# This is used by a bot on request of one or more game statuses.
# @param idList [array] An array of integers, each defining the id of a game world.
# @return [promise] A promise, resolving to a list of data maps.
# Each data map must have at least the key `id` to reference the corresponding game world.
# The bot will output any further values of a data map as a game's status information.
# (The key of each of these values is used to label the value on output. Underscores are replaced by spaces.)
# The list may be empty, if none of the given games could be found.
getGameStatuses: (idList=[]) ->
##
# Note: This is an example implementation - overwrite it for your own game API
##
# Convert given array to string of comma-separated values
idListSanitized = idList.map (idGame) =>
@_toQuery(idGame)
idListString = idListSanitized.join(',')
# Read the status values 'current_state' and 'start_time' for each game:
sql = "
SELECT `ID` as `id`, `StateText` AS `current_state`, `StartTime` AS `start_time`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `ID` IN (#{idListString})
ORDER BY `Status` ASC, `ID` DESC
"
return @_readMultipleData(sql)
# Returns the list of game worlds, which each have a bot to use for bot-channels.
# If the mono-bot is configured, returns the list of all game worlds having a chat.
# This list is also used to manage the lifetime of corresponding channels and its logs
# by the game lookup interval.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `id` (The unique id of the game world) and
# `title` (The display name of the game world - is allowed to contain spaces, etc.).
# The list may be empty, if there are no games at all.
getBotRepresentedGames: ->
##
# Note: This is an example implementation - overwrite it for your own game API
##
if config.MAX_BOTS > 0
sql = "
SELECT `ID` AS `id`, `Name` AS `title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `Running`=1 AND `Deleted`=0
ORDER BY `ID` ASC
LIMIT #{config.MAX_BOTS}
"
else
sql = "
SELECT `ID` AS `id`, `Name` AS `title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `Deleted`=0
ORDER BY `ID` ASC
"
return @_readMultipleData(sql)
#
# Server management
#
# Returns a list of channels, which should be mirrored to IRC, but each belong to only one game.
# This excludes the global channel.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `game_id` (The id of the game, the channel belongs to),
# `creator_id` (The id of the user, who created the channel),
# `name` (The unique name of a channel - used internally),
# `title` (The display name of the channel - is allowed to contain spaces, etc.),
# `password` (The password for joining the channel - not encrypted),
# `irc_channel` (The exact name of the IRC channel to mirror) and
# `is_public` (TRUE, if the channel is meant to be public and therefor joined players have to be hidden; else FALSE).
# The list may be empty, if no appropriate channels exist.
getGameBoundBotChannels: ->
sql = "
SELECT CONCAT(#{@_toQuery(config.INTERN_NONGAME_CHANNEL_PREFIX)}, `ID`) AS `name`,
`GameID` AS `game_id`, `CreatorUserID` AS `creator_id`,
`Title` AS `title`, `Password` AS `password`,
`IrcChannel` AS `irc_channel`, `IsPublic` AS `is_public`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `IrcChannel` IS NOT NULL
"
return @_readMultipleData(sql)
# Returns the data for the global channel, which should be mirrored to IRC for every game world.
# Thus, if not using the mono-bot, it will contain multiple bots.
# @return [promise] A promise, resolving to a data map with keys
# `name` (The unique name of the channel - used internally),
# `title` (The display name of the channel - is allowed to contain spaces, etc.),
# `password` (Optional: The password for joining the channel on IRC - not encrypted),
# `irc_channel` (The exact name of the IRC channel to mirror) and
# `is_public` (TRUE, if players joined to the channel should to be hidden; else FALSE).
getGlobalChannelData: ->
promise = Q.fcall =>
return {
name: config.INTERN_GLOBAL_CHANNEL_NAME
title: config.INTERN_GLOBAL_CHANNEL_TITLE
irc_channel: config.IRC_GLOBAL_CHANNEL
is_public: true
}
return promise
# Returns the data for the channel matching given game and title.
# @param idGame [int] The id of the game world, the requested channel belongs to.
# @param channelTitle [string] The title of the requested channel (is allowed to contain spaces, etc.).
# @return [promise] A promise, resolving to a data map with keys
# `game_id` (The id of the game, a channel belongs to - should normally equal the given idGame),
# `creator_id` (The id of the user, who created the channel),
# `name` (The unique name of the channel - used internally),
# `title` (The display name of the channel - should normally equal the given title),
# `password` (The password for joining the channel - not encrypted),
# `irc_channel` (The exact name of the IRC channel to optionally mirror) and
# `is_public` (TRUE, if players joined to the channel should to be hidden; else FALSE).
# If the read data set is empty, the promise is rejected.
getChannelDataByTitle: (idGame, channelTitle) ->
sql = "
SELECT CONCAT(#{@_toQuery(config.INTERN_NONGAME_CHANNEL_PREFIX)}, `ID`) AS `name`,
`GameID` AS `game_id`, `CreatorUserID` AS `creator_id`,
`Title` AS `title`, `Password` AS `password`,
`IrcChannel` AS `irc_channel`, `IsPublic` AS `is_public`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(idGame)}
AND `Title` LIKE #{@_toQuery(channelTitle)}
"
return @_readSimpleData(sql, true)
# Returns a list of channels, which were joined by the given client.
# @param clientIdentity [ClientIdentity] The identity of the client to read the channels for.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `name` (The unique name of a channel - used internally),
# `title` (The display name of the channel - is allowed to contain spaces, etc.),
# `creator_id` (Optional: The id of the user, who created the channel),
# `irc_channel` (Optional: The exact name of an IRC channel to mirror) and
# `is_public` (TRUE, if the channel is meant to be public and therefor joined player's have to be hidden; else FALSE).
# The list may be empty, if no channels are joined by the client.
getClientChannels: (clientIdentity) ->
# Read data of client's game as default channel
idGame = clientIdentity.getGameID()
gamePromise = @_getGameData(idGame)
gamePromise = gamePromise.then (gameData) =>
return {
name: "#{config.INTERN_GAME_CHANNEL_PREFIX}#{gameData.game_id}"
title: gameData.game_title
is_public: true
}
# Read non-default channels
idUser = clientIdentity.getUserID()
sql = "
SELECT CONCAT(#{@_toQuery(config.INTERN_NONGAME_CHANNEL_PREFIX)}, `C`.`ID`) AS `name`,
`C`.`CreatorUserID` AS `creator_id`, `C`.`Title` AS `title`,
`C`.`IrcChannel` AS `irc_channel`, `C`.`IsPublic` AS `is_public`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}` AS `C`
JOIN `#{config.SQL_TABLES.CHANNEL_JOININGS}` AS `CJ`
ON `CJ`.`ChannelID`=`C`.`ID`
WHERE `CJ`.`UserID`=#{@_toQuery(idUser)}
AND `C`.`GameID`=#{@_toQuery(idGame)}
ORDER BY `CJ`.`ID` ASC
"
channelsPromise = @_readMultipleData(sql)
# Read data of default channel
globalChannelPromise = @getGlobalChannelData()
# Merge promise results to one array
resultPromise = channelsPromise.then (channelListData) =>
list = channelListData
return gamePromise.then (gameChannelData) =>
list.unshift(gameChannelData) if gameChannelData?
return globalChannelPromise.then (defaultChannelData) =>
list.unshift(defaultChannelData)
return list
return resultPromise
# Returns the number of channels, which were created by the given client.
# @param clientIdentity [ClientIdentity] The identity of the client to count the channels for.
# @return [promise] A promise, resolving to the number of channels.
getClientCreatedChannelsCount: (clientIdentity) ->
idGame = clientIdentity.getGameID()
idUser = clientIdentity.getUserID()
sql = "
SELECT COUNT(`ID`) AS `channels`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(idGame)}
AND `CreatorUserID`=#{@_toQuery(idUser)}
"
promise = @_readSimpleData(sql)
promise = promise.then (data) =>
return data?.channels
return promise
#
# Channel management
#
# Returns a list of messages/channel events, which had been logged for the given channel.
# @param channelName [string] The internal name of the channel.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `id` (The id of the list entry),
# `event_name` (The name of the logged channel event),
# `event_data` (The logged data for the event, serialized as JSON string - contains values like message text or sender identity) and
# `timestamp` (The timestamp of the log entry/event).
# The list may be empty, if no logs exists for the channel.
getLoggedChannelMessages: (channelName) ->
sql = "
(
SELECT `ChannelLogID` AS `id`, `EventTextID` AS `event_name`, `EventData` AS `event_data`, `Timestamp` AS `timestamp`
FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelTextID`=#{@_toQuery(channelName)}
ORDER BY `Timestamp` DESC
LIMIT #{config.MAX_CHANNEL_LOGS_TO_CLIENT}
)
ORDER BY `Timestamp` ASC
"
promise = @_readMultipleData(sql)
return promise
# Saves the given message/channel event to the channel logs. May replaces old logs.
# @param channelName [string] The internal name of the channel.
# @param timestamp [int] The timestamp of the event (in milliseconds).
# @param eventName [string] The name of the channel event.
# @param eventData [object] A data map, containing the main data for the event (like message text or sender identity).
logChannelMessage: (channelName, timestamp, eventName, eventData) ->
channelID = 0
if channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
try
serialEventData = JSON.stringify(eventData)
catch
log.warn 'Could not serializable json string!', 'Database message logging'
serialEventData = '{}'
@_doTransaction =>
sql = "
SELECT COALESCE(MAX(`ChannelLogID`), 0) AS `max_id`
FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelTextID`=#{@_toQuery(channelName)}
"
promise = @_readSimpleData(sql, true)
promise = promise.then (data) =>
maxLogID = data.max_id
nextLogID = maxLogID + 1
nextBufferID = (maxLogID % config.MAX_CHANNEL_LOGS) + 1
sql = "
REPLACE INTO `#{config.SQL_TABLES.CHANNEL_LOGS}` SET
`ChannelLogID`=#{@_toQuery(nextLogID)},
`ChannelBufferID`=#{@_toQuery(nextBufferID)},
`ChannelTextID`=#{@_toQuery(channelName)},
`ChannelID`=#{@_toQuery(channelID)},
`EventTextID`=#{@_toQuery(eventName)},
`EventData`=#{@_toQuery(serialEventData)},
`Timestamp`=#{@_toQuery(timestamp)}
"
return @_sendQuery(sql)
return promise
# Creates a new channel with given data and returns the resulting data of the channel in database.
# @param clientIdentity [ClientIdentity] The identity of the client to set as channel creator.
# @param channelData [object] A data map with keys
# `game_id` (The id of the game, a channel should belong to),
# `title` (The display name for the channel - is allowed to contain spaces, etc.),
# `password` (The password for joining the channel - not encrypted),
# `is_for_irc` (TRUE, if the channel should to be mirrored to IRC; else FALSE - defaults to FALSE) and
# `is_public` (TRUE, if players joined to the channel should to be hidden; else FALSE - defaults to FALSE).
# @return [promise] A promise, resolving to a data map with keys equal to the given object, but complemented with keys
# `creator_id` (The id of the user, who created the channel - should equal user id of given identity),
# `name` (The unique name of the channel - used internally) and
# `irc_channel` (The exact name of an IRC channel to mirror - defaults to null, if `is_for_irc` was false).
# If the channel could not be created, the promise is rejected.
createChannelByData: (clientIdentity, channelData) ->
# Create the channel
userID = clientIdentity.getUserID()
channelData.creator_id = userID
sql = "
INSERT INTO `#{config.SQL_TABLES.CHANNEL_LIST}` SET
`GameID`=#{@_toQuery(channelData.game_id)},
`CreatorUserID`=#{@_toQuery(userID)},
`Title`=#{@_toQuery(channelData.title)},
`Password`=#{@_toQuery(channelData.password)},
`IsPublic`=#{@_toQuery(channelData.is_public)}
"
promise = @_sendQuery(sql)
# Finalize result object
promise = promise.then (resultData) =>
channelID = resultData.insertId
# Add channel name to data object
channelName = "#{config.INTERN_NONGAME_CHANNEL_PREFIX}#{channelID}"
channelData.name = channelName
# Add irc channel name
if channelData.is_for_irc
randomID = Math.floor(Math.random() * 1000)
ircChannelName = "#{config.IRC_NONGAME_CHANNEL_PREFIX}#{channelID}_#{randomID}"
channelData.irc_channel = ircChannelName
# Save name of irc channel
sql = "
UPDATE `#{config.SQL_TABLES.CHANNEL_LIST}` SET
`IrcChannel`=#{@_toQuery(ircChannelName)}
WHERE `ID`=#{@_toQuery(channelID)}
"
@_sendQuery(sql)
return channelData
return promise
# Deletes all related data (logs, joinings, etc.) of the channel with the given game.
# @param channelName [string] The internal name of the channel to delete.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
deleteChannel: (channelName) ->
return unless channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0 # Only non-game channels can be deleted
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
# Delete channel logs
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelID`=#{@_toQuery(channelID)}
"
logsPromise = @_sendQuery(sql)
# Delete channel joinings
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_JOININGS}`
WHERE `ChannelID`=#{@_toQuery(channelID)}
"
joinsPromise = @_sendQuery(sql)
# Delete channels
promise = Q.all([logsPromise, joinsPromise]).then =>
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `ID`=#{@_toQuery(channelID)}
"
return @_sendQuery(sql)
return promise
# Deletes all related data (logs, joinings, etc.) of all channels, which belong to the given game.
# @param gameID [int] The id of the game world.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
deleteChannelsByGame: (gameID) ->
internalGameChannel = "#{config.INTERN_GAME_CHANNEL_PREFIX}#{gameID}"
# Delete channel logs
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelID` IN (
SELECT `ID` FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(gameID)}
)
OR `ChannelTextID`=#{@_toQuery(internalGameChannel)}
"
logsPromise = @_sendQuery(sql)
# Delete channel joinings
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_JOININGS}`
WHERE `ChannelID` IN (
SELECT `ID` FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(gameID)}
)
"
joinsPromise = @_sendQuery(sql)
# Delete channels
promise = Q.all([logsPromise, joinsPromise]).then =>
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(gameID)}
"
return @_sendQuery(sql)
return promise
# Saves the given client for having joined the given channel.
# @param clientIdentity [ClientIdentity] The identity of the client.
# @param channelName [string] The name of the channel.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
addClientToChannel: (clientIdentity, channelName) ->
return unless channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0 # Only non-game channels can be joined explicitly
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
userID = clientIdentity.getUserID()
sql = "
INSERT INTO `#{config.SQL_TABLES.CHANNEL_JOININGS}` SET
`UserID`=#{@_toQuery(userID)},
`ChannelID`=#{@_toQuery(channelID)}
"
return @_sendQuery(sql)
# Deletes the given client from having joined the given channel.
# @param clientIdentity [ClientIdentity] The identity of the client.
# @param channelName [string] The name of the channel.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
removeClientFromChannel: (clientIdentity, channelName) ->
return unless channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0 # Only non-game channels can be parted explicitly
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
userID = clientIdentity.getUserID()
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_JOININGS}`
WHERE `UserID`=#{@_toQuery(userID)}
AND `ChannelID`=#{@_toQuery(channelID)}
"
return @_sendQuery(sql)
## Export class
module.exports = DefaultDatasource
| 82489 |
## Include libraries
Q = require 'q'
crypto = require 'crypto'
## Include app modules
config = require '../config'
log = require '../logger'
## Include data classes
MysqlDatabaseHandler = require '../databasehandlers/dbh.mysql'
AbstractDatasource = require './ds.abstract'
## Default abstraction of data managing methods.
## See `AbstractDatasource` for more.
##
## Uses the MySQL database handler by default.
##
## Structure:
## * Client identity (with example implementations)
## * Game-specific queries (with example implementations)
## * Server management
## * Channel management
##
class DefaultDatasource extends AbstractDatasource
# @override
_createHandler: ->
return new MysqlDatabaseHandler(config, log)
#
# Client identity (with example implementations)
#
# Returns the saved identification data for the given player in the given game.
# @param idUser [int] The id of the player's account or game identity/character as given by a client on logon.
# @param idGame [int] The id of the player's game world as given by a client on logon.
# @return [promise] A promise, resolving to a data map with keys
# `id` (The id of the player for the chat),
# `idGame` (Should equal given idGame),
# `idUser` (The id of the player's account),
# `name` (The player's name for the chat),
# `title` (An optional more detail name for the chat, will default to the name),
# `gameTitle` (The full name of the player's game world),
# `gameTag` (An optional shortened version of the name of the player's game world, will default to the full name),
# `token` (The security token for the player).
# If the read data set is empty, the promise is rejected.
getClientIdentityData: (idUser, idGame) ->
##
# Note: This is an example implementation - overwrite it for your own game API
##
# Read (meta) data of given game
promise = @_getGameData(idGame)
# Read data of given player in given game
promise = promise.then (gameData) =>
sql = "
SELECT `Ch`.`ID` AS `character_id`,
`Ch`.`Name` AS `character_name`,
`Ch`.`Class` AS `class_name`,
#{@_toQuery(gameData.game_title)} AS `game_title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.PLAYER_GAMES}` AS `PG`
JOIN `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAME_PLAYER_IDENTITIES}` AS `Ch`
ON `Ch`.`ID`=`PG`.`CharacterID`
WHERE `PG`.`GameID`=#{@_toQuery(idGame)}
AND `PG`.`UserID`=#{@_toQuery(idUser)}
"
return @_readSimpleData(sql, true)
# Build final result
promise = promise.then (playerData) =>
return {
id: playerData.character_id
idGame: idGame
idUser: idUser
name: playerData.character_name
title: "#{playerData.character_name} - #{playerData.class_name}"
gameTitle: playerData.game_title
gameTag: @_getShortenedGameTitle(playerData.game_title)
token: @_getSecurityToken(idUser, playerData)
}
return promise
# Returns the current security token for the given player.
# This token must be sent on auth request by the client.
_getSecurityToken: (idUser, playerData) ->
return @_getHashValue("#{config.CLIENT_AUTH_SECRET}_#{idUser}")
# Returns the md5 hash of the given string
_getHashValue: (original_val) ->
hashingStream = crypto.createHash('md5')
hashingStream.update(original_val);
return hashingStream.digest('hex')
# Returns the first part of the given game title (split by underscore, hyphen or space)
_getShortenedGameTitle: (fullGameTitle) ->
shortTitle = String(fullGameTitle)
shortTitle = shortTitle.replace(/[_- ](.+)/, '')
return shortTitle
#
# Game-specific queries (with example implementations)
#
# Helper query - Returns the data for the given game world.
# @param idGame [int] The id of the game world.
# @return [promise] A promise, resolving to a data map with keys
# `game_id` (Should equal idGame),
# `database_id` (The id of the database, which stores the game tables) and
# `game_title` (The display name of the game world - is allowed to contain spaces, etc.).
# If the read data set is empty, the promise is rejected.
_getGameData: (idGame) ->
##
# Note: This is an example implementation - overwrite it for your own requirements
##
sql = "
SELECT `ID` AS `game_id`, `ServerID` AS `database_id`, `Name` AS `game_title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `ID`=#{@_toQuery(idGame)}
"
return @_readSimpleData(sql, true)
# Returns the status information for each of the given list of game worlds.
# This is used by a bot on request of one or more game statuses.
# @param idList [array] An array of integers, each defining the id of a game world.
# @return [promise] A promise, resolving to a list of data maps.
# Each data map must have at least the key `id` to reference the corresponding game world.
# The bot will output any further values of a data map as a game's status information.
# (The key of each of these values is used to label the value on output. Underscores are replaced by spaces.)
# The list may be empty, if none of the given games could be found.
getGameStatuses: (idList=[]) ->
##
# Note: This is an example implementation - overwrite it for your own game API
##
# Convert given array to string of comma-separated values
idListSanitized = idList.map (idGame) =>
@_toQuery(idGame)
idListString = idListSanitized.join(',')
# Read the status values 'current_state' and 'start_time' for each game:
sql = "
SELECT `ID` as `id`, `StateText` AS `current_state`, `StartTime` AS `start_time`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `ID` IN (#{idListString})
ORDER BY `Status` ASC, `ID` DESC
"
return @_readMultipleData(sql)
# Returns the list of game worlds, which each have a bot to use for bot-channels.
# If the mono-bot is configured, returns the list of all game worlds having a chat.
# This list is also used to manage the lifetime of corresponding channels and its logs
# by the game lookup interval.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `id` (The unique id of the game world) and
# `title` (The display name of the game world - is allowed to contain spaces, etc.).
# The list may be empty, if there are no games at all.
getBotRepresentedGames: ->
##
# Note: This is an example implementation - overwrite it for your own game API
##
if config.MAX_BOTS > 0
sql = "
SELECT `ID` AS `id`, `Name` AS `title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `Running`=1 AND `Deleted`=0
ORDER BY `ID` ASC
LIMIT #{config.MAX_BOTS}
"
else
sql = "
SELECT `ID` AS `id`, `Name` AS `title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `Deleted`=0
ORDER BY `ID` ASC
"
return @_readMultipleData(sql)
#
# Server management
#
# Returns a list of channels, which should be mirrored to IRC, but each belong to only one game.
# This excludes the global channel.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `game_id` (The id of the game, the channel belongs to),
# `creator_id` (The id of the user, who created the channel),
# `name` (The unique name of a channel - used internally),
# `title` (The display name of the channel - is allowed to contain spaces, etc.),
# `password` (The password for joining the channel - not encrypted),
# `irc_channel` (The exact name of the IRC channel to mirror) and
# `is_public` (TRUE, if the channel is meant to be public and therefor joined players have to be hidden; else FALSE).
# The list may be empty, if no appropriate channels exist.
getGameBoundBotChannels: ->
sql = "
SELECT CONCAT(#{@_toQuery(config.INTERN_NONGAME_CHANNEL_PREFIX)}, `ID`) AS `name`,
`GameID` AS `game_id`, `CreatorUserID` AS `creator_id`,
`Title` AS `title`, `Password` AS `password`,
`IrcChannel` AS `irc_channel`, `IsPublic` AS `is_public`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `IrcChannel` IS NOT NULL
"
return @_readMultipleData(sql)
# Returns the data for the global channel, which should be mirrored to IRC for every game world.
# Thus, if not using the mono-bot, it will contain multiple bots.
# @return [promise] A promise, resolving to a data map with keys
# `name` (The unique name of the channel - used internally),
# `title` (The display name of the channel - is allowed to contain spaces, etc.),
# `password` (Optional: The password for joining the channel on IRC - not encrypted),
# `irc_channel` (The exact name of the IRC channel to mirror) and
# `is_public` (TRUE, if players joined to the channel should to be hidden; else FALSE).
getGlobalChannelData: ->
promise = Q.fcall =>
return {
name: config.INTERN_GLOBAL_CHANNEL_NAME
title: config.INTERN_GLOBAL_CHANNEL_TITLE
irc_channel: config.IRC_GLOBAL_CHANNEL
is_public: true
}
return promise
# Returns the data for the channel matching given game and title.
# @param idGame [int] The id of the game world, the requested channel belongs to.
# @param channelTitle [string] The title of the requested channel (is allowed to contain spaces, etc.).
# @return [promise] A promise, resolving to a data map with keys
# `game_id` (The id of the game, a channel belongs to - should normally equal the given idGame),
# `creator_id` (The id of the user, who created the channel),
# `name` (The unique name of the channel - used internally),
# `title` (The display name of the channel - should normally equal the given title),
# `password` (The password for joining the channel - not encrypted),
# `irc_channel` (The exact name of the IRC channel to optionally mirror) and
# `is_public` (TRUE, if players joined to the channel should to be hidden; else FALSE).
# If the read data set is empty, the promise is rejected.
getChannelDataByTitle: (idGame, channelTitle) ->
sql = "
SELECT CONCAT(#{@_toQuery(config.INTERN_NONGAME_CHANNEL_PREFIX)}, `ID`) AS `name`,
`GameID` AS `game_id`, `CreatorUserID` AS `creator_id`,
`Title` AS `title`, `Password` AS `<PASSWORD>`,
`IrcChannel` AS `irc_channel`, `IsPublic` AS `is_public`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(idGame)}
AND `Title` LIKE #{@_toQuery(channelTitle)}
"
return @_readSimpleData(sql, true)
# Returns a list of channels, which were joined by the given client.
# @param clientIdentity [ClientIdentity] The identity of the client to read the channels for.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `name` (The unique name of a channel - used internally),
# `title` (The display name of the channel - is allowed to contain spaces, etc.),
# `creator_id` (Optional: The id of the user, who created the channel),
# `irc_channel` (Optional: The exact name of an IRC channel to mirror) and
# `is_public` (TRUE, if the channel is meant to be public and therefor joined player's have to be hidden; else FALSE).
# The list may be empty, if no channels are joined by the client.
getClientChannels: (clientIdentity) ->
# Read data of client's game as default channel
idGame = clientIdentity.getGameID()
gamePromise = @_getGameData(idGame)
gamePromise = gamePromise.then (gameData) =>
return {
name: "#{config.INTERN_GAME_CHANNEL_PREFIX}#{gameData.game_id}"
title: gameData.game_title
is_public: true
}
# Read non-default channels
idUser = clientIdentity.getUserID()
sql = "
SELECT CONCAT(#{@_toQuery(config.INTERN_NONGAME_CHANNEL_PREFIX)}, `C`.`ID`) AS `name`,
`C`.`CreatorUserID` AS `creator_id`, `C`.`Title` AS `title`,
`C`.`IrcChannel` AS `irc_channel`, `C`.`IsPublic` AS `is_public`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}` AS `C`
JOIN `#{config.SQL_TABLES.CHANNEL_JOININGS}` AS `CJ`
ON `CJ`.`ChannelID`=`C`.`ID`
WHERE `CJ`.`UserID`=#{@_toQuery(idUser)}
AND `C`.`GameID`=#{@_toQuery(idGame)}
ORDER BY `CJ`.`ID` ASC
"
channelsPromise = @_readMultipleData(sql)
# Read data of default channel
globalChannelPromise = @getGlobalChannelData()
# Merge promise results to one array
resultPromise = channelsPromise.then (channelListData) =>
list = channelListData
return gamePromise.then (gameChannelData) =>
list.unshift(gameChannelData) if gameChannelData?
return globalChannelPromise.then (defaultChannelData) =>
list.unshift(defaultChannelData)
return list
return resultPromise
# Returns the number of channels, which were created by the given client.
# @param clientIdentity [ClientIdentity] The identity of the client to count the channels for.
# @return [promise] A promise, resolving to the number of channels.
getClientCreatedChannelsCount: (clientIdentity) ->
idGame = clientIdentity.getGameID()
idUser = clientIdentity.getUserID()
sql = "
SELECT COUNT(`ID`) AS `channels`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(idGame)}
AND `CreatorUserID`=#{@_toQuery(idUser)}
"
promise = @_readSimpleData(sql)
promise = promise.then (data) =>
return data?.channels
return promise
#
# Channel management
#
# Returns a list of messages/channel events, which had been logged for the given channel.
# @param channelName [string] The internal name of the channel.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `id` (The id of the list entry),
# `event_name` (The name of the logged channel event),
# `event_data` (The logged data for the event, serialized as JSON string - contains values like message text or sender identity) and
# `timestamp` (The timestamp of the log entry/event).
# The list may be empty, if no logs exists for the channel.
getLoggedChannelMessages: (channelName) ->
sql = "
(
SELECT `ChannelLogID` AS `id`, `EventTextID` AS `event_name`, `EventData` AS `event_data`, `Timestamp` AS `timestamp`
FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelTextID`=#{@_toQuery(channelName)}
ORDER BY `Timestamp` DESC
LIMIT #{config.MAX_CHANNEL_LOGS_TO_CLIENT}
)
ORDER BY `Timestamp` ASC
"
promise = @_readMultipleData(sql)
return promise
# Saves the given message/channel event to the channel logs. May replaces old logs.
# @param channelName [string] The internal name of the channel.
# @param timestamp [int] The timestamp of the event (in milliseconds).
# @param eventName [string] The name of the channel event.
# @param eventData [object] A data map, containing the main data for the event (like message text or sender identity).
logChannelMessage: (channelName, timestamp, eventName, eventData) ->
channelID = 0
if channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
try
serialEventData = JSON.stringify(eventData)
catch
log.warn 'Could not serializable json string!', 'Database message logging'
serialEventData = '{}'
@_doTransaction =>
sql = "
SELECT COALESCE(MAX(`ChannelLogID`), 0) AS `max_id`
FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelTextID`=#{@_toQuery(channelName)}
"
promise = @_readSimpleData(sql, true)
promise = promise.then (data) =>
maxLogID = data.max_id
nextLogID = maxLogID + 1
nextBufferID = (maxLogID % config.MAX_CHANNEL_LOGS) + 1
sql = "
REPLACE INTO `#{config.SQL_TABLES.CHANNEL_LOGS}` SET
`ChannelLogID`=#{@_toQuery(nextLogID)},
`ChannelBufferID`=#{@_toQuery(nextBufferID)},
`ChannelTextID`=#{@_toQuery(channelName)},
`ChannelID`=#{@_toQuery(channelID)},
`EventTextID`=#{@_toQuery(eventName)},
`EventData`=#{@_toQuery(serialEventData)},
`Timestamp`=#{@_toQuery(timestamp)}
"
return @_sendQuery(sql)
return promise
# Creates a new channel with given data and returns the resulting data of the channel in database.
# @param clientIdentity [ClientIdentity] The identity of the client to set as channel creator.
# @param channelData [object] A data map with keys
# `game_id` (The id of the game, a channel should belong to),
# `title` (The display name for the channel - is allowed to contain spaces, etc.),
# `password` (The password for joining the channel - not encrypted),
# `is_for_irc` (TRUE, if the channel should to be mirrored to IRC; else FALSE - defaults to FALSE) and
# `is_public` (TRUE, if players joined to the channel should to be hidden; else FALSE - defaults to FALSE).
# @return [promise] A promise, resolving to a data map with keys equal to the given object, but complemented with keys
# `creator_id` (The id of the user, who created the channel - should equal user id of given identity),
# `name` (The unique name of the channel - used internally) and
# `irc_channel` (The exact name of an IRC channel to mirror - defaults to null, if `is_for_irc` was false).
# If the channel could not be created, the promise is rejected.
createChannelByData: (clientIdentity, channelData) ->
# Create the channel
userID = clientIdentity.getUserID()
channelData.creator_id = userID
sql = "
INSERT INTO `#{config.SQL_TABLES.CHANNEL_LIST}` SET
`GameID`=#{@_toQuery(channelData.game_id)},
`CreatorUserID`=#{@_toQuery(userID)},
`Title`=#{@_toQuery(channelData.title)},
`Password`=#{<PASSWORD>Query(channelData.password)},
`IsPublic`=#{@_toQuery(channelData.is_public)}
"
promise = @_sendQuery(sql)
# Finalize result object
promise = promise.then (resultData) =>
channelID = resultData.insertId
# Add channel name to data object
channelName = "#{config.INTERN_NONGAME_CHANNEL_PREFIX}#{channelID}"
channelData.name = channelName
# Add irc channel name
if channelData.is_for_irc
randomID = Math.floor(Math.random() * 1000)
ircChannelName = "#{config.IRC_NONGAME_CHANNEL_PREFIX}#{channelID}_#{randomID}"
channelData.irc_channel = ircChannelName
# Save name of irc channel
sql = "
UPDATE `#{config.SQL_TABLES.CHANNEL_LIST}` SET
`IrcChannel`=#{@_toQuery(ircChannelName)}
WHERE `ID`=#{@_toQuery(channelID)}
"
@_sendQuery(sql)
return channelData
return promise
# Deletes all related data (logs, joinings, etc.) of the channel with the given game.
# @param channelName [string] The internal name of the channel to delete.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
deleteChannel: (channelName) ->
return unless channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0 # Only non-game channels can be deleted
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
# Delete channel logs
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelID`=#{@_toQuery(channelID)}
"
logsPromise = @_sendQuery(sql)
# Delete channel joinings
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_JOININGS}`
WHERE `ChannelID`=#{@_toQuery(channelID)}
"
joinsPromise = @_sendQuery(sql)
# Delete channels
promise = Q.all([logsPromise, joinsPromise]).then =>
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `ID`=#{@_toQuery(channelID)}
"
return @_sendQuery(sql)
return promise
# Deletes all related data (logs, joinings, etc.) of all channels, which belong to the given game.
# @param gameID [int] The id of the game world.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
deleteChannelsByGame: (gameID) ->
internalGameChannel = "#{config.INTERN_GAME_CHANNEL_PREFIX}#{gameID}"
# Delete channel logs
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelID` IN (
SELECT `ID` FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(gameID)}
)
OR `ChannelTextID`=#{@_toQuery(internalGameChannel)}
"
logsPromise = @_sendQuery(sql)
# Delete channel joinings
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_JOININGS}`
WHERE `ChannelID` IN (
SELECT `ID` FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(gameID)}
)
"
joinsPromise = @_sendQuery(sql)
# Delete channels
promise = Q.all([logsPromise, joinsPromise]).then =>
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(gameID)}
"
return @_sendQuery(sql)
return promise
# Saves the given client for having joined the given channel.
# @param clientIdentity [ClientIdentity] The identity of the client.
# @param channelName [string] The name of the channel.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
addClientToChannel: (clientIdentity, channelName) ->
return unless channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0 # Only non-game channels can be joined explicitly
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
userID = clientIdentity.getUserID()
sql = "
INSERT INTO `#{config.SQL_TABLES.CHANNEL_JOININGS}` SET
`UserID`=#{@_toQuery(userID)},
`ChannelID`=#{@_toQuery(channelID)}
"
return @_sendQuery(sql)
# Deletes the given client from having joined the given channel.
# @param clientIdentity [ClientIdentity] The identity of the client.
# @param channelName [string] The name of the channel.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
removeClientFromChannel: (clientIdentity, channelName) ->
return unless channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0 # Only non-game channels can be parted explicitly
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
userID = clientIdentity.getUserID()
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_JOININGS}`
WHERE `UserID`=#{@_toQuery(userID)}
AND `ChannelID`=#{@_toQuery(channelID)}
"
return @_sendQuery(sql)
## Export class
module.exports = DefaultDatasource
| true |
## Include libraries
Q = require 'q'
crypto = require 'crypto'
## Include app modules
config = require '../config'
log = require '../logger'
## Include data classes
MysqlDatabaseHandler = require '../databasehandlers/dbh.mysql'
AbstractDatasource = require './ds.abstract'
## Default abstraction of data managing methods.
## See `AbstractDatasource` for more.
##
## Uses the MySQL database handler by default.
##
## Structure:
## * Client identity (with example implementations)
## * Game-specific queries (with example implementations)
## * Server management
## * Channel management
##
class DefaultDatasource extends AbstractDatasource
# @override
_createHandler: ->
return new MysqlDatabaseHandler(config, log)
#
# Client identity (with example implementations)
#
# Returns the saved identification data for the given player in the given game.
# @param idUser [int] The id of the player's account or game identity/character as given by a client on logon.
# @param idGame [int] The id of the player's game world as given by a client on logon.
# @return [promise] A promise, resolving to a data map with keys
# `id` (The id of the player for the chat),
# `idGame` (Should equal given idGame),
# `idUser` (The id of the player's account),
# `name` (The player's name for the chat),
# `title` (An optional more detail name for the chat, will default to the name),
# `gameTitle` (The full name of the player's game world),
# `gameTag` (An optional shortened version of the name of the player's game world, will default to the full name),
# `token` (The security token for the player).
# If the read data set is empty, the promise is rejected.
getClientIdentityData: (idUser, idGame) ->
##
# Note: This is an example implementation - overwrite it for your own game API
##
# Read (meta) data of given game
promise = @_getGameData(idGame)
# Read data of given player in given game
promise = promise.then (gameData) =>
sql = "
SELECT `Ch`.`ID` AS `character_id`,
`Ch`.`Name` AS `character_name`,
`Ch`.`Class` AS `class_name`,
#{@_toQuery(gameData.game_title)} AS `game_title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.PLAYER_GAMES}` AS `PG`
JOIN `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAME_PLAYER_IDENTITIES}` AS `Ch`
ON `Ch`.`ID`=`PG`.`CharacterID`
WHERE `PG`.`GameID`=#{@_toQuery(idGame)}
AND `PG`.`UserID`=#{@_toQuery(idUser)}
"
return @_readSimpleData(sql, true)
# Build final result
promise = promise.then (playerData) =>
return {
id: playerData.character_id
idGame: idGame
idUser: idUser
name: playerData.character_name
title: "#{playerData.character_name} - #{playerData.class_name}"
gameTitle: playerData.game_title
gameTag: @_getShortenedGameTitle(playerData.game_title)
token: @_getSecurityToken(idUser, playerData)
}
return promise
# Returns the current security token for the given player.
# This token must be sent on auth request by the client.
_getSecurityToken: (idUser, playerData) ->
return @_getHashValue("#{config.CLIENT_AUTH_SECRET}_#{idUser}")
# Returns the md5 hash of the given string
_getHashValue: (original_val) ->
hashingStream = crypto.createHash('md5')
hashingStream.update(original_val);
return hashingStream.digest('hex')
# Returns the first part of the given game title (split by underscore, hyphen or space)
_getShortenedGameTitle: (fullGameTitle) ->
shortTitle = String(fullGameTitle)
shortTitle = shortTitle.replace(/[_- ](.+)/, '')
return shortTitle
#
# Game-specific queries (with example implementations)
#
# Helper query - Returns the data for the given game world.
# @param idGame [int] The id of the game world.
# @return [promise] A promise, resolving to a data map with keys
# `game_id` (Should equal idGame),
# `database_id` (The id of the database, which stores the game tables) and
# `game_title` (The display name of the game world - is allowed to contain spaces, etc.).
# If the read data set is empty, the promise is rejected.
_getGameData: (idGame) ->
##
# Note: This is an example implementation - overwrite it for your own requirements
##
sql = "
SELECT `ID` AS `game_id`, `ServerID` AS `database_id`, `Name` AS `game_title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `ID`=#{@_toQuery(idGame)}
"
return @_readSimpleData(sql, true)
# Returns the status information for each of the given list of game worlds.
# This is used by a bot on request of one or more game statuses.
# @param idList [array] An array of integers, each defining the id of a game world.
# @return [promise] A promise, resolving to a list of data maps.
# Each data map must have at least the key `id` to reference the corresponding game world.
# The bot will output any further values of a data map as a game's status information.
# (The key of each of these values is used to label the value on output. Underscores are replaced by spaces.)
# The list may be empty, if none of the given games could be found.
getGameStatuses: (idList=[]) ->
##
# Note: This is an example implementation - overwrite it for your own game API
##
# Convert given array to string of comma-separated values
idListSanitized = idList.map (idGame) =>
@_toQuery(idGame)
idListString = idListSanitized.join(',')
# Read the status values 'current_state' and 'start_time' for each game:
sql = "
SELECT `ID` as `id`, `StateText` AS `current_state`, `StartTime` AS `start_time`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `ID` IN (#{idListString})
ORDER BY `Status` ASC, `ID` DESC
"
return @_readMultipleData(sql)
# Returns the list of game worlds, which each have a bot to use for bot-channels.
# If the mono-bot is configured, returns the list of all game worlds having a chat.
# This list is also used to manage the lifetime of corresponding channels and its logs
# by the game lookup interval.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `id` (The unique id of the game world) and
# `title` (The display name of the game world - is allowed to contain spaces, etc.).
# The list may be empty, if there are no games at all.
getBotRepresentedGames: ->
##
# Note: This is an example implementation - overwrite it for your own game API
##
if config.MAX_BOTS > 0
sql = "
SELECT `ID` AS `id`, `Name` AS `title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `Running`=1 AND `Deleted`=0
ORDER BY `ID` ASC
LIMIT #{config.MAX_BOTS}
"
else
sql = "
SELECT `ID` AS `id`, `Name` AS `title`
FROM `#{config.SQL_DATABASE_GAME}`.`#{config.SQL_TABLES.GAMES_LIST}`
WHERE `Deleted`=0
ORDER BY `ID` ASC
"
return @_readMultipleData(sql)
#
# Server management
#
# Returns a list of channels, which should be mirrored to IRC, but each belong to only one game.
# This excludes the global channel.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `game_id` (The id of the game, the channel belongs to),
# `creator_id` (The id of the user, who created the channel),
# `name` (The unique name of a channel - used internally),
# `title` (The display name of the channel - is allowed to contain spaces, etc.),
# `password` (The password for joining the channel - not encrypted),
# `irc_channel` (The exact name of the IRC channel to mirror) and
# `is_public` (TRUE, if the channel is meant to be public and therefor joined players have to be hidden; else FALSE).
# The list may be empty, if no appropriate channels exist.
getGameBoundBotChannels: ->
sql = "
SELECT CONCAT(#{@_toQuery(config.INTERN_NONGAME_CHANNEL_PREFIX)}, `ID`) AS `name`,
`GameID` AS `game_id`, `CreatorUserID` AS `creator_id`,
`Title` AS `title`, `Password` AS `password`,
`IrcChannel` AS `irc_channel`, `IsPublic` AS `is_public`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `IrcChannel` IS NOT NULL
"
return @_readMultipleData(sql)
# Returns the data for the global channel, which should be mirrored to IRC for every game world.
# Thus, if not using the mono-bot, it will contain multiple bots.
# @return [promise] A promise, resolving to a data map with keys
# `name` (The unique name of the channel - used internally),
# `title` (The display name of the channel - is allowed to contain spaces, etc.),
# `password` (Optional: The password for joining the channel on IRC - not encrypted),
# `irc_channel` (The exact name of the IRC channel to mirror) and
# `is_public` (TRUE, if players joined to the channel should to be hidden; else FALSE).
getGlobalChannelData: ->
promise = Q.fcall =>
return {
name: config.INTERN_GLOBAL_CHANNEL_NAME
title: config.INTERN_GLOBAL_CHANNEL_TITLE
irc_channel: config.IRC_GLOBAL_CHANNEL
is_public: true
}
return promise
# Returns the data for the channel matching given game and title.
# @param idGame [int] The id of the game world, the requested channel belongs to.
# @param channelTitle [string] The title of the requested channel (is allowed to contain spaces, etc.).
# @return [promise] A promise, resolving to a data map with keys
# `game_id` (The id of the game, a channel belongs to - should normally equal the given idGame),
# `creator_id` (The id of the user, who created the channel),
# `name` (The unique name of the channel - used internally),
# `title` (The display name of the channel - should normally equal the given title),
# `password` (The password for joining the channel - not encrypted),
# `irc_channel` (The exact name of the IRC channel to optionally mirror) and
# `is_public` (TRUE, if players joined to the channel should to be hidden; else FALSE).
# If the read data set is empty, the promise is rejected.
getChannelDataByTitle: (idGame, channelTitle) ->
sql = "
SELECT CONCAT(#{@_toQuery(config.INTERN_NONGAME_CHANNEL_PREFIX)}, `ID`) AS `name`,
`GameID` AS `game_id`, `CreatorUserID` AS `creator_id`,
`Title` AS `title`, `Password` AS `PI:PASSWORD:<PASSWORD>END_PI`,
`IrcChannel` AS `irc_channel`, `IsPublic` AS `is_public`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(idGame)}
AND `Title` LIKE #{@_toQuery(channelTitle)}
"
return @_readSimpleData(sql, true)
# Returns a list of channels, which were joined by the given client.
# @param clientIdentity [ClientIdentity] The identity of the client to read the channels for.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `name` (The unique name of a channel - used internally),
# `title` (The display name of the channel - is allowed to contain spaces, etc.),
# `creator_id` (Optional: The id of the user, who created the channel),
# `irc_channel` (Optional: The exact name of an IRC channel to mirror) and
# `is_public` (TRUE, if the channel is meant to be public and therefor joined player's have to be hidden; else FALSE).
# The list may be empty, if no channels are joined by the client.
getClientChannels: (clientIdentity) ->
# Read data of client's game as default channel
idGame = clientIdentity.getGameID()
gamePromise = @_getGameData(idGame)
gamePromise = gamePromise.then (gameData) =>
return {
name: "#{config.INTERN_GAME_CHANNEL_PREFIX}#{gameData.game_id}"
title: gameData.game_title
is_public: true
}
# Read non-default channels
idUser = clientIdentity.getUserID()
sql = "
SELECT CONCAT(#{@_toQuery(config.INTERN_NONGAME_CHANNEL_PREFIX)}, `C`.`ID`) AS `name`,
`C`.`CreatorUserID` AS `creator_id`, `C`.`Title` AS `title`,
`C`.`IrcChannel` AS `irc_channel`, `C`.`IsPublic` AS `is_public`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}` AS `C`
JOIN `#{config.SQL_TABLES.CHANNEL_JOININGS}` AS `CJ`
ON `CJ`.`ChannelID`=`C`.`ID`
WHERE `CJ`.`UserID`=#{@_toQuery(idUser)}
AND `C`.`GameID`=#{@_toQuery(idGame)}
ORDER BY `CJ`.`ID` ASC
"
channelsPromise = @_readMultipleData(sql)
# Read data of default channel
globalChannelPromise = @getGlobalChannelData()
# Merge promise results to one array
resultPromise = channelsPromise.then (channelListData) =>
list = channelListData
return gamePromise.then (gameChannelData) =>
list.unshift(gameChannelData) if gameChannelData?
return globalChannelPromise.then (defaultChannelData) =>
list.unshift(defaultChannelData)
return list
return resultPromise
# Returns the number of channels, which were created by the given client.
# @param clientIdentity [ClientIdentity] The identity of the client to count the channels for.
# @return [promise] A promise, resolving to the number of channels.
getClientCreatedChannelsCount: (clientIdentity) ->
idGame = clientIdentity.getGameID()
idUser = clientIdentity.getUserID()
sql = "
SELECT COUNT(`ID`) AS `channels`
FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(idGame)}
AND `CreatorUserID`=#{@_toQuery(idUser)}
"
promise = @_readSimpleData(sql)
promise = promise.then (data) =>
return data?.channels
return promise
#
# Channel management
#
# Returns a list of messages/channel events, which had been logged for the given channel.
# @param channelName [string] The internal name of the channel.
# @return [promise] A promise, resolving to a list of data maps, each having keys
# `id` (The id of the list entry),
# `event_name` (The name of the logged channel event),
# `event_data` (The logged data for the event, serialized as JSON string - contains values like message text or sender identity) and
# `timestamp` (The timestamp of the log entry/event).
# The list may be empty, if no logs exists for the channel.
getLoggedChannelMessages: (channelName) ->
sql = "
(
SELECT `ChannelLogID` AS `id`, `EventTextID` AS `event_name`, `EventData` AS `event_data`, `Timestamp` AS `timestamp`
FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelTextID`=#{@_toQuery(channelName)}
ORDER BY `Timestamp` DESC
LIMIT #{config.MAX_CHANNEL_LOGS_TO_CLIENT}
)
ORDER BY `Timestamp` ASC
"
promise = @_readMultipleData(sql)
return promise
# Saves the given message/channel event to the channel logs. May replaces old logs.
# @param channelName [string] The internal name of the channel.
# @param timestamp [int] The timestamp of the event (in milliseconds).
# @param eventName [string] The name of the channel event.
# @param eventData [object] A data map, containing the main data for the event (like message text or sender identity).
logChannelMessage: (channelName, timestamp, eventName, eventData) ->
channelID = 0
if channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
try
serialEventData = JSON.stringify(eventData)
catch
log.warn 'Could not serializable json string!', 'Database message logging'
serialEventData = '{}'
@_doTransaction =>
sql = "
SELECT COALESCE(MAX(`ChannelLogID`), 0) AS `max_id`
FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelTextID`=#{@_toQuery(channelName)}
"
promise = @_readSimpleData(sql, true)
promise = promise.then (data) =>
maxLogID = data.max_id
nextLogID = maxLogID + 1
nextBufferID = (maxLogID % config.MAX_CHANNEL_LOGS) + 1
sql = "
REPLACE INTO `#{config.SQL_TABLES.CHANNEL_LOGS}` SET
`ChannelLogID`=#{@_toQuery(nextLogID)},
`ChannelBufferID`=#{@_toQuery(nextBufferID)},
`ChannelTextID`=#{@_toQuery(channelName)},
`ChannelID`=#{@_toQuery(channelID)},
`EventTextID`=#{@_toQuery(eventName)},
`EventData`=#{@_toQuery(serialEventData)},
`Timestamp`=#{@_toQuery(timestamp)}
"
return @_sendQuery(sql)
return promise
# Creates a new channel with given data and returns the resulting data of the channel in database.
# @param clientIdentity [ClientIdentity] The identity of the client to set as channel creator.
# @param channelData [object] A data map with keys
# `game_id` (The id of the game, a channel should belong to),
# `title` (The display name for the channel - is allowed to contain spaces, etc.),
# `password` (The password for joining the channel - not encrypted),
# `is_for_irc` (TRUE, if the channel should to be mirrored to IRC; else FALSE - defaults to FALSE) and
# `is_public` (TRUE, if players joined to the channel should to be hidden; else FALSE - defaults to FALSE).
# @return [promise] A promise, resolving to a data map with keys equal to the given object, but complemented with keys
# `creator_id` (The id of the user, who created the channel - should equal user id of given identity),
# `name` (The unique name of the channel - used internally) and
# `irc_channel` (The exact name of an IRC channel to mirror - defaults to null, if `is_for_irc` was false).
# If the channel could not be created, the promise is rejected.
createChannelByData: (clientIdentity, channelData) ->
# Create the channel
userID = clientIdentity.getUserID()
channelData.creator_id = userID
sql = "
INSERT INTO `#{config.SQL_TABLES.CHANNEL_LIST}` SET
`GameID`=#{@_toQuery(channelData.game_id)},
`CreatorUserID`=#{@_toQuery(userID)},
`Title`=#{@_toQuery(channelData.title)},
`Password`=#{PI:PASSWORD:<PASSWORD>END_PIQuery(channelData.password)},
`IsPublic`=#{@_toQuery(channelData.is_public)}
"
promise = @_sendQuery(sql)
# Finalize result object
promise = promise.then (resultData) =>
channelID = resultData.insertId
# Add channel name to data object
channelName = "#{config.INTERN_NONGAME_CHANNEL_PREFIX}#{channelID}"
channelData.name = channelName
# Add irc channel name
if channelData.is_for_irc
randomID = Math.floor(Math.random() * 1000)
ircChannelName = "#{config.IRC_NONGAME_CHANNEL_PREFIX}#{channelID}_#{randomID}"
channelData.irc_channel = ircChannelName
# Save name of irc channel
sql = "
UPDATE `#{config.SQL_TABLES.CHANNEL_LIST}` SET
`IrcChannel`=#{@_toQuery(ircChannelName)}
WHERE `ID`=#{@_toQuery(channelID)}
"
@_sendQuery(sql)
return channelData
return promise
# Deletes all related data (logs, joinings, etc.) of the channel with the given game.
# @param channelName [string] The internal name of the channel to delete.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
deleteChannel: (channelName) ->
return unless channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0 # Only non-game channels can be deleted
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
# Delete channel logs
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelID`=#{@_toQuery(channelID)}
"
logsPromise = @_sendQuery(sql)
# Delete channel joinings
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_JOININGS}`
WHERE `ChannelID`=#{@_toQuery(channelID)}
"
joinsPromise = @_sendQuery(sql)
# Delete channels
promise = Q.all([logsPromise, joinsPromise]).then =>
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `ID`=#{@_toQuery(channelID)}
"
return @_sendQuery(sql)
return promise
# Deletes all related data (logs, joinings, etc.) of all channels, which belong to the given game.
# @param gameID [int] The id of the game world.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
deleteChannelsByGame: (gameID) ->
internalGameChannel = "#{config.INTERN_GAME_CHANNEL_PREFIX}#{gameID}"
# Delete channel logs
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LOGS}`
WHERE `ChannelID` IN (
SELECT `ID` FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(gameID)}
)
OR `ChannelTextID`=#{@_toQuery(internalGameChannel)}
"
logsPromise = @_sendQuery(sql)
# Delete channel joinings
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_JOININGS}`
WHERE `ChannelID` IN (
SELECT `ID` FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(gameID)}
)
"
joinsPromise = @_sendQuery(sql)
# Delete channels
promise = Q.all([logsPromise, joinsPromise]).then =>
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_LIST}`
WHERE `GameID`=#{@_toQuery(gameID)}
"
return @_sendQuery(sql)
return promise
# Saves the given client for having joined the given channel.
# @param clientIdentity [ClientIdentity] The identity of the client.
# @param channelName [string] The name of the channel.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
addClientToChannel: (clientIdentity, channelName) ->
return unless channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0 # Only non-game channels can be joined explicitly
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
userID = clientIdentity.getUserID()
sql = "
INSERT INTO `#{config.SQL_TABLES.CHANNEL_JOININGS}` SET
`UserID`=#{@_toQuery(userID)},
`ChannelID`=#{@_toQuery(channelID)}
"
return @_sendQuery(sql)
# Deletes the given client from having joined the given channel.
# @param clientIdentity [ClientIdentity] The identity of the client.
# @param channelName [string] The name of the channel.
# @return [promise] A promise to be resolved/rejected, when the operation has been finished or an error occured.
removeClientFromChannel: (clientIdentity, channelName) ->
return unless channelName.indexOf(config.INTERN_NONGAME_CHANNEL_PREFIX) is 0 # Only non-game channels can be parted explicitly
channelID = channelName.replace(config.INTERN_NONGAME_CHANNEL_PREFIX, '')
userID = clientIdentity.getUserID()
sql = "
DELETE FROM `#{config.SQL_TABLES.CHANNEL_JOININGS}`
WHERE `UserID`=#{@_toQuery(userID)}
AND `ChannelID`=#{@_toQuery(channelID)}
"
return @_sendQuery(sql)
## Export class
module.exports = DefaultDatasource
|
[
{
"context": " {}\n ]\n keys: get: ->\n [\n ['z', 'uuu', '3', 'b'],\n ['g', 'b', 'z', '3'],",
"end": 324,
"score": 0.899425208568573,
"start": 323,
"tag": "KEY",
"value": "z"
},
{
"context": "\n ]\n keys: get: ->\n [\n ['z', 'uuu', '3', 'b'],\n ['g', 'b', 'z', '3'],\n ",
"end": 331,
"score": 0.8524986505508423,
"start": 328,
"tag": "KEY",
"value": "uuu"
},
{
"context": "]\n keys: get: ->\n [\n ['z', 'uuu', '3', 'b'],\n ['g', 'b', 'z', '3'],\n ['a",
"end": 336,
"score": 0.5685726404190063,
"start": 335,
"tag": "KEY",
"value": "3"
},
{
"context": " keys: get: ->\n [\n ['z', 'uuu', '3', 'b'],\n ['g', 'b', 'z', '3'],\n ['aaa'],",
"end": 341,
"score": 0.9303798079490662,
"start": 340,
"tag": "KEY",
"value": "b"
},
{
"context": "cted: get: ->\n [\n [\n keys: ['3', 'g', 'k','z', 'b']\n ,\n keys: ['3', 'k', 'g', 'b', ",
"end": 490,
"score": 0.9915704131126404,
"start": 470,
"tag": "KEY",
"value": "3', 'g', 'k','z', 'b"
},
{
"context": "', 'g', 'k','z', 'b']\n ,\n keys: ['3', 'k', 'g', 'b', 'z']\n ,\n keys: ['3', 'b', 'g', 'z', ",
"end": 542,
"score": 0.9947540760040283,
"start": 521,
"tag": "KEY",
"value": "3', 'k', 'g', 'b', 'z"
},
{
"context": ", 'k', 'g', 'b', 'z']\n ,\n keys: ['3', 'b', 'g', 'z', 'k']\n ,\n keys: ['3', 'b', 'g', 'z', ",
"end": 594,
"score": 0.9726217985153198,
"start": 573,
"tag": "KEY",
"value": "3', 'b', 'g', 'z', 'k"
},
{
"context": ", 'b', 'g', 'z', 'k']\n ,\n keys: ['3', 'b', 'g', 'z', 'k']\n ]\n ,\n [\n keys: []\n",
"end": 646,
"score": 0.9958500266075134,
"start": 625,
"tag": "KEY",
"value": "3', 'b', 'g', 'z', 'k"
}
] | test/ext-order/order-key.coffee | xinchaobeta/cress-type | 0 | {__test__: {orderKey}} = require 'cress-type/dest/ext-order'
Should = require 'should'
_ = require 'lodash'
describe 'function orderKey', ->
Object.defineProperties (different = {}),
obj: get: ->
[
{b: '', '3': 0, g: null, z: undefined, k: {}},
{}
]
keys: get: ->
[
['z', 'uuu', '3', 'b'],
['g', 'b', 'z', '3'],
['aaa'],
[]
]
expected: get: ->
[
[
keys: ['3', 'g', 'k','z', 'b']
,
keys: ['3', 'k', 'g', 'b', 'z']
,
keys: ['3', 'b', 'g', 'z', 'k']
,
keys: ['3', 'b', 'g', 'z', 'k']
]
,
[
keys: []
,
keys: []
,
keys: []
,
keys: []
]
]
different.obj.forEach (__, i) ->
different.keys.forEach (__, j) ->
obj = different.obj[i]
keys = different.keys[j]
describe "obj = #{JSON.stringify obj}, keys = #{JSON.stringify keys}", ->
clone = _.clone obj
pointer = obj
orderKey obj, keys
expected = different.expected[i][j]
it "whether keys is correct", ->
Should(expected.keys).be.eql Object.keys(obj)
it 'whether value is correct', ->
Should(pointer).be.equal obj
Should(obj[key]).equal clone[key] for key in Object.keys(obj)
| 139023 | {__test__: {orderKey}} = require 'cress-type/dest/ext-order'
Should = require 'should'
_ = require 'lodash'
describe 'function orderKey', ->
Object.defineProperties (different = {}),
obj: get: ->
[
{b: '', '3': 0, g: null, z: undefined, k: {}},
{}
]
keys: get: ->
[
['<KEY>', '<KEY>', '<KEY>', '<KEY>'],
['g', 'b', 'z', '3'],
['aaa'],
[]
]
expected: get: ->
[
[
keys: ['<KEY>']
,
keys: ['<KEY>']
,
keys: ['<KEY>']
,
keys: ['<KEY>']
]
,
[
keys: []
,
keys: []
,
keys: []
,
keys: []
]
]
different.obj.forEach (__, i) ->
different.keys.forEach (__, j) ->
obj = different.obj[i]
keys = different.keys[j]
describe "obj = #{JSON.stringify obj}, keys = #{JSON.stringify keys}", ->
clone = _.clone obj
pointer = obj
orderKey obj, keys
expected = different.expected[i][j]
it "whether keys is correct", ->
Should(expected.keys).be.eql Object.keys(obj)
it 'whether value is correct', ->
Should(pointer).be.equal obj
Should(obj[key]).equal clone[key] for key in Object.keys(obj)
| true | {__test__: {orderKey}} = require 'cress-type/dest/ext-order'
Should = require 'should'
_ = require 'lodash'
describe 'function orderKey', ->
Object.defineProperties (different = {}),
obj: get: ->
[
{b: '', '3': 0, g: null, z: undefined, k: {}},
{}
]
keys: get: ->
[
['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'],
['g', 'b', 'z', '3'],
['aaa'],
[]
]
expected: get: ->
[
[
keys: ['PI:KEY:<KEY>END_PI']
,
keys: ['PI:KEY:<KEY>END_PI']
,
keys: ['PI:KEY:<KEY>END_PI']
,
keys: ['PI:KEY:<KEY>END_PI']
]
,
[
keys: []
,
keys: []
,
keys: []
,
keys: []
]
]
different.obj.forEach (__, i) ->
different.keys.forEach (__, j) ->
obj = different.obj[i]
keys = different.keys[j]
describe "obj = #{JSON.stringify obj}, keys = #{JSON.stringify keys}", ->
clone = _.clone obj
pointer = obj
orderKey obj, keys
expected = different.expected[i][j]
it "whether keys is correct", ->
Should(expected.keys).be.eql Object.keys(obj)
it 'whether value is correct', ->
Should(pointer).be.equal obj
Should(obj[key]).equal clone[key] for key in Object.keys(obj)
|
[
{
"context": " beforeEach ->\n view.set {\n name: 'Test'\n command: 'echo test'\n wd: '.'\n ",
"end": 363,
"score": 0.9229791760444641,
"start": 359,
"tag": "NAME",
"value": "Test"
},
{
"context": "and', ->\n expect(c).toEqual {\n name: 'Foo'\n command: 'Bar'\n wd: '.'\n }\n",
"end": 1606,
"score": 0.5613759160041809,
"start": 1603,
"tag": "NAME",
"value": "Foo"
}
] | spec/command-edit-main-pane-spec.coffee | fstiewitz/build-tools-cpp | 3 | CommandEditMainPane = require '../lib/view/command-edit-main-pane'
describe 'Command Edit Main Pane', ->
view = null
beforeEach ->
view = new CommandEditMainPane
afterEach ->
view.destroy?()
it 'has a pane', ->
expect(view.element).toBeDefined()
describe 'On set with a value', ->
beforeEach ->
view.set {
name: 'Test'
command: 'echo test'
wd: '.'
shell: true
wildcards: false
}
it 'sets the fields accordingly', ->
expect(view.command_name.getModel().getText()).toBe 'Test'
expect(view.command_text.getModel().getText()).toBe 'echo test'
expect(view.working_directory.getModel().getText()).toBe '.'
describe 'On set without a value', ->
beforeEach ->
view.set()
it 'sets the fields to their default values', ->
expect(view.command_name.getModel().getText()).toBe ''
expect(view.command_text.getModel().getText()).toBe ''
expect(view.working_directory.getModel().getText()).toBe '.'
describe 'On get with wrong values', ->
c = {}
r = null
beforeEach ->
r = view.get c
it 'returns an error', ->
expect(r).toBe 'Empty Name'
it 'does not update the command', ->
expect(c).toEqual {}
describe 'On get with correct values', ->
c = {}
r = null
beforeEach ->
view.command_name.getModel().setText 'Foo'
view.command_text.getModel().setText 'Bar'
r = view.get c
it 'returns null', ->
expect(r).toBe null
it 'updates the command', ->
expect(c).toEqual {
name: 'Foo'
command: 'Bar'
wd: '.'
}
| 125845 | CommandEditMainPane = require '../lib/view/command-edit-main-pane'
describe 'Command Edit Main Pane', ->
view = null
beforeEach ->
view = new CommandEditMainPane
afterEach ->
view.destroy?()
it 'has a pane', ->
expect(view.element).toBeDefined()
describe 'On set with a value', ->
beforeEach ->
view.set {
name: '<NAME>'
command: 'echo test'
wd: '.'
shell: true
wildcards: false
}
it 'sets the fields accordingly', ->
expect(view.command_name.getModel().getText()).toBe 'Test'
expect(view.command_text.getModel().getText()).toBe 'echo test'
expect(view.working_directory.getModel().getText()).toBe '.'
describe 'On set without a value', ->
beforeEach ->
view.set()
it 'sets the fields to their default values', ->
expect(view.command_name.getModel().getText()).toBe ''
expect(view.command_text.getModel().getText()).toBe ''
expect(view.working_directory.getModel().getText()).toBe '.'
describe 'On get with wrong values', ->
c = {}
r = null
beforeEach ->
r = view.get c
it 'returns an error', ->
expect(r).toBe 'Empty Name'
it 'does not update the command', ->
expect(c).toEqual {}
describe 'On get with correct values', ->
c = {}
r = null
beforeEach ->
view.command_name.getModel().setText 'Foo'
view.command_text.getModel().setText 'Bar'
r = view.get c
it 'returns null', ->
expect(r).toBe null
it 'updates the command', ->
expect(c).toEqual {
name: '<NAME>'
command: 'Bar'
wd: '.'
}
| true | CommandEditMainPane = require '../lib/view/command-edit-main-pane'
describe 'Command Edit Main Pane', ->
view = null
beforeEach ->
view = new CommandEditMainPane
afterEach ->
view.destroy?()
it 'has a pane', ->
expect(view.element).toBeDefined()
describe 'On set with a value', ->
beforeEach ->
view.set {
name: 'PI:NAME:<NAME>END_PI'
command: 'echo test'
wd: '.'
shell: true
wildcards: false
}
it 'sets the fields accordingly', ->
expect(view.command_name.getModel().getText()).toBe 'Test'
expect(view.command_text.getModel().getText()).toBe 'echo test'
expect(view.working_directory.getModel().getText()).toBe '.'
describe 'On set without a value', ->
beforeEach ->
view.set()
it 'sets the fields to their default values', ->
expect(view.command_name.getModel().getText()).toBe ''
expect(view.command_text.getModel().getText()).toBe ''
expect(view.working_directory.getModel().getText()).toBe '.'
describe 'On get with wrong values', ->
c = {}
r = null
beforeEach ->
r = view.get c
it 'returns an error', ->
expect(r).toBe 'Empty Name'
it 'does not update the command', ->
expect(c).toEqual {}
describe 'On get with correct values', ->
c = {}
r = null
beforeEach ->
view.command_name.getModel().setText 'Foo'
view.command_text.getModel().setText 'Bar'
r = view.get c
it 'returns null', ->
expect(r).toBe null
it 'updates the command', ->
expect(c).toEqual {
name: 'PI:NAME:<NAME>END_PI'
command: 'Bar'
wd: '.'
}
|
[
{
"context": "eplace(/^\\/+/, '')\n \n key = [conn.key, root_path].join(':')\n \n return @cache[key] if @cache[key]?\n ",
"end": 291,
"score": 0.8689416646957397,
"start": 278,
"tag": "KEY",
"value": "path].join(':"
}
] | lib/connection.coffee | mattinsler/firebase-work | 2 | q = require 'q'
URL = require 'url'
FirebaseConnection = require './firebase_connection'
class Connection
@cache: {}
@connect: (url) ->
conn = FirebaseConnection.connect(url)
root_path = URL.parse(url).pathname.replace(/^\/+/, '')
key = [conn.key, root_path].join(':')
return @cache[key] if @cache[key]?
@cache[key] = new Connection(
key: key
fb_connection: conn
root_path: root_path
)
_connect: ->
@fb_connection.get().then (conn) =>
@promise.resolve(conn.child(@root_path))
.catch (err) =>
@promise.reject(err)
constructor: ({@key, @fb_connection, @root_path}) ->
@promise = q.defer()
@server_time_offset = null
@promise.promise.then (conn) =>
conn.root().child('.info/serverTimeOffset').once 'value', (snap) =>
@server_time_offset = snap.val()
@__defineGetter__ 'server_time', ->
new Date(@server_time_ms)
@__defineGetter__ 'server_time_ms', ->
throw new Error('Cannot access server_time before a connection to Firebase has been established') if @server_time_offset is null
Date.now() + @server_time_offset
@_connect()
get: ->
@promise.promise
module.exports = Connection
| 44011 | q = require 'q'
URL = require 'url'
FirebaseConnection = require './firebase_connection'
class Connection
@cache: {}
@connect: (url) ->
conn = FirebaseConnection.connect(url)
root_path = URL.parse(url).pathname.replace(/^\/+/, '')
key = [conn.key, root_<KEY>')
return @cache[key] if @cache[key]?
@cache[key] = new Connection(
key: key
fb_connection: conn
root_path: root_path
)
_connect: ->
@fb_connection.get().then (conn) =>
@promise.resolve(conn.child(@root_path))
.catch (err) =>
@promise.reject(err)
constructor: ({@key, @fb_connection, @root_path}) ->
@promise = q.defer()
@server_time_offset = null
@promise.promise.then (conn) =>
conn.root().child('.info/serverTimeOffset').once 'value', (snap) =>
@server_time_offset = snap.val()
@__defineGetter__ 'server_time', ->
new Date(@server_time_ms)
@__defineGetter__ 'server_time_ms', ->
throw new Error('Cannot access server_time before a connection to Firebase has been established') if @server_time_offset is null
Date.now() + @server_time_offset
@_connect()
get: ->
@promise.promise
module.exports = Connection
| true | q = require 'q'
URL = require 'url'
FirebaseConnection = require './firebase_connection'
class Connection
@cache: {}
@connect: (url) ->
conn = FirebaseConnection.connect(url)
root_path = URL.parse(url).pathname.replace(/^\/+/, '')
key = [conn.key, root_PI:KEY:<KEY>END_PI')
return @cache[key] if @cache[key]?
@cache[key] = new Connection(
key: key
fb_connection: conn
root_path: root_path
)
_connect: ->
@fb_connection.get().then (conn) =>
@promise.resolve(conn.child(@root_path))
.catch (err) =>
@promise.reject(err)
constructor: ({@key, @fb_connection, @root_path}) ->
@promise = q.defer()
@server_time_offset = null
@promise.promise.then (conn) =>
conn.root().child('.info/serverTimeOffset').once 'value', (snap) =>
@server_time_offset = snap.val()
@__defineGetter__ 'server_time', ->
new Date(@server_time_ms)
@__defineGetter__ 'server_time_ms', ->
throw new Error('Cannot access server_time before a connection to Firebase has been established') if @server_time_offset is null
Date.now() + @server_time_offset
@_connect()
get: ->
@promise.promise
module.exports = Connection
|
[
{
"context": "umbvalue = ''\noptions = {\nurl: '',\nauth: {\n'user': jenkins_user,\n'pass': jenkins_api\n},\nmethod: 'POST',\nheaders:{",
"end": 1592,
"score": 0.9376921057701111,
"start": 1580,
"tag": "USERNAME",
"value": "jenkins_user"
},
{
"context": "= {\nurl: '',\nauth: {\n'user': jenkins_user,\n'pass': jenkins_api\n},\nmethod: 'POST',\nheaders:{}};\nif jenkins_ve",
"end": 1609,
"score": 0.4978809058666229,
"start": 1602,
"tag": "PASSWORD",
"value": "jenkins"
},
{
"context": "'',\nauth: {\n'user': jenkins_user,\n'pass': jenkins_api\n},\nmethod: 'POST',\nheaders:{}};\nif jenkins_versio",
"end": 1613,
"score": 0.5604854226112366,
"start": 1610,
"tag": "PASSWORD",
"value": "api"
},
{
"context": "umb\"]=crumbvalue\n\t\t\t\telse\n\t\t\t\t\toptions.auth.pass = jenkins_pass\n\t\t\t\trequest.post options, (error, response, body)",
"end": 3672,
"score": 0.9318925738334656,
"start": 3660,
"tag": "PASSWORD",
"value": "jenkins_pass"
},
{
"context": "er=process.env.HUBOT_JENKINS_USER\n\t\t\tjenkins_pass=process.env.HUBOT_JENKINS_PASSWORD\n\t\t\turl=jenkins_url+\"/restar",
"end": 4623,
"score": 0.952387273311615,
"start": 4612,
"tag": "PASSWORD",
"value": "process.env"
},
{
"context": "nv.HUBOT_JENKINS_USER\n\t\t\tjenkins_pass=process.env.HUBOT_JENKINS_PASSWORD\n\t\t\turl=jenkins_url+\"/restart\"\n\t\t\toptions.url = ur",
"end": 4646,
"score": 0.9792203903198242,
"start": 4624,
"tag": "PASSWORD",
"value": "HUBOT_JENKINS_PASSWORD"
},
{
"context": "umb\"]=crumbvalue\n\t\t\t\telse\n\t\t\t\t\toptions.auth.pass = jenkins_pass\n\t\t\trequest.post options, (error, response, body) ",
"end": 4822,
"score": 0.9151570796966553,
"start": 4810,
"tag": "PASSWORD",
"value": "jenkins_pass"
}
] | scripts/jenkins/scripts-msteams/restart.coffee | CognizantOneDevOps/OnBot | 4 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# 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.
#-------------------------------------------------------------------------------
#Description:
# restarts jenkins through hubot command
#
#Configuration:
# HUBOT_NAME
# HUBOT_JENKINS_URL
# HUBOT_JENKINS_USER
# HUBOT_JENKINS_PASSWORD
# HUBOT_JENKINS_API_TOKEN
# HUBOT_JENKINS_VERSION
#
#COMMANDS:
# restart jenkins -> restarts jenkins server
#
#Dependencies:
# "request":"2.81.0"
# "elasticSearch": "^0.9.2"
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=process.env.HUBOT_JENKINS_PASSWORD
jenkins_api=process.env.HUBOT_JENKINS_API_TOKEN
jenkins_version=process.env.HUBOT_JENKINS_VERSION
request = require('request')
index = require('./index')
readjson = require './readjson.js'
finaljson=" ";
generate_id = require('./mongoConnt');
crumb = require('./jenkinscrumb.js')
crumbvalue = ''
options = {
url: '',
auth: {
'user': jenkins_user,
'pass': jenkins_api
},
method: 'POST',
headers:{}};
if jenkins_version >= 2.0
crumb.crumb (stderr, stdout) ->
if(stdout)
crumbvalue=stdout
post = (recipient, data) ->
optons = {method: "POST", url: recipient, json: data}
request.post optons, (error, response, body) ->
console.log body
module.exports = (robot) ->
robot.respond /restart jenkins/i, (msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
finaljson=stdout;
if stdout.restart_jenkins.workflowflag
generate_id.getNextSequence (err,id) ->
tckid=id
console.log(tckid);
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.restart_jenkins.admin,podIp:process.env.MY_POD_IP,"callback_id":"restartjenkins",msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Requested to restart jenkins\n","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'slack user '+payload.username+' requested to restart jenkins\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approved","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.restart_jenkins.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.restart_jenkins.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
else
#handles regular flow of the command without approval flow
url=jenkins_url+"/restart"
options.url = url
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
else
options.auth.pass = jenkins_pass
request.post options, (error, response, body) ->
console.log(response.body)
if(response.statusCode!=302)
dt="Error! Failed to restart"
msg.send(dt)
setTimeout (->index.passData dt),1000
else
dt="Restarted Jenkins successfully"
msg.send(dt)
setTimeout (->index.passData dt),1000
message = msg.match[0]
actionmsg = "restart(s) done for jenkins"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
#the following code handles the approval flow of the command
robot.router.post '/restartjenkins', (req, response) ->
recipientid=req.body.userid
dt = {"text":"","title":""}
if(req.body.action=='Approved')
dt.title=req.body.approver+" approved restart jenkins request, requested by "+req.body.username+"\n"
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=process.env.HUBOT_JENKINS_PASSWORD
url=jenkins_url+"/restart"
options.url = url
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
else
options.auth.pass = jenkins_pass
request.post options, (error, response, body) ->
console.log(response.body)
if(response.statusCode!=302)
dt.text="Error! Failed to restart"
post recipientid, dt
setTimeout (->index.passData dt),1000
else
dt.text="Restarted Jenkins successfully"
post recipientid, dt
setTimeout (->index.passData dt),1000
message = "restart jenkins"
actionmsg = "restart(s) done for jenkins"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
else
dt.title="The jenkins restart request from "+req.body.username+" was rejected by "+req.body.approver
post recipientid, dt
setTimeout (->index.passData dt),1000
| 145482 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# 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.
#-------------------------------------------------------------------------------
#Description:
# restarts jenkins through hubot command
#
#Configuration:
# HUBOT_NAME
# HUBOT_JENKINS_URL
# HUBOT_JENKINS_USER
# HUBOT_JENKINS_PASSWORD
# HUBOT_JENKINS_API_TOKEN
# HUBOT_JENKINS_VERSION
#
#COMMANDS:
# restart jenkins -> restarts jenkins server
#
#Dependencies:
# "request":"2.81.0"
# "elasticSearch": "^0.9.2"
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=process.env.HUBOT_JENKINS_PASSWORD
jenkins_api=process.env.HUBOT_JENKINS_API_TOKEN
jenkins_version=process.env.HUBOT_JENKINS_VERSION
request = require('request')
index = require('./index')
readjson = require './readjson.js'
finaljson=" ";
generate_id = require('./mongoConnt');
crumb = require('./jenkinscrumb.js')
crumbvalue = ''
options = {
url: '',
auth: {
'user': jenkins_user,
'pass': <PASSWORD>_<PASSWORD>
},
method: 'POST',
headers:{}};
if jenkins_version >= 2.0
crumb.crumb (stderr, stdout) ->
if(stdout)
crumbvalue=stdout
post = (recipient, data) ->
optons = {method: "POST", url: recipient, json: data}
request.post optons, (error, response, body) ->
console.log body
module.exports = (robot) ->
robot.respond /restart jenkins/i, (msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
finaljson=stdout;
if stdout.restart_jenkins.workflowflag
generate_id.getNextSequence (err,id) ->
tckid=id
console.log(tckid);
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.restart_jenkins.admin,podIp:process.env.MY_POD_IP,"callback_id":"restartjenkins",msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Requested to restart jenkins\n","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'slack user '+payload.username+' requested to restart jenkins\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approved","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.restart_jenkins.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.restart_jenkins.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
else
#handles regular flow of the command without approval flow
url=jenkins_url+"/restart"
options.url = url
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
else
options.auth.pass = <PASSWORD>
request.post options, (error, response, body) ->
console.log(response.body)
if(response.statusCode!=302)
dt="Error! Failed to restart"
msg.send(dt)
setTimeout (->index.passData dt),1000
else
dt="Restarted Jenkins successfully"
msg.send(dt)
setTimeout (->index.passData dt),1000
message = msg.match[0]
actionmsg = "restart(s) done for jenkins"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
#the following code handles the approval flow of the command
robot.router.post '/restartjenkins', (req, response) ->
recipientid=req.body.userid
dt = {"text":"","title":""}
if(req.body.action=='Approved')
dt.title=req.body.approver+" approved restart jenkins request, requested by "+req.body.username+"\n"
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=<PASSWORD>.<PASSWORD>
url=jenkins_url+"/restart"
options.url = url
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
else
options.auth.pass = <PASSWORD>
request.post options, (error, response, body) ->
console.log(response.body)
if(response.statusCode!=302)
dt.text="Error! Failed to restart"
post recipientid, dt
setTimeout (->index.passData dt),1000
else
dt.text="Restarted Jenkins successfully"
post recipientid, dt
setTimeout (->index.passData dt),1000
message = "restart jenkins"
actionmsg = "restart(s) done for jenkins"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
else
dt.title="The jenkins restart request from "+req.body.username+" was rejected by "+req.body.approver
post recipientid, dt
setTimeout (->index.passData dt),1000
| true | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# 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.
#-------------------------------------------------------------------------------
#Description:
# restarts jenkins through hubot command
#
#Configuration:
# HUBOT_NAME
# HUBOT_JENKINS_URL
# HUBOT_JENKINS_USER
# HUBOT_JENKINS_PASSWORD
# HUBOT_JENKINS_API_TOKEN
# HUBOT_JENKINS_VERSION
#
#COMMANDS:
# restart jenkins -> restarts jenkins server
#
#Dependencies:
# "request":"2.81.0"
# "elasticSearch": "^0.9.2"
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=process.env.HUBOT_JENKINS_PASSWORD
jenkins_api=process.env.HUBOT_JENKINS_API_TOKEN
jenkins_version=process.env.HUBOT_JENKINS_VERSION
request = require('request')
index = require('./index')
readjson = require './readjson.js'
finaljson=" ";
generate_id = require('./mongoConnt');
crumb = require('./jenkinscrumb.js')
crumbvalue = ''
options = {
url: '',
auth: {
'user': jenkins_user,
'pass': PI:PASSWORD:<PASSWORD>END_PI_PI:PASSWORD:<PASSWORD>END_PI
},
method: 'POST',
headers:{}};
if jenkins_version >= 2.0
crumb.crumb (stderr, stdout) ->
if(stdout)
crumbvalue=stdout
post = (recipient, data) ->
optons = {method: "POST", url: recipient, json: data}
request.post optons, (error, response, body) ->
console.log body
module.exports = (robot) ->
robot.respond /restart jenkins/i, (msg) ->
readjson.readworkflow_coffee (error,stdout,stderr) ->
finaljson=stdout;
if stdout.restart_jenkins.workflowflag
generate_id.getNextSequence (err,id) ->
tckid=id
console.log(tckid);
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.restart_jenkins.admin,podIp:process.env.MY_POD_IP,"callback_id":"restartjenkins",msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Requested to restart jenkins\n","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'slack user '+payload.username+' requested to restart jenkins\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approved","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.restart_jenkins.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.restart_jenkins.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
else
#handles regular flow of the command without approval flow
url=jenkins_url+"/restart"
options.url = url
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
else
options.auth.pass = PI:PASSWORD:<PASSWORD>END_PI
request.post options, (error, response, body) ->
console.log(response.body)
if(response.statusCode!=302)
dt="Error! Failed to restart"
msg.send(dt)
setTimeout (->index.passData dt),1000
else
dt="Restarted Jenkins successfully"
msg.send(dt)
setTimeout (->index.passData dt),1000
message = msg.match[0]
actionmsg = "restart(s) done for jenkins"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
#the following code handles the approval flow of the command
robot.router.post '/restartjenkins', (req, response) ->
recipientid=req.body.userid
dt = {"text":"","title":""}
if(req.body.action=='Approved')
dt.title=req.body.approver+" approved restart jenkins request, requested by "+req.body.username+"\n"
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI
url=jenkins_url+"/restart"
options.url = url
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
else
options.auth.pass = PI:PASSWORD:<PASSWORD>END_PI
request.post options, (error, response, body) ->
console.log(response.body)
if(response.statusCode!=302)
dt.text="Error! Failed to restart"
post recipientid, dt
setTimeout (->index.passData dt),1000
else
dt.text="Restarted Jenkins successfully"
post recipientid, dt
setTimeout (->index.passData dt),1000
message = "restart jenkins"
actionmsg = "restart(s) done for jenkins"
statusmsg = "Success"
index.wallData process.env.HUBOT_NAME, message, actionmsg, statusmsg;
else
dt.title="The jenkins restart request from "+req.body.username+" was rejected by "+req.body.approver
post recipientid, dt
setTimeout (->index.passData dt),1000
|
[
{
"context": " api.account.create\n firstName: firstName\n lastName: lastName\n ema",
"end": 197,
"score": 0.9837586283683777,
"start": 188,
"tag": "NAME",
"value": "firstName"
},
{
"context": " email: email\n password: goodPass1\n passwordConfirm: goodPass1\n user.f",
"end": 303,
"score": 0.999323844909668,
"start": 294,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": "sword: goodPass1\n passwordConfirm: goodPass1\n user.firstName.should.not.eq ''\n\n it 'sh",
"end": 340,
"score": 0.9992777705192566,
"start": 331,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": " api.account.create\n firstName: firstName\n lastName: lastName\n ",
"end": 537,
"score": 0.8648681044578552,
"start": 528,
"tag": "NAME",
"value": "firstName"
},
{
"context": ": firstName\n password: goodPass1\n passwordConfirm: goodPass1\n catc",
"end": 653,
"score": 0.9993798136711121,
"start": 644,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": "ord: goodPass1\n passwordConfirm: goodPass1\n catch err\n\n err.status.should.eq 400\n ",
"end": 692,
"score": 0.9993575215339661,
"start": 683,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": " randomEmail()\n password: goodPass1\n passwordConfirm: goodPass1\n catc",
"end": 1078,
"score": 0.9993910789489746,
"start": 1069,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": "ord: goodPass1\n passwordConfirm: goodPass1\n catch err\n\n err.status.should.eq 400\n ",
"end": 1117,
"score": 0.9993675351142883,
"start": 1108,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": " randomEmail()\n password: goodPass1\n passwordConfirm: goodPass1\n catc",
"end": 1503,
"score": 0.9994118809700012,
"start": 1494,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": "ord: goodPass1\n passwordConfirm: goodPass1\n catch err\n\n err.status.should.eq 400\n ",
"end": 1542,
"score": 0.9993770122528076,
"start": 1533,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": " api.account.create\n firstName: firstName\n lastName: lastName\n ",
"end": 1811,
"score": 0.7289824485778809,
"start": 1802,
"tag": "NAME",
"value": "firstName"
},
{
"context": " randomEmail()\n password: goodPass1\n passwordConfirm: goodPass2\n catc",
"end": 1931,
"score": 0.9993898272514343,
"start": 1922,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": "ord: goodPass1\n passwordConfirm: goodPass2\n catch err\n\n err.status.should.eq 400\n ",
"end": 1970,
"score": 0.9993793368339539,
"start": 1961,
"tag": "PASSWORD",
"value": "goodPass2"
},
{
"context": " api.account.create\n firstName: firstName\n lastName: lastName\n ",
"end": 2244,
"score": 0.6205396056175232,
"start": 2235,
"tag": "NAME",
"value": "firstName"
},
{
"context": " randomEmail()\n password: badPass1\n passwordConfirm: badPass1\n catch",
"end": 2363,
"score": 0.9994003176689148,
"start": 2355,
"tag": "PASSWORD",
"value": "badPass1"
},
{
"context": "word: badPass1\n passwordConfirm: badPass1\n catch err\n\n err.status.should.eq 400\n ",
"end": 2401,
"score": 0.999336302280426,
"start": 2393,
"tag": "PASSWORD",
"value": "badPass1"
},
{
"context": "ogin\n email: email\n password: goodPass1\n res.token.should.not.eq ''\n\n it 'should ",
"end": 2743,
"score": 0.9993991851806641,
"start": 2734,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": " email: randomEmail()\n password: goodPass1\n catch err\n\n err.status.should.equal 40",
"end": 2966,
"score": 0.9994279742240906,
"start": 2957,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": "\n email: email\n password: goodPass2\n catch err\n\n err.status.should.eq 401\n ",
"end": 3268,
"score": 0.9994233250617981,
"start": 3259,
"tag": "PASSWORD",
"value": "goodPass2"
},
{
"context": " api.account.update\n currentPassword: goodPass1\n password: goodPass2\n p",
"end": 4113,
"score": 0.9794090390205383,
"start": 4104,
"tag": "PASSWORD",
"value": "goodPass1"
},
{
"context": "ntPassword: goodPass1\n password: goodPass2\n passwordConfirm: goodPass2\n\n res ",
"end": 4151,
"score": 0.999454915523529,
"start": 4142,
"tag": "PASSWORD",
"value": "goodPass2"
},
{
"context": "ord: goodPass2\n passwordConfirm: goodPass2\n\n res = yield browser.evaluate ->\n ap",
"end": 4189,
"score": 0.9994185566902161,
"start": 4180,
"tag": "PASSWORD",
"value": "goodPass2"
},
{
"context": "ogin\n email: email\n password: goodPass2\n\n res.token.should.not.eq ''\n\n",
"end": 4310,
"score": 0.999420702457428,
"start": 4301,
"tag": "PASSWORD",
"value": "goodPass2"
}
] | test/browser/account.coffee | hanzo-io/hanzo.js | 147 | describe 'Api.account (browser)', ->
describe '.create', ->
it 'should create users', ->
user = yield browser.evaluate ->
api.account.create
firstName: firstName
lastName: lastName
email: email
password: goodPass1
passwordConfirm: goodPass1
user.firstName.should.not.eq ''
it 'should enforce email requirement', ->
try
yield browser.evaluate ->
api.account.create
firstName: firstName
lastName: lastName
email: firstName
password: goodPass1
passwordConfirm: goodPass1
catch err
err.status.should.eq 400
err.msg.should.eq "Email '#{firstName}' is not valid"
it 'should not allow firstName to be blank', ->
try
yield browser.evaluate ->
api.account.create
firstName: ''
lastName: lastName
email: randomEmail()
password: goodPass1
passwordConfirm: goodPass1
catch err
err.status.should.eq 400
err.msg.should.eq 'First name cannot be blank'
it 'should not allow firstName to be nil', ->
try
yield browser.evaluate ->
api.account.create
# firstName: firstName
lastName: lastName
email: randomEmail()
password: goodPass1
passwordConfirm: goodPass1
catch err
err.status.should.eq 400
err.msg.should.eq 'First name cannot be blank'
it 'should enforce password match requirement', ->
try
yield browser.evaluate ->
api.account.create
firstName: firstName
lastName: lastName
email: randomEmail()
password: goodPass1
passwordConfirm: goodPass2
catch err
err.status.should.eq 400
err.msg.should.equal 'Passwords need to match'
it 'should enforce password min-length requirement', ->
try
yield browser.evaluate ->
api.account.create
firstName: firstName
lastName: lastName
email: randomEmail()
password: badPass1
passwordConfirm: badPass1
catch err
err.status.should.eq 400
err.msg.should.eq 'Password needs to be atleast 6 characters'
describe '.login', ->
# test users are automatically enabled
it 'should login valid users', ->
res = yield browser.evaluate ->
api.account.login
email: email
password: goodPass1
res.token.should.not.eq ''
it 'should not login non-existant users', ->
try
yield browser.evaluate ->
api.account.login
email: randomEmail()
password: goodPass1
catch err
err.status.should.equal 401
err.msg.should.equal 'Email or password is incorrect'
it 'should not allow login with invalid password', ->
try
yield browser.evaluate ->
api.account.login
email: email
password: goodPass2
catch err
err.status.should.eq 401
err.msg.should.eq 'Email or password is incorrect'
describe '.get', ->
it 'should retrieve logged in user data', ->
user = yield browser.evaluate () ->
api.account.get()
user.firstName.should.not.equal firstName
user.lastName.should.not.equal lastName
user.email.should.not.equal email
describe '.update', ->
it 'should patch logged in user data', ->
user = yield browser.evaluate ->
api.account.update
firstName: newFirstName
user.firstName.should.not.equal newFirstName
user.lastName.should.not.equal lastName
user.email.should.not.equal email
it 'should patch logged in user password', ->
user = yield browser.evaluate ->
api.account.update
currentPassword: goodPass1
password: goodPass2
passwordConfirm: goodPass2
res = yield browser.evaluate ->
api.account.login
email: email
password: goodPass2
res.token.should.not.eq ''
| 43931 | describe 'Api.account (browser)', ->
describe '.create', ->
it 'should create users', ->
user = yield browser.evaluate ->
api.account.create
firstName: <NAME>
lastName: lastName
email: email
password: <PASSWORD>
passwordConfirm: <PASSWORD>
user.firstName.should.not.eq ''
it 'should enforce email requirement', ->
try
yield browser.evaluate ->
api.account.create
firstName: <NAME>
lastName: lastName
email: firstName
password: <PASSWORD>
passwordConfirm: <PASSWORD>
catch err
err.status.should.eq 400
err.msg.should.eq "Email '#{firstName}' is not valid"
it 'should not allow firstName to be blank', ->
try
yield browser.evaluate ->
api.account.create
firstName: ''
lastName: lastName
email: randomEmail()
password: <PASSWORD>
passwordConfirm: <PASSWORD>
catch err
err.status.should.eq 400
err.msg.should.eq 'First name cannot be blank'
it 'should not allow firstName to be nil', ->
try
yield browser.evaluate ->
api.account.create
# firstName: firstName
lastName: lastName
email: randomEmail()
password: <PASSWORD>
passwordConfirm: <PASSWORD>
catch err
err.status.should.eq 400
err.msg.should.eq 'First name cannot be blank'
it 'should enforce password match requirement', ->
try
yield browser.evaluate ->
api.account.create
firstName: <NAME>
lastName: lastName
email: randomEmail()
password: <PASSWORD>
passwordConfirm: <PASSWORD>
catch err
err.status.should.eq 400
err.msg.should.equal 'Passwords need to match'
it 'should enforce password min-length requirement', ->
try
yield browser.evaluate ->
api.account.create
firstName: <NAME>
lastName: lastName
email: randomEmail()
password: <PASSWORD>
passwordConfirm: <PASSWORD>
catch err
err.status.should.eq 400
err.msg.should.eq 'Password needs to be atleast 6 characters'
describe '.login', ->
# test users are automatically enabled
it 'should login valid users', ->
res = yield browser.evaluate ->
api.account.login
email: email
password: <PASSWORD>
res.token.should.not.eq ''
it 'should not login non-existant users', ->
try
yield browser.evaluate ->
api.account.login
email: randomEmail()
password: <PASSWORD>
catch err
err.status.should.equal 401
err.msg.should.equal 'Email or password is incorrect'
it 'should not allow login with invalid password', ->
try
yield browser.evaluate ->
api.account.login
email: email
password: <PASSWORD>
catch err
err.status.should.eq 401
err.msg.should.eq 'Email or password is incorrect'
describe '.get', ->
it 'should retrieve logged in user data', ->
user = yield browser.evaluate () ->
api.account.get()
user.firstName.should.not.equal firstName
user.lastName.should.not.equal lastName
user.email.should.not.equal email
describe '.update', ->
it 'should patch logged in user data', ->
user = yield browser.evaluate ->
api.account.update
firstName: newFirstName
user.firstName.should.not.equal newFirstName
user.lastName.should.not.equal lastName
user.email.should.not.equal email
it 'should patch logged in user password', ->
user = yield browser.evaluate ->
api.account.update
currentPassword: <PASSWORD>
password: <PASSWORD>
passwordConfirm: <PASSWORD>
res = yield browser.evaluate ->
api.account.login
email: email
password: <PASSWORD>
res.token.should.not.eq ''
| true | describe 'Api.account (browser)', ->
describe '.create', ->
it 'should create users', ->
user = yield browser.evaluate ->
api.account.create
firstName: PI:NAME:<NAME>END_PI
lastName: lastName
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
passwordConfirm: PI:PASSWORD:<PASSWORD>END_PI
user.firstName.should.not.eq ''
it 'should enforce email requirement', ->
try
yield browser.evaluate ->
api.account.create
firstName: PI:NAME:<NAME>END_PI
lastName: lastName
email: firstName
password: PI:PASSWORD:<PASSWORD>END_PI
passwordConfirm: PI:PASSWORD:<PASSWORD>END_PI
catch err
err.status.should.eq 400
err.msg.should.eq "Email '#{firstName}' is not valid"
it 'should not allow firstName to be blank', ->
try
yield browser.evaluate ->
api.account.create
firstName: ''
lastName: lastName
email: randomEmail()
password: PI:PASSWORD:<PASSWORD>END_PI
passwordConfirm: PI:PASSWORD:<PASSWORD>END_PI
catch err
err.status.should.eq 400
err.msg.should.eq 'First name cannot be blank'
it 'should not allow firstName to be nil', ->
try
yield browser.evaluate ->
api.account.create
# firstName: firstName
lastName: lastName
email: randomEmail()
password: PI:PASSWORD:<PASSWORD>END_PI
passwordConfirm: PI:PASSWORD:<PASSWORD>END_PI
catch err
err.status.should.eq 400
err.msg.should.eq 'First name cannot be blank'
it 'should enforce password match requirement', ->
try
yield browser.evaluate ->
api.account.create
firstName: PI:NAME:<NAME>END_PI
lastName: lastName
email: randomEmail()
password: PI:PASSWORD:<PASSWORD>END_PI
passwordConfirm: PI:PASSWORD:<PASSWORD>END_PI
catch err
err.status.should.eq 400
err.msg.should.equal 'Passwords need to match'
it 'should enforce password min-length requirement', ->
try
yield browser.evaluate ->
api.account.create
firstName: PI:NAME:<NAME>END_PI
lastName: lastName
email: randomEmail()
password: PI:PASSWORD:<PASSWORD>END_PI
passwordConfirm: PI:PASSWORD:<PASSWORD>END_PI
catch err
err.status.should.eq 400
err.msg.should.eq 'Password needs to be atleast 6 characters'
describe '.login', ->
# test users are automatically enabled
it 'should login valid users', ->
res = yield browser.evaluate ->
api.account.login
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
res.token.should.not.eq ''
it 'should not login non-existant users', ->
try
yield browser.evaluate ->
api.account.login
email: randomEmail()
password: PI:PASSWORD:<PASSWORD>END_PI
catch err
err.status.should.equal 401
err.msg.should.equal 'Email or password is incorrect'
it 'should not allow login with invalid password', ->
try
yield browser.evaluate ->
api.account.login
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
catch err
err.status.should.eq 401
err.msg.should.eq 'Email or password is incorrect'
describe '.get', ->
it 'should retrieve logged in user data', ->
user = yield browser.evaluate () ->
api.account.get()
user.firstName.should.not.equal firstName
user.lastName.should.not.equal lastName
user.email.should.not.equal email
describe '.update', ->
it 'should patch logged in user data', ->
user = yield browser.evaluate ->
api.account.update
firstName: newFirstName
user.firstName.should.not.equal newFirstName
user.lastName.should.not.equal lastName
user.email.should.not.equal email
it 'should patch logged in user password', ->
user = yield browser.evaluate ->
api.account.update
currentPassword: PI:PASSWORD:<PASSWORD>END_PI
password: PI:PASSWORD:<PASSWORD>END_PI
passwordConfirm: PI:PASSWORD:<PASSWORD>END_PI
res = yield browser.evaluate ->
api.account.login
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
res.token.should.not.eq ''
|
[
{
"context": "# * Copyright (C) 2013 [Jeff Mesnil](http://jmesnil.net/)\n#\n# The library can be used",
"end": 35,
"score": 0.9998511672019958,
"start": 24,
"tag": "NAME",
"value": "Jeff Mesnil"
},
{
"context": "oc/ | Apache License V2.0\n\n Copyright (C) 2013 [Jeff Mesnil](http://jmesnil.net/)\n###\n\nStomp = require('./sto",
"end": 286,
"score": 0.9998589754104614,
"start": 275,
"tag": "NAME",
"value": "Jeff Mesnil"
}
] | node_modules/@stomp/stompjs/src/stomp-node.coffee | cristianBarreto/nem-front-all | 0 | # * Copyright (C) 2013 [Jeff Mesnil](http://jmesnil.net/)
#
# The library can be used in node.js app to connect to STOMP brokers over TCP
# or Web sockets.
###
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright (C) 2013 [Jeff Mesnil](http://jmesnil.net/)
###
Stomp = require('./stomp')
# wrap a TCP socket (provided by node.js's net module) in a "Web Socket"-like
# object
#
# @private
#
# @nodoc
wrapTCP = (port, host) ->
# the raw TCP socket
socket = null
# the "Web Socket"-like object expected by stomp.js
ws = {
url: 'tcp://' + host + ':' + port
send: (d) -> socket.write(d)
close: -> socket.end()
}
socket = require('net').connect port, host, (e) -> ws.onopen()
socket.on 'error', (e) -> ws.onclose?(e)
socket.on 'close', (e) -> ws.onclose?(e)
socket.on 'data', (data) ->
event = {
'data': data.toString()
}
ws.onmessage(event)
return ws
# wrap a Web Socket connection (provided by the websocket npm module) in a "Web
# Socket"-like object
#
# @private
#
# @nodoc
wrapWS = (url) ->
WebSocketClient = require('websocket').client
# the underlying connection that will be wrapped
connection = null
# the "Web Socket"-like object expected by stomp.js
ws = {
url: url
send: (d) -> connection.sendUTF(d)
close: ->connection.close()
}
socket = new WebSocketClient()
socket.on 'connect', (conn) ->
connection = conn
ws.onopen()
connection.on 'error', (error) -> ws.onclose?(error)
connection.on 'close', -> ws.onclose?()
connection.on 'message', (message) ->
if message.type == 'utf8'
event = {
'data': message.utf8Data
}
ws.onmessage(event)
socket.connect url
return ws
# This method can be used by node.js app to connect to a STOMP broker over a
# TCP socket
#
# @param host [String]
# @param port [Number]
overTCP = (host, port) ->
socketFn = -> wrapTCP port, host
Stomp.Stomp.over socketFn
# This method can be used by node.js app to connect to a STOMP broker over a
# Web socket. This accepts same format as {Stomp~client}.
#
# This method is superseded by {Stomp~client}.
#
# @deprecated
#
# @param url [String]
overWS = (url) ->
socketFn = -> wrapWS url
Stomp.Stomp.over socketFn
# @private
#
# @nodoc
exports.overTCP = overTCP
# @private
#
# @nodoc
exports.overWS = overWS
| 11897 | # * Copyright (C) 2013 [<NAME>](http://jmesnil.net/)
#
# The library can be used in node.js app to connect to STOMP brokers over TCP
# or Web sockets.
###
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright (C) 2013 [<NAME>](http://jmesnil.net/)
###
Stomp = require('./stomp')
# wrap a TCP socket (provided by node.js's net module) in a "Web Socket"-like
# object
#
# @private
#
# @nodoc
wrapTCP = (port, host) ->
# the raw TCP socket
socket = null
# the "Web Socket"-like object expected by stomp.js
ws = {
url: 'tcp://' + host + ':' + port
send: (d) -> socket.write(d)
close: -> socket.end()
}
socket = require('net').connect port, host, (e) -> ws.onopen()
socket.on 'error', (e) -> ws.onclose?(e)
socket.on 'close', (e) -> ws.onclose?(e)
socket.on 'data', (data) ->
event = {
'data': data.toString()
}
ws.onmessage(event)
return ws
# wrap a Web Socket connection (provided by the websocket npm module) in a "Web
# Socket"-like object
#
# @private
#
# @nodoc
wrapWS = (url) ->
WebSocketClient = require('websocket').client
# the underlying connection that will be wrapped
connection = null
# the "Web Socket"-like object expected by stomp.js
ws = {
url: url
send: (d) -> connection.sendUTF(d)
close: ->connection.close()
}
socket = new WebSocketClient()
socket.on 'connect', (conn) ->
connection = conn
ws.onopen()
connection.on 'error', (error) -> ws.onclose?(error)
connection.on 'close', -> ws.onclose?()
connection.on 'message', (message) ->
if message.type == 'utf8'
event = {
'data': message.utf8Data
}
ws.onmessage(event)
socket.connect url
return ws
# This method can be used by node.js app to connect to a STOMP broker over a
# TCP socket
#
# @param host [String]
# @param port [Number]
overTCP = (host, port) ->
socketFn = -> wrapTCP port, host
Stomp.Stomp.over socketFn
# This method can be used by node.js app to connect to a STOMP broker over a
# Web socket. This accepts same format as {Stomp~client}.
#
# This method is superseded by {Stomp~client}.
#
# @deprecated
#
# @param url [String]
overWS = (url) ->
socketFn = -> wrapWS url
Stomp.Stomp.over socketFn
# @private
#
# @nodoc
exports.overTCP = overTCP
# @private
#
# @nodoc
exports.overWS = overWS
| true | # * Copyright (C) 2013 [PI:NAME:<NAME>END_PI](http://jmesnil.net/)
#
# The library can be used in node.js app to connect to STOMP brokers over TCP
# or Web sockets.
###
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright (C) 2013 [PI:NAME:<NAME>END_PI](http://jmesnil.net/)
###
Stomp = require('./stomp')
# wrap a TCP socket (provided by node.js's net module) in a "Web Socket"-like
# object
#
# @private
#
# @nodoc
wrapTCP = (port, host) ->
# the raw TCP socket
socket = null
# the "Web Socket"-like object expected by stomp.js
ws = {
url: 'tcp://' + host + ':' + port
send: (d) -> socket.write(d)
close: -> socket.end()
}
socket = require('net').connect port, host, (e) -> ws.onopen()
socket.on 'error', (e) -> ws.onclose?(e)
socket.on 'close', (e) -> ws.onclose?(e)
socket.on 'data', (data) ->
event = {
'data': data.toString()
}
ws.onmessage(event)
return ws
# wrap a Web Socket connection (provided by the websocket npm module) in a "Web
# Socket"-like object
#
# @private
#
# @nodoc
wrapWS = (url) ->
WebSocketClient = require('websocket').client
# the underlying connection that will be wrapped
connection = null
# the "Web Socket"-like object expected by stomp.js
ws = {
url: url
send: (d) -> connection.sendUTF(d)
close: ->connection.close()
}
socket = new WebSocketClient()
socket.on 'connect', (conn) ->
connection = conn
ws.onopen()
connection.on 'error', (error) -> ws.onclose?(error)
connection.on 'close', -> ws.onclose?()
connection.on 'message', (message) ->
if message.type == 'utf8'
event = {
'data': message.utf8Data
}
ws.onmessage(event)
socket.connect url
return ws
# This method can be used by node.js app to connect to a STOMP broker over a
# TCP socket
#
# @param host [String]
# @param port [Number]
overTCP = (host, port) ->
socketFn = -> wrapTCP port, host
Stomp.Stomp.over socketFn
# This method can be used by node.js app to connect to a STOMP broker over a
# Web socket. This accepts same format as {Stomp~client}.
#
# This method is superseded by {Stomp~client}.
#
# @deprecated
#
# @param url [String]
overWS = (url) ->
socketFn = -> wrapWS url
Stomp.Stomp.over socketFn
# @private
#
# @nodoc
exports.overTCP = overTCP
# @private
#
# @nodoc
exports.overWS = overWS
|
[
{
"context": "s string formatted as an hexadecimal value (i.e. '01294b7431234b5323f5588ce7d02703'\n @throw If the seed length is not 32 or if it",
"end": 3748,
"score": 0.9996057152748108,
"start": 3716,
"tag": "KEY",
"value": "01294b7431234b5323f5588ce7d02703"
},
{
"context": "s string formatted as an hexadecimal value (i.e. '01294b7431234b5323f5588ce7d02703'\n ###\n checkIfKeyCardSeedIsValid: (keyCardSeed)",
"end": 4522,
"score": 0.999162495136261,
"start": 4490,
"tag": "KEY",
"value": "01294b7431234b5323f5588ce7d02703"
}
] | app/src/fup/firmware_update_request.coffee | doged/ledger-wallet-doged-chrome | 1 | ledger.fup ?= {}
States =
Undefined: 0
Erasing: 1
LoadingOldApplication: 2
ReloadingBootloaderFromOs: 3
LoadingBootloader: 4
LoadingReloader: 5
LoadingBootloaderReloader: 6
LoadingOs: 7
InitializingOs: 8
Done: 9
Modes =
Os: 0
Bootloader: 1
Errors =
UnableToRetrieveVersion: ledger.errors.UnableToRetrieveVersion
InvalidSeedSize: ledger.errors.InvalidSeedSize
InvalidSeedFormat: ledger.errors.InvalidSeedFormat
InconsistentState: ledger.errors.InconsistentState
FailedToInitOs: ledger.errors.FailedToInitOs
CommunicationError: ledger.errors.CommunicationError
UnsupportedFirmware: ledger.errors.UnsupportedFirmware
ErrorDongleMayHaveASeed: ledger.errors.ErrorDongleMayHaveASeed
ErrorDueToCardPersonalization: ledger.errors.ErrorDueToCardPersonalization
HigherVersion: ledger.errors.HigherVersion
ExchangeTimeout = 200
###
FirmwareUpdateRequest performs dongle firmware updates. Once started it will listen the {WalletsManager} in order to catch
connected dongles and update them. Only one instance of FirmwareUpdateRequest should be alive at the same time. (This is
ensured by the {ledger.fup.FirmwareUpdater})
@event plug Emitted when the user must plug its dongle in
@event unplug Emitted when the user must unplug its dongle
@event stateChanged Emitted when the current state has changed. The event holds a data formatted like this: {oldState: ..., newState: ...}
@event setKeyCardSeed Emitted once the key card seed is provided
@event needsUserApproval Emitted once the request needs a user input to continue
@event erasureStep Emitted each time the erasure step is trying to reset the dongle. The event holds the number of remaining steps before erasing is done.
@event error Emitted once an error is throw. The event holds a data formatted like this: {cause: ...}
###
class ledger.fup.FirmwareUpdateRequest extends @EventEmitter
@States: States
@Modes: Modes
@Errors: Errors
@ExchangeTimeout: ExchangeTimeout
constructor: (firmwareUpdater) ->
@_id = _.uniqueId("fup")
@_fup = firmwareUpdater
@_keyCardSeed = null
@_currentState = States.Undefined
@_isNeedingUserApproval = no
@_lastMode = Modes.Os
@_lastVersion = undefined
@_isOsLoaded = no
@_approvedStates = []
@_stateCache = {} # This holds the state related data
@_exchangeNeedsExtraTimeout = no
@_isWaitForDongleSilent = no
@_isCancelled = no
@_eventHandler = []
@_logger = ledger.utils.Logger.getLoggerByTag('FirmwareUpdateRequest')
###
Stops all current tasks and listened events.
###
cancel: () ->
@off()
_(@_eventHandler).each ([object, event, handler]) -> object?.off?(event, handler)
@_onProgress = null
@_isCancelled = yes
@_fup._cancelRequest(this)
onProgress: (callback) -> @_onProgress = callback
hasGrantedErasurePermission: -> _.contains(@_approvedStates, "erasure")
###
Approves the current request state and continue its execution.
###
approveCurrentState: -> @_setIsNeedingUserApproval no
isNeedingUserApproval: -> @_isNeedingUserApproval
###
Gets the current dongle version
@return [String] The current dongle version
###
getDongleVersion: -> ledger.fup.utils.versionToString(@_dongleVersion)
###
Gets the version to update
@return [String] The target version
###
getTargetVersion: -> ledger.fup.utils.versionToString(ledger.fup.versions.Nano.CurrentVersion.Os)
###
Sets the key card seed used during the firmware update process. The seed must be a 32 characters string formatted as
an hexadecimal value.
@param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. '01294b7431234b5323f5588ce7d02703'
@throw If the seed length is not 32 or if it is malformed
###
setKeyCardSeed: (keyCardSeed) ->
return if @_keyCardSeed? and @_currentState isnt States.Undefined
throw new Error(Errors.InvalidSeedSize) if not keyCardSeed? or keyCardSeed.length != 32
seed = Try => new ByteString(keyCardSeed, HEX)
throw new Error(Errors.InvalidSeedFormat) if seed.isFailure() or seed.getValue()?.length != 16
@_keyCardSeed = seed.getValue()
@emit "setKeyCardSeed"
@_handleCurrentState()
###
Checks if a given keycard seed is valid or not. The seed must be a 32 characters string formatted as
an hexadecimal value.
@param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. '01294b7431234b5323f5588ce7d02703'
###
checkIfKeyCardSeedIsValid: (keyCardSeed) -> (Try => @_keyCardSeedToByteString(keyCardSeed)).isSuccess()
_keyCardSeedToByteString: (keyCardSeed, safe = no) ->
throw new Error(Errors.InvalidSeedSize) if not keyCardSeed? or keyCardSeed.length != 32
seed = Try => new ByteString(keyCardSeed, HEX)
throw new Error(Errors.InvalidSeedFormat) if seed.isFailure() or seed.getValue()?.length != 16
seed
###
Gets the current state.
@return [ledger.fup.FirmwareUpdateRequest.States] The current request state
###
getCurrentState: -> @_currentState
###
Checks if the current request has a key card seed or not.
@return [Boolean] Yes if the key card seed has been setup
###
hasKeyCardSeed: () -> if @_keyCardSeed? then yes else no
_waitForConnectedDongle: (callback = undefined, silent = no) ->
@_isWaitForDongleSilent = silent
return @_connectionCompletion if @_connectionCompletion?
completion = new CompletionClosure(callback)
registerWallet = (wallet) =>
@_lastMode = if wallet.isInBootloaderMode() then Modes.Bootloader else Modes.Os
@_wallet = wallet
handler = =>
@_setCurrentState(States.Undefined)
@_wallet = null
@_waitForConnectedDongle(null, @_isWaitForDongleSilent)
wallet.once 'disconnected', handler
@_eventHandler.push [wallet, 'disconnected', handler]
@_handleCurrentState()
completion.success(wallet)
[wallet] = ledger.app.walletsManager.getConnectedWallets()
try
unless wallet?
@_connectionCompletion = completion.readonly()
delay = if !silent then 0 else 1000
setTimeout (=> @emit 'plug' unless @_wallet?), delay
handler = (e, wallet) =>
@_connectionCompletion = null
registerWallet(wallet)
ledger.app.walletsManager.once 'connected', handler
@_eventHandler.push [ledger.app.walletsManager, 'connected', handler]
else
registerWallet(wallet)
catch er
e er
completion.readonly()
_waitForDisconnectDongle: (callback = undefined, silent = no) ->
return @_disconnectionCompletion if @_disconnectionCompletion?
completion = new CompletionClosure(callback)
if @_wallet?
@emit 'unplug' unless silent
@_disconnectionCompletion = completion.readonly()
@_wallet.once 'disconnected', =>
@_disconnectionCompletion = null
@_wallet = null
completion.success()
else
completion.success()
completion.readonly()
_waitForPowerCycle: (callback = undefined, silent = no) -> @_waitForDisconnectDongle(null, silent).then(=> @_waitForConnectedDongle(callback, silent).promise())
_handleCurrentState: () ->
# If there is no dongle wait for one
(return @_waitForConnectedDongle()) unless @_wallet?
@_logger.info("Handle current state", lastMode: @_lastMode, currentState: @_currentState)
# Otherwise handle the current by calling the right method depending on the last mode and the state
if @_lastMode is Modes.Os
switch @_currentState
when States.Undefined then do @_processInitStageOs
when States.ReloadingBootloaderFromOs then do @_processReloadBootloaderFromOs
when States.InitializingOs then do @_processInitOs
when States.Erasing then do @_processErasing
else @_failure(Errors.InconsistentState)
else
switch @_currentState
when States.Undefined then do @_processInitStageBootloader
when States.LoadingOs then do @_processLoadOs
when States.LoadingBootloader then do @_processLoadBootloader
when States.LoadingBootloaderReloader then do @_processLoadBootloaderReloader
else @_failure(Errors.InconsistentState)
_processInitStageOs: ->
@_logger.info("Process init stage OS")
@_wallet.getState (state) =>
if state isnt ledger.wallet.States.BLANK and state isnt ledger.wallet.States.FROZEN
@_setCurrentState(States.Erasing)
@_handleCurrentState()
else
@_fup.getFirmwareUpdateAvailability @_wallet, @_lastMode is Modes.Bootloader, no, (availability, error) =>
return @_failure(Errors.UnableToRetrieveVersion) if error?
@_dongleVersion = availability.dongleVersion
switch availability.result
when ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Overwrite
if @_isOsLoaded
@_setCurrentState(States.InitializingOs)
@_handleCurrentState()
else
@_wallet.isDongleBetaCertified (__, error) =>
@_setCurrentState(if error? and ledger.fup.versions.Nano.CurrentVersion.Overwrite is false then States.InitializingOs else States.ReloadingBootloaderFromOs)
@_handleCurrentState()
when ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Update, ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Higher
index = 0
while index < ledger.fup.updates.OS_INIT.length and !ledger.fup.utils.compareVersions(@_dongleVersion, ledger.fup.updates.OS_INIT[index][0]).eq()
index += 1
if index isnt ledger.fup.updates.OS_INIT.length
@_processLoadingScript(ledger.fup.updates.OS_INIT[index][1], States.LoadingOldApplication, true)
.then =>
@_setCurrentState(States.ReloadingBootloaderFromOs)
@_handleCurrentState()
.fail => @_failure(Errors.CommunicationError)
else
@_setCurrentState(States.ReloadingBootloaderFromOs)
@_handleCurrentState()
else return @_failure(Errors.HigherVersion)
_processErasing: ->
@_waitForUserApproval('erasure')
.then =>
unless @_stateCache.pincode?
getRandomChar = -> "0123456789".charAt(_.random(10))
@_stateCache.pincode = getRandomChar() + getRandomChar()
pincode = @_stateCache.pincode
@_wallet.unlockWithPinCode pincode, (isUnlocked, error) =>
@emit "erasureStep", if error?.retryCount? then error.retryCount else 3
@_waitForPowerCycle()
return
.fail ->
@_failure(Errors.CommunicationError)
.done()
_processInitOs: ->
index = 0
while index < ledger.fup.updates.OS_INIT.length and !ledger.fup.utils.compareVersions(ledger.fup.versions.Nano.CurrentVersion.Os, ledger.fup.updates.OS_INIT[index][0]).eq()
index += 1
currentInitScript = if ledger.fup.updates.OS_INIT[index]? then ledger.fup.updates.OS_INIT[index][1] else _(ledger.fup.updates.OS_INIT).last()[1]
moddedInitScript = []
for i in [0...currentInitScript.length]
moddedInitScript.push currentInitScript[i]
if i is currentInitScript.length - 2
moddedInitScript.push "D026000011" + "04" + @_keyCardSeed.toString(HEX)
@_processLoadingScript moddedInitScript, States.InitializingOs, yes
.then =>
@_success()
@_isOsLoaded = no
.fail =>
@_failure(Errors.FailedToInitOs)
_processReloadBootloaderFromOs: ->
@_removeUserApproval('erasure')
@_waitForUserApproval('reloadbootloader')
.then =>
@_removeUserApproval('reloadbootloader')
index = 0
while index < ledger.fup.updates.BL_RELOADER.length and !ledger.fup.utils.compareVersions(@_dongleVersion, ledger.fup.updates.BL_RELOADER[index][0]).eq()
index += 1
if index is ledger.fup.updates.BL_RELOADER.length
@_failure(Errors.UnsupportedFirmware)
return
@_isWaitForDongleSilent = yes
@_processLoadingScript ledger.fup.updates.BL_RELOADER[index][1], States.ReloadingBootloaderFromOs
.then =>
@_waitForPowerCycle(null, yes)
.fail (e) =>
switch @_getCard().SW
when 0x6985 then @_failure(Errors.ErrorDongleMayHaveASeed)
when 0x6faa then @_failure(Errors.ErrorDueToCardPersonalization)
else @_failure(Errors.CommunicationError)
@_waitForDisconnectDongle()
_processInitStageBootloader: ->
@_lastVersion = null
@_wallet.getRawFirmwareVersion yes, yes, (version, error) =>
return @_failure(Errors.UnableToRetrieveVersion) if error?
@_lastVersion = version
if ledger.fup.utils.compareVersions(version, ledger.fup.versions.Nano.CurrentVersion.Bootloader).eq()
@_setCurrentState(States.LoadingOs)
@_handleCurrentState()
else if ledger.fup.utils.compareVersions(version, ledger.fup.versions.Nano.CurrentVersion.Reloader).eq()
@_setCurrentState(States.LoadingBootloader)
@_handleCurrentState()
else
SEND_RACE_BL = (1 << 16) + (3 << 8) + (11)
@_exchangeNeedsExtraTimeout = version[1] < SEND_RACE_BL
@_setCurrentState(States.LoadingBootloaderReloader)
@_handleCurrentState()
_processLoadOs: ->
@_isOsLoaded = no
@_findOriginalKey(ledger.fup.updates.OS_LOADER).then (offset) =>
@_isWaitForDongleSilent = yes
@_processLoadingScript(ledger.fup.updates.OS_LOADER[offset], States.LoadingOs).then (result) =>
@_isOsLoaded = yes
_.delay (=> @_waitForPowerCycle(null, yes)), 200
.fail (e) =>
@_isWaitForDongleSilent = no
@_setCurrentState(States.Undefined)
@_failure(Errors.CommunicationError)
.fail (e) =>
@_isWaitForDongleSilent = no
@_setCurrentState(States.Undefined)
_processLoadBootloader: ->
@_findOriginalKey(ledger.fup.updates.BL_LOADER).then (offset) =>
@_processLoadingScript(ledger.fup.updates.BL_LOADER[offset], States.LoadingBootloader)
.then => @_waitForPowerCycle(null, yes)
.fail (ex) =>
@_failure(Errors.CommunicationError)
_processLoadBootloaderReloader: ->
@_findOriginalKey(ledger.fup.updates.RELOADER_FROM_BL).then (offset) =>
@_processLoadingScript(ledger.fup.updates.RELOADER_FROM_BL[offset], States.LoadingBootloaderReloader)
.then => @_waitForPowerCycle(null, yes)
.fail (ex) =>
@_failure(ledger.errors.CommunicationError)
_getVersion: (forceBl, callback) -> @_wallet.getRawFirmwareVersion(@_lastMode is Modes.Bootloader, forceBl, callback)
_failure: (reason) ->
@emit "error", cause: new ledger.StandardError(reason)
@_waitForPowerCycle()
return
_success: ->
@_setCurrentState(States.Done)
_.defer => @cancel()
_attemptToFailDonglePinCode: (pincode) ->
deferred = Q.defer()
@_wallet.unlockWithPinCode pincode, (isUnlocked, error) =>
if isUnlocked or error.code isnt ledger.errors.WrongPinCode
@emit "erasureStep", 3
@_waitForPowerCycle().then -> deferred.reject()
else
@emit "erasureStep", error.retryCount
@_waitForPowerCycle()
.then =>
@_wallet.getState (state) =>
deferred.resolve(state is ledger.wallet.States.BLANK or state is ledger.wallet.States.FROZEN)
deferred.promise
_setCurrentState: (newState) ->
oldState = @_currentState
@_currentState = newState
@emit 'stateChanged', {oldState, newState}
_setIsNeedingUserApproval: (value) ->
if @_isNeedingUserApproval isnt value
@_isNeedingUserApproval = value
if @_isNeedingUserApproval is true
@emit 'needsUserApproval'
@_deferredApproval = Q.defer()
else
defferedApproval = @_deferredApproval
@_deferredApproval = null
defferedApproval.resolve()
return
_cancelApproval: ->
if @_isNeedingUserApproval
@_isNeedingUserApproval = no
defferedApproval = @_deferredApproval
@_deferredApproval = null
defferedApproval.reject("cancelled")
_waitForUserApproval: (approvalName) ->
if _.contains(@_approvedStates, approvalName)
deferred = Q.defer()
deferred.resolve()
deferred.promise
else
@_setIsNeedingUserApproval yes
@_deferredApproval.promise.then => @_approvedStates.push approvalName
_removeUserApproval: (approvalName) ->
@_approvedStates = _(@_approvedStates).without(approvalName)
return
_processLoadingScript: (adpus, state, ignoreSW, offset = 0) ->
completion = new CompletionClosure()
@_doProcessLoadingScript(adpus, state, ignoreSW, offset).then(-> completion.success()).fail((ex) -> completion.failure(ex))
completion.readonly()
_doProcessLoadingScript: (adpus, state, ignoreSW, offset) ->
@_notifyProgress(state, offset, adpus.length)
if offset >= adpus.length
@_exchangeNeedsExtraTimeout = no
return
try
@_getCard().exchange_async(new ByteString(adpus[offset], HEX))
.then =>
if ignoreSW or @_getCard().SW == 0x9000
if @_exchangeNeedsExtraTimeout
deferred = Q.defer()
_.delay (=> deferred.resolve(@_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1))), ExchangeTimeout
deferred.promise()
else
@_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1)
else
@_exchangeNeedsExtraTimeout = no
throw new Error('Unexpected status ' + @_getCard().SW)
.fail (ex) =>
return @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) if offset is adpus.length - 1
@_exchangeNeedsExtraTimeout = no
throw new Error("ADPU sending failed " + ex)
catch ex
e ex
_findOriginalKey: (loadingArray, offset = 0) ->
throw new Error("Key not found") if offset >= loadingArray.length
@_getCard().exchange_async(new ByteString(loadingArray[offset][0], HEX)).then (result) =>
if @_getCard().SW == 0x9000
offset
else
@_findOriginalKey(loadingArray, offset + 1)
.fail (er) =>
e er
throw new Error("Communication Error")
_getCard: -> @_wallet?._lwCard.dongle.card
_notifyProgress: (state, offset, total) -> _.defer => @_onProgress?(state, offset, total) | 28776 | ledger.fup ?= {}
States =
Undefined: 0
Erasing: 1
LoadingOldApplication: 2
ReloadingBootloaderFromOs: 3
LoadingBootloader: 4
LoadingReloader: 5
LoadingBootloaderReloader: 6
LoadingOs: 7
InitializingOs: 8
Done: 9
Modes =
Os: 0
Bootloader: 1
Errors =
UnableToRetrieveVersion: ledger.errors.UnableToRetrieveVersion
InvalidSeedSize: ledger.errors.InvalidSeedSize
InvalidSeedFormat: ledger.errors.InvalidSeedFormat
InconsistentState: ledger.errors.InconsistentState
FailedToInitOs: ledger.errors.FailedToInitOs
CommunicationError: ledger.errors.CommunicationError
UnsupportedFirmware: ledger.errors.UnsupportedFirmware
ErrorDongleMayHaveASeed: ledger.errors.ErrorDongleMayHaveASeed
ErrorDueToCardPersonalization: ledger.errors.ErrorDueToCardPersonalization
HigherVersion: ledger.errors.HigherVersion
ExchangeTimeout = 200
###
FirmwareUpdateRequest performs dongle firmware updates. Once started it will listen the {WalletsManager} in order to catch
connected dongles and update them. Only one instance of FirmwareUpdateRequest should be alive at the same time. (This is
ensured by the {ledger.fup.FirmwareUpdater})
@event plug Emitted when the user must plug its dongle in
@event unplug Emitted when the user must unplug its dongle
@event stateChanged Emitted when the current state has changed. The event holds a data formatted like this: {oldState: ..., newState: ...}
@event setKeyCardSeed Emitted once the key card seed is provided
@event needsUserApproval Emitted once the request needs a user input to continue
@event erasureStep Emitted each time the erasure step is trying to reset the dongle. The event holds the number of remaining steps before erasing is done.
@event error Emitted once an error is throw. The event holds a data formatted like this: {cause: ...}
###
class ledger.fup.FirmwareUpdateRequest extends @EventEmitter
@States: States
@Modes: Modes
@Errors: Errors
@ExchangeTimeout: ExchangeTimeout
constructor: (firmwareUpdater) ->
@_id = _.uniqueId("fup")
@_fup = firmwareUpdater
@_keyCardSeed = null
@_currentState = States.Undefined
@_isNeedingUserApproval = no
@_lastMode = Modes.Os
@_lastVersion = undefined
@_isOsLoaded = no
@_approvedStates = []
@_stateCache = {} # This holds the state related data
@_exchangeNeedsExtraTimeout = no
@_isWaitForDongleSilent = no
@_isCancelled = no
@_eventHandler = []
@_logger = ledger.utils.Logger.getLoggerByTag('FirmwareUpdateRequest')
###
Stops all current tasks and listened events.
###
cancel: () ->
@off()
_(@_eventHandler).each ([object, event, handler]) -> object?.off?(event, handler)
@_onProgress = null
@_isCancelled = yes
@_fup._cancelRequest(this)
onProgress: (callback) -> @_onProgress = callback
hasGrantedErasurePermission: -> _.contains(@_approvedStates, "erasure")
###
Approves the current request state and continue its execution.
###
approveCurrentState: -> @_setIsNeedingUserApproval no
isNeedingUserApproval: -> @_isNeedingUserApproval
###
Gets the current dongle version
@return [String] The current dongle version
###
getDongleVersion: -> ledger.fup.utils.versionToString(@_dongleVersion)
###
Gets the version to update
@return [String] The target version
###
getTargetVersion: -> ledger.fup.utils.versionToString(ledger.fup.versions.Nano.CurrentVersion.Os)
###
Sets the key card seed used during the firmware update process. The seed must be a 32 characters string formatted as
an hexadecimal value.
@param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. '<KEY>'
@throw If the seed length is not 32 or if it is malformed
###
setKeyCardSeed: (keyCardSeed) ->
return if @_keyCardSeed? and @_currentState isnt States.Undefined
throw new Error(Errors.InvalidSeedSize) if not keyCardSeed? or keyCardSeed.length != 32
seed = Try => new ByteString(keyCardSeed, HEX)
throw new Error(Errors.InvalidSeedFormat) if seed.isFailure() or seed.getValue()?.length != 16
@_keyCardSeed = seed.getValue()
@emit "setKeyCardSeed"
@_handleCurrentState()
###
Checks if a given keycard seed is valid or not. The seed must be a 32 characters string formatted as
an hexadecimal value.
@param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. '<KEY>'
###
checkIfKeyCardSeedIsValid: (keyCardSeed) -> (Try => @_keyCardSeedToByteString(keyCardSeed)).isSuccess()
_keyCardSeedToByteString: (keyCardSeed, safe = no) ->
throw new Error(Errors.InvalidSeedSize) if not keyCardSeed? or keyCardSeed.length != 32
seed = Try => new ByteString(keyCardSeed, HEX)
throw new Error(Errors.InvalidSeedFormat) if seed.isFailure() or seed.getValue()?.length != 16
seed
###
Gets the current state.
@return [ledger.fup.FirmwareUpdateRequest.States] The current request state
###
getCurrentState: -> @_currentState
###
Checks if the current request has a key card seed or not.
@return [Boolean] Yes if the key card seed has been setup
###
hasKeyCardSeed: () -> if @_keyCardSeed? then yes else no
_waitForConnectedDongle: (callback = undefined, silent = no) ->
@_isWaitForDongleSilent = silent
return @_connectionCompletion if @_connectionCompletion?
completion = new CompletionClosure(callback)
registerWallet = (wallet) =>
@_lastMode = if wallet.isInBootloaderMode() then Modes.Bootloader else Modes.Os
@_wallet = wallet
handler = =>
@_setCurrentState(States.Undefined)
@_wallet = null
@_waitForConnectedDongle(null, @_isWaitForDongleSilent)
wallet.once 'disconnected', handler
@_eventHandler.push [wallet, 'disconnected', handler]
@_handleCurrentState()
completion.success(wallet)
[wallet] = ledger.app.walletsManager.getConnectedWallets()
try
unless wallet?
@_connectionCompletion = completion.readonly()
delay = if !silent then 0 else 1000
setTimeout (=> @emit 'plug' unless @_wallet?), delay
handler = (e, wallet) =>
@_connectionCompletion = null
registerWallet(wallet)
ledger.app.walletsManager.once 'connected', handler
@_eventHandler.push [ledger.app.walletsManager, 'connected', handler]
else
registerWallet(wallet)
catch er
e er
completion.readonly()
_waitForDisconnectDongle: (callback = undefined, silent = no) ->
return @_disconnectionCompletion if @_disconnectionCompletion?
completion = new CompletionClosure(callback)
if @_wallet?
@emit 'unplug' unless silent
@_disconnectionCompletion = completion.readonly()
@_wallet.once 'disconnected', =>
@_disconnectionCompletion = null
@_wallet = null
completion.success()
else
completion.success()
completion.readonly()
_waitForPowerCycle: (callback = undefined, silent = no) -> @_waitForDisconnectDongle(null, silent).then(=> @_waitForConnectedDongle(callback, silent).promise())
_handleCurrentState: () ->
# If there is no dongle wait for one
(return @_waitForConnectedDongle()) unless @_wallet?
@_logger.info("Handle current state", lastMode: @_lastMode, currentState: @_currentState)
# Otherwise handle the current by calling the right method depending on the last mode and the state
if @_lastMode is Modes.Os
switch @_currentState
when States.Undefined then do @_processInitStageOs
when States.ReloadingBootloaderFromOs then do @_processReloadBootloaderFromOs
when States.InitializingOs then do @_processInitOs
when States.Erasing then do @_processErasing
else @_failure(Errors.InconsistentState)
else
switch @_currentState
when States.Undefined then do @_processInitStageBootloader
when States.LoadingOs then do @_processLoadOs
when States.LoadingBootloader then do @_processLoadBootloader
when States.LoadingBootloaderReloader then do @_processLoadBootloaderReloader
else @_failure(Errors.InconsistentState)
_processInitStageOs: ->
@_logger.info("Process init stage OS")
@_wallet.getState (state) =>
if state isnt ledger.wallet.States.BLANK and state isnt ledger.wallet.States.FROZEN
@_setCurrentState(States.Erasing)
@_handleCurrentState()
else
@_fup.getFirmwareUpdateAvailability @_wallet, @_lastMode is Modes.Bootloader, no, (availability, error) =>
return @_failure(Errors.UnableToRetrieveVersion) if error?
@_dongleVersion = availability.dongleVersion
switch availability.result
when ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Overwrite
if @_isOsLoaded
@_setCurrentState(States.InitializingOs)
@_handleCurrentState()
else
@_wallet.isDongleBetaCertified (__, error) =>
@_setCurrentState(if error? and ledger.fup.versions.Nano.CurrentVersion.Overwrite is false then States.InitializingOs else States.ReloadingBootloaderFromOs)
@_handleCurrentState()
when ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Update, ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Higher
index = 0
while index < ledger.fup.updates.OS_INIT.length and !ledger.fup.utils.compareVersions(@_dongleVersion, ledger.fup.updates.OS_INIT[index][0]).eq()
index += 1
if index isnt ledger.fup.updates.OS_INIT.length
@_processLoadingScript(ledger.fup.updates.OS_INIT[index][1], States.LoadingOldApplication, true)
.then =>
@_setCurrentState(States.ReloadingBootloaderFromOs)
@_handleCurrentState()
.fail => @_failure(Errors.CommunicationError)
else
@_setCurrentState(States.ReloadingBootloaderFromOs)
@_handleCurrentState()
else return @_failure(Errors.HigherVersion)
_processErasing: ->
@_waitForUserApproval('erasure')
.then =>
unless @_stateCache.pincode?
getRandomChar = -> "0123456789".charAt(_.random(10))
@_stateCache.pincode = getRandomChar() + getRandomChar()
pincode = @_stateCache.pincode
@_wallet.unlockWithPinCode pincode, (isUnlocked, error) =>
@emit "erasureStep", if error?.retryCount? then error.retryCount else 3
@_waitForPowerCycle()
return
.fail ->
@_failure(Errors.CommunicationError)
.done()
_processInitOs: ->
index = 0
while index < ledger.fup.updates.OS_INIT.length and !ledger.fup.utils.compareVersions(ledger.fup.versions.Nano.CurrentVersion.Os, ledger.fup.updates.OS_INIT[index][0]).eq()
index += 1
currentInitScript = if ledger.fup.updates.OS_INIT[index]? then ledger.fup.updates.OS_INIT[index][1] else _(ledger.fup.updates.OS_INIT).last()[1]
moddedInitScript = []
for i in [0...currentInitScript.length]
moddedInitScript.push currentInitScript[i]
if i is currentInitScript.length - 2
moddedInitScript.push "D026000011" + "04" + @_keyCardSeed.toString(HEX)
@_processLoadingScript moddedInitScript, States.InitializingOs, yes
.then =>
@_success()
@_isOsLoaded = no
.fail =>
@_failure(Errors.FailedToInitOs)
_processReloadBootloaderFromOs: ->
@_removeUserApproval('erasure')
@_waitForUserApproval('reloadbootloader')
.then =>
@_removeUserApproval('reloadbootloader')
index = 0
while index < ledger.fup.updates.BL_RELOADER.length and !ledger.fup.utils.compareVersions(@_dongleVersion, ledger.fup.updates.BL_RELOADER[index][0]).eq()
index += 1
if index is ledger.fup.updates.BL_RELOADER.length
@_failure(Errors.UnsupportedFirmware)
return
@_isWaitForDongleSilent = yes
@_processLoadingScript ledger.fup.updates.BL_RELOADER[index][1], States.ReloadingBootloaderFromOs
.then =>
@_waitForPowerCycle(null, yes)
.fail (e) =>
switch @_getCard().SW
when 0x6985 then @_failure(Errors.ErrorDongleMayHaveASeed)
when 0x6faa then @_failure(Errors.ErrorDueToCardPersonalization)
else @_failure(Errors.CommunicationError)
@_waitForDisconnectDongle()
_processInitStageBootloader: ->
@_lastVersion = null
@_wallet.getRawFirmwareVersion yes, yes, (version, error) =>
return @_failure(Errors.UnableToRetrieveVersion) if error?
@_lastVersion = version
if ledger.fup.utils.compareVersions(version, ledger.fup.versions.Nano.CurrentVersion.Bootloader).eq()
@_setCurrentState(States.LoadingOs)
@_handleCurrentState()
else if ledger.fup.utils.compareVersions(version, ledger.fup.versions.Nano.CurrentVersion.Reloader).eq()
@_setCurrentState(States.LoadingBootloader)
@_handleCurrentState()
else
SEND_RACE_BL = (1 << 16) + (3 << 8) + (11)
@_exchangeNeedsExtraTimeout = version[1] < SEND_RACE_BL
@_setCurrentState(States.LoadingBootloaderReloader)
@_handleCurrentState()
_processLoadOs: ->
@_isOsLoaded = no
@_findOriginalKey(ledger.fup.updates.OS_LOADER).then (offset) =>
@_isWaitForDongleSilent = yes
@_processLoadingScript(ledger.fup.updates.OS_LOADER[offset], States.LoadingOs).then (result) =>
@_isOsLoaded = yes
_.delay (=> @_waitForPowerCycle(null, yes)), 200
.fail (e) =>
@_isWaitForDongleSilent = no
@_setCurrentState(States.Undefined)
@_failure(Errors.CommunicationError)
.fail (e) =>
@_isWaitForDongleSilent = no
@_setCurrentState(States.Undefined)
_processLoadBootloader: ->
@_findOriginalKey(ledger.fup.updates.BL_LOADER).then (offset) =>
@_processLoadingScript(ledger.fup.updates.BL_LOADER[offset], States.LoadingBootloader)
.then => @_waitForPowerCycle(null, yes)
.fail (ex) =>
@_failure(Errors.CommunicationError)
_processLoadBootloaderReloader: ->
@_findOriginalKey(ledger.fup.updates.RELOADER_FROM_BL).then (offset) =>
@_processLoadingScript(ledger.fup.updates.RELOADER_FROM_BL[offset], States.LoadingBootloaderReloader)
.then => @_waitForPowerCycle(null, yes)
.fail (ex) =>
@_failure(ledger.errors.CommunicationError)
_getVersion: (forceBl, callback) -> @_wallet.getRawFirmwareVersion(@_lastMode is Modes.Bootloader, forceBl, callback)
_failure: (reason) ->
@emit "error", cause: new ledger.StandardError(reason)
@_waitForPowerCycle()
return
_success: ->
@_setCurrentState(States.Done)
_.defer => @cancel()
_attemptToFailDonglePinCode: (pincode) ->
deferred = Q.defer()
@_wallet.unlockWithPinCode pincode, (isUnlocked, error) =>
if isUnlocked or error.code isnt ledger.errors.WrongPinCode
@emit "erasureStep", 3
@_waitForPowerCycle().then -> deferred.reject()
else
@emit "erasureStep", error.retryCount
@_waitForPowerCycle()
.then =>
@_wallet.getState (state) =>
deferred.resolve(state is ledger.wallet.States.BLANK or state is ledger.wallet.States.FROZEN)
deferred.promise
_setCurrentState: (newState) ->
oldState = @_currentState
@_currentState = newState
@emit 'stateChanged', {oldState, newState}
_setIsNeedingUserApproval: (value) ->
if @_isNeedingUserApproval isnt value
@_isNeedingUserApproval = value
if @_isNeedingUserApproval is true
@emit 'needsUserApproval'
@_deferredApproval = Q.defer()
else
defferedApproval = @_deferredApproval
@_deferredApproval = null
defferedApproval.resolve()
return
_cancelApproval: ->
if @_isNeedingUserApproval
@_isNeedingUserApproval = no
defferedApproval = @_deferredApproval
@_deferredApproval = null
defferedApproval.reject("cancelled")
_waitForUserApproval: (approvalName) ->
if _.contains(@_approvedStates, approvalName)
deferred = Q.defer()
deferred.resolve()
deferred.promise
else
@_setIsNeedingUserApproval yes
@_deferredApproval.promise.then => @_approvedStates.push approvalName
_removeUserApproval: (approvalName) ->
@_approvedStates = _(@_approvedStates).without(approvalName)
return
_processLoadingScript: (adpus, state, ignoreSW, offset = 0) ->
completion = new CompletionClosure()
@_doProcessLoadingScript(adpus, state, ignoreSW, offset).then(-> completion.success()).fail((ex) -> completion.failure(ex))
completion.readonly()
_doProcessLoadingScript: (adpus, state, ignoreSW, offset) ->
@_notifyProgress(state, offset, adpus.length)
if offset >= adpus.length
@_exchangeNeedsExtraTimeout = no
return
try
@_getCard().exchange_async(new ByteString(adpus[offset], HEX))
.then =>
if ignoreSW or @_getCard().SW == 0x9000
if @_exchangeNeedsExtraTimeout
deferred = Q.defer()
_.delay (=> deferred.resolve(@_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1))), ExchangeTimeout
deferred.promise()
else
@_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1)
else
@_exchangeNeedsExtraTimeout = no
throw new Error('Unexpected status ' + @_getCard().SW)
.fail (ex) =>
return @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) if offset is adpus.length - 1
@_exchangeNeedsExtraTimeout = no
throw new Error("ADPU sending failed " + ex)
catch ex
e ex
_findOriginalKey: (loadingArray, offset = 0) ->
throw new Error("Key not found") if offset >= loadingArray.length
@_getCard().exchange_async(new ByteString(loadingArray[offset][0], HEX)).then (result) =>
if @_getCard().SW == 0x9000
offset
else
@_findOriginalKey(loadingArray, offset + 1)
.fail (er) =>
e er
throw new Error("Communication Error")
_getCard: -> @_wallet?._lwCard.dongle.card
_notifyProgress: (state, offset, total) -> _.defer => @_onProgress?(state, offset, total) | true | ledger.fup ?= {}
States =
Undefined: 0
Erasing: 1
LoadingOldApplication: 2
ReloadingBootloaderFromOs: 3
LoadingBootloader: 4
LoadingReloader: 5
LoadingBootloaderReloader: 6
LoadingOs: 7
InitializingOs: 8
Done: 9
Modes =
Os: 0
Bootloader: 1
Errors =
UnableToRetrieveVersion: ledger.errors.UnableToRetrieveVersion
InvalidSeedSize: ledger.errors.InvalidSeedSize
InvalidSeedFormat: ledger.errors.InvalidSeedFormat
InconsistentState: ledger.errors.InconsistentState
FailedToInitOs: ledger.errors.FailedToInitOs
CommunicationError: ledger.errors.CommunicationError
UnsupportedFirmware: ledger.errors.UnsupportedFirmware
ErrorDongleMayHaveASeed: ledger.errors.ErrorDongleMayHaveASeed
ErrorDueToCardPersonalization: ledger.errors.ErrorDueToCardPersonalization
HigherVersion: ledger.errors.HigherVersion
ExchangeTimeout = 200
###
FirmwareUpdateRequest performs dongle firmware updates. Once started it will listen the {WalletsManager} in order to catch
connected dongles and update them. Only one instance of FirmwareUpdateRequest should be alive at the same time. (This is
ensured by the {ledger.fup.FirmwareUpdater})
@event plug Emitted when the user must plug its dongle in
@event unplug Emitted when the user must unplug its dongle
@event stateChanged Emitted when the current state has changed. The event holds a data formatted like this: {oldState: ..., newState: ...}
@event setKeyCardSeed Emitted once the key card seed is provided
@event needsUserApproval Emitted once the request needs a user input to continue
@event erasureStep Emitted each time the erasure step is trying to reset the dongle. The event holds the number of remaining steps before erasing is done.
@event error Emitted once an error is throw. The event holds a data formatted like this: {cause: ...}
###
class ledger.fup.FirmwareUpdateRequest extends @EventEmitter
@States: States
@Modes: Modes
@Errors: Errors
@ExchangeTimeout: ExchangeTimeout
constructor: (firmwareUpdater) ->
@_id = _.uniqueId("fup")
@_fup = firmwareUpdater
@_keyCardSeed = null
@_currentState = States.Undefined
@_isNeedingUserApproval = no
@_lastMode = Modes.Os
@_lastVersion = undefined
@_isOsLoaded = no
@_approvedStates = []
@_stateCache = {} # This holds the state related data
@_exchangeNeedsExtraTimeout = no
@_isWaitForDongleSilent = no
@_isCancelled = no
@_eventHandler = []
@_logger = ledger.utils.Logger.getLoggerByTag('FirmwareUpdateRequest')
###
Stops all current tasks and listened events.
###
cancel: () ->
@off()
_(@_eventHandler).each ([object, event, handler]) -> object?.off?(event, handler)
@_onProgress = null
@_isCancelled = yes
@_fup._cancelRequest(this)
onProgress: (callback) -> @_onProgress = callback
hasGrantedErasurePermission: -> _.contains(@_approvedStates, "erasure")
###
Approves the current request state and continue its execution.
###
approveCurrentState: -> @_setIsNeedingUserApproval no
isNeedingUserApproval: -> @_isNeedingUserApproval
###
Gets the current dongle version
@return [String] The current dongle version
###
getDongleVersion: -> ledger.fup.utils.versionToString(@_dongleVersion)
###
Gets the version to update
@return [String] The target version
###
getTargetVersion: -> ledger.fup.utils.versionToString(ledger.fup.versions.Nano.CurrentVersion.Os)
###
Sets the key card seed used during the firmware update process. The seed must be a 32 characters string formatted as
an hexadecimal value.
@param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. 'PI:KEY:<KEY>END_PI'
@throw If the seed length is not 32 or if it is malformed
###
setKeyCardSeed: (keyCardSeed) ->
return if @_keyCardSeed? and @_currentState isnt States.Undefined
throw new Error(Errors.InvalidSeedSize) if not keyCardSeed? or keyCardSeed.length != 32
seed = Try => new ByteString(keyCardSeed, HEX)
throw new Error(Errors.InvalidSeedFormat) if seed.isFailure() or seed.getValue()?.length != 16
@_keyCardSeed = seed.getValue()
@emit "setKeyCardSeed"
@_handleCurrentState()
###
Checks if a given keycard seed is valid or not. The seed must be a 32 characters string formatted as
an hexadecimal value.
@param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. 'PI:KEY:<KEY>END_PI'
###
checkIfKeyCardSeedIsValid: (keyCardSeed) -> (Try => @_keyCardSeedToByteString(keyCardSeed)).isSuccess()
_keyCardSeedToByteString: (keyCardSeed, safe = no) ->
throw new Error(Errors.InvalidSeedSize) if not keyCardSeed? or keyCardSeed.length != 32
seed = Try => new ByteString(keyCardSeed, HEX)
throw new Error(Errors.InvalidSeedFormat) if seed.isFailure() or seed.getValue()?.length != 16
seed
###
Gets the current state.
@return [ledger.fup.FirmwareUpdateRequest.States] The current request state
###
getCurrentState: -> @_currentState
###
Checks if the current request has a key card seed or not.
@return [Boolean] Yes if the key card seed has been setup
###
hasKeyCardSeed: () -> if @_keyCardSeed? then yes else no
_waitForConnectedDongle: (callback = undefined, silent = no) ->
@_isWaitForDongleSilent = silent
return @_connectionCompletion if @_connectionCompletion?
completion = new CompletionClosure(callback)
registerWallet = (wallet) =>
@_lastMode = if wallet.isInBootloaderMode() then Modes.Bootloader else Modes.Os
@_wallet = wallet
handler = =>
@_setCurrentState(States.Undefined)
@_wallet = null
@_waitForConnectedDongle(null, @_isWaitForDongleSilent)
wallet.once 'disconnected', handler
@_eventHandler.push [wallet, 'disconnected', handler]
@_handleCurrentState()
completion.success(wallet)
[wallet] = ledger.app.walletsManager.getConnectedWallets()
try
unless wallet?
@_connectionCompletion = completion.readonly()
delay = if !silent then 0 else 1000
setTimeout (=> @emit 'plug' unless @_wallet?), delay
handler = (e, wallet) =>
@_connectionCompletion = null
registerWallet(wallet)
ledger.app.walletsManager.once 'connected', handler
@_eventHandler.push [ledger.app.walletsManager, 'connected', handler]
else
registerWallet(wallet)
catch er
e er
completion.readonly()
_waitForDisconnectDongle: (callback = undefined, silent = no) ->
return @_disconnectionCompletion if @_disconnectionCompletion?
completion = new CompletionClosure(callback)
if @_wallet?
@emit 'unplug' unless silent
@_disconnectionCompletion = completion.readonly()
@_wallet.once 'disconnected', =>
@_disconnectionCompletion = null
@_wallet = null
completion.success()
else
completion.success()
completion.readonly()
_waitForPowerCycle: (callback = undefined, silent = no) -> @_waitForDisconnectDongle(null, silent).then(=> @_waitForConnectedDongle(callback, silent).promise())
_handleCurrentState: () ->
# If there is no dongle wait for one
(return @_waitForConnectedDongle()) unless @_wallet?
@_logger.info("Handle current state", lastMode: @_lastMode, currentState: @_currentState)
# Otherwise handle the current by calling the right method depending on the last mode and the state
if @_lastMode is Modes.Os
switch @_currentState
when States.Undefined then do @_processInitStageOs
when States.ReloadingBootloaderFromOs then do @_processReloadBootloaderFromOs
when States.InitializingOs then do @_processInitOs
when States.Erasing then do @_processErasing
else @_failure(Errors.InconsistentState)
else
switch @_currentState
when States.Undefined then do @_processInitStageBootloader
when States.LoadingOs then do @_processLoadOs
when States.LoadingBootloader then do @_processLoadBootloader
when States.LoadingBootloaderReloader then do @_processLoadBootloaderReloader
else @_failure(Errors.InconsistentState)
_processInitStageOs: ->
@_logger.info("Process init stage OS")
@_wallet.getState (state) =>
if state isnt ledger.wallet.States.BLANK and state isnt ledger.wallet.States.FROZEN
@_setCurrentState(States.Erasing)
@_handleCurrentState()
else
@_fup.getFirmwareUpdateAvailability @_wallet, @_lastMode is Modes.Bootloader, no, (availability, error) =>
return @_failure(Errors.UnableToRetrieveVersion) if error?
@_dongleVersion = availability.dongleVersion
switch availability.result
when ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Overwrite
if @_isOsLoaded
@_setCurrentState(States.InitializingOs)
@_handleCurrentState()
else
@_wallet.isDongleBetaCertified (__, error) =>
@_setCurrentState(if error? and ledger.fup.versions.Nano.CurrentVersion.Overwrite is false then States.InitializingOs else States.ReloadingBootloaderFromOs)
@_handleCurrentState()
when ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Update, ledger.fup.FirmwareUpdater.FirmwareAvailabilityResult.Higher
index = 0
while index < ledger.fup.updates.OS_INIT.length and !ledger.fup.utils.compareVersions(@_dongleVersion, ledger.fup.updates.OS_INIT[index][0]).eq()
index += 1
if index isnt ledger.fup.updates.OS_INIT.length
@_processLoadingScript(ledger.fup.updates.OS_INIT[index][1], States.LoadingOldApplication, true)
.then =>
@_setCurrentState(States.ReloadingBootloaderFromOs)
@_handleCurrentState()
.fail => @_failure(Errors.CommunicationError)
else
@_setCurrentState(States.ReloadingBootloaderFromOs)
@_handleCurrentState()
else return @_failure(Errors.HigherVersion)
_processErasing: ->
@_waitForUserApproval('erasure')
.then =>
unless @_stateCache.pincode?
getRandomChar = -> "0123456789".charAt(_.random(10))
@_stateCache.pincode = getRandomChar() + getRandomChar()
pincode = @_stateCache.pincode
@_wallet.unlockWithPinCode pincode, (isUnlocked, error) =>
@emit "erasureStep", if error?.retryCount? then error.retryCount else 3
@_waitForPowerCycle()
return
.fail ->
@_failure(Errors.CommunicationError)
.done()
_processInitOs: ->
index = 0
while index < ledger.fup.updates.OS_INIT.length and !ledger.fup.utils.compareVersions(ledger.fup.versions.Nano.CurrentVersion.Os, ledger.fup.updates.OS_INIT[index][0]).eq()
index += 1
currentInitScript = if ledger.fup.updates.OS_INIT[index]? then ledger.fup.updates.OS_INIT[index][1] else _(ledger.fup.updates.OS_INIT).last()[1]
moddedInitScript = []
for i in [0...currentInitScript.length]
moddedInitScript.push currentInitScript[i]
if i is currentInitScript.length - 2
moddedInitScript.push "D026000011" + "04" + @_keyCardSeed.toString(HEX)
@_processLoadingScript moddedInitScript, States.InitializingOs, yes
.then =>
@_success()
@_isOsLoaded = no
.fail =>
@_failure(Errors.FailedToInitOs)
_processReloadBootloaderFromOs: ->
@_removeUserApproval('erasure')
@_waitForUserApproval('reloadbootloader')
.then =>
@_removeUserApproval('reloadbootloader')
index = 0
while index < ledger.fup.updates.BL_RELOADER.length and !ledger.fup.utils.compareVersions(@_dongleVersion, ledger.fup.updates.BL_RELOADER[index][0]).eq()
index += 1
if index is ledger.fup.updates.BL_RELOADER.length
@_failure(Errors.UnsupportedFirmware)
return
@_isWaitForDongleSilent = yes
@_processLoadingScript ledger.fup.updates.BL_RELOADER[index][1], States.ReloadingBootloaderFromOs
.then =>
@_waitForPowerCycle(null, yes)
.fail (e) =>
switch @_getCard().SW
when 0x6985 then @_failure(Errors.ErrorDongleMayHaveASeed)
when 0x6faa then @_failure(Errors.ErrorDueToCardPersonalization)
else @_failure(Errors.CommunicationError)
@_waitForDisconnectDongle()
_processInitStageBootloader: ->
@_lastVersion = null
@_wallet.getRawFirmwareVersion yes, yes, (version, error) =>
return @_failure(Errors.UnableToRetrieveVersion) if error?
@_lastVersion = version
if ledger.fup.utils.compareVersions(version, ledger.fup.versions.Nano.CurrentVersion.Bootloader).eq()
@_setCurrentState(States.LoadingOs)
@_handleCurrentState()
else if ledger.fup.utils.compareVersions(version, ledger.fup.versions.Nano.CurrentVersion.Reloader).eq()
@_setCurrentState(States.LoadingBootloader)
@_handleCurrentState()
else
SEND_RACE_BL = (1 << 16) + (3 << 8) + (11)
@_exchangeNeedsExtraTimeout = version[1] < SEND_RACE_BL
@_setCurrentState(States.LoadingBootloaderReloader)
@_handleCurrentState()
_processLoadOs: ->
@_isOsLoaded = no
@_findOriginalKey(ledger.fup.updates.OS_LOADER).then (offset) =>
@_isWaitForDongleSilent = yes
@_processLoadingScript(ledger.fup.updates.OS_LOADER[offset], States.LoadingOs).then (result) =>
@_isOsLoaded = yes
_.delay (=> @_waitForPowerCycle(null, yes)), 200
.fail (e) =>
@_isWaitForDongleSilent = no
@_setCurrentState(States.Undefined)
@_failure(Errors.CommunicationError)
.fail (e) =>
@_isWaitForDongleSilent = no
@_setCurrentState(States.Undefined)
_processLoadBootloader: ->
@_findOriginalKey(ledger.fup.updates.BL_LOADER).then (offset) =>
@_processLoadingScript(ledger.fup.updates.BL_LOADER[offset], States.LoadingBootloader)
.then => @_waitForPowerCycle(null, yes)
.fail (ex) =>
@_failure(Errors.CommunicationError)
_processLoadBootloaderReloader: ->
@_findOriginalKey(ledger.fup.updates.RELOADER_FROM_BL).then (offset) =>
@_processLoadingScript(ledger.fup.updates.RELOADER_FROM_BL[offset], States.LoadingBootloaderReloader)
.then => @_waitForPowerCycle(null, yes)
.fail (ex) =>
@_failure(ledger.errors.CommunicationError)
_getVersion: (forceBl, callback) -> @_wallet.getRawFirmwareVersion(@_lastMode is Modes.Bootloader, forceBl, callback)
_failure: (reason) ->
@emit "error", cause: new ledger.StandardError(reason)
@_waitForPowerCycle()
return
_success: ->
@_setCurrentState(States.Done)
_.defer => @cancel()
_attemptToFailDonglePinCode: (pincode) ->
deferred = Q.defer()
@_wallet.unlockWithPinCode pincode, (isUnlocked, error) =>
if isUnlocked or error.code isnt ledger.errors.WrongPinCode
@emit "erasureStep", 3
@_waitForPowerCycle().then -> deferred.reject()
else
@emit "erasureStep", error.retryCount
@_waitForPowerCycle()
.then =>
@_wallet.getState (state) =>
deferred.resolve(state is ledger.wallet.States.BLANK or state is ledger.wallet.States.FROZEN)
deferred.promise
_setCurrentState: (newState) ->
oldState = @_currentState
@_currentState = newState
@emit 'stateChanged', {oldState, newState}
_setIsNeedingUserApproval: (value) ->
if @_isNeedingUserApproval isnt value
@_isNeedingUserApproval = value
if @_isNeedingUserApproval is true
@emit 'needsUserApproval'
@_deferredApproval = Q.defer()
else
defferedApproval = @_deferredApproval
@_deferredApproval = null
defferedApproval.resolve()
return
_cancelApproval: ->
if @_isNeedingUserApproval
@_isNeedingUserApproval = no
defferedApproval = @_deferredApproval
@_deferredApproval = null
defferedApproval.reject("cancelled")
_waitForUserApproval: (approvalName) ->
if _.contains(@_approvedStates, approvalName)
deferred = Q.defer()
deferred.resolve()
deferred.promise
else
@_setIsNeedingUserApproval yes
@_deferredApproval.promise.then => @_approvedStates.push approvalName
_removeUserApproval: (approvalName) ->
@_approvedStates = _(@_approvedStates).without(approvalName)
return
_processLoadingScript: (adpus, state, ignoreSW, offset = 0) ->
completion = new CompletionClosure()
@_doProcessLoadingScript(adpus, state, ignoreSW, offset).then(-> completion.success()).fail((ex) -> completion.failure(ex))
completion.readonly()
_doProcessLoadingScript: (adpus, state, ignoreSW, offset) ->
@_notifyProgress(state, offset, adpus.length)
if offset >= adpus.length
@_exchangeNeedsExtraTimeout = no
return
try
@_getCard().exchange_async(new ByteString(adpus[offset], HEX))
.then =>
if ignoreSW or @_getCard().SW == 0x9000
if @_exchangeNeedsExtraTimeout
deferred = Q.defer()
_.delay (=> deferred.resolve(@_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1))), ExchangeTimeout
deferred.promise()
else
@_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1)
else
@_exchangeNeedsExtraTimeout = no
throw new Error('Unexpected status ' + @_getCard().SW)
.fail (ex) =>
return @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) if offset is adpus.length - 1
@_exchangeNeedsExtraTimeout = no
throw new Error("ADPU sending failed " + ex)
catch ex
e ex
_findOriginalKey: (loadingArray, offset = 0) ->
throw new Error("Key not found") if offset >= loadingArray.length
@_getCard().exchange_async(new ByteString(loadingArray[offset][0], HEX)).then (result) =>
if @_getCard().SW == 0x9000
offset
else
@_findOriginalKey(loadingArray, offset + 1)
.fail (er) =>
e er
throw new Error("Communication Error")
_getCard: -> @_wallet?._lwCard.dongle.card
_notifyProgress: (state, offset, total) -> _.defer => @_onProgress?(state, offset, total) |
[
{
"context": " type: 'agent'\n bucket: 'agent'\n key: '7ec23d7d-9522-478c-97a4-2f577335e023'\n content:\n content_type: 'applicatio",
"end": 1092,
"score": 0.9997471570968628,
"start": 1056,
"tag": "KEY",
"value": "7ec23d7d-9522-478c-97a4-2f577335e023"
},
{
"context": "\n key: 'email_bin'\n value: 'isaac.johnston@joukou.com'\n }\n ]\n value: JSON.string",
"end": 1255,
"score": 0.9999229311943054,
"start": 1230,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": "\n value: JSON.stringify(\n email: 'isaac.johnston@joukou.com'\n roles: [ 'operator' ]\n passwo",
"end": 1353,
"score": 0.9999281764030457,
"start": 1328,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": " roles: [ 'operator' ]\n password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG' # \"password\" in bcrypt w/ 10 rounds\n )\n ",
"end": 1468,
"score": 0.9994821548461914,
"start": 1407,
"tag": "PASSWORD",
"value": "'$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG"
},
{
"context": " type: 'agent'\n bucket: 'agent'\n key: '7ec23d7d-9522-478c-97a4-2f577335e023'\n , ( err, reply ) -",
"end": 1652,
"score": 0.9997114539146423,
"start": 1642,
"tag": "KEY",
"value": "7ec23d7d-9"
},
{
"context": "one ) ->\n AgentModel.create(\n email: 'ben.brabant@joukou.com'\n password: 'password'\n )\n .then",
"end": 1917,
"score": 0.9999273419380188,
"start": 1895,
"tag": "EMAIL",
"value": "ben.brabant@joukou.com"
},
{
"context": "mail: 'ben.brabant@joukou.com'\n password: 'password'\n )\n .then( ( agent ) ->\n { emai",
"end": 1946,
"score": 0.999235987663269,
"start": 1938,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "} = agent.getValue()\n email.should.equal( 'ben.brabant@joukou.com' )\n bcrypt.compareSync( 'password', passwo",
"end": 2086,
"score": 0.9999300837516785,
"start": 2064,
"tag": "EMAIL",
"value": "ben.brabant@joukou.com"
},
{
"context": "one ) ->\n AgentModel.create(\n email: 'ben.brabant@joukou.com'\n password: 'password'\n )\n .then",
"end": 2507,
"score": 0.9999244213104248,
"start": 2485,
"tag": "EMAIL",
"value": "ben.brabant@joukou.com"
},
{
"context": "mail: 'ben.brabant@joukou.com'\n password: 'password'\n )\n .then( ( agent ) ->\n agent.",
"end": 2536,
"score": 0.9992092847824097,
"start": 2528,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "( agent ) ->\n AgentModel.retrieveByEmail( 'ben.brabant@joukou.com' )\n )\n .then( ( agent ) ->\n pbc.",
"end": 2686,
"score": 0.9999281764030457,
"start": 2664,
"tag": "EMAIL",
"value": "ben.brabant@joukou.com"
},
{
"context": "oes exist', ->\n AgentModel.retrieveByEmail( 'isaac.johnston@joukou.com' ).then( ( agent ) ->\n agent.getValue().sh",
"end": 3287,
"score": 0.9999297261238098,
"start": 3262,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": "t.getValue().should.deep.equal(\n email: 'isaac.johnston@joukou.com'\n roles: [ 'operator' ]\n passwo",
"end": 3397,
"score": 0.9999281764030457,
"start": 3372,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": " roles: [ 'operator' ]\n password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG'\n )\n )\n\n describe '::verifyPassword(",
"end": 3512,
"score": 0.9995075464248657,
"start": 3451,
"tag": "PASSWORD",
"value": "'$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG"
},
{
"context": "not match', ->\n AgentModel.retrieveByEmail( 'isaac.johnston@joukou.com' ).then( ( agent ) ->\n agent.verifyPasswor",
"end": 3723,
"score": 0.9999268054962158,
"start": 3698,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": "oes match', ->\n AgentModel.retrieveByEmail( 'isaac.johnston@joukou.com' ).then( ( agent ) ->\n agent.verifyPasswor",
"end": 3969,
"score": 0.9999287724494934,
"start": 3944,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": "then( ( agent ) ->\n agent.verifyPassword( 'password' ).should.eventually.be.equal( true )\n )\n\n ",
"end": 4031,
"score": 0.9903057217597961,
"start": 4023,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " new AgentModel(\n value:\n email: 'isaac.johnston@joukou.com'\n roles: [ 'operator' ]\n passwo",
"end": 4594,
"score": 0.9999316334724426,
"start": 4569,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": " roles: [ 'operator' ]\n password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG'\n )\n instance.getRepresentation().shoul",
"end": 4709,
"score": 0.9994959235191345,
"start": 4648,
"tag": "PASSWORD",
"value": "'$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG"
},
{
"context": "presentation().should.deep.equal(\n email: 'isaac.johnston@joukou.com'\n roles: [ 'operator' ]\n )\n\n describ",
"end": 4814,
"score": 0.9999322891235352,
"start": 4789,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": " new AgentModel(\n value:\n email: 'isaac.johnston@joukou.com'\n roles: [ 'operator' ]\n passwo",
"end": 5154,
"score": 0.9999308586120605,
"start": 5129,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": " roles: [ 'operator' ]\n password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG'\n )\n instance.getEmail().should.equal( ",
"end": 5269,
"score": 0.9994842410087585,
"start": 5208,
"tag": "PASSWORD",
"value": "'$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG"
},
{
"context": "\n )\n instance.getEmail().should.equal( 'isaac.johnston@joukou.com' ) \n\n describe '::getRoles', ->\n\n specify",
"end": 5345,
"score": 0.9999313950538635,
"start": 5320,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": " new AgentModel(\n value:\n email: 'isaac.johnston@joukou.com'\n roles: [ 'operator' ]\n passwo",
"end": 5663,
"score": 0.9999306201934814,
"start": 5638,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": " roles: [ 'operator' ]\n password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG'\n )\n instance.getRoles().should.deep.eq",
"end": 5778,
"score": 0.9994917511940002,
"start": 5717,
"tag": "PASSWORD",
"value": "'$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG"
},
{
"context": "ce = new AgentModel(\n value:\n email: 'isaac.johnston@joukou.com'\n roles: [ 'operator', 'administrator' ]\n ",
"end": 5990,
"score": 0.9999291896820068,
"start": 5965,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
},
{
"context": " [ 'operator', 'administrator' ]\n password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG' \n )\n\n specify 'is defined', ->\n ",
"end": 6118,
"score": 0.9994850754737854,
"start": 6057,
"tag": "PASSWORD",
"value": "'$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG"
}
] | test/agent/Model.coffee | joukou/joukou-api | 0 | ###*
Copyright 2014 Joukou Ltd
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.
###
assert = require( 'assert' )
chai = require( 'chai' )
chaiAsPromised = require( 'chai-as-promised' )
chai.use( chaiAsPromised )
should = chai.should()
bcrypt = require( 'bcrypt' )
AgentModel = require( '../../dist/agent/Model' )
{ NotFoundError } = require( 'restify' )
pbc = require( '../../dist/riak/pbc' )
describe 'agent/Model', ->
before ( done ) ->
pbc.put(
type: 'agent'
bucket: 'agent'
key: '7ec23d7d-9522-478c-97a4-2f577335e023'
content:
content_type: 'application/json'
indexes: [
{
key: 'email_bin'
value: 'isaac.johnston@joukou.com'
}
]
value: JSON.stringify(
email: 'isaac.johnston@joukou.com'
roles: [ 'operator' ]
password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG' # "password" in bcrypt w/ 10 rounds
)
, ( err, reply ) -> done( err ) )
after ( done ) ->
pbc.del(
type: 'agent'
bucket: 'agent'
key: '7ec23d7d-9522-478c-97a4-2f577335e023'
, ( err, reply ) -> done( err ) )
specify 'is defined', ->
should.exist( AgentModel )
describe '.create( )', ->
specify 'creates a new agent', ( done ) ->
AgentModel.create(
email: 'ben.brabant@joukou.com'
password: 'password'
)
.then( ( agent ) ->
{ email, name, password } = agent.getValue()
email.should.equal( 'ben.brabant@joukou.com' )
bcrypt.compareSync( 'password', password ).should.be.true
pbc.del(
type: 'agent'
bucket: 'agent'
key: agent.getKey()
, ( err, reply ) -> done( err ) )
)
.fail( ( err ) -> done( err ) )
describe '::save( )', ->
specify 'persists an agent model instance to Basho Riak', ( done ) ->
AgentModel.create(
email: 'ben.brabant@joukou.com'
password: 'password'
)
.then( ( agent ) ->
agent.save()
)
.then( ( agent ) ->
AgentModel.retrieveByEmail( 'ben.brabant@joukou.com' )
)
.then( ( agent ) ->
pbc.del(
type: 'agent'
bucket: 'agent'
key: agent.getKey()
, ( err, reply ) -> done( err ) )
)
.fail( ( err ) -> done( err ) )
describe '.retrieveByEmail( email )', ->
specify 'is eventually rejected with a NotFoundError if the email does not exist', ->
AgentModel.retrieveByEmail( 'bogus' ).should.eventually.be.rejectedWith( NotFoundError )
specify 'is eventually resolved with a Model instance if the email does exist', ->
AgentModel.retrieveByEmail( 'isaac.johnston@joukou.com' ).then( ( agent ) ->
agent.getValue().should.deep.equal(
email: 'isaac.johnston@joukou.com'
roles: [ 'operator' ]
password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG'
)
)
describe '::verifyPassword( password )', ->
specify 'is eventually resolved with false if the password does not match', ->
AgentModel.retrieveByEmail( 'isaac.johnston@joukou.com' ).then( ( agent ) ->
agent.verifyPassword( 'bogus' ).should.eventually.be.equal( false )
)
specify 'is eventually resolved with true if the password does match', ->
AgentModel.retrieveByEmail( 'isaac.johnston@joukou.com' ).then( ( agent ) ->
agent.verifyPassword( 'password' ).should.eventually.be.equal( true )
)
describe '.retrieveByEmail( email )', ->
specify 'is defined', ->
should.exist( AgentModel.retrieveByEmail )
AgentModel.retrieveByEmail.should.be.a( 'function' )
describe '::getRepresentation', ->
specify 'is defined', ->
should.exist( AgentModel::getRepresentation )
AgentModel::getRepresentation.should.be.a( 'function' )
specify 'is a representation of the model instance', ->
instance = new AgentModel(
value:
email: 'isaac.johnston@joukou.com'
roles: [ 'operator' ]
password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG'
)
instance.getRepresentation().should.deep.equal(
email: 'isaac.johnston@joukou.com'
roles: [ 'operator' ]
)
describe '::getEmail', ->
specify 'is defined', ->
should.exist( AgentModel::getEmail )
AgentModel::getEmail.should.be.a( 'function' )
specify 'is the email of the model instance', ->
instance = new AgentModel(
value:
email: 'isaac.johnston@joukou.com'
roles: [ 'operator' ]
password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG'
)
instance.getEmail().should.equal( 'isaac.johnston@joukou.com' )
describe '::getRoles', ->
specify 'is defined', ->
should.exist( AgentModel::getRoles )
AgentModel::getRoles.should.be.a( 'function' )
specify 'is the array of roles of the model instance', ->
instance = new AgentModel(
value:
email: 'isaac.johnston@joukou.com'
roles: [ 'operator' ]
password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG'
)
instance.getRoles().should.deep.equal( [ 'operator' ] )
describe '::hasSomeRoles( roles )', ->
hasSomeRolesInstance = new AgentModel(
value:
email: 'isaac.johnston@joukou.com'
roles: [ 'operator', 'administrator' ]
password: '$2a$10$JMhLJZ2DZiLMSvfGXHHo2e7jkrONex08eSLaStW15P0SavzyPF5GG'
)
specify 'is defined', ->
should.exist( AgentModel::hasSomeRoles )
AgentModel::hasSomeRoles.should.be.a( 'function' )
specify 'is true when the model instance has at least one of the given roles', ->
hasSomeRolesInstance.hasSomeRoles( [ 'operator' ] ).should.be.true
specify 'is true when the model instance has at least one of the given roles but not all of them', ->
hasSomeRolesInstance.hasSomeRoles( [ 'operator', 'guest' ] ).should.be.true
specify 'is false when the model instance does not have the given roles', ->
hasSomeRolesInstance.hasSomeRoles( [ 'superman' ] ).should.be.false
| 219484 | ###*
Copyright 2014 Joukou Ltd
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.
###
assert = require( 'assert' )
chai = require( 'chai' )
chaiAsPromised = require( 'chai-as-promised' )
chai.use( chaiAsPromised )
should = chai.should()
bcrypt = require( 'bcrypt' )
AgentModel = require( '../../dist/agent/Model' )
{ NotFoundError } = require( 'restify' )
pbc = require( '../../dist/riak/pbc' )
describe 'agent/Model', ->
before ( done ) ->
pbc.put(
type: 'agent'
bucket: 'agent'
key: '<KEY>'
content:
content_type: 'application/json'
indexes: [
{
key: 'email_bin'
value: '<EMAIL>'
}
]
value: JSON.stringify(
email: '<EMAIL>'
roles: [ 'operator' ]
password: <PASSWORD>' # "password" in bcrypt w/ 10 rounds
)
, ( err, reply ) -> done( err ) )
after ( done ) ->
pbc.del(
type: 'agent'
bucket: 'agent'
key: '<KEY>522-478c-97a4-2f577335e023'
, ( err, reply ) -> done( err ) )
specify 'is defined', ->
should.exist( AgentModel )
describe '.create( )', ->
specify 'creates a new agent', ( done ) ->
AgentModel.create(
email: '<EMAIL>'
password: '<PASSWORD>'
)
.then( ( agent ) ->
{ email, name, password } = agent.getValue()
email.should.equal( '<EMAIL>' )
bcrypt.compareSync( 'password', password ).should.be.true
pbc.del(
type: 'agent'
bucket: 'agent'
key: agent.getKey()
, ( err, reply ) -> done( err ) )
)
.fail( ( err ) -> done( err ) )
describe '::save( )', ->
specify 'persists an agent model instance to Basho Riak', ( done ) ->
AgentModel.create(
email: '<EMAIL>'
password: '<PASSWORD>'
)
.then( ( agent ) ->
agent.save()
)
.then( ( agent ) ->
AgentModel.retrieveByEmail( '<EMAIL>' )
)
.then( ( agent ) ->
pbc.del(
type: 'agent'
bucket: 'agent'
key: agent.getKey()
, ( err, reply ) -> done( err ) )
)
.fail( ( err ) -> done( err ) )
describe '.retrieveByEmail( email )', ->
specify 'is eventually rejected with a NotFoundError if the email does not exist', ->
AgentModel.retrieveByEmail( 'bogus' ).should.eventually.be.rejectedWith( NotFoundError )
specify 'is eventually resolved with a Model instance if the email does exist', ->
AgentModel.retrieveByEmail( '<EMAIL>' ).then( ( agent ) ->
agent.getValue().should.deep.equal(
email: '<EMAIL>'
roles: [ 'operator' ]
password: <PASSWORD>'
)
)
describe '::verifyPassword( password )', ->
specify 'is eventually resolved with false if the password does not match', ->
AgentModel.retrieveByEmail( '<EMAIL>' ).then( ( agent ) ->
agent.verifyPassword( 'bogus' ).should.eventually.be.equal( false )
)
specify 'is eventually resolved with true if the password does match', ->
AgentModel.retrieveByEmail( '<EMAIL>' ).then( ( agent ) ->
agent.verifyPassword( '<PASSWORD>' ).should.eventually.be.equal( true )
)
describe '.retrieveByEmail( email )', ->
specify 'is defined', ->
should.exist( AgentModel.retrieveByEmail )
AgentModel.retrieveByEmail.should.be.a( 'function' )
describe '::getRepresentation', ->
specify 'is defined', ->
should.exist( AgentModel::getRepresentation )
AgentModel::getRepresentation.should.be.a( 'function' )
specify 'is a representation of the model instance', ->
instance = new AgentModel(
value:
email: '<EMAIL>'
roles: [ 'operator' ]
password: <PASSWORD>'
)
instance.getRepresentation().should.deep.equal(
email: '<EMAIL>'
roles: [ 'operator' ]
)
describe '::getEmail', ->
specify 'is defined', ->
should.exist( AgentModel::getEmail )
AgentModel::getEmail.should.be.a( 'function' )
specify 'is the email of the model instance', ->
instance = new AgentModel(
value:
email: '<EMAIL>'
roles: [ 'operator' ]
password: <PASSWORD>'
)
instance.getEmail().should.equal( '<EMAIL>' )
describe '::getRoles', ->
specify 'is defined', ->
should.exist( AgentModel::getRoles )
AgentModel::getRoles.should.be.a( 'function' )
specify 'is the array of roles of the model instance', ->
instance = new AgentModel(
value:
email: '<EMAIL>'
roles: [ 'operator' ]
password: <PASSWORD>'
)
instance.getRoles().should.deep.equal( [ 'operator' ] )
describe '::hasSomeRoles( roles )', ->
hasSomeRolesInstance = new AgentModel(
value:
email: '<EMAIL>'
roles: [ 'operator', 'administrator' ]
password: <PASSWORD>'
)
specify 'is defined', ->
should.exist( AgentModel::hasSomeRoles )
AgentModel::hasSomeRoles.should.be.a( 'function' )
specify 'is true when the model instance has at least one of the given roles', ->
hasSomeRolesInstance.hasSomeRoles( [ 'operator' ] ).should.be.true
specify 'is true when the model instance has at least one of the given roles but not all of them', ->
hasSomeRolesInstance.hasSomeRoles( [ 'operator', 'guest' ] ).should.be.true
specify 'is false when the model instance does not have the given roles', ->
hasSomeRolesInstance.hasSomeRoles( [ 'superman' ] ).should.be.false
| true | ###*
Copyright 2014 Joukou Ltd
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.
###
assert = require( 'assert' )
chai = require( 'chai' )
chaiAsPromised = require( 'chai-as-promised' )
chai.use( chaiAsPromised )
should = chai.should()
bcrypt = require( 'bcrypt' )
AgentModel = require( '../../dist/agent/Model' )
{ NotFoundError } = require( 'restify' )
pbc = require( '../../dist/riak/pbc' )
describe 'agent/Model', ->
before ( done ) ->
pbc.put(
type: 'agent'
bucket: 'agent'
key: 'PI:KEY:<KEY>END_PI'
content:
content_type: 'application/json'
indexes: [
{
key: 'email_bin'
value: 'PI:EMAIL:<EMAIL>END_PI'
}
]
value: JSON.stringify(
email: 'PI:EMAIL:<EMAIL>END_PI'
roles: [ 'operator' ]
password: PI:PASSWORD:<PASSWORD>END_PI' # "password" in bcrypt w/ 10 rounds
)
, ( err, reply ) -> done( err ) )
after ( done ) ->
pbc.del(
type: 'agent'
bucket: 'agent'
key: 'PI:KEY:<KEY>END_PI522-478c-97a4-2f577335e023'
, ( err, reply ) -> done( err ) )
specify 'is defined', ->
should.exist( AgentModel )
describe '.create( )', ->
specify 'creates a new agent', ( done ) ->
AgentModel.create(
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
)
.then( ( agent ) ->
{ email, name, password } = agent.getValue()
email.should.equal( 'PI:EMAIL:<EMAIL>END_PI' )
bcrypt.compareSync( 'password', password ).should.be.true
pbc.del(
type: 'agent'
bucket: 'agent'
key: agent.getKey()
, ( err, reply ) -> done( err ) )
)
.fail( ( err ) -> done( err ) )
describe '::save( )', ->
specify 'persists an agent model instance to Basho Riak', ( done ) ->
AgentModel.create(
email: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
)
.then( ( agent ) ->
agent.save()
)
.then( ( agent ) ->
AgentModel.retrieveByEmail( 'PI:EMAIL:<EMAIL>END_PI' )
)
.then( ( agent ) ->
pbc.del(
type: 'agent'
bucket: 'agent'
key: agent.getKey()
, ( err, reply ) -> done( err ) )
)
.fail( ( err ) -> done( err ) )
describe '.retrieveByEmail( email )', ->
specify 'is eventually rejected with a NotFoundError if the email does not exist', ->
AgentModel.retrieveByEmail( 'bogus' ).should.eventually.be.rejectedWith( NotFoundError )
specify 'is eventually resolved with a Model instance if the email does exist', ->
AgentModel.retrieveByEmail( 'PI:EMAIL:<EMAIL>END_PI' ).then( ( agent ) ->
agent.getValue().should.deep.equal(
email: 'PI:EMAIL:<EMAIL>END_PI'
roles: [ 'operator' ]
password: PI:PASSWORD:<PASSWORD>END_PI'
)
)
describe '::verifyPassword( password )', ->
specify 'is eventually resolved with false if the password does not match', ->
AgentModel.retrieveByEmail( 'PI:EMAIL:<EMAIL>END_PI' ).then( ( agent ) ->
agent.verifyPassword( 'bogus' ).should.eventually.be.equal( false )
)
specify 'is eventually resolved with true if the password does match', ->
AgentModel.retrieveByEmail( 'PI:EMAIL:<EMAIL>END_PI' ).then( ( agent ) ->
agent.verifyPassword( 'PI:PASSWORD:<PASSWORD>END_PI' ).should.eventually.be.equal( true )
)
describe '.retrieveByEmail( email )', ->
specify 'is defined', ->
should.exist( AgentModel.retrieveByEmail )
AgentModel.retrieveByEmail.should.be.a( 'function' )
describe '::getRepresentation', ->
specify 'is defined', ->
should.exist( AgentModel::getRepresentation )
AgentModel::getRepresentation.should.be.a( 'function' )
specify 'is a representation of the model instance', ->
instance = new AgentModel(
value:
email: 'PI:EMAIL:<EMAIL>END_PI'
roles: [ 'operator' ]
password: PI:PASSWORD:<PASSWORD>END_PI'
)
instance.getRepresentation().should.deep.equal(
email: 'PI:EMAIL:<EMAIL>END_PI'
roles: [ 'operator' ]
)
describe '::getEmail', ->
specify 'is defined', ->
should.exist( AgentModel::getEmail )
AgentModel::getEmail.should.be.a( 'function' )
specify 'is the email of the model instance', ->
instance = new AgentModel(
value:
email: 'PI:EMAIL:<EMAIL>END_PI'
roles: [ 'operator' ]
password: PI:PASSWORD:<PASSWORD>END_PI'
)
instance.getEmail().should.equal( 'PI:EMAIL:<EMAIL>END_PI' )
describe '::getRoles', ->
specify 'is defined', ->
should.exist( AgentModel::getRoles )
AgentModel::getRoles.should.be.a( 'function' )
specify 'is the array of roles of the model instance', ->
instance = new AgentModel(
value:
email: 'PI:EMAIL:<EMAIL>END_PI'
roles: [ 'operator' ]
password: PI:PASSWORD:<PASSWORD>END_PI'
)
instance.getRoles().should.deep.equal( [ 'operator' ] )
describe '::hasSomeRoles( roles )', ->
hasSomeRolesInstance = new AgentModel(
value:
email: 'PI:EMAIL:<EMAIL>END_PI'
roles: [ 'operator', 'administrator' ]
password: PI:PASSWORD:<PASSWORD>END_PI'
)
specify 'is defined', ->
should.exist( AgentModel::hasSomeRoles )
AgentModel::hasSomeRoles.should.be.a( 'function' )
specify 'is true when the model instance has at least one of the given roles', ->
hasSomeRolesInstance.hasSomeRoles( [ 'operator' ] ).should.be.true
specify 'is true when the model instance has at least one of the given roles but not all of them', ->
hasSomeRolesInstance.hasSomeRoles( [ 'operator', 'guest' ] ).should.be.true
specify 'is false when the model instance does not have the given roles', ->
hasSomeRolesInstance.hasSomeRoles( [ 'superman' ] ).should.be.false
|
[
{
"context": "DB './mochaTest.json'\n user =\n username: 'dreyacosta'\n name: 'David'\n blog: 'dreyacosta.com'",
"end": 2415,
"score": 0.9996777772903442,
"start": 2405,
"tag": "USERNAME",
"value": "dreyacosta"
},
{
"context": " user =\n username: 'dreyacosta'\n name: 'David'\n blog: 'dreyacosta.com'\n source: 'twit",
"end": 2435,
"score": 0.999748945236206,
"start": 2430,
"tag": "NAME",
"value": "David"
},
{
"context": "\", ->\n item = db.findOne 'users', username: 'dreyacosta'\n expect(item.name).to.equal 'David'\n\n it",
"end": 2607,
"score": 0.9996744394302368,
"start": 2597,
"tag": "USERNAME",
"value": "dreyacosta"
},
{
"context": "e: 'dreyacosta'\n expect(item.name).to.equal 'David'\n\n it \"should find all\", ->\n user =\n ",
"end": 2648,
"score": 0.9989482760429382,
"start": 2643,
"tag": "NAME",
"value": "David"
},
{
"context": "uld find all\", ->\n user =\n username: 'drey'\n name: 'David'\n blog: 'drey.com'\n ",
"end": 2716,
"score": 0.9996382594108582,
"start": 2712,
"tag": "USERNAME",
"value": "drey"
},
{
"context": " user =\n username: 'drey'\n name: 'David'\n blog: 'drey.com'\n source: 'twitte",
"end": 2738,
"score": 0.9997737407684326,
"start": 2733,
"tag": "NAME",
"value": "David"
},
{
"context": "sers', user\n items = db.find 'users', name: 'David'\n expect(items.length).to.equal 2\n\n it \"s",
"end": 2869,
"score": 0.9995983242988586,
"start": 2864,
"tag": "NAME",
"value": "David"
},
{
"context": " one\", ->\n item = db.findOne 'users', name: 'Paul'\n expect(typeof item).to.equal 'object'\n ",
"end": 3021,
"score": 0.9746416211128235,
"start": 3017,
"tag": "NAME",
"value": "Paul"
},
{
"context": "nd all\", ->\n items = db.find 'users', name: 'Paul'\n expect(items.push).to.be.a 'function'\n ",
"end": 3226,
"score": 0.9627222418785095,
"start": 3222,
"tag": "NAME",
"value": "Paul"
},
{
"context": "\", ->\n item = db.findOne 'users', username: 'dreyacosta'\n expect(item.name).to.equal 'David'\n i",
"end": 3420,
"score": 0.9996734857559204,
"start": 3410,
"tag": "USERNAME",
"value": "dreyacosta"
},
{
"context": "e: 'dreyacosta'\n expect(item.name).to.equal 'David'\n item.name = 'Mike'\n item = db.findOne",
"end": 3461,
"score": 0.999130129814148,
"start": 3456,
"tag": "NAME",
"value": "David"
},
{
"context": "ct(item.name).to.equal 'David'\n item.name = 'Mike'\n item = db.findOne 'users', username: 'drey",
"end": 3486,
"score": 0.9674705266952515,
"start": 3482,
"tag": "NAME",
"value": "Mike"
},
{
"context": "Mike'\n item = db.findOne 'users', username: 'dreyacosta'\n expect(item.name).to.equal 'David'\n\n it",
"end": 3542,
"score": 0.9996783137321472,
"start": 3532,
"tag": "USERNAME",
"value": "dreyacosta"
},
{
"context": "e: 'dreyacosta'\n expect(item.name).to.equal 'David'\n\n it \"should return a pure array when find al",
"end": 3583,
"score": 0.9994202852249146,
"start": 3578,
"tag": "NAME",
"value": "David"
},
{
"context": "hen find all\", ->\n user =\n username: 'pirish'\n name: 'Paul'\n blog: 'pirish.com'\n",
"end": 3678,
"score": 0.9995431900024414,
"start": 3672,
"tag": "USERNAME",
"value": "pirish"
},
{
"context": " user =\n username: 'pirish'\n name: 'Paul'\n blog: 'pirish.com'\n source: 'twit",
"end": 3699,
"score": 0.999703049659729,
"start": 3695,
"tag": "NAME",
"value": "Paul"
},
{
"context": "\", ->\n item = db.findOne 'users', username: 'dreyacosta'\n item = db.update 'users', item.id, name: '",
"end": 4106,
"score": 0.9996406435966492,
"start": 4096,
"tag": "USERNAME",
"value": "dreyacosta"
},
{
"context": "'\n item = db.update 'users', item.id, name: 'David Rey'\n expect(item.name).to.equal 'David Rey'\n ",
"end": 4165,
"score": 0.9997207522392273,
"start": 4156,
"tag": "NAME",
"value": "David Rey"
},
{
"context": "me: 'David Rey'\n expect(item.name).to.equal 'David Rey'\n item.name = 'Mike'\n item = db.findOne",
"end": 4210,
"score": 0.9997571110725403,
"start": 4201,
"tag": "NAME",
"value": "David Rey"
},
{
"context": "tem.name).to.equal 'David Rey'\n item.name = 'Mike'\n item = db.findOne 'users', username: 'drey",
"end": 4235,
"score": 0.9997138977050781,
"start": 4231,
"tag": "NAME",
"value": "Mike"
},
{
"context": "Mike'\n item = db.findOne 'users', username: 'dreyacosta'\n expect(item.name).to.equal 'David Rey'\n\n ",
"end": 4291,
"score": 0.9996465444564819,
"start": 4281,
"tag": "USERNAME",
"value": "dreyacosta"
},
{
"context": "e: 'dreyacosta'\n expect(item.name).to.equal 'David Rey'\n\n it \"should update item\", ->\n data =\n ",
"end": 4336,
"score": 0.9997432827949524,
"start": 4327,
"tag": "NAME",
"value": "David Rey"
},
{
"context": "pain'\n item = db.findOne 'users', username: 'drey'\n item = db.update 'users', item.id, data\n ",
"end": 4457,
"score": 0.9996289014816284,
"start": 4453,
"tag": "USERNAME",
"value": "drey"
},
{
"context": ">\n item = db.update 'users', '12345', name: 'Brad'\n expect(typeof item).to.equal 'object'\n ",
"end": 4680,
"score": 0.9996271133422852,
"start": 4676,
"tag": "NAME",
"value": "Brad"
},
{
"context": "\", ->\n item = db.findOne 'users', username: 'drey'\n expect(item.username).to.equal 'drey'\n ",
"end": 4875,
"score": 0.9996163845062256,
"start": 4871,
"tag": "USERNAME",
"value": "drey"
},
{
"context": "ame: 'drey'\n expect(item.username).to.equal 'drey'\n result = db.remove 'users', item.id\n ",
"end": 4919,
"score": 0.9996252059936523,
"start": 4915,
"tag": "USERNAME",
"value": "drey"
},
{
"context": "newline char\", ->\n user =\n username: 'martinfowler'\n name: 'Martin'\n blog: 'martinfowl",
"end": 5530,
"score": 0.9996017813682556,
"start": 5518,
"tag": "USERNAME",
"value": "martinfowler"
},
{
"context": "=\n username: 'martinfowler'\n name: 'Martin'\n blog: 'martinfowler.com'\n source:",
"end": 5553,
"score": 0.9996090531349182,
"start": 5547,
"tag": "NAME",
"value": "Martin"
},
{
"context": "ser\n result = db.findOne 'users', username: 'martinfowler'\n expect(result.name).to.equal 'Martin'\n ",
"end": 5773,
"score": 0.9995888471603394,
"start": 5761,
"tag": "USERNAME",
"value": "martinfowler"
},
{
"context": "martinfowler'\n expect(result.name).to.equal 'Martin'\n expect(result.description).to.equal 'Progr",
"end": 5817,
"score": 0.9996525049209595,
"start": 5811,
"tag": "NAME",
"value": "Martin"
}
] | specs/somewhereSpec.coffee | dreyacosta/somewhere.js | 27 | 'use strict'
expect = require('chai').expect
DB = require '../index'
describe "JSONdb module", ->
describe "Memory and disk persistence", ->
it "should set new database path", ->
db = new DB './database.json'
expect(db.databasePath).to.equal './database.json'
it "should write first record on memory and persists on file", ->
db = new DB './database.json'
fruit =
name: 'Apple'
color: 'Green'
db.save 'fruits', fruit
expect(db.database.fruits.length).to.equal 1
db = new DB './database.json'
expect(db.database.fruits.length).to.equal 1
it "should clear file database", ->
db = new DB './database.json'
results = db.find 'fruits'
expect(results.length).to.equal 1
do db.clear
results = db.find 'fruits'
expect(results.length).to.equal 0
it "should only work on memory if path not provide", ->
db = new DB()
fruit =
name: 'Apple'
color: 'Green'
db.save 'fruits', fruit
expect(db.database.fruits.length).to.equal 1
db = new DB()
results = db.find 'fruits'
expect(results.length).to.equal 0
describe "findOne, find, update, remove, save if collection not exist", ->
db = new DB()
it "should return empty collection on findOne", ->
item = db.findOne 'computers', brand: 'Apple'
expect(db.database.computers.length).to.equal 0
it "should return empty collection on find", ->
item = db.find 'cars', brand: 'Ferrari'
expect(db.database.cars.length).to.equal 0
it "should return empty collection on update", ->
item = db.update 'ebooks', brand: 'Kindle'
expect(db.database.ebooks.length).to.equal 0
it "should return empty collection on remove", ->
item = db.remove 'electronic', brand: 'Philips'
expect(db.database.electronic.length).to.equal 0
it "should return a new collection with 1 element on save", ->
item = db.save 'books', title: 'Testable JavaScript'
expect(db.database.books.length).to.equal 1
it "should return the item save with new line char", ->
item = db.save 'books', title: 'Beyond the line: \r\n The Good Way'
expect(item.title).to.equal 'Beyond the line: \r\n The Good Way'
describe "Check findOne, find, update and remove methods", ->
db = new DB './mochaTest.json'
user =
username: 'dreyacosta'
name: 'David'
blog: 'dreyacosta.com'
source: 'twitter'
item = db.save 'users', user
it "should find one", ->
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal 'David'
it "should find all", ->
user =
username: 'drey'
name: 'David'
blog: 'drey.com'
source: 'twitter'
item = db.save 'users', user
items = db.find 'users', name: 'David'
expect(items.length).to.equal 2
it "should return an empty object if no match on find one", ->
item = db.findOne 'users', name: 'Paul'
expect(typeof item).to.equal 'object'
expect(Object.keys(item).length).to.equal 0
it "should return an empty array if no match on find all", ->
items = db.find 'users', name: 'Paul'
expect(items.push).to.be.a 'function'
expect(items.length).to.equal 0
it "should return a pure object when find one", ->
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal 'David'
item.name = 'Mike'
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal 'David'
it "should return a pure array when find all", ->
user =
username: 'pirish'
name: 'Paul'
blog: 'pirish.com'
source: 'twitter'
item = db.save 'users', user
items = db.find 'users', source: 'twitter'
expect(items.length).to.equal 3
items[0].source = 'facebook'
items = db.find 'users', source: 'twitter'
expect(items.length).to.equal 3
it "should return a pure object when update", ->
item = db.findOne 'users', username: 'dreyacosta'
item = db.update 'users', item.id, name: 'David Rey'
expect(item.name).to.equal 'David Rey'
item.name = 'Mike'
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal 'David Rey'
it "should update item", ->
data =
country: 'Spain'
item = db.findOne 'users', username: 'drey'
item = db.update 'users', item.id, data
expect(item.country).to.equal 'Spain'
it "should not update an item that not exist and return empty object", ->
item = db.update 'users', '12345', name: 'Brad'
expect(typeof item).to.equal 'object'
expect(Object.keys(item).length).to.equal 0
it "should remove item from a collection", ->
item = db.findOne 'users', username: 'drey'
expect(item.username).to.equal 'drey'
result = db.remove 'users', item.id
expect(result).to.equal true
item = db.findOne 'users', id: item.id
expect(typeof item).to.equal 'object'
expect(Object.keys(item).length).to.equal 0
it "should remove first item from a collection", ->
item = db.database.users[0]
result = db.remove 'users', item.id
expect(result).to.equal true
it "should not remove an item that not exist", ->
item = db.remove 'users', '12345'
expect(item).to.equal false
it "should save an item with newline char", ->
user =
username: 'martinfowler'
name: 'Martin'
blog: 'martinfowler.com'
source: 'twitter'
description: 'Programmer, Loud Mouth. \r\n ThoughtWorker'
item = db.save 'users', user
result = db.findOne 'users', username: 'martinfowler'
expect(result.name).to.equal 'Martin'
expect(result.description).to.equal 'Programmer, Loud Mouth. \r\n ThoughtWorker'
it "should clear the database file", ->
do db.clear
| 109027 | 'use strict'
expect = require('chai').expect
DB = require '../index'
describe "JSONdb module", ->
describe "Memory and disk persistence", ->
it "should set new database path", ->
db = new DB './database.json'
expect(db.databasePath).to.equal './database.json'
it "should write first record on memory and persists on file", ->
db = new DB './database.json'
fruit =
name: 'Apple'
color: 'Green'
db.save 'fruits', fruit
expect(db.database.fruits.length).to.equal 1
db = new DB './database.json'
expect(db.database.fruits.length).to.equal 1
it "should clear file database", ->
db = new DB './database.json'
results = db.find 'fruits'
expect(results.length).to.equal 1
do db.clear
results = db.find 'fruits'
expect(results.length).to.equal 0
it "should only work on memory if path not provide", ->
db = new DB()
fruit =
name: 'Apple'
color: 'Green'
db.save 'fruits', fruit
expect(db.database.fruits.length).to.equal 1
db = new DB()
results = db.find 'fruits'
expect(results.length).to.equal 0
describe "findOne, find, update, remove, save if collection not exist", ->
db = new DB()
it "should return empty collection on findOne", ->
item = db.findOne 'computers', brand: 'Apple'
expect(db.database.computers.length).to.equal 0
it "should return empty collection on find", ->
item = db.find 'cars', brand: 'Ferrari'
expect(db.database.cars.length).to.equal 0
it "should return empty collection on update", ->
item = db.update 'ebooks', brand: 'Kindle'
expect(db.database.ebooks.length).to.equal 0
it "should return empty collection on remove", ->
item = db.remove 'electronic', brand: 'Philips'
expect(db.database.electronic.length).to.equal 0
it "should return a new collection with 1 element on save", ->
item = db.save 'books', title: 'Testable JavaScript'
expect(db.database.books.length).to.equal 1
it "should return the item save with new line char", ->
item = db.save 'books', title: 'Beyond the line: \r\n The Good Way'
expect(item.title).to.equal 'Beyond the line: \r\n The Good Way'
describe "Check findOne, find, update and remove methods", ->
db = new DB './mochaTest.json'
user =
username: 'dreyacosta'
name: '<NAME>'
blog: 'dreyacosta.com'
source: 'twitter'
item = db.save 'users', user
it "should find one", ->
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal '<NAME>'
it "should find all", ->
user =
username: 'drey'
name: '<NAME>'
blog: 'drey.com'
source: 'twitter'
item = db.save 'users', user
items = db.find 'users', name: '<NAME>'
expect(items.length).to.equal 2
it "should return an empty object if no match on find one", ->
item = db.findOne 'users', name: '<NAME>'
expect(typeof item).to.equal 'object'
expect(Object.keys(item).length).to.equal 0
it "should return an empty array if no match on find all", ->
items = db.find 'users', name: '<NAME>'
expect(items.push).to.be.a 'function'
expect(items.length).to.equal 0
it "should return a pure object when find one", ->
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal '<NAME>'
item.name = '<NAME>'
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal '<NAME>'
it "should return a pure array when find all", ->
user =
username: 'pirish'
name: '<NAME>'
blog: 'pirish.com'
source: 'twitter'
item = db.save 'users', user
items = db.find 'users', source: 'twitter'
expect(items.length).to.equal 3
items[0].source = 'facebook'
items = db.find 'users', source: 'twitter'
expect(items.length).to.equal 3
it "should return a pure object when update", ->
item = db.findOne 'users', username: 'dreyacosta'
item = db.update 'users', item.id, name: '<NAME>'
expect(item.name).to.equal '<NAME>'
item.name = '<NAME>'
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal '<NAME>'
it "should update item", ->
data =
country: 'Spain'
item = db.findOne 'users', username: 'drey'
item = db.update 'users', item.id, data
expect(item.country).to.equal 'Spain'
it "should not update an item that not exist and return empty object", ->
item = db.update 'users', '12345', name: '<NAME>'
expect(typeof item).to.equal 'object'
expect(Object.keys(item).length).to.equal 0
it "should remove item from a collection", ->
item = db.findOne 'users', username: 'drey'
expect(item.username).to.equal 'drey'
result = db.remove 'users', item.id
expect(result).to.equal true
item = db.findOne 'users', id: item.id
expect(typeof item).to.equal 'object'
expect(Object.keys(item).length).to.equal 0
it "should remove first item from a collection", ->
item = db.database.users[0]
result = db.remove 'users', item.id
expect(result).to.equal true
it "should not remove an item that not exist", ->
item = db.remove 'users', '12345'
expect(item).to.equal false
it "should save an item with newline char", ->
user =
username: 'martinfowler'
name: '<NAME>'
blog: 'martinfowler.com'
source: 'twitter'
description: 'Programmer, Loud Mouth. \r\n ThoughtWorker'
item = db.save 'users', user
result = db.findOne 'users', username: 'martinfowler'
expect(result.name).to.equal '<NAME>'
expect(result.description).to.equal 'Programmer, Loud Mouth. \r\n ThoughtWorker'
it "should clear the database file", ->
do db.clear
| true | 'use strict'
expect = require('chai').expect
DB = require '../index'
describe "JSONdb module", ->
describe "Memory and disk persistence", ->
it "should set new database path", ->
db = new DB './database.json'
expect(db.databasePath).to.equal './database.json'
it "should write first record on memory and persists on file", ->
db = new DB './database.json'
fruit =
name: 'Apple'
color: 'Green'
db.save 'fruits', fruit
expect(db.database.fruits.length).to.equal 1
db = new DB './database.json'
expect(db.database.fruits.length).to.equal 1
it "should clear file database", ->
db = new DB './database.json'
results = db.find 'fruits'
expect(results.length).to.equal 1
do db.clear
results = db.find 'fruits'
expect(results.length).to.equal 0
it "should only work on memory if path not provide", ->
db = new DB()
fruit =
name: 'Apple'
color: 'Green'
db.save 'fruits', fruit
expect(db.database.fruits.length).to.equal 1
db = new DB()
results = db.find 'fruits'
expect(results.length).to.equal 0
describe "findOne, find, update, remove, save if collection not exist", ->
db = new DB()
it "should return empty collection on findOne", ->
item = db.findOne 'computers', brand: 'Apple'
expect(db.database.computers.length).to.equal 0
it "should return empty collection on find", ->
item = db.find 'cars', brand: 'Ferrari'
expect(db.database.cars.length).to.equal 0
it "should return empty collection on update", ->
item = db.update 'ebooks', brand: 'Kindle'
expect(db.database.ebooks.length).to.equal 0
it "should return empty collection on remove", ->
item = db.remove 'electronic', brand: 'Philips'
expect(db.database.electronic.length).to.equal 0
it "should return a new collection with 1 element on save", ->
item = db.save 'books', title: 'Testable JavaScript'
expect(db.database.books.length).to.equal 1
it "should return the item save with new line char", ->
item = db.save 'books', title: 'Beyond the line: \r\n The Good Way'
expect(item.title).to.equal 'Beyond the line: \r\n The Good Way'
describe "Check findOne, find, update and remove methods", ->
db = new DB './mochaTest.json'
user =
username: 'dreyacosta'
name: 'PI:NAME:<NAME>END_PI'
blog: 'dreyacosta.com'
source: 'twitter'
item = db.save 'users', user
it "should find one", ->
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal 'PI:NAME:<NAME>END_PI'
it "should find all", ->
user =
username: 'drey'
name: 'PI:NAME:<NAME>END_PI'
blog: 'drey.com'
source: 'twitter'
item = db.save 'users', user
items = db.find 'users', name: 'PI:NAME:<NAME>END_PI'
expect(items.length).to.equal 2
it "should return an empty object if no match on find one", ->
item = db.findOne 'users', name: 'PI:NAME:<NAME>END_PI'
expect(typeof item).to.equal 'object'
expect(Object.keys(item).length).to.equal 0
it "should return an empty array if no match on find all", ->
items = db.find 'users', name: 'PI:NAME:<NAME>END_PI'
expect(items.push).to.be.a 'function'
expect(items.length).to.equal 0
it "should return a pure object when find one", ->
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal 'PI:NAME:<NAME>END_PI'
item.name = 'PI:NAME:<NAME>END_PI'
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal 'PI:NAME:<NAME>END_PI'
it "should return a pure array when find all", ->
user =
username: 'pirish'
name: 'PI:NAME:<NAME>END_PI'
blog: 'pirish.com'
source: 'twitter'
item = db.save 'users', user
items = db.find 'users', source: 'twitter'
expect(items.length).to.equal 3
items[0].source = 'facebook'
items = db.find 'users', source: 'twitter'
expect(items.length).to.equal 3
it "should return a pure object when update", ->
item = db.findOne 'users', username: 'dreyacosta'
item = db.update 'users', item.id, name: 'PI:NAME:<NAME>END_PI'
expect(item.name).to.equal 'PI:NAME:<NAME>END_PI'
item.name = 'PI:NAME:<NAME>END_PI'
item = db.findOne 'users', username: 'dreyacosta'
expect(item.name).to.equal 'PI:NAME:<NAME>END_PI'
it "should update item", ->
data =
country: 'Spain'
item = db.findOne 'users', username: 'drey'
item = db.update 'users', item.id, data
expect(item.country).to.equal 'Spain'
it "should not update an item that not exist and return empty object", ->
item = db.update 'users', '12345', name: 'PI:NAME:<NAME>END_PI'
expect(typeof item).to.equal 'object'
expect(Object.keys(item).length).to.equal 0
it "should remove item from a collection", ->
item = db.findOne 'users', username: 'drey'
expect(item.username).to.equal 'drey'
result = db.remove 'users', item.id
expect(result).to.equal true
item = db.findOne 'users', id: item.id
expect(typeof item).to.equal 'object'
expect(Object.keys(item).length).to.equal 0
it "should remove first item from a collection", ->
item = db.database.users[0]
result = db.remove 'users', item.id
expect(result).to.equal true
it "should not remove an item that not exist", ->
item = db.remove 'users', '12345'
expect(item).to.equal false
it "should save an item with newline char", ->
user =
username: 'martinfowler'
name: 'PI:NAME:<NAME>END_PI'
blog: 'martinfowler.com'
source: 'twitter'
description: 'Programmer, Loud Mouth. \r\n ThoughtWorker'
item = db.save 'users', user
result = db.findOne 'users', username: 'martinfowler'
expect(result.name).to.equal 'PI:NAME:<NAME>END_PI'
expect(result.description).to.equal 'Programmer, Loud Mouth. \r\n ThoughtWorker'
it "should clear the database file", ->
do db.clear
|
[
{
"context": "ri: \"https://bsc-dataseed.binance.org/\"\n\napiKey: \"CHANGEME\"\n\ninvoices:\n minConfirmations: 1\n\npublic:\n allo",
"end": 98,
"score": 0.979032039642334,
"start": 90,
"tag": "KEY",
"value": "CHANGEME"
},
{
"context": ":\n minConfirmations: 1\n\npublic:\n allowTokens: ['WMUE']\n contracts:\n WMUE: \n address: \"0x00aba",
"end": 163,
"score": 0.7895255088806152,
"start": 159,
"tag": "KEY",
"value": "WMUE"
}
] | config/default.cson | sotblad/decentrapay | 0 | listen: 8000
provider:
type: "rpc"
uri: "https://bsc-dataseed.binance.org/"
apiKey: "CHANGEME"
invoices:
minConfirmations: 1
public:
allowTokens: ['WMUE']
contracts:
WMUE:
address: "0x00abaa93faf8fdc4f382135a7a56f9cf7c3edd21" # Mainnet
| 191389 | listen: 8000
provider:
type: "rpc"
uri: "https://bsc-dataseed.binance.org/"
apiKey: "<KEY>"
invoices:
minConfirmations: 1
public:
allowTokens: ['<KEY>']
contracts:
WMUE:
address: "0x00abaa93faf8fdc4f382135a7a56f9cf7c3edd21" # Mainnet
| true | listen: 8000
provider:
type: "rpc"
uri: "https://bsc-dataseed.binance.org/"
apiKey: "PI:KEY:<KEY>END_PI"
invoices:
minConfirmations: 1
public:
allowTokens: ['PI:KEY:<KEY>END_PI']
contracts:
WMUE:
address: "0x00abaa93faf8fdc4f382135a7a56f9cf7c3edd21" # Mainnet
|
[
{
"context": " beforeEach ->\n input.value('bob')\n emit(input.node(), 'input')\n ",
"end": 12231,
"score": 0.9726568460464478,
"start": 12228,
"tag": "NAME",
"value": "bob"
}
] | src/components/date-picker/spec.coffee | p-koscielniak/hexagonjs | 0 | import chai from 'chai'
import { select, div } from 'utils/selection'
import logger from 'utils/logger'
import { preferences } from 'utils/preferences'
import { DatePicker } from 'components/date-picker'
import { config as dropdownConfig } from 'components/dropdown'
import emit from 'test/utils/fake-event'
import installFakeTimers from 'test/utils/fake-time'
export default () ->
describe 'date-picker', ->
oneDayMs = 1000 * 60 * 60 * 24
oneMonthMs = 31 * oneDayMs
animationDelay = 301
origAttachSelector = dropdownConfig.attachToSelector
originalLoggerWarn = logger.warn
fixture = undefined
body = select('body')
beforeEach ->
logger.warn = chai.spy()
fixture = body.append('div').class('hx-test-date-picker')
dropdownConfig.attachToSelector = fixture
afterEach ->
logger.warn = originalLoggerWarn
dropdownConfig.attachToSelector = origAttachSelector
fixture.remove()
roundedDate = (start, today) ->
date = new Date
if today? and not today
day = (new Date).getDate()
if start
date.setDate(day - 2)
else
date.setDate(day + 2)
date.setHours(0, 0, 0, 0)
date
# The datepicker re-orders the start and end in case they are accidentally
# supplied in the wrong order so this is a helper for re-ordering them.
whichDateFirst = (range) ->
if range.start > range.end
{
start: range.end
end: range.start
}
else
range
describe 'test return types:', ->
describe 'should return this for getter setters with parameters:', ->
it 'dp.date', ->
dp = new DatePicker(div())
dp.date(roundedDate()).should.equal(dp)
it 'dp.day', ->
dp = new DatePicker(div())
dp.day(10).should.equal(dp)
it 'dp.month', ->
dp = new DatePicker(div())
dp.month(10).should.equal(dp)
it 'dp.year', ->
dp = new DatePicker(div())
dp.year(10).should.equal(dp)
it 'dp.locale', ->
dp = new DatePicker(div())
dp.locale('en-GB').should.equal(dp)
describe 'should return values for setter/getters without parameters:', ->
it 'dp.date', ->
dp = new DatePicker(div())
date = roundedDate()
dp.date(date).date().should.eql(date)
it 'dp.day', ->
dp = new DatePicker(div())
dp.day(10).day().should.equal(10)
it 'dp.month', ->
dp = new DatePicker(div())
dp.month(10).month().should.equal(10)
it 'dp.year', ->
dp = new DatePicker(div())
dp.year(10).year().should.equal(10)
it 'dp.locale', ->
dp = new DatePicker(div())
dp.locale('en-GB').locale().should.equal('en-GB')
it 'should return this for show', ->
dp = new DatePicker(div())
dp.show().should.equal(dp)
it 'should return this for hide', ->
dp = new DatePicker(div())
dp.hide().should.equal(dp)
it 'should return this for visibleMonth', ->
dp = new DatePicker(div())
dp.visibleMonth(10, 2015).should.equal(dp)
dp.visibleMonth().should.eql({month: 10, year: 2015})
it 'should return this for range', ->
dp = new DatePicker(div())
dp.range(roundedDate(), roundedDate()).should.equal(dp)
describe 'validRange', ->
it 'set both ends in one go and get should work', ->
dp = new DatePicker(div())
range = {start: roundedDate(), end: roundedDate()}
dp.validRange(range).should.equal(dp)
dp.validRange().should.eql(range)
it 'set start and get should work', ->
dp = new DatePicker(div())
range = {start: roundedDate()}
dp.validRange(range).should.equal(dp)
dp.validRange().should.eql({start: range.start, end: undefined})
it 'set end and get should work', ->
dp = new DatePicker(div())
range = {end: roundedDate()}
dp.validRange(range).should.equal(dp)
dp.validRange().should.eql({start: undefined, end: range.end})
it 'set both ends individually and get should work', ->
dp = new DatePicker(div())
start = {start: roundedDate()}
end = {end: roundedDate()}
dp.validRange(start).should.equal(dp)
dp.validRange(end).should.equal(dp)
dp.validRange().should.eql({start: start.start, end: end.end})
it 'using undefined should remove the start range', ->
dp = new DatePicker(div())
range1 = {start: roundedDate(), end: roundedDate()}
range2 = {start: undefined}
dp.validRange(range1).should.equal(dp)
dp.validRange(range2).should.equal(dp)
dp.validRange().should.eql({start: undefined, end: range1.end})
it 'using undefined should remove the end range', ->
dp = new DatePicker(div())
range1 = {start: roundedDate(), end: roundedDate()}
range2 = {end: undefined}
dp.validRange(range1).should.equal(dp)
dp.validRange(range2).should.equal(dp)
dp.validRange().should.eql({start: range1.start, end: undefined})
it 'using undefined should remove both ends range', ->
dp = new DatePicker(div())
range1 = {start: roundedDate(), end: roundedDate()}
range2 = {start: undefined, end: undefined}
dp.validRange(range1).should.equal(dp)
dp.validRange(range2).should.equal(dp)
dp.validRange().should.eql({start: undefined, end: undefined})
it 'defaults should be undefined', ->
dp = new DatePicker(div())
dp.validRange().should.eql({start: undefined, end: undefined})
it 'can be set in the constructor', ->
validRange = {
start: roundedDate(),
end: roundedDate()
}
dp = new DatePicker(div(), { validRange })
dp.validRange().should.eql(validRange)
describe 'range', ->
it 'should do nothing when attempting to use without setting selectRange', ->
dp = new DatePicker(div())
dp.range({start: roundedDate(true), end: roundedDate()})
logger.warn.should.have.been.called.with('datePicker.range can only be used for datepickers with \'selectRange\' of true')
it 'set both ends in one go and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
range = {start: roundedDate(true), end: roundedDate()}
dp.range(range).should.equal(dp)
dp.range().should.eql(whichDateFirst(range))
it 'set start and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
range = {start: roundedDate(true)}
dp.range(range).should.equal(dp)
dp.range().should.eql(whichDateFirst({start: range.start, end: roundedDate(null, true)}))
it 'set end and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
range = {end: roundedDate()}
dp.range(range).should.equal(dp)
dp.range().should.eql(whichDateFirst({start: roundedDate(null, true), end: range.end}))
it 'set both ends individually and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
start = {start: roundedDate(true)}
end = {end: roundedDate()}
dp.range(start).should.equal(dp)
dp.range(end).should.equal(dp)
dp.range().should.eql(whichDateFirst({start: start.start, end: end.end}))
it 'defaults should be today', ->
dp = new DatePicker(div(), {selectRange: true})
dp.range().should.eql({start: roundedDate(null, true), end: roundedDate(null, true)})
it 'can be set in the constructor', ->
range = {start: roundedDate(true), end: roundedDate()}
dp = new DatePicker(div(), { selectRange: true, range: range })
dp.range().should.eql({start: roundedDate(true), end: roundedDate()})
describe 'options', ->
origDateNow = Date.now
clock = undefined
before ->
clock = installFakeTimers()
Date.now = () -> 1541675114940
after ->
clock.restore()
Date.now = origDateNow
describe 'allowViewChange', ->
dp = undefined
innerFixture = undefined
headerElem = undefined
beforeEach ->
innerFixture = fixture.append('div')
describe 'when false', ->
beforeEach ->
dp = new DatePicker(innerFixture, {
allowViewChange: false,
defaultView: 'y',
})
dp.show()
clock.tick(animationDelay)
headerElem = fixture.select('.hx-calendar-header-title')
it 'creates a div for the header text', ->
headerElem.node().tagName.toLowerCase().should.equal('div')
it 'changes the default view to month', ->
dp.options.defaultView.should.equal('m')
describe 'when true', ->
beforeEach ->
dp = new DatePicker(innerFixture, {
allowViewChange: true,
defaultView: 'd'
})
dp.show()
clock.tick(animationDelay)
headerElem = fixture.select('.hx-calendar-header-title')
it 'creates a button for the header text', ->
headerElem.node().tagName.toLowerCase().should.equal('button')
it 'allows the default view of decade', ->
dp.options.defaultView.should.equal('d')
describe 'v2Flags', ->
describe 'when using an input', ->
dp = undefined
input = undefined
beforeEach ->
input = fixture.append('input')
dp = new DatePicker(input, { v2Features: {
dontModifyDateOnError: true,
displayLongMonthInCalendar: true,
dontSetInitialInputValue: true,
updateVisibleMonthOnDateChange: true,
}})
it 'does not set the initial value', ->
input.value().should.equal('')
it 'has the correct visible month', ->
dp.visibleMonth().should.eql({ month: 11, year: 2018 })
describe 'when opening the picker', ->
beforeEach ->
dp.show()
it 'renders the month header as MMMM YYYY', ->
fixture.select('.hx-calendar-header-title').text().should.equal('November 2018')
describe 'and passing a dateValidityCallback', ->
dateValidityCallback = undefined
inputDebounceDelay = 501
beforeEach ->
input.remove()
input = fixture.append('input')
dateValidityCallback = chai.spy()
dp = new DatePicker(input, {
v2Features: {
dontModifyDateOnError: true,
displayLongMonthInCalendar: true,
dontSetInitialInputValue: true,
updateVisibleMonthOnDateChange: true,
dateValidityCallback: dateValidityCallback,
},
validRange: {
start: new Date(Date.now() - (oneDayMs * 4))
end: new Date(Date.now() + (oneDayMs * 4))
}
})
describe 'when the date is valid', ->
beforeEach ->
input.value('8/11/2018')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(2)
describe 'when the date is invalid', ->
beforeEach ->
input.value('bob')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with false and INVALID_DATE', ->
dateValidityCallback.should.have.been.called.with(false, 'INVALID_DATE')
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(2)
describe 'and clearing the input value', ->
beforeEach ->
input.value('')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function three times', ->
dateValidityCallback.should.have.been.called.exactly(3)
describe 'when the date is before the valid range', ->
beforeEach ->
input.value('1/11/2018')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with false and DATE_OUTSIDE_RANGE_START', ->
dateValidityCallback.should.have.been.called.with(false, 'DATE_OUTSIDE_RANGE_START')
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(3)
describe 'and clearing the input value', ->
beforeEach ->
input.value('')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function three times', ->
dateValidityCallback.should.have.been.called.exactly(4)
describe 'when the date is after the valid range', ->
beforeEach ->
input.value('30/11/2018')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with false and DATE_OUTSIDE_RANGE_END', ->
dateValidityCallback.should.have.been.called.with(false, 'DATE_OUTSIDE_RANGE_END')
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(3)
describe 'and clearing the input value', ->
beforeEach ->
input.value('')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function three times', ->
dateValidityCallback.should.have.been.called.exactly(4)
describe 'and selectRange', ->
beforeEach ->
input.remove()
input = fixture.append('input')
dp = new DatePicker(input, {
v2Features: {
dontModifyDateOnError: true,
displayLongMonthInCalendar: true,
dontSetInitialInputValue: true,
updateVisibleMonthOnDateChange: true,
},
selectRange: true
})
it 'sets selectRange to false', ->
dp.options.selectRange.should.equal(false)
it 'logs a console warning', ->
logger.warn.should.have.been.called.with('DatePicker: options.selectRange is not supported when using an input')
describe 'and setting the date', ->
beforeEach ->
dp.date(new Date(Date.now() - (2 * oneMonthMs)))
it 'updates the visible month', ->
dp.visibleMonth().should.eql({ month: 9, year: 2018 })
describe 'localized timezones', () ->
testDateMs = Date.UTC(2019, 4, 22, 0, 20)
origDateNow = Date.now
beforeEach () ->
Date.now = ()-> testDateMs
afterEach () ->
Date.now = origDateNow
describe 'when using en-GB and UTC+01:00', () ->
stdDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('UTC+01:00')
stdDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
stdDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
stdDp.date().should.eql(new Date(2019, 4, 22))
# Default date localizer doesn't support timezones
describe 'when using en-GB and UTC-07:00', () ->
stdDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('UTC-07:00')
stdDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
stdDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
stdDp.date().should.eql(new Date(2019, 4, 22))
# PhantomJS doesn't support `Intl` and the polyfill doesn't support timezones...
if navigator.userAgent.indexOf('PhantomJS') is -1
describe 'localized timezones (preferences Intl API)', () ->
testDateMs = Date.UTC(2019, 4, 22, 0, 20)
origDateNow = Date.now
beforeEach () ->
Date.now = ()-> testDateMs
preferences.setup({
featureFlags: {
useIntlFormat: true,
},
})
afterEach () ->
Date.now = origDateNow
preferences.off()
preferences.setup()
describe 'default behaviour', ->
describe 'when using en-GB and Europe/London', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('Europe/London')
intlDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'when using en-US and America/Los_Angeles', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en')
preferences.timezone('America/Los_Angeles')
intlDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/21/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/22/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'when using fr and Pacific/Auckland', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('fr')
preferences.timezone('Pacific/Auckland')
intlDp = new DatePicker(fixture.append(div()), {
date: new Date(Date.UTC(2019, 4, 22, 20, 0))
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('23/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'outputFullDate behaviour', ->
describe 'when using en-GB and Europe/London', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('Europe/London')
intlDp = new DatePicker(fixture.append(div()), {
outputFullDate: true
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(testDateMs))
describe 'when using en-US and America/Los_Angeles', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en')
preferences.timezone('America/Los_Angeles')
intlDp = new DatePicker(fixture.append(div()), {
outputFullDate: true
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/21/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(testDateMs))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/22/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(testDateMs))
describe 'when using fr and Pacific/Auckland', () ->
intlDp = undefined
nzTestDate = Date.UTC(2019, 4, 22, 20, 0)
beforeEach () ->
preferences.locale('fr')
preferences.timezone('Pacific/Auckland')
intlDp = new DatePicker(fixture.append(div()), {
date: new Date(nzTestDate),
outputFullDate: true
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('23/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(nzTestDate))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(nzTestDate))
| 64412 | import chai from 'chai'
import { select, div } from 'utils/selection'
import logger from 'utils/logger'
import { preferences } from 'utils/preferences'
import { DatePicker } from 'components/date-picker'
import { config as dropdownConfig } from 'components/dropdown'
import emit from 'test/utils/fake-event'
import installFakeTimers from 'test/utils/fake-time'
export default () ->
describe 'date-picker', ->
oneDayMs = 1000 * 60 * 60 * 24
oneMonthMs = 31 * oneDayMs
animationDelay = 301
origAttachSelector = dropdownConfig.attachToSelector
originalLoggerWarn = logger.warn
fixture = undefined
body = select('body')
beforeEach ->
logger.warn = chai.spy()
fixture = body.append('div').class('hx-test-date-picker')
dropdownConfig.attachToSelector = fixture
afterEach ->
logger.warn = originalLoggerWarn
dropdownConfig.attachToSelector = origAttachSelector
fixture.remove()
roundedDate = (start, today) ->
date = new Date
if today? and not today
day = (new Date).getDate()
if start
date.setDate(day - 2)
else
date.setDate(day + 2)
date.setHours(0, 0, 0, 0)
date
# The datepicker re-orders the start and end in case they are accidentally
# supplied in the wrong order so this is a helper for re-ordering them.
whichDateFirst = (range) ->
if range.start > range.end
{
start: range.end
end: range.start
}
else
range
describe 'test return types:', ->
describe 'should return this for getter setters with parameters:', ->
it 'dp.date', ->
dp = new DatePicker(div())
dp.date(roundedDate()).should.equal(dp)
it 'dp.day', ->
dp = new DatePicker(div())
dp.day(10).should.equal(dp)
it 'dp.month', ->
dp = new DatePicker(div())
dp.month(10).should.equal(dp)
it 'dp.year', ->
dp = new DatePicker(div())
dp.year(10).should.equal(dp)
it 'dp.locale', ->
dp = new DatePicker(div())
dp.locale('en-GB').should.equal(dp)
describe 'should return values for setter/getters without parameters:', ->
it 'dp.date', ->
dp = new DatePicker(div())
date = roundedDate()
dp.date(date).date().should.eql(date)
it 'dp.day', ->
dp = new DatePicker(div())
dp.day(10).day().should.equal(10)
it 'dp.month', ->
dp = new DatePicker(div())
dp.month(10).month().should.equal(10)
it 'dp.year', ->
dp = new DatePicker(div())
dp.year(10).year().should.equal(10)
it 'dp.locale', ->
dp = new DatePicker(div())
dp.locale('en-GB').locale().should.equal('en-GB')
it 'should return this for show', ->
dp = new DatePicker(div())
dp.show().should.equal(dp)
it 'should return this for hide', ->
dp = new DatePicker(div())
dp.hide().should.equal(dp)
it 'should return this for visibleMonth', ->
dp = new DatePicker(div())
dp.visibleMonth(10, 2015).should.equal(dp)
dp.visibleMonth().should.eql({month: 10, year: 2015})
it 'should return this for range', ->
dp = new DatePicker(div())
dp.range(roundedDate(), roundedDate()).should.equal(dp)
describe 'validRange', ->
it 'set both ends in one go and get should work', ->
dp = new DatePicker(div())
range = {start: roundedDate(), end: roundedDate()}
dp.validRange(range).should.equal(dp)
dp.validRange().should.eql(range)
it 'set start and get should work', ->
dp = new DatePicker(div())
range = {start: roundedDate()}
dp.validRange(range).should.equal(dp)
dp.validRange().should.eql({start: range.start, end: undefined})
it 'set end and get should work', ->
dp = new DatePicker(div())
range = {end: roundedDate()}
dp.validRange(range).should.equal(dp)
dp.validRange().should.eql({start: undefined, end: range.end})
it 'set both ends individually and get should work', ->
dp = new DatePicker(div())
start = {start: roundedDate()}
end = {end: roundedDate()}
dp.validRange(start).should.equal(dp)
dp.validRange(end).should.equal(dp)
dp.validRange().should.eql({start: start.start, end: end.end})
it 'using undefined should remove the start range', ->
dp = new DatePicker(div())
range1 = {start: roundedDate(), end: roundedDate()}
range2 = {start: undefined}
dp.validRange(range1).should.equal(dp)
dp.validRange(range2).should.equal(dp)
dp.validRange().should.eql({start: undefined, end: range1.end})
it 'using undefined should remove the end range', ->
dp = new DatePicker(div())
range1 = {start: roundedDate(), end: roundedDate()}
range2 = {end: undefined}
dp.validRange(range1).should.equal(dp)
dp.validRange(range2).should.equal(dp)
dp.validRange().should.eql({start: range1.start, end: undefined})
it 'using undefined should remove both ends range', ->
dp = new DatePicker(div())
range1 = {start: roundedDate(), end: roundedDate()}
range2 = {start: undefined, end: undefined}
dp.validRange(range1).should.equal(dp)
dp.validRange(range2).should.equal(dp)
dp.validRange().should.eql({start: undefined, end: undefined})
it 'defaults should be undefined', ->
dp = new DatePicker(div())
dp.validRange().should.eql({start: undefined, end: undefined})
it 'can be set in the constructor', ->
validRange = {
start: roundedDate(),
end: roundedDate()
}
dp = new DatePicker(div(), { validRange })
dp.validRange().should.eql(validRange)
describe 'range', ->
it 'should do nothing when attempting to use without setting selectRange', ->
dp = new DatePicker(div())
dp.range({start: roundedDate(true), end: roundedDate()})
logger.warn.should.have.been.called.with('datePicker.range can only be used for datepickers with \'selectRange\' of true')
it 'set both ends in one go and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
range = {start: roundedDate(true), end: roundedDate()}
dp.range(range).should.equal(dp)
dp.range().should.eql(whichDateFirst(range))
it 'set start and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
range = {start: roundedDate(true)}
dp.range(range).should.equal(dp)
dp.range().should.eql(whichDateFirst({start: range.start, end: roundedDate(null, true)}))
it 'set end and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
range = {end: roundedDate()}
dp.range(range).should.equal(dp)
dp.range().should.eql(whichDateFirst({start: roundedDate(null, true), end: range.end}))
it 'set both ends individually and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
start = {start: roundedDate(true)}
end = {end: roundedDate()}
dp.range(start).should.equal(dp)
dp.range(end).should.equal(dp)
dp.range().should.eql(whichDateFirst({start: start.start, end: end.end}))
it 'defaults should be today', ->
dp = new DatePicker(div(), {selectRange: true})
dp.range().should.eql({start: roundedDate(null, true), end: roundedDate(null, true)})
it 'can be set in the constructor', ->
range = {start: roundedDate(true), end: roundedDate()}
dp = new DatePicker(div(), { selectRange: true, range: range })
dp.range().should.eql({start: roundedDate(true), end: roundedDate()})
describe 'options', ->
origDateNow = Date.now
clock = undefined
before ->
clock = installFakeTimers()
Date.now = () -> 1541675114940
after ->
clock.restore()
Date.now = origDateNow
describe 'allowViewChange', ->
dp = undefined
innerFixture = undefined
headerElem = undefined
beforeEach ->
innerFixture = fixture.append('div')
describe 'when false', ->
beforeEach ->
dp = new DatePicker(innerFixture, {
allowViewChange: false,
defaultView: 'y',
})
dp.show()
clock.tick(animationDelay)
headerElem = fixture.select('.hx-calendar-header-title')
it 'creates a div for the header text', ->
headerElem.node().tagName.toLowerCase().should.equal('div')
it 'changes the default view to month', ->
dp.options.defaultView.should.equal('m')
describe 'when true', ->
beforeEach ->
dp = new DatePicker(innerFixture, {
allowViewChange: true,
defaultView: 'd'
})
dp.show()
clock.tick(animationDelay)
headerElem = fixture.select('.hx-calendar-header-title')
it 'creates a button for the header text', ->
headerElem.node().tagName.toLowerCase().should.equal('button')
it 'allows the default view of decade', ->
dp.options.defaultView.should.equal('d')
describe 'v2Flags', ->
describe 'when using an input', ->
dp = undefined
input = undefined
beforeEach ->
input = fixture.append('input')
dp = new DatePicker(input, { v2Features: {
dontModifyDateOnError: true,
displayLongMonthInCalendar: true,
dontSetInitialInputValue: true,
updateVisibleMonthOnDateChange: true,
}})
it 'does not set the initial value', ->
input.value().should.equal('')
it 'has the correct visible month', ->
dp.visibleMonth().should.eql({ month: 11, year: 2018 })
describe 'when opening the picker', ->
beforeEach ->
dp.show()
it 'renders the month header as MMMM YYYY', ->
fixture.select('.hx-calendar-header-title').text().should.equal('November 2018')
describe 'and passing a dateValidityCallback', ->
dateValidityCallback = undefined
inputDebounceDelay = 501
beforeEach ->
input.remove()
input = fixture.append('input')
dateValidityCallback = chai.spy()
dp = new DatePicker(input, {
v2Features: {
dontModifyDateOnError: true,
displayLongMonthInCalendar: true,
dontSetInitialInputValue: true,
updateVisibleMonthOnDateChange: true,
dateValidityCallback: dateValidityCallback,
},
validRange: {
start: new Date(Date.now() - (oneDayMs * 4))
end: new Date(Date.now() + (oneDayMs * 4))
}
})
describe 'when the date is valid', ->
beforeEach ->
input.value('8/11/2018')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(2)
describe 'when the date is invalid', ->
beforeEach ->
input.value('<NAME>')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with false and INVALID_DATE', ->
dateValidityCallback.should.have.been.called.with(false, 'INVALID_DATE')
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(2)
describe 'and clearing the input value', ->
beforeEach ->
input.value('')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function three times', ->
dateValidityCallback.should.have.been.called.exactly(3)
describe 'when the date is before the valid range', ->
beforeEach ->
input.value('1/11/2018')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with false and DATE_OUTSIDE_RANGE_START', ->
dateValidityCallback.should.have.been.called.with(false, 'DATE_OUTSIDE_RANGE_START')
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(3)
describe 'and clearing the input value', ->
beforeEach ->
input.value('')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function three times', ->
dateValidityCallback.should.have.been.called.exactly(4)
describe 'when the date is after the valid range', ->
beforeEach ->
input.value('30/11/2018')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with false and DATE_OUTSIDE_RANGE_END', ->
dateValidityCallback.should.have.been.called.with(false, 'DATE_OUTSIDE_RANGE_END')
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(3)
describe 'and clearing the input value', ->
beforeEach ->
input.value('')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function three times', ->
dateValidityCallback.should.have.been.called.exactly(4)
describe 'and selectRange', ->
beforeEach ->
input.remove()
input = fixture.append('input')
dp = new DatePicker(input, {
v2Features: {
dontModifyDateOnError: true,
displayLongMonthInCalendar: true,
dontSetInitialInputValue: true,
updateVisibleMonthOnDateChange: true,
},
selectRange: true
})
it 'sets selectRange to false', ->
dp.options.selectRange.should.equal(false)
it 'logs a console warning', ->
logger.warn.should.have.been.called.with('DatePicker: options.selectRange is not supported when using an input')
describe 'and setting the date', ->
beforeEach ->
dp.date(new Date(Date.now() - (2 * oneMonthMs)))
it 'updates the visible month', ->
dp.visibleMonth().should.eql({ month: 9, year: 2018 })
describe 'localized timezones', () ->
testDateMs = Date.UTC(2019, 4, 22, 0, 20)
origDateNow = Date.now
beforeEach () ->
Date.now = ()-> testDateMs
afterEach () ->
Date.now = origDateNow
describe 'when using en-GB and UTC+01:00', () ->
stdDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('UTC+01:00')
stdDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
stdDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
stdDp.date().should.eql(new Date(2019, 4, 22))
# Default date localizer doesn't support timezones
describe 'when using en-GB and UTC-07:00', () ->
stdDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('UTC-07:00')
stdDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
stdDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
stdDp.date().should.eql(new Date(2019, 4, 22))
# PhantomJS doesn't support `Intl` and the polyfill doesn't support timezones...
if navigator.userAgent.indexOf('PhantomJS') is -1
describe 'localized timezones (preferences Intl API)', () ->
testDateMs = Date.UTC(2019, 4, 22, 0, 20)
origDateNow = Date.now
beforeEach () ->
Date.now = ()-> testDateMs
preferences.setup({
featureFlags: {
useIntlFormat: true,
},
})
afterEach () ->
Date.now = origDateNow
preferences.off()
preferences.setup()
describe 'default behaviour', ->
describe 'when using en-GB and Europe/London', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('Europe/London')
intlDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'when using en-US and America/Los_Angeles', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en')
preferences.timezone('America/Los_Angeles')
intlDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/21/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/22/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'when using fr and Pacific/Auckland', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('fr')
preferences.timezone('Pacific/Auckland')
intlDp = new DatePicker(fixture.append(div()), {
date: new Date(Date.UTC(2019, 4, 22, 20, 0))
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('23/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'outputFullDate behaviour', ->
describe 'when using en-GB and Europe/London', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('Europe/London')
intlDp = new DatePicker(fixture.append(div()), {
outputFullDate: true
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(testDateMs))
describe 'when using en-US and America/Los_Angeles', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en')
preferences.timezone('America/Los_Angeles')
intlDp = new DatePicker(fixture.append(div()), {
outputFullDate: true
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/21/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(testDateMs))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/22/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(testDateMs))
describe 'when using fr and Pacific/Auckland', () ->
intlDp = undefined
nzTestDate = Date.UTC(2019, 4, 22, 20, 0)
beforeEach () ->
preferences.locale('fr')
preferences.timezone('Pacific/Auckland')
intlDp = new DatePicker(fixture.append(div()), {
date: new Date(nzTestDate),
outputFullDate: true
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('23/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(nzTestDate))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(nzTestDate))
| true | import chai from 'chai'
import { select, div } from 'utils/selection'
import logger from 'utils/logger'
import { preferences } from 'utils/preferences'
import { DatePicker } from 'components/date-picker'
import { config as dropdownConfig } from 'components/dropdown'
import emit from 'test/utils/fake-event'
import installFakeTimers from 'test/utils/fake-time'
export default () ->
describe 'date-picker', ->
oneDayMs = 1000 * 60 * 60 * 24
oneMonthMs = 31 * oneDayMs
animationDelay = 301
origAttachSelector = dropdownConfig.attachToSelector
originalLoggerWarn = logger.warn
fixture = undefined
body = select('body')
beforeEach ->
logger.warn = chai.spy()
fixture = body.append('div').class('hx-test-date-picker')
dropdownConfig.attachToSelector = fixture
afterEach ->
logger.warn = originalLoggerWarn
dropdownConfig.attachToSelector = origAttachSelector
fixture.remove()
roundedDate = (start, today) ->
date = new Date
if today? and not today
day = (new Date).getDate()
if start
date.setDate(day - 2)
else
date.setDate(day + 2)
date.setHours(0, 0, 0, 0)
date
# The datepicker re-orders the start and end in case they are accidentally
# supplied in the wrong order so this is a helper for re-ordering them.
whichDateFirst = (range) ->
if range.start > range.end
{
start: range.end
end: range.start
}
else
range
describe 'test return types:', ->
describe 'should return this for getter setters with parameters:', ->
it 'dp.date', ->
dp = new DatePicker(div())
dp.date(roundedDate()).should.equal(dp)
it 'dp.day', ->
dp = new DatePicker(div())
dp.day(10).should.equal(dp)
it 'dp.month', ->
dp = new DatePicker(div())
dp.month(10).should.equal(dp)
it 'dp.year', ->
dp = new DatePicker(div())
dp.year(10).should.equal(dp)
it 'dp.locale', ->
dp = new DatePicker(div())
dp.locale('en-GB').should.equal(dp)
describe 'should return values for setter/getters without parameters:', ->
it 'dp.date', ->
dp = new DatePicker(div())
date = roundedDate()
dp.date(date).date().should.eql(date)
it 'dp.day', ->
dp = new DatePicker(div())
dp.day(10).day().should.equal(10)
it 'dp.month', ->
dp = new DatePicker(div())
dp.month(10).month().should.equal(10)
it 'dp.year', ->
dp = new DatePicker(div())
dp.year(10).year().should.equal(10)
it 'dp.locale', ->
dp = new DatePicker(div())
dp.locale('en-GB').locale().should.equal('en-GB')
it 'should return this for show', ->
dp = new DatePicker(div())
dp.show().should.equal(dp)
it 'should return this for hide', ->
dp = new DatePicker(div())
dp.hide().should.equal(dp)
it 'should return this for visibleMonth', ->
dp = new DatePicker(div())
dp.visibleMonth(10, 2015).should.equal(dp)
dp.visibleMonth().should.eql({month: 10, year: 2015})
it 'should return this for range', ->
dp = new DatePicker(div())
dp.range(roundedDate(), roundedDate()).should.equal(dp)
describe 'validRange', ->
it 'set both ends in one go and get should work', ->
dp = new DatePicker(div())
range = {start: roundedDate(), end: roundedDate()}
dp.validRange(range).should.equal(dp)
dp.validRange().should.eql(range)
it 'set start and get should work', ->
dp = new DatePicker(div())
range = {start: roundedDate()}
dp.validRange(range).should.equal(dp)
dp.validRange().should.eql({start: range.start, end: undefined})
it 'set end and get should work', ->
dp = new DatePicker(div())
range = {end: roundedDate()}
dp.validRange(range).should.equal(dp)
dp.validRange().should.eql({start: undefined, end: range.end})
it 'set both ends individually and get should work', ->
dp = new DatePicker(div())
start = {start: roundedDate()}
end = {end: roundedDate()}
dp.validRange(start).should.equal(dp)
dp.validRange(end).should.equal(dp)
dp.validRange().should.eql({start: start.start, end: end.end})
it 'using undefined should remove the start range', ->
dp = new DatePicker(div())
range1 = {start: roundedDate(), end: roundedDate()}
range2 = {start: undefined}
dp.validRange(range1).should.equal(dp)
dp.validRange(range2).should.equal(dp)
dp.validRange().should.eql({start: undefined, end: range1.end})
it 'using undefined should remove the end range', ->
dp = new DatePicker(div())
range1 = {start: roundedDate(), end: roundedDate()}
range2 = {end: undefined}
dp.validRange(range1).should.equal(dp)
dp.validRange(range2).should.equal(dp)
dp.validRange().should.eql({start: range1.start, end: undefined})
it 'using undefined should remove both ends range', ->
dp = new DatePicker(div())
range1 = {start: roundedDate(), end: roundedDate()}
range2 = {start: undefined, end: undefined}
dp.validRange(range1).should.equal(dp)
dp.validRange(range2).should.equal(dp)
dp.validRange().should.eql({start: undefined, end: undefined})
it 'defaults should be undefined', ->
dp = new DatePicker(div())
dp.validRange().should.eql({start: undefined, end: undefined})
it 'can be set in the constructor', ->
validRange = {
start: roundedDate(),
end: roundedDate()
}
dp = new DatePicker(div(), { validRange })
dp.validRange().should.eql(validRange)
describe 'range', ->
it 'should do nothing when attempting to use without setting selectRange', ->
dp = new DatePicker(div())
dp.range({start: roundedDate(true), end: roundedDate()})
logger.warn.should.have.been.called.with('datePicker.range can only be used for datepickers with \'selectRange\' of true')
it 'set both ends in one go and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
range = {start: roundedDate(true), end: roundedDate()}
dp.range(range).should.equal(dp)
dp.range().should.eql(whichDateFirst(range))
it 'set start and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
range = {start: roundedDate(true)}
dp.range(range).should.equal(dp)
dp.range().should.eql(whichDateFirst({start: range.start, end: roundedDate(null, true)}))
it 'set end and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
range = {end: roundedDate()}
dp.range(range).should.equal(dp)
dp.range().should.eql(whichDateFirst({start: roundedDate(null, true), end: range.end}))
it 'set both ends individually and get should work', ->
dp = new DatePicker(div(), {selectRange: true})
start = {start: roundedDate(true)}
end = {end: roundedDate()}
dp.range(start).should.equal(dp)
dp.range(end).should.equal(dp)
dp.range().should.eql(whichDateFirst({start: start.start, end: end.end}))
it 'defaults should be today', ->
dp = new DatePicker(div(), {selectRange: true})
dp.range().should.eql({start: roundedDate(null, true), end: roundedDate(null, true)})
it 'can be set in the constructor', ->
range = {start: roundedDate(true), end: roundedDate()}
dp = new DatePicker(div(), { selectRange: true, range: range })
dp.range().should.eql({start: roundedDate(true), end: roundedDate()})
describe 'options', ->
origDateNow = Date.now
clock = undefined
before ->
clock = installFakeTimers()
Date.now = () -> 1541675114940
after ->
clock.restore()
Date.now = origDateNow
describe 'allowViewChange', ->
dp = undefined
innerFixture = undefined
headerElem = undefined
beforeEach ->
innerFixture = fixture.append('div')
describe 'when false', ->
beforeEach ->
dp = new DatePicker(innerFixture, {
allowViewChange: false,
defaultView: 'y',
})
dp.show()
clock.tick(animationDelay)
headerElem = fixture.select('.hx-calendar-header-title')
it 'creates a div for the header text', ->
headerElem.node().tagName.toLowerCase().should.equal('div')
it 'changes the default view to month', ->
dp.options.defaultView.should.equal('m')
describe 'when true', ->
beforeEach ->
dp = new DatePicker(innerFixture, {
allowViewChange: true,
defaultView: 'd'
})
dp.show()
clock.tick(animationDelay)
headerElem = fixture.select('.hx-calendar-header-title')
it 'creates a button for the header text', ->
headerElem.node().tagName.toLowerCase().should.equal('button')
it 'allows the default view of decade', ->
dp.options.defaultView.should.equal('d')
describe 'v2Flags', ->
describe 'when using an input', ->
dp = undefined
input = undefined
beforeEach ->
input = fixture.append('input')
dp = new DatePicker(input, { v2Features: {
dontModifyDateOnError: true,
displayLongMonthInCalendar: true,
dontSetInitialInputValue: true,
updateVisibleMonthOnDateChange: true,
}})
it 'does not set the initial value', ->
input.value().should.equal('')
it 'has the correct visible month', ->
dp.visibleMonth().should.eql({ month: 11, year: 2018 })
describe 'when opening the picker', ->
beforeEach ->
dp.show()
it 'renders the month header as MMMM YYYY', ->
fixture.select('.hx-calendar-header-title').text().should.equal('November 2018')
describe 'and passing a dateValidityCallback', ->
dateValidityCallback = undefined
inputDebounceDelay = 501
beforeEach ->
input.remove()
input = fixture.append('input')
dateValidityCallback = chai.spy()
dp = new DatePicker(input, {
v2Features: {
dontModifyDateOnError: true,
displayLongMonthInCalendar: true,
dontSetInitialInputValue: true,
updateVisibleMonthOnDateChange: true,
dateValidityCallback: dateValidityCallback,
},
validRange: {
start: new Date(Date.now() - (oneDayMs * 4))
end: new Date(Date.now() + (oneDayMs * 4))
}
})
describe 'when the date is valid', ->
beforeEach ->
input.value('8/11/2018')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(2)
describe 'when the date is invalid', ->
beforeEach ->
input.value('PI:NAME:<NAME>END_PI')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with false and INVALID_DATE', ->
dateValidityCallback.should.have.been.called.with(false, 'INVALID_DATE')
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(2)
describe 'and clearing the input value', ->
beforeEach ->
input.value('')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function three times', ->
dateValidityCallback.should.have.been.called.exactly(3)
describe 'when the date is before the valid range', ->
beforeEach ->
input.value('1/11/2018')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with false and DATE_OUTSIDE_RANGE_START', ->
dateValidityCallback.should.have.been.called.with(false, 'DATE_OUTSIDE_RANGE_START')
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(3)
describe 'and clearing the input value', ->
beforeEach ->
input.value('')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function three times', ->
dateValidityCallback.should.have.been.called.exactly(4)
describe 'when the date is after the valid range', ->
beforeEach ->
input.value('30/11/2018')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with false and DATE_OUTSIDE_RANGE_END', ->
dateValidityCallback.should.have.been.called.with(false, 'DATE_OUTSIDE_RANGE_END')
it 'calls the function twice', ->
dateValidityCallback.should.have.been.called.exactly(3)
describe 'and clearing the input value', ->
beforeEach ->
input.value('')
emit(input.node(), 'input')
clock.tick(inputDebounceDelay)
it 'calls the function with true', ->
dateValidityCallback.should.have.been.called.with(true, undefined)
it 'calls the function three times', ->
dateValidityCallback.should.have.been.called.exactly(4)
describe 'and selectRange', ->
beforeEach ->
input.remove()
input = fixture.append('input')
dp = new DatePicker(input, {
v2Features: {
dontModifyDateOnError: true,
displayLongMonthInCalendar: true,
dontSetInitialInputValue: true,
updateVisibleMonthOnDateChange: true,
},
selectRange: true
})
it 'sets selectRange to false', ->
dp.options.selectRange.should.equal(false)
it 'logs a console warning', ->
logger.warn.should.have.been.called.with('DatePicker: options.selectRange is not supported when using an input')
describe 'and setting the date', ->
beforeEach ->
dp.date(new Date(Date.now() - (2 * oneMonthMs)))
it 'updates the visible month', ->
dp.visibleMonth().should.eql({ month: 9, year: 2018 })
describe 'localized timezones', () ->
testDateMs = Date.UTC(2019, 4, 22, 0, 20)
origDateNow = Date.now
beforeEach () ->
Date.now = ()-> testDateMs
afterEach () ->
Date.now = origDateNow
describe 'when using en-GB and UTC+01:00', () ->
stdDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('UTC+01:00')
stdDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
stdDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
stdDp.date().should.eql(new Date(2019, 4, 22))
# Default date localizer doesn't support timezones
describe 'when using en-GB and UTC-07:00', () ->
stdDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('UTC-07:00')
stdDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
stdDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
stdDp.date().should.eql(new Date(2019, 4, 22))
# PhantomJS doesn't support `Intl` and the polyfill doesn't support timezones...
if navigator.userAgent.indexOf('PhantomJS') is -1
describe 'localized timezones (preferences Intl API)', () ->
testDateMs = Date.UTC(2019, 4, 22, 0, 20)
origDateNow = Date.now
beforeEach () ->
Date.now = ()-> testDateMs
preferences.setup({
featureFlags: {
useIntlFormat: true,
},
})
afterEach () ->
Date.now = origDateNow
preferences.off()
preferences.setup()
describe 'default behaviour', ->
describe 'when using en-GB and Europe/London', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('Europe/London')
intlDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'when using en-US and America/Los_Angeles', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en')
preferences.timezone('America/Los_Angeles')
intlDp = new DatePicker(fixture.append(div()))
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/21/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/22/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'when using fr and Pacific/Auckland', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('fr')
preferences.timezone('Pacific/Auckland')
intlDp = new DatePicker(fixture.append(div()), {
date: new Date(Date.UTC(2019, 4, 22, 20, 0))
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('23/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(2019, 4, 22))
describe 'outputFullDate behaviour', ->
describe 'when using en-GB and Europe/London', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en-GB')
preferences.timezone('Europe/London')
intlDp = new DatePicker(fixture.append(div()), {
outputFullDate: true
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(testDateMs))
describe 'when using en-US and America/Los_Angeles', () ->
intlDp = undefined
beforeEach () ->
preferences.locale('en')
preferences.timezone('America/Los_Angeles')
intlDp = new DatePicker(fixture.append(div()), {
outputFullDate: true
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/21/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(testDateMs))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('5/22/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(testDateMs))
describe 'when using fr and Pacific/Auckland', () ->
intlDp = undefined
nzTestDate = Date.UTC(2019, 4, 22, 20, 0)
beforeEach () ->
preferences.locale('fr')
preferences.timezone('Pacific/Auckland')
intlDp = new DatePicker(fixture.append(div()), {
date: new Date(nzTestDate),
outputFullDate: true
})
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('23/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(nzTestDate))
describe 'then changing to Europe/London', ->
beforeEach ->
preferences.timezone('Europe/London')
it 'has the correct screen date', () ->
intlDp.getScreenDate().should.equal('22/05/2019')
it 'has the correct date', () ->
intlDp.date().should.eql(new Date(nzTestDate))
|
[
{
"context": "0-e4a1-4de3-b8a3-20d4db3d3481\"\n name: \"Livre\"\n matter: [\n {\n ",
"end": 419,
"score": 0.9438744783401489,
"start": 414,
"tag": "NAME",
"value": "Livre"
},
{
"context": "308-88ad-9489f1a44bb2\"\n name: \"Titre\"\n data: \"La Genèse\"\n ",
"end": 558,
"score": 0.8160903453826904,
"start": 553,
"tag": "NAME",
"value": "Titre"
}
] | general/locco/document.spec.coffee | DrJekyllandMrHyde/chocolate | 41 | Document = require '../../general/locco/document'
describe 'Document', ->
it 'should create a Document with no input', ->
expect((new Document) instanceof Document).toBeTruthy()
expect(typeof (new Document).uuid).toEqual('string')
it 'should create a Document with a simple input', ->
doc = new Document
uuid: "913ae9b0-e4a1-4de3-b8a3-20d4db3d3481"
name: "Livre"
matter: [
{
uuid: "46479fe8-499f-4308-88ad-9489f1a44bb2"
name: "Titre"
data: "La Genèse"
}
]
expect(doc.uuid).toEqual("913ae9b0-e4a1-4de3-b8a3-20d4db3d3481")
| 220496 | Document = require '../../general/locco/document'
describe 'Document', ->
it 'should create a Document with no input', ->
expect((new Document) instanceof Document).toBeTruthy()
expect(typeof (new Document).uuid).toEqual('string')
it 'should create a Document with a simple input', ->
doc = new Document
uuid: "913ae9b0-e4a1-4de3-b8a3-20d4db3d3481"
name: "<NAME>"
matter: [
{
uuid: "46479fe8-499f-4308-88ad-9489f1a44bb2"
name: "<NAME>"
data: "La Genèse"
}
]
expect(doc.uuid).toEqual("913ae9b0-e4a1-4de3-b8a3-20d4db3d3481")
| true | Document = require '../../general/locco/document'
describe 'Document', ->
it 'should create a Document with no input', ->
expect((new Document) instanceof Document).toBeTruthy()
expect(typeof (new Document).uuid).toEqual('string')
it 'should create a Document with a simple input', ->
doc = new Document
uuid: "913ae9b0-e4a1-4de3-b8a3-20d4db3d3481"
name: "PI:NAME:<NAME>END_PI"
matter: [
{
uuid: "46479fe8-499f-4308-88ad-9489f1a44bb2"
name: "PI:NAME:<NAME>END_PI"
data: "La Genèse"
}
]
expect(doc.uuid).toEqual("913ae9b0-e4a1-4de3-b8a3-20d4db3d3481")
|
[
{
"context": "resolve) ->\n resolve\n id: id\n name: 'Kitty'\n)",
"end": 160,
"score": 0.9993953704833984,
"start": 155,
"tag": "NAME",
"value": "Kitty"
}
] | app/api/resources/cat.coffee | dlepaux/mithril-isomorphic-kitstarter | 3 | 'use strict'
# Requires
Promise = require('promise')
module.exports = cat: get: (id) ->
new Promise((resolve) ->
resolve
id: id
name: 'Kitty'
) | 39315 | 'use strict'
# Requires
Promise = require('promise')
module.exports = cat: get: (id) ->
new Promise((resolve) ->
resolve
id: id
name: '<NAME>'
) | true | 'use strict'
# Requires
Promise = require('promise')
module.exports = cat: get: (id) ->
new Promise((resolve) ->
resolve
id: id
name: 'PI:NAME:<NAME>END_PI'
) |
[
{
"context": "elago_-adults_and_chicks-8.jpg\" title=\"Uploaded by snowmanradio\">Background image by Liam Quinn from Canada<",
"end": 372,
"score": 0.5334264039993286,
"start": 365,
"tag": "USERNAME",
"value": "snowman"
},
{
"context": "tle=\"Uploaded by snowmanradio\">Background image by Liam Quinn from Canada</a>\n <a href=\"http://creativecommo",
"end": 409,
"score": 0.9984060525894165,
"start": 399,
"tag": "NAME",
"value": "Liam Quinn"
}
] | attribute-background-image.coffee | zooniverse/penguinwatch | 0 | document.body.insertAdjacentHTML 'beforeEnd', '''
<div id="background-image-attribution">
<a href="http://commons.wikimedia.org/wiki/File:Pygoscelis_papua_-Jougla_Point,_Wiencke_Island,_Palmer_Archipelago_-adults_and_chicks-8.jpg#mediaviewer/File:Pygoscelis_papua_-Jougla_Point,_Wiencke_Island,_Palmer_Archipelago_-adults_and_chicks-8.jpg" title="Uploaded by snowmanradio">Background image by Liam Quinn from Canada</a>
<a href="http://creativecommons.org/licenses/by-sa/2.0">(CC BY-SA 2.0)</a>
</div>
'''
| 139224 | document.body.insertAdjacentHTML 'beforeEnd', '''
<div id="background-image-attribution">
<a href="http://commons.wikimedia.org/wiki/File:Pygoscelis_papua_-Jougla_Point,_Wiencke_Island,_Palmer_Archipelago_-adults_and_chicks-8.jpg#mediaviewer/File:Pygoscelis_papua_-Jougla_Point,_Wiencke_Island,_Palmer_Archipelago_-adults_and_chicks-8.jpg" title="Uploaded by snowmanradio">Background image by <NAME> from Canada</a>
<a href="http://creativecommons.org/licenses/by-sa/2.0">(CC BY-SA 2.0)</a>
</div>
'''
| true | document.body.insertAdjacentHTML 'beforeEnd', '''
<div id="background-image-attribution">
<a href="http://commons.wikimedia.org/wiki/File:Pygoscelis_papua_-Jougla_Point,_Wiencke_Island,_Palmer_Archipelago_-adults_and_chicks-8.jpg#mediaviewer/File:Pygoscelis_papua_-Jougla_Point,_Wiencke_Island,_Palmer_Archipelago_-adults_and_chicks-8.jpg" title="Uploaded by snowmanradio">Background image by PI:NAME:<NAME>END_PI from Canada</a>
<a href="http://creativecommons.org/licenses/by-sa/2.0">(CC BY-SA 2.0)</a>
</div>
'''
|
[
{
"context": "blesorter.com\n###\n\nlast_name_options =\n id: 'last_name' # the parser na",
"end": 170,
"score": 0.7529597282409668,
"start": 166,
"tag": "NAME",
"value": "last"
}
] | app/assets/javascripts/members/mem_indx_table.js.coffee | andyl/BAMRU-Private | 1 | ###
This is jQuery code that manages the
table sorting on the members/index page.
Table sorter plugin at: http://tablesorter.com
###
last_name_options =
id: 'last_name' # the parser name
is: (s) -> false # disable standard parser
type: 'text' # either text or numeric
format: (s) -> (new MemberName(s)).last_name() # the sort key (last name)
role_score_options =
id: 'role_score' # the parser name
is: (s) -> false # disable standard parser
type: 'numeric' # either text or numeric
format: (s) -> (new RoleScore(s)).score() # the sort key (last name)
sort_opts =
headers:
0: {sorter: 'role_score'} # sort col 0 using role_score options
1: {sorter: false }
2: {sorter: false }
3: {sorter: 'last_name'} # sort col 3 using last_name options
filter_params =
filterContainer: "#filter-box"
filterClearContainer: "#filter-clear-button"
filterColumns: [0,3]
columns: ["role", "name"]
save_member_sort_to_cookie = (sort_spec) ->
spec_string = JSON.stringify(sort_spec)
createCookie("mem_sort", spec_string)
read_member_sort_from_cookie = ->
string = readCookie("mem_sort")
if (string == null) then null else JSON.parse(string)
$(document).ready ->
$.tablesorter.addParser last_name_options
$.tablesorter.addParser role_score_options
sort_spec = read_member_sort_from_cookie()
sort_opts['sortList'] = sort_spec unless sort_spec == null
$("#myTable").tablesorter(sort_opts).bind "sortEnd", (sorter) ->
save_member_sort_to_cookie(sorter.target.config.sortList)
$("#myTable").tablesorterFilter(filter_params)
$("#filter-box").focus()
$("#filter-clear-button").click ->
setTimeout('updateAddressCount()', 50)
$("#filter-box").keyup ->
setTimeout('setEqualHeight()', 600)
setTimeout('updateAddressCount()', 600)
$(document).ready ->
$('#clearsort').click ->
eraseCookie("mem_sort")
refresh_url = window.location.href.split(/[?#]/, 1)
window.location.assign(refresh_url) | 180756 | ###
This is jQuery code that manages the
table sorting on the members/index page.
Table sorter plugin at: http://tablesorter.com
###
last_name_options =
id: '<NAME>_name' # the parser name
is: (s) -> false # disable standard parser
type: 'text' # either text or numeric
format: (s) -> (new MemberName(s)).last_name() # the sort key (last name)
role_score_options =
id: 'role_score' # the parser name
is: (s) -> false # disable standard parser
type: 'numeric' # either text or numeric
format: (s) -> (new RoleScore(s)).score() # the sort key (last name)
sort_opts =
headers:
0: {sorter: 'role_score'} # sort col 0 using role_score options
1: {sorter: false }
2: {sorter: false }
3: {sorter: 'last_name'} # sort col 3 using last_name options
filter_params =
filterContainer: "#filter-box"
filterClearContainer: "#filter-clear-button"
filterColumns: [0,3]
columns: ["role", "name"]
save_member_sort_to_cookie = (sort_spec) ->
spec_string = JSON.stringify(sort_spec)
createCookie("mem_sort", spec_string)
read_member_sort_from_cookie = ->
string = readCookie("mem_sort")
if (string == null) then null else JSON.parse(string)
$(document).ready ->
$.tablesorter.addParser last_name_options
$.tablesorter.addParser role_score_options
sort_spec = read_member_sort_from_cookie()
sort_opts['sortList'] = sort_spec unless sort_spec == null
$("#myTable").tablesorter(sort_opts).bind "sortEnd", (sorter) ->
save_member_sort_to_cookie(sorter.target.config.sortList)
$("#myTable").tablesorterFilter(filter_params)
$("#filter-box").focus()
$("#filter-clear-button").click ->
setTimeout('updateAddressCount()', 50)
$("#filter-box").keyup ->
setTimeout('setEqualHeight()', 600)
setTimeout('updateAddressCount()', 600)
$(document).ready ->
$('#clearsort').click ->
eraseCookie("mem_sort")
refresh_url = window.location.href.split(/[?#]/, 1)
window.location.assign(refresh_url) | true | ###
This is jQuery code that manages the
table sorting on the members/index page.
Table sorter plugin at: http://tablesorter.com
###
last_name_options =
id: 'PI:NAME:<NAME>END_PI_name' # the parser name
is: (s) -> false # disable standard parser
type: 'text' # either text or numeric
format: (s) -> (new MemberName(s)).last_name() # the sort key (last name)
role_score_options =
id: 'role_score' # the parser name
is: (s) -> false # disable standard parser
type: 'numeric' # either text or numeric
format: (s) -> (new RoleScore(s)).score() # the sort key (last name)
sort_opts =
headers:
0: {sorter: 'role_score'} # sort col 0 using role_score options
1: {sorter: false }
2: {sorter: false }
3: {sorter: 'last_name'} # sort col 3 using last_name options
filter_params =
filterContainer: "#filter-box"
filterClearContainer: "#filter-clear-button"
filterColumns: [0,3]
columns: ["role", "name"]
save_member_sort_to_cookie = (sort_spec) ->
spec_string = JSON.stringify(sort_spec)
createCookie("mem_sort", spec_string)
read_member_sort_from_cookie = ->
string = readCookie("mem_sort")
if (string == null) then null else JSON.parse(string)
$(document).ready ->
$.tablesorter.addParser last_name_options
$.tablesorter.addParser role_score_options
sort_spec = read_member_sort_from_cookie()
sort_opts['sortList'] = sort_spec unless sort_spec == null
$("#myTable").tablesorter(sort_opts).bind "sortEnd", (sorter) ->
save_member_sort_to_cookie(sorter.target.config.sortList)
$("#myTable").tablesorterFilter(filter_params)
$("#filter-box").focus()
$("#filter-clear-button").click ->
setTimeout('updateAddressCount()', 50)
$("#filter-box").keyup ->
setTimeout('setEqualHeight()', 600)
setTimeout('updateAddressCount()', 600)
$(document).ready ->
$('#clearsort').click ->
eraseCookie("mem_sort")
refresh_url = window.location.href.split(/[?#]/, 1)
window.location.assign(refresh_url) |
[
{
"context": "orm Javascript Library\n\n URL: https://github.com/jondavidjohn/payform\n Author: Jonathan D. Johnson <me@jondavi",
"end": 72,
"score": 0.8233920335769653,
"start": 60,
"tag": "USERNAME",
"value": "jondavidjohn"
},
{
"context": " https://github.com/jondavidjohn/payform\n Author: Jonathan D. Johnson <me@jondavidjohn.com>\n License: MIT\n Version: 1",
"end": 110,
"score": 0.9998731017112732,
"start": 91,
"tag": "NAME",
"value": "Jonathan D. Johnson"
},
{
"context": "ndavidjohn/payform\n Author: Jonathan D. Johnson <me@jondavidjohn.com>\n License: MIT\n Version: 1.0.2\n###\n((name, defi",
"end": 131,
"score": 0.9999344944953918,
"start": 112,
"tag": "EMAIL",
"value": "me@jondavidjohn.com"
}
] | src/payform.coffee | nickpresta/payform | 3 | ###
Payform Javascript Library
URL: https://github.com/jondavidjohn/payform
Author: Jonathan D. Johnson <me@jondavidjohn.com>
License: MIT
Version: 1.0.2
###
((name, definition) ->
if module?
module.exports = definition()
else if typeof define is 'function' and typeof define.amd is 'object'
define(name, definition)
else
this[name] = definition()
)('payform', ->
_getCaretPos = (ele) ->
if ele.selectionStart?
return ele.selectionStart
else if document.selection?
ele.focus()
r = document.selection.createRange()
re = ele.createTextRange()
rc = re.duplicate()
re.moveToBookmark(r.getBookmark())
rc.setEndPoint('EndToStart', re)
return rc.text.length
_eventNormalize = (listener) ->
return (e = window.event) ->
e.target = e.target or e.srcElement
e.which = e.which or e.keyCode
unless e.preventDefault?
e.preventDefault = -> this.returnValue = false
listener(e)
_on = (ele, event, listener) ->
listener = _eventNormalize(listener)
if ele.addEventListener?
ele.addEventListener(event, listener, false)
else
ele.attachEvent("on#{event}", listener)
payform = {}
# Utils
defaultFormat = /(\d{1,4})/g
payform.cards = [
# Debit cards must come first, since they have more
# specific patterns than their credit-card equivalents.
{
type: 'visaelectron'
pattern: /^4(026|17500|405|508|844|91[37])/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'maestro'
pattern: /^(5(018|0[23]|[68])|6(39|7))/
format: defaultFormat
length: [12..19]
cvcLength: [3]
luhn: true
}
{
type: 'forbrugsforeningen'
pattern: /^600/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'dankort'
pattern: /^5019/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
# Credit cards
{
type: 'visa'
pattern: /^4/
format: defaultFormat
length: [13, 16]
cvcLength: [3]
luhn: true
}
{
type: 'mastercard'
pattern: /^5[0-5]/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'amex'
pattern: /^3[47]/
format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/
length: [15]
cvcLength: [3..4]
luhn: true
}
{
type: 'dinersclub'
pattern: /^3[0689]/
format: defaultFormat
length: [14]
cvcLength: [3]
luhn: true
}
{
type: 'discover'
pattern: /^6([045]|22)/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'unionpay'
pattern: /^(62|88)/
format: defaultFormat
length: [16..19]
cvcLength: [3]
luhn: false
}
{
type: 'jcb'
pattern: /^35/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
]
cardFromNumber = (num) ->
num = (num + '').replace(/\D/g, '')
return card for card in payform.cards when card.pattern.test(num)
cardFromType = (type) ->
return card for card in payform.cards when card.type is type
luhnCheck = (num) ->
odd = true
sum = 0
digits = (num + '').split('').reverse()
for digit in digits
digit = parseInt(digit, 10)
digit *= 2 if (odd = !odd)
digit -= 9 if digit > 9
sum += digit
sum % 10 == 0
hasTextSelected = (target) ->
# If some text is selected in IE
if document?.selection?.createRange?
return true if document.selection.createRange().text
target.selectionStart? and target.selectionStart isnt target.selectionEnd
# Private
# Format Card Number
reFormatCardNumber = (e) ->
cursor = _getCaretPos(e.target)
e.target.value = payform.formatCardNumber(e.target.value)
if cursor? and e.type isnt 'change'
e.target.setSelectionRange(cursor, cursor)
formatCardNumber = (e) ->
# Only format if input is a number
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
value = e.target.value
card = cardFromNumber(value + digit)
length = (value.replace(/\D/g, '') + digit).length
upperLength = 16
upperLength = card.length[card.length.length - 1] if card
return if length >= upperLength
# Return if focus isn't at the end of the text
cursor = _getCaretPos(e.target)
return if cursor and cursor isnt value.length
if card && card.type is 'amex'
# AMEX cards are formatted differently
re = /^(\d{4}|\d{4}\s\d{6})$/
else
re = /(?:^|\s)(\d{4})$/
# If '4242' + 4
if re.test(value)
e.preventDefault()
setTimeout -> e.target.value = "#{value} #{digit}"
# If '424' + 2
else if re.test(value + digit)
e.preventDefault()
setTimeout -> e.target.value = "#{value + digit} "
formatBackCardNumber = (e) ->
value = e.target.value
# Return unless backspacing
return unless e.which is 8
# Return if focus isn't at the end of the text
cursor = _getCaretPos(e.target)
return if cursor and cursor isnt value.length
# Remove the digit + trailing space
if /\d\s$/.test(value)
e.preventDefault()
setTimeout -> e.target.value = value.replace /\d\s$/, ''
# Remove digit if ends in space + digit
else if /\s\d?$/.test(value)
e.preventDefault()
setTimeout -> e.target.value = value.replace /\d$/, ''
# Format Expiry
reFormatExpiry = (e) ->
cursor = _getCaretPos(e.target)
e.target.value = payform.formatCardExpiry(e.target.value)
if cursor? and e.type isnt 'change'
e.target.setSelectionRange(cursor, cursor)
formatCardExpiry = (e) ->
# Only format if input is a number
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
val = e.target.value + digit
if /^\d$/.test(val) and val not in ['0', '1']
e.preventDefault()
setTimeout -> e.target.value = "0#{val} / "
else if /^\d\d$/.test(val)
e.preventDefault()
setTimeout -> e.target.value = "#{val} / "
formatForwardExpiry = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
val = e.target.value
if /^\d\d$/.test(val)
e.target.value = "#{val} / "
formatForwardSlashAndSpace = (e) ->
which = String.fromCharCode(e.which)
return unless which is '/' or which is ' '
val = e.target.value
if /^\d$/.test(val) and val isnt '0'
e.target.value = "0#{val} / "
formatBackExpiry = (e) ->
value = e.target.value
# Return unless backspacing
return unless e.which is 8
# Return if focus isn't at the end of the text
cursor = _getCaretPos(e.target)
return if cursor and cursor isnt value.length
# Remove the trailing space + last digit
if /\d\s\/\s$/.test(value)
e.preventDefault()
setTimeout -> e.target.value = value.replace(/\d\s\/\s$/, '')
# Format CVC
reFormatCVC = (e) ->
cursor = _getCaretPos(e.target)
e.target.value = e.target.value.replace(/\D/g, '')[0...4]
if cursor? and e.type isnt 'change'
e.target.setSelectionRange(cursor, cursor)
# Restrictions
restrictNumeric = (e) ->
# Key event is for a browser shortcut
return if e.metaKey or e.ctrlKey
# If keycode is a special char (WebKit)
return if e.which is 0
# If char is a special char (Firefox)
return if e.which < 33
input = String.fromCharCode(e.which)
# Char is a number
unless /^\d+$/.test(input)
e.preventDefault()
restrictCardNumber = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
return if hasTextSelected(e.target)
# Restrict number of digits
value = (e.target.value + digit).replace(/\D/g, '')
card = cardFromNumber(value)
if card and value.length > card.length[card.length.length - 1]
e.preventDefault()
else if value.length > 16
e.preventDefault()
restrictExpiry = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
return if hasTextSelected(e.target)
value = e.target.value + digit
value = value.replace(/\D/g, '')
if value.length > 6
e.preventDefault()
restrictCVC = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
return if hasTextSelected(e.target)
val = e.target.value + digit
if val.length > 4
e.preventDefault()
# Public
# Formatting
payform.cvcInput = (input) ->
_on(input, 'keypress', restrictNumeric)
_on(input, 'keypress', restrictCVC)
_on(input, 'paste', reFormatCVC)
_on(input, 'change', reFormatCVC)
_on(input, 'input', reFormatCVC)
payform.expiryInput = (input) ->
_on(input, 'keypress', restrictNumeric)
_on(input, 'keypress', restrictExpiry)
_on(input, 'keypress', formatCardExpiry)
_on(input, 'keypress', formatForwardSlashAndSpace)
_on(input, 'keypress', formatForwardExpiry)
_on(input, 'keydown', formatBackExpiry)
_on(input, 'change', reFormatExpiry)
_on(input, 'input', reFormatExpiry)
payform.cardNumberInput = (input) ->
_on(input, 'keypress', restrictNumeric)
_on(input, 'keypress', restrictCardNumber)
_on(input, 'keypress', formatCardNumber)
_on(input, 'keydown', formatBackCardNumber)
_on(input, 'paste', reFormatCardNumber)
_on(input, 'change', reFormatCardNumber)
_on(input, 'input', reFormatCardNumber)
# Validations
payform.parseCardExpiry = (value) ->
value = value.replace(/\s/g, '')
[month, year] = value.split('/', 2)
# Allow for year shortcut
if year?.length is 2 and /^\d+$/.test(year)
prefix = (new Date).getFullYear()
prefix = prefix.toString()[0..1]
year = prefix + year
month = parseInt(month, 10)
year = parseInt(year, 10)
month: month, year: year
payform.validateCardNumber = (num) ->
num = (num + '').replace(/\s+|-/g, '')
return false unless /^\d+$/.test(num)
card = cardFromNumber(num)
return false unless card
num.length in card.length and
(card.luhn is false or luhnCheck(num))
payform.validateCardExpiry = (month, year) ->
# Allow passing an object
if typeof month is 'object' and 'month' of month
{month, year} = month
return false unless month and year
month = String(month).trim()
year = String(year).trim()
return false unless /^\d+$/.test(month)
return false unless /^\d+$/.test(year)
return false unless 1 <= month <= 12
if year.length == 2
if year < 70
year = "20#{year}"
else
year = "19#{year}"
return false unless year.length == 4
expiry = new Date(year, month)
currentTime = new Date
# Months start from 0 in JavaScript
expiry.setMonth(expiry.getMonth() - 1)
# The cc expires at the end of the month,
# so we need to make the expiry the first day
# of the month after
expiry.setMonth(expiry.getMonth() + 1, 1)
expiry > currentTime
payform.validateCardCVC = (cvc, type) ->
cvc = String(cvc).trim()
return false unless /^\d+$/.test(cvc)
card = cardFromType(type)
if card?
# Check against a explicit card type
cvc.length in card.cvcLength
else
# Check against all types
cvc.length >= 3 and cvc.length <= 4
payform.parseCardType = (num) ->
return null unless num
cardFromNumber(num)?.type or null
payform.formatCardNumber = (num) ->
num = num.replace(/\D/g, '')
card = cardFromNumber(num)
return num unless card
upperLength = card.length[card.length.length - 1]
num = num[0...upperLength]
if card.format.global
num.match(card.format)?.join(' ')
else
groups = card.format.exec(num)
return unless groups?
groups.shift()
groups = groups.filter(Boolean)
groups.join(' ')
payform.formatCardExpiry = (expiry) ->
parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/)
return '' unless parts
mon = parts[1] || ''
sep = parts[2] || ''
year = parts[3] || ''
if year.length > 0
sep = ' / '
else if sep is ' /'
mon = mon.substring(0, 1)
sep = ''
else if mon.length == 2 or sep.length > 0
sep = ' / '
else if mon.length == 1 and mon not in ['0', '1']
mon = "0#{mon}"
sep = ' / '
return mon + sep + year
payform
)
| 22872 | ###
Payform Javascript Library
URL: https://github.com/jondavidjohn/payform
Author: <NAME> <<EMAIL>>
License: MIT
Version: 1.0.2
###
((name, definition) ->
if module?
module.exports = definition()
else if typeof define is 'function' and typeof define.amd is 'object'
define(name, definition)
else
this[name] = definition()
)('payform', ->
_getCaretPos = (ele) ->
if ele.selectionStart?
return ele.selectionStart
else if document.selection?
ele.focus()
r = document.selection.createRange()
re = ele.createTextRange()
rc = re.duplicate()
re.moveToBookmark(r.getBookmark())
rc.setEndPoint('EndToStart', re)
return rc.text.length
_eventNormalize = (listener) ->
return (e = window.event) ->
e.target = e.target or e.srcElement
e.which = e.which or e.keyCode
unless e.preventDefault?
e.preventDefault = -> this.returnValue = false
listener(e)
_on = (ele, event, listener) ->
listener = _eventNormalize(listener)
if ele.addEventListener?
ele.addEventListener(event, listener, false)
else
ele.attachEvent("on#{event}", listener)
payform = {}
# Utils
defaultFormat = /(\d{1,4})/g
payform.cards = [
# Debit cards must come first, since they have more
# specific patterns than their credit-card equivalents.
{
type: 'visaelectron'
pattern: /^4(026|17500|405|508|844|91[37])/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'maestro'
pattern: /^(5(018|0[23]|[68])|6(39|7))/
format: defaultFormat
length: [12..19]
cvcLength: [3]
luhn: true
}
{
type: 'forbrugsforeningen'
pattern: /^600/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'dankort'
pattern: /^5019/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
# Credit cards
{
type: 'visa'
pattern: /^4/
format: defaultFormat
length: [13, 16]
cvcLength: [3]
luhn: true
}
{
type: 'mastercard'
pattern: /^5[0-5]/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'amex'
pattern: /^3[47]/
format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/
length: [15]
cvcLength: [3..4]
luhn: true
}
{
type: 'dinersclub'
pattern: /^3[0689]/
format: defaultFormat
length: [14]
cvcLength: [3]
luhn: true
}
{
type: 'discover'
pattern: /^6([045]|22)/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'unionpay'
pattern: /^(62|88)/
format: defaultFormat
length: [16..19]
cvcLength: [3]
luhn: false
}
{
type: 'jcb'
pattern: /^35/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
]
cardFromNumber = (num) ->
num = (num + '').replace(/\D/g, '')
return card for card in payform.cards when card.pattern.test(num)
cardFromType = (type) ->
return card for card in payform.cards when card.type is type
luhnCheck = (num) ->
odd = true
sum = 0
digits = (num + '').split('').reverse()
for digit in digits
digit = parseInt(digit, 10)
digit *= 2 if (odd = !odd)
digit -= 9 if digit > 9
sum += digit
sum % 10 == 0
hasTextSelected = (target) ->
# If some text is selected in IE
if document?.selection?.createRange?
return true if document.selection.createRange().text
target.selectionStart? and target.selectionStart isnt target.selectionEnd
# Private
# Format Card Number
reFormatCardNumber = (e) ->
cursor = _getCaretPos(e.target)
e.target.value = payform.formatCardNumber(e.target.value)
if cursor? and e.type isnt 'change'
e.target.setSelectionRange(cursor, cursor)
formatCardNumber = (e) ->
# Only format if input is a number
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
value = e.target.value
card = cardFromNumber(value + digit)
length = (value.replace(/\D/g, '') + digit).length
upperLength = 16
upperLength = card.length[card.length.length - 1] if card
return if length >= upperLength
# Return if focus isn't at the end of the text
cursor = _getCaretPos(e.target)
return if cursor and cursor isnt value.length
if card && card.type is 'amex'
# AMEX cards are formatted differently
re = /^(\d{4}|\d{4}\s\d{6})$/
else
re = /(?:^|\s)(\d{4})$/
# If '4242' + 4
if re.test(value)
e.preventDefault()
setTimeout -> e.target.value = "#{value} #{digit}"
# If '424' + 2
else if re.test(value + digit)
e.preventDefault()
setTimeout -> e.target.value = "#{value + digit} "
formatBackCardNumber = (e) ->
value = e.target.value
# Return unless backspacing
return unless e.which is 8
# Return if focus isn't at the end of the text
cursor = _getCaretPos(e.target)
return if cursor and cursor isnt value.length
# Remove the digit + trailing space
if /\d\s$/.test(value)
e.preventDefault()
setTimeout -> e.target.value = value.replace /\d\s$/, ''
# Remove digit if ends in space + digit
else if /\s\d?$/.test(value)
e.preventDefault()
setTimeout -> e.target.value = value.replace /\d$/, ''
# Format Expiry
reFormatExpiry = (e) ->
cursor = _getCaretPos(e.target)
e.target.value = payform.formatCardExpiry(e.target.value)
if cursor? and e.type isnt 'change'
e.target.setSelectionRange(cursor, cursor)
formatCardExpiry = (e) ->
# Only format if input is a number
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
val = e.target.value + digit
if /^\d$/.test(val) and val not in ['0', '1']
e.preventDefault()
setTimeout -> e.target.value = "0#{val} / "
else if /^\d\d$/.test(val)
e.preventDefault()
setTimeout -> e.target.value = "#{val} / "
formatForwardExpiry = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
val = e.target.value
if /^\d\d$/.test(val)
e.target.value = "#{val} / "
formatForwardSlashAndSpace = (e) ->
which = String.fromCharCode(e.which)
return unless which is '/' or which is ' '
val = e.target.value
if /^\d$/.test(val) and val isnt '0'
e.target.value = "0#{val} / "
formatBackExpiry = (e) ->
value = e.target.value
# Return unless backspacing
return unless e.which is 8
# Return if focus isn't at the end of the text
cursor = _getCaretPos(e.target)
return if cursor and cursor isnt value.length
# Remove the trailing space + last digit
if /\d\s\/\s$/.test(value)
e.preventDefault()
setTimeout -> e.target.value = value.replace(/\d\s\/\s$/, '')
# Format CVC
reFormatCVC = (e) ->
cursor = _getCaretPos(e.target)
e.target.value = e.target.value.replace(/\D/g, '')[0...4]
if cursor? and e.type isnt 'change'
e.target.setSelectionRange(cursor, cursor)
# Restrictions
restrictNumeric = (e) ->
# Key event is for a browser shortcut
return if e.metaKey or e.ctrlKey
# If keycode is a special char (WebKit)
return if e.which is 0
# If char is a special char (Firefox)
return if e.which < 33
input = String.fromCharCode(e.which)
# Char is a number
unless /^\d+$/.test(input)
e.preventDefault()
restrictCardNumber = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
return if hasTextSelected(e.target)
# Restrict number of digits
value = (e.target.value + digit).replace(/\D/g, '')
card = cardFromNumber(value)
if card and value.length > card.length[card.length.length - 1]
e.preventDefault()
else if value.length > 16
e.preventDefault()
restrictExpiry = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
return if hasTextSelected(e.target)
value = e.target.value + digit
value = value.replace(/\D/g, '')
if value.length > 6
e.preventDefault()
restrictCVC = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
return if hasTextSelected(e.target)
val = e.target.value + digit
if val.length > 4
e.preventDefault()
# Public
# Formatting
payform.cvcInput = (input) ->
_on(input, 'keypress', restrictNumeric)
_on(input, 'keypress', restrictCVC)
_on(input, 'paste', reFormatCVC)
_on(input, 'change', reFormatCVC)
_on(input, 'input', reFormatCVC)
payform.expiryInput = (input) ->
_on(input, 'keypress', restrictNumeric)
_on(input, 'keypress', restrictExpiry)
_on(input, 'keypress', formatCardExpiry)
_on(input, 'keypress', formatForwardSlashAndSpace)
_on(input, 'keypress', formatForwardExpiry)
_on(input, 'keydown', formatBackExpiry)
_on(input, 'change', reFormatExpiry)
_on(input, 'input', reFormatExpiry)
payform.cardNumberInput = (input) ->
_on(input, 'keypress', restrictNumeric)
_on(input, 'keypress', restrictCardNumber)
_on(input, 'keypress', formatCardNumber)
_on(input, 'keydown', formatBackCardNumber)
_on(input, 'paste', reFormatCardNumber)
_on(input, 'change', reFormatCardNumber)
_on(input, 'input', reFormatCardNumber)
# Validations
payform.parseCardExpiry = (value) ->
value = value.replace(/\s/g, '')
[month, year] = value.split('/', 2)
# Allow for year shortcut
if year?.length is 2 and /^\d+$/.test(year)
prefix = (new Date).getFullYear()
prefix = prefix.toString()[0..1]
year = prefix + year
month = parseInt(month, 10)
year = parseInt(year, 10)
month: month, year: year
payform.validateCardNumber = (num) ->
num = (num + '').replace(/\s+|-/g, '')
return false unless /^\d+$/.test(num)
card = cardFromNumber(num)
return false unless card
num.length in card.length and
(card.luhn is false or luhnCheck(num))
payform.validateCardExpiry = (month, year) ->
# Allow passing an object
if typeof month is 'object' and 'month' of month
{month, year} = month
return false unless month and year
month = String(month).trim()
year = String(year).trim()
return false unless /^\d+$/.test(month)
return false unless /^\d+$/.test(year)
return false unless 1 <= month <= 12
if year.length == 2
if year < 70
year = "20#{year}"
else
year = "19#{year}"
return false unless year.length == 4
expiry = new Date(year, month)
currentTime = new Date
# Months start from 0 in JavaScript
expiry.setMonth(expiry.getMonth() - 1)
# The cc expires at the end of the month,
# so we need to make the expiry the first day
# of the month after
expiry.setMonth(expiry.getMonth() + 1, 1)
expiry > currentTime
payform.validateCardCVC = (cvc, type) ->
cvc = String(cvc).trim()
return false unless /^\d+$/.test(cvc)
card = cardFromType(type)
if card?
# Check against a explicit card type
cvc.length in card.cvcLength
else
# Check against all types
cvc.length >= 3 and cvc.length <= 4
payform.parseCardType = (num) ->
return null unless num
cardFromNumber(num)?.type or null
payform.formatCardNumber = (num) ->
num = num.replace(/\D/g, '')
card = cardFromNumber(num)
return num unless card
upperLength = card.length[card.length.length - 1]
num = num[0...upperLength]
if card.format.global
num.match(card.format)?.join(' ')
else
groups = card.format.exec(num)
return unless groups?
groups.shift()
groups = groups.filter(Boolean)
groups.join(' ')
payform.formatCardExpiry = (expiry) ->
parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/)
return '' unless parts
mon = parts[1] || ''
sep = parts[2] || ''
year = parts[3] || ''
if year.length > 0
sep = ' / '
else if sep is ' /'
mon = mon.substring(0, 1)
sep = ''
else if mon.length == 2 or sep.length > 0
sep = ' / '
else if mon.length == 1 and mon not in ['0', '1']
mon = "0#{mon}"
sep = ' / '
return mon + sep + year
payform
)
| true | ###
Payform Javascript Library
URL: https://github.com/jondavidjohn/payform
Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
License: MIT
Version: 1.0.2
###
((name, definition) ->
if module?
module.exports = definition()
else if typeof define is 'function' and typeof define.amd is 'object'
define(name, definition)
else
this[name] = definition()
)('payform', ->
_getCaretPos = (ele) ->
if ele.selectionStart?
return ele.selectionStart
else if document.selection?
ele.focus()
r = document.selection.createRange()
re = ele.createTextRange()
rc = re.duplicate()
re.moveToBookmark(r.getBookmark())
rc.setEndPoint('EndToStart', re)
return rc.text.length
_eventNormalize = (listener) ->
return (e = window.event) ->
e.target = e.target or e.srcElement
e.which = e.which or e.keyCode
unless e.preventDefault?
e.preventDefault = -> this.returnValue = false
listener(e)
_on = (ele, event, listener) ->
listener = _eventNormalize(listener)
if ele.addEventListener?
ele.addEventListener(event, listener, false)
else
ele.attachEvent("on#{event}", listener)
payform = {}
# Utils
defaultFormat = /(\d{1,4})/g
payform.cards = [
# Debit cards must come first, since they have more
# specific patterns than their credit-card equivalents.
{
type: 'visaelectron'
pattern: /^4(026|17500|405|508|844|91[37])/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'maestro'
pattern: /^(5(018|0[23]|[68])|6(39|7))/
format: defaultFormat
length: [12..19]
cvcLength: [3]
luhn: true
}
{
type: 'forbrugsforeningen'
pattern: /^600/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'dankort'
pattern: /^5019/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
# Credit cards
{
type: 'visa'
pattern: /^4/
format: defaultFormat
length: [13, 16]
cvcLength: [3]
luhn: true
}
{
type: 'mastercard'
pattern: /^5[0-5]/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'amex'
pattern: /^3[47]/
format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/
length: [15]
cvcLength: [3..4]
luhn: true
}
{
type: 'dinersclub'
pattern: /^3[0689]/
format: defaultFormat
length: [14]
cvcLength: [3]
luhn: true
}
{
type: 'discover'
pattern: /^6([045]|22)/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
{
type: 'unionpay'
pattern: /^(62|88)/
format: defaultFormat
length: [16..19]
cvcLength: [3]
luhn: false
}
{
type: 'jcb'
pattern: /^35/
format: defaultFormat
length: [16]
cvcLength: [3]
luhn: true
}
]
cardFromNumber = (num) ->
num = (num + '').replace(/\D/g, '')
return card for card in payform.cards when card.pattern.test(num)
cardFromType = (type) ->
return card for card in payform.cards when card.type is type
luhnCheck = (num) ->
odd = true
sum = 0
digits = (num + '').split('').reverse()
for digit in digits
digit = parseInt(digit, 10)
digit *= 2 if (odd = !odd)
digit -= 9 if digit > 9
sum += digit
sum % 10 == 0
hasTextSelected = (target) ->
# If some text is selected in IE
if document?.selection?.createRange?
return true if document.selection.createRange().text
target.selectionStart? and target.selectionStart isnt target.selectionEnd
# Private
# Format Card Number
reFormatCardNumber = (e) ->
cursor = _getCaretPos(e.target)
e.target.value = payform.formatCardNumber(e.target.value)
if cursor? and e.type isnt 'change'
e.target.setSelectionRange(cursor, cursor)
formatCardNumber = (e) ->
# Only format if input is a number
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
value = e.target.value
card = cardFromNumber(value + digit)
length = (value.replace(/\D/g, '') + digit).length
upperLength = 16
upperLength = card.length[card.length.length - 1] if card
return if length >= upperLength
# Return if focus isn't at the end of the text
cursor = _getCaretPos(e.target)
return if cursor and cursor isnt value.length
if card && card.type is 'amex'
# AMEX cards are formatted differently
re = /^(\d{4}|\d{4}\s\d{6})$/
else
re = /(?:^|\s)(\d{4})$/
# If '4242' + 4
if re.test(value)
e.preventDefault()
setTimeout -> e.target.value = "#{value} #{digit}"
# If '424' + 2
else if re.test(value + digit)
e.preventDefault()
setTimeout -> e.target.value = "#{value + digit} "
formatBackCardNumber = (e) ->
value = e.target.value
# Return unless backspacing
return unless e.which is 8
# Return if focus isn't at the end of the text
cursor = _getCaretPos(e.target)
return if cursor and cursor isnt value.length
# Remove the digit + trailing space
if /\d\s$/.test(value)
e.preventDefault()
setTimeout -> e.target.value = value.replace /\d\s$/, ''
# Remove digit if ends in space + digit
else if /\s\d?$/.test(value)
e.preventDefault()
setTimeout -> e.target.value = value.replace /\d$/, ''
# Format Expiry
reFormatExpiry = (e) ->
cursor = _getCaretPos(e.target)
e.target.value = payform.formatCardExpiry(e.target.value)
if cursor? and e.type isnt 'change'
e.target.setSelectionRange(cursor, cursor)
formatCardExpiry = (e) ->
# Only format if input is a number
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
val = e.target.value + digit
if /^\d$/.test(val) and val not in ['0', '1']
e.preventDefault()
setTimeout -> e.target.value = "0#{val} / "
else if /^\d\d$/.test(val)
e.preventDefault()
setTimeout -> e.target.value = "#{val} / "
formatForwardExpiry = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
val = e.target.value
if /^\d\d$/.test(val)
e.target.value = "#{val} / "
formatForwardSlashAndSpace = (e) ->
which = String.fromCharCode(e.which)
return unless which is '/' or which is ' '
val = e.target.value
if /^\d$/.test(val) and val isnt '0'
e.target.value = "0#{val} / "
formatBackExpiry = (e) ->
value = e.target.value
# Return unless backspacing
return unless e.which is 8
# Return if focus isn't at the end of the text
cursor = _getCaretPos(e.target)
return if cursor and cursor isnt value.length
# Remove the trailing space + last digit
if /\d\s\/\s$/.test(value)
e.preventDefault()
setTimeout -> e.target.value = value.replace(/\d\s\/\s$/, '')
# Format CVC
reFormatCVC = (e) ->
cursor = _getCaretPos(e.target)
e.target.value = e.target.value.replace(/\D/g, '')[0...4]
if cursor? and e.type isnt 'change'
e.target.setSelectionRange(cursor, cursor)
# Restrictions
restrictNumeric = (e) ->
# Key event is for a browser shortcut
return if e.metaKey or e.ctrlKey
# If keycode is a special char (WebKit)
return if e.which is 0
# If char is a special char (Firefox)
return if e.which < 33
input = String.fromCharCode(e.which)
# Char is a number
unless /^\d+$/.test(input)
e.preventDefault()
restrictCardNumber = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
return if hasTextSelected(e.target)
# Restrict number of digits
value = (e.target.value + digit).replace(/\D/g, '')
card = cardFromNumber(value)
if card and value.length > card.length[card.length.length - 1]
e.preventDefault()
else if value.length > 16
e.preventDefault()
restrictExpiry = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
return if hasTextSelected(e.target)
value = e.target.value + digit
value = value.replace(/\D/g, '')
if value.length > 6
e.preventDefault()
restrictCVC = (e) ->
digit = String.fromCharCode(e.which)
return unless /^\d+$/.test(digit)
return if hasTextSelected(e.target)
val = e.target.value + digit
if val.length > 4
e.preventDefault()
# Public
# Formatting
payform.cvcInput = (input) ->
_on(input, 'keypress', restrictNumeric)
_on(input, 'keypress', restrictCVC)
_on(input, 'paste', reFormatCVC)
_on(input, 'change', reFormatCVC)
_on(input, 'input', reFormatCVC)
payform.expiryInput = (input) ->
_on(input, 'keypress', restrictNumeric)
_on(input, 'keypress', restrictExpiry)
_on(input, 'keypress', formatCardExpiry)
_on(input, 'keypress', formatForwardSlashAndSpace)
_on(input, 'keypress', formatForwardExpiry)
_on(input, 'keydown', formatBackExpiry)
_on(input, 'change', reFormatExpiry)
_on(input, 'input', reFormatExpiry)
payform.cardNumberInput = (input) ->
_on(input, 'keypress', restrictNumeric)
_on(input, 'keypress', restrictCardNumber)
_on(input, 'keypress', formatCardNumber)
_on(input, 'keydown', formatBackCardNumber)
_on(input, 'paste', reFormatCardNumber)
_on(input, 'change', reFormatCardNumber)
_on(input, 'input', reFormatCardNumber)
# Validations
payform.parseCardExpiry = (value) ->
value = value.replace(/\s/g, '')
[month, year] = value.split('/', 2)
# Allow for year shortcut
if year?.length is 2 and /^\d+$/.test(year)
prefix = (new Date).getFullYear()
prefix = prefix.toString()[0..1]
year = prefix + year
month = parseInt(month, 10)
year = parseInt(year, 10)
month: month, year: year
payform.validateCardNumber = (num) ->
num = (num + '').replace(/\s+|-/g, '')
return false unless /^\d+$/.test(num)
card = cardFromNumber(num)
return false unless card
num.length in card.length and
(card.luhn is false or luhnCheck(num))
payform.validateCardExpiry = (month, year) ->
# Allow passing an object
if typeof month is 'object' and 'month' of month
{month, year} = month
return false unless month and year
month = String(month).trim()
year = String(year).trim()
return false unless /^\d+$/.test(month)
return false unless /^\d+$/.test(year)
return false unless 1 <= month <= 12
if year.length == 2
if year < 70
year = "20#{year}"
else
year = "19#{year}"
return false unless year.length == 4
expiry = new Date(year, month)
currentTime = new Date
# Months start from 0 in JavaScript
expiry.setMonth(expiry.getMonth() - 1)
# The cc expires at the end of the month,
# so we need to make the expiry the first day
# of the month after
expiry.setMonth(expiry.getMonth() + 1, 1)
expiry > currentTime
payform.validateCardCVC = (cvc, type) ->
cvc = String(cvc).trim()
return false unless /^\d+$/.test(cvc)
card = cardFromType(type)
if card?
# Check against a explicit card type
cvc.length in card.cvcLength
else
# Check against all types
cvc.length >= 3 and cvc.length <= 4
payform.parseCardType = (num) ->
return null unless num
cardFromNumber(num)?.type or null
payform.formatCardNumber = (num) ->
num = num.replace(/\D/g, '')
card = cardFromNumber(num)
return num unless card
upperLength = card.length[card.length.length - 1]
num = num[0...upperLength]
if card.format.global
num.match(card.format)?.join(' ')
else
groups = card.format.exec(num)
return unless groups?
groups.shift()
groups = groups.filter(Boolean)
groups.join(' ')
payform.formatCardExpiry = (expiry) ->
parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/)
return '' unless parts
mon = parts[1] || ''
sep = parts[2] || ''
year = parts[3] || ''
if year.length > 0
sep = ' / '
else if sep is ' /'
mon = mon.substring(0, 1)
sep = ''
else if mon.length == 2 or sep.length > 0
sep = ' / '
else if mon.length == 1 and mon not in ['0', '1']
mon = "0#{mon}"
sep = ' / '
return mon + sep + year
payform
)
|
[
{
"context": "5.github.com/#x15.2.3.2\n \n # https://github.com/kriskowal/es5-shim/issues#issue/2\n # http://ejohn.org/blog",
"end": 494,
"score": 0.9878845810890198,
"start": 485,
"tag": "USERNAME",
"value": "kriskowal"
},
{
"context": ".org/blog/objectgetprototypeof/\n # recommended by fschaefer on github\n \n #ES5 15.2.3.3\n #http://es5.github",
"end": 595,
"score": 0.9524807333946228,
"start": 586,
"tag": "USERNAME",
"value": "fschaefer"
},
{
"context": " # recommended by fschaefer on github\n \n #ES5 15.2.3.3\n #http://es5.github.com/#x15.2.3.3\n doesGetOwnP",
"end": 624,
"score": 0.680463433265686,
"start": 617,
"tag": "IP_ADDRESS",
"value": "5.2.3.3"
},
{
"context": "://es5.github.com/#x15.2.3.5\n \n # Contributed by Brandon Benvie, October, 2012\n \n # In old IE __proto__ can't b",
"end": 2106,
"score": 0.9998780488967896,
"start": 2092,
"tag": "NAME",
"value": "Brandon Benvie"
},
{
"context": "h for WebKit and IE8 standard mode\n # Designed by hax <hax.github.com>\n # related issue: https://git",
"end": 3272,
"score": 0.7642508745193481,
"start": 3271,
"tag": "USERNAME",
"value": "h"
},
{
"context": "github.com>\n # related issue: https://github.com/kriskowal/es5-shim/issues#issue/5\n # IE8 Reference:\n # ",
"end": 3339,
"score": 0.9801464676856995,
"start": 3330,
"tag": "USERNAME",
"value": "kriskowal"
},
{
"context": " # but insecure code.\n object\n \n # ES5 15.2.3.9\n # http://es5.github.com/#x15.2.3.9\n unless Ob",
"end": 12000,
"score": 0.7917544841766357,
"start": 11995,
"tag": "IP_ADDRESS",
"value": "5.2.3"
},
{
"context": "eezeObject object\n )(Object.freeze)\n \n # ES5 15.2.3.10\n # http://es5.github.com/#x15.2.3.10\n unless Ob",
"end": 12579,
"score": 0.9238774180412292,
"start": 12570,
"tag": "IP_ADDRESS",
"value": "15.2.3.10"
},
{
"context": " # ES5 15.2.3.10\n # http://es5.github.com/#x15.2.3.10\n unless Object.preventExtensions\n Object.pr",
"end": 12614,
"score": 0.703942596912384,
"start": 12613,
"tag": "IP_ADDRESS",
"value": "3"
},
{
"context": " # but insecure code.\n object\n \n # ES5 15.2.3.11\n # http://es5.github.com/#x15.2.3.11\n unless Ob",
"end": 12910,
"score": 0.9564850926399231,
"start": 12901,
"tag": "IP_ADDRESS",
"value": "15.2.3.11"
}
] | lib/generators/app/templates/coffeescript/assets/vendor/es5-sham.coffee | technicolorenvy/rendr-cli | 1 | # Copyright 2009-2012 by contributors, MIT License
# vim: ts=4 sts=4 sw=4 expandtab
# Module systems magic dance
((definition) ->
# RequireJS
if typeof define is "function"
define definition
# YUI3
else if typeof YUI is "function"
YUI.add "es5-sham", definition
# CommonJS and <script>
else
definition()
) ->
# If JS engine supports accessors creating shortcuts.
# ES5 15.2.3.2
# http://es5.github.com/#x15.2.3.2
# https://github.com/kriskowal/es5-shim/issues#issue/2
# http://ejohn.org/blog/objectgetprototypeof/
# recommended by fschaefer on github
#ES5 15.2.3.3
#http://es5.github.com/#x15.2.3.3
doesGetOwnPropertyDescriptorWork = (object) ->
try
object.sentinel = 0
return Object.getOwnPropertyDescriptor(object, "sentinel").value is 0
# returns falsy
#check whether getOwnPropertyDescriptor works if it's given. Otherwise,
#shim partially.
# make a valiant attempt to use the real getOwnPropertyDescriptor
# for I8's DOM elements.
# try the shim if the real one doesn't work
# If object does not owns property return undefined immediately.
# If object has a property then it's for sure both `enumerable` and
# `configurable`.
# If JS engine supports accessor properties then property may be a
# getter or setter.
# Unfortunately `__lookupGetter__` will return a getter even
# if object has own non getter property along with a same named
# inherited getter. To avoid misbehavior we temporary remove
# `__proto__` so that `__lookupGetter__` will return getter only
# if it's owned by an object.
# Once we have getter and setter we can put values back.
# If it was accessor property we're done and return here
# in order to avoid adding `value` to the descriptor.
# If we got this far we know that object has an own property that is
# not an accessor so we set it as a value and return descriptor.
# ES5 15.2.3.4
# http://es5.github.com/#x15.2.3.4
# ES5 15.2.3.5
# http://es5.github.com/#x15.2.3.5
# Contributed by Brandon Benvie, October, 2012
# In old IE __proto__ can't be used to manually set `null`, nor does
# any other method exist to make an object that inherits from nothing,
# aside from Object.prototype itself. Instead, create a new global
# object and *steal* its Object.prototype and strip it bare. This is
# used as the prototype to create nullary objects.
# short-circuit future calls
# An empty constructor.
# In the native implementation `parent` can be `null`
# OR *any* `instanceof Object` (Object|Function|Array|RegExp|etc)
# Use `typeof` tho, b/c in old IE, DOM elements are not `instanceof Object`
# like they are in modern browsers. Using `Object.create` on DOM elements
# is...err...probably inappropriate, but the native version allows for it.
# same msg as Chrome
# IE has no built-in implementation of `Object.getPrototypeOf`
# neither `__proto__`, but this manually setting `__proto__` will
# guarantee that `Object.getPrototypeOf` will work as expected with
# objects created using `Object.create`
# ES5 15.2.3.6
# http://es5.github.com/#x15.2.3.6
# Patch for WebKit and IE8 standard mode
# Designed by hax <hax.github.com>
# related issue: https://github.com/kriskowal/es5-shim/issues#issue/5
# IE8 Reference:
# http://msdn.microsoft.com/en-us/library/dd282900.aspx
# http://msdn.microsoft.com/en-us/library/dd229916.aspx
# WebKit Bugs:
# https://bugs.webkit.org/show_bug.cgi?id=36423
doesDefinePropertyWork = (object) ->
try
Object.defineProperty object, "sentinel", {}
return "sentinel" of object
call = Function::call
prototypeOfObject = Object::
owns = call.bind(prototypeOfObject.hasOwnProperty)
defineGetter = undefined
defineSetter = undefined
lookupGetter = undefined
lookupSetter = undefined
supportsAccessors = undefined
if supportsAccessors = owns(prototypeOfObject, "__defineGetter__")
defineGetter = call.bind(prototypeOfObject.__defineGetter__)
defineSetter = call.bind(prototypeOfObject.__defineSetter__)
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__)
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__)
unless Object.getPrototypeOf
Object.getPrototypeOf = getPrototypeOf = (object) ->
object.__proto__ or ((if object.constructor then object.constructor:: else prototypeOfObject))
if Object.defineProperty
getOwnPropertyDescriptorWorksOnObject = doesGetOwnPropertyDescriptorWork({})
getOwnPropertyDescriptorWorksOnDom = typeof document is "undefined" or doesGetOwnPropertyDescriptorWork(document.createElement("div"))
getOwnPropertyDescriptorFallback = Object.getOwnPropertyDescriptor if not getOwnPropertyDescriptorWorksOnDom or not getOwnPropertyDescriptorWorksOnObject
if not Object.getOwnPropertyDescriptor or getOwnPropertyDescriptorFallback
ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a non-object: "
Object.getOwnPropertyDescriptor = getOwnPropertyDescriptor = (object, property) ->
throw new TypeError(ERR_NON_OBJECT + object) if (typeof object isnt "object" and typeof object isnt "function") or object is null
if getOwnPropertyDescriptorFallback
try
return getOwnPropertyDescriptorFallback.call(Object, object, property)
return unless owns(object, property)
descriptor =
enumerable: true
configurable: true
if supportsAccessors
prototype = object.__proto__
object.__proto__ = prototypeOfObject
getter = lookupGetter(object, property)
setter = lookupSetter(object, property)
object.__proto__ = prototype
if getter or setter
descriptor.get = getter if getter
descriptor.set = setter if setter
return descriptor
descriptor.value = object[property]
descriptor.writable = true
descriptor
unless Object.getOwnPropertyNames
Object.getOwnPropertyNames = getOwnPropertyNames = (object) ->
Object.keys object
unless Object.create
createEmpty = undefined
supportsProto = Object::__proto__ is null
if supportsProto or typeof document is "undefined"
createEmpty = ->
__proto__: null
else
createEmpty = ->
Empty = ->
iframe = document.createElement("iframe")
parent = document.body or document.documentElement
iframe.style.display = "none"
parent.appendChild iframe
iframe.src = "javascript:"
empty = iframe.contentWindow.Object::
parent.removeChild iframe
iframe = null
delete empty.constructor
delete empty.hasOwnProperty
delete empty.propertyIsEnumerable
delete empty.isPrototypeOf
delete empty.toLocaleString
delete empty.toString
delete empty.valueOf
empty.__proto__ = null
Empty:: = empty
createEmpty = ->
new Empty()
new Empty()
Object.create = create = (prototype, properties) ->
Type = ->
object = undefined
if prototype is null
object = createEmpty()
else
throw new TypeError("Object prototype may only be an Object or null") if typeof prototype isnt "object" and typeof prototype isnt "function"
Type:: = prototype
object = new Type()
object.__proto__ = prototype
Object.defineProperties object, properties if properties isnt undefined
object
# returns falsy
# check whether defineProperty works if it's given. Otherwise,
# shim partially.
if Object.defineProperty
definePropertyWorksOnObject = doesDefinePropertyWork({})
definePropertyWorksOnDom = typeof document is "undefined" or doesDefinePropertyWork(document.createElement("div"))
if not definePropertyWorksOnObject or not definePropertyWorksOnDom
definePropertyFallback = Object.defineProperty
definePropertiesFallback = Object.defineProperties
if not Object.defineProperty or definePropertyFallback
ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "
ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"
Object.defineProperty = defineProperty = (object, property, descriptor) ->
throw new TypeError(ERR_NON_OBJECT_TARGET + object) if (typeof object isnt "object" and typeof object isnt "function") or object is null
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor) if (typeof descriptor isnt "object" and typeof descriptor isnt "function") or descriptor is null
# make a valiant attempt to use the real defineProperty
# for I8's DOM elements.
if definePropertyFallback
try
return definePropertyFallback.call(Object, object, property, descriptor)
# try the shim if the real one doesn't work
# If it's a data property.
if owns(descriptor, "value")
# fail silently if "writable", "enumerable", or "configurable"
# are requested but not supported
#
# // alternate approach:
# if ( // can't implement these features; allow false but not true
# !(owns(descriptor, "writable") ? descriptor.writable : true) ||
# !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
# !(owns(descriptor, "configurable") ? descriptor.configurable : true)
# )
# throw new RangeError(
# "This implementation of Object.defineProperty does not " +
# "support configurable, enumerable, or writable."
# );
#
if supportsAccessors and (lookupGetter(object, property) or lookupSetter(object, property))
# As accessors are supported only on engines implementing
# `__proto__` we can safely override `__proto__` while defining
# a property to make sure that we don't hit an inherited
# accessor.
prototype = object.__proto__
object.__proto__ = prototypeOfObject
# Deleting a property anyway since getter / setter may be
# defined on object itself.
delete object[property]
object[property] = descriptor.value
# Setting original `__proto__` back now.
object.__proto__ = prototype
else
object[property] = descriptor.value
else
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED) unless supportsAccessors
# If we got that far then getters and setters can be defined !!
defineGetter object, property, descriptor.get if owns(descriptor, "get")
defineSetter object, property, descriptor.set if owns(descriptor, "set")
object
# ES5 15.2.3.7
# http://es5.github.com/#x15.2.3.7
if not Object.defineProperties or definePropertiesFallback
Object.defineProperties = defineProperties = (object, properties) ->
# make a valiant attempt to use the real defineProperties
if definePropertiesFallback
try
return definePropertiesFallback.call(Object, object, properties)
# try the shim if the real one doesn't work
for property of properties
Object.defineProperty object, property, properties[property] if owns(properties, property) and property isnt "__proto__"
object
# ES5 15.2.3.8
# http://es5.github.com/#x15.2.3.8
unless Object.seal
Object.seal = seal = (object) ->
# this is misleading and breaks feature-detection, but
# allows "securable" code to "gracefully" degrade to working
# but insecure code.
object
# ES5 15.2.3.9
# http://es5.github.com/#x15.2.3.9
unless Object.freeze
Object.freeze = freeze = (object) ->
# this is misleading and breaks feature-detection, but
# allows "securable" code to "gracefully" degrade to working
# but insecure code.
object
# detect a Rhino bug and patch it
try
Object.freeze ->
catch exception
Object.freeze = (freeze = (freezeObject) ->
freeze = (object) ->
if typeof object is "function"
object
else
freezeObject object
)(Object.freeze)
# ES5 15.2.3.10
# http://es5.github.com/#x15.2.3.10
unless Object.preventExtensions
Object.preventExtensions = preventExtensions = (object) ->
# this is misleading and breaks feature-detection, but
# allows "securable" code to "gracefully" degrade to working
# but insecure code.
object
# ES5 15.2.3.11
# http://es5.github.com/#x15.2.3.11
unless Object.isSealed
Object.isSealed = isSealed = (object) ->
false
# ES5 15.2.3.12
# http://es5.github.com/#x15.2.3.12
unless Object.isFrozen
Object.isFrozen = isFrozen = (object) ->
false
# ES5 15.2.3.13
# http://es5.github.com/#x15.2.3.13
unless Object.isExtensible
Object.isExtensible = isExtensible = (object) ->
# 1. If Type(O) is not Object throw a TypeError exception.
throw new TypeError() if Object(object) isnt object # TODO message
# 2. Return the Boolean value of the [[Extensible]] internal property of O.
name = ""
name += "?" while owns(object, name)
object[name] = true
returnValue = owns(object, name)
delete object[name]
returnValue
| 130072 | # Copyright 2009-2012 by contributors, MIT License
# vim: ts=4 sts=4 sw=4 expandtab
# Module systems magic dance
((definition) ->
# RequireJS
if typeof define is "function"
define definition
# YUI3
else if typeof YUI is "function"
YUI.add "es5-sham", definition
# CommonJS and <script>
else
definition()
) ->
# If JS engine supports accessors creating shortcuts.
# ES5 15.2.3.2
# http://es5.github.com/#x15.2.3.2
# https://github.com/kriskowal/es5-shim/issues#issue/2
# http://ejohn.org/blog/objectgetprototypeof/
# recommended by fschaefer on github
#ES5 1172.16.58.3
#http://es5.github.com/#x15.2.3.3
doesGetOwnPropertyDescriptorWork = (object) ->
try
object.sentinel = 0
return Object.getOwnPropertyDescriptor(object, "sentinel").value is 0
# returns falsy
#check whether getOwnPropertyDescriptor works if it's given. Otherwise,
#shim partially.
# make a valiant attempt to use the real getOwnPropertyDescriptor
# for I8's DOM elements.
# try the shim if the real one doesn't work
# If object does not owns property return undefined immediately.
# If object has a property then it's for sure both `enumerable` and
# `configurable`.
# If JS engine supports accessor properties then property may be a
# getter or setter.
# Unfortunately `__lookupGetter__` will return a getter even
# if object has own non getter property along with a same named
# inherited getter. To avoid misbehavior we temporary remove
# `__proto__` so that `__lookupGetter__` will return getter only
# if it's owned by an object.
# Once we have getter and setter we can put values back.
# If it was accessor property we're done and return here
# in order to avoid adding `value` to the descriptor.
# If we got this far we know that object has an own property that is
# not an accessor so we set it as a value and return descriptor.
# ES5 15.2.3.4
# http://es5.github.com/#x15.2.3.4
# ES5 15.2.3.5
# http://es5.github.com/#x15.2.3.5
# Contributed by <NAME>, October, 2012
# In old IE __proto__ can't be used to manually set `null`, nor does
# any other method exist to make an object that inherits from nothing,
# aside from Object.prototype itself. Instead, create a new global
# object and *steal* its Object.prototype and strip it bare. This is
# used as the prototype to create nullary objects.
# short-circuit future calls
# An empty constructor.
# In the native implementation `parent` can be `null`
# OR *any* `instanceof Object` (Object|Function|Array|RegExp|etc)
# Use `typeof` tho, b/c in old IE, DOM elements are not `instanceof Object`
# like they are in modern browsers. Using `Object.create` on DOM elements
# is...err...probably inappropriate, but the native version allows for it.
# same msg as Chrome
# IE has no built-in implementation of `Object.getPrototypeOf`
# neither `__proto__`, but this manually setting `__proto__` will
# guarantee that `Object.getPrototypeOf` will work as expected with
# objects created using `Object.create`
# ES5 15.2.3.6
# http://es5.github.com/#x15.2.3.6
# Patch for WebKit and IE8 standard mode
# Designed by hax <hax.github.com>
# related issue: https://github.com/kriskowal/es5-shim/issues#issue/5
# IE8 Reference:
# http://msdn.microsoft.com/en-us/library/dd282900.aspx
# http://msdn.microsoft.com/en-us/library/dd229916.aspx
# WebKit Bugs:
# https://bugs.webkit.org/show_bug.cgi?id=36423
doesDefinePropertyWork = (object) ->
try
Object.defineProperty object, "sentinel", {}
return "sentinel" of object
call = Function::call
prototypeOfObject = Object::
owns = call.bind(prototypeOfObject.hasOwnProperty)
defineGetter = undefined
defineSetter = undefined
lookupGetter = undefined
lookupSetter = undefined
supportsAccessors = undefined
if supportsAccessors = owns(prototypeOfObject, "__defineGetter__")
defineGetter = call.bind(prototypeOfObject.__defineGetter__)
defineSetter = call.bind(prototypeOfObject.__defineSetter__)
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__)
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__)
unless Object.getPrototypeOf
Object.getPrototypeOf = getPrototypeOf = (object) ->
object.__proto__ or ((if object.constructor then object.constructor:: else prototypeOfObject))
if Object.defineProperty
getOwnPropertyDescriptorWorksOnObject = doesGetOwnPropertyDescriptorWork({})
getOwnPropertyDescriptorWorksOnDom = typeof document is "undefined" or doesGetOwnPropertyDescriptorWork(document.createElement("div"))
getOwnPropertyDescriptorFallback = Object.getOwnPropertyDescriptor if not getOwnPropertyDescriptorWorksOnDom or not getOwnPropertyDescriptorWorksOnObject
if not Object.getOwnPropertyDescriptor or getOwnPropertyDescriptorFallback
ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a non-object: "
Object.getOwnPropertyDescriptor = getOwnPropertyDescriptor = (object, property) ->
throw new TypeError(ERR_NON_OBJECT + object) if (typeof object isnt "object" and typeof object isnt "function") or object is null
if getOwnPropertyDescriptorFallback
try
return getOwnPropertyDescriptorFallback.call(Object, object, property)
return unless owns(object, property)
descriptor =
enumerable: true
configurable: true
if supportsAccessors
prototype = object.__proto__
object.__proto__ = prototypeOfObject
getter = lookupGetter(object, property)
setter = lookupSetter(object, property)
object.__proto__ = prototype
if getter or setter
descriptor.get = getter if getter
descriptor.set = setter if setter
return descriptor
descriptor.value = object[property]
descriptor.writable = true
descriptor
unless Object.getOwnPropertyNames
Object.getOwnPropertyNames = getOwnPropertyNames = (object) ->
Object.keys object
unless Object.create
createEmpty = undefined
supportsProto = Object::__proto__ is null
if supportsProto or typeof document is "undefined"
createEmpty = ->
__proto__: null
else
createEmpty = ->
Empty = ->
iframe = document.createElement("iframe")
parent = document.body or document.documentElement
iframe.style.display = "none"
parent.appendChild iframe
iframe.src = "javascript:"
empty = iframe.contentWindow.Object::
parent.removeChild iframe
iframe = null
delete empty.constructor
delete empty.hasOwnProperty
delete empty.propertyIsEnumerable
delete empty.isPrototypeOf
delete empty.toLocaleString
delete empty.toString
delete empty.valueOf
empty.__proto__ = null
Empty:: = empty
createEmpty = ->
new Empty()
new Empty()
Object.create = create = (prototype, properties) ->
Type = ->
object = undefined
if prototype is null
object = createEmpty()
else
throw new TypeError("Object prototype may only be an Object or null") if typeof prototype isnt "object" and typeof prototype isnt "function"
Type:: = prototype
object = new Type()
object.__proto__ = prototype
Object.defineProperties object, properties if properties isnt undefined
object
# returns falsy
# check whether defineProperty works if it's given. Otherwise,
# shim partially.
if Object.defineProperty
definePropertyWorksOnObject = doesDefinePropertyWork({})
definePropertyWorksOnDom = typeof document is "undefined" or doesDefinePropertyWork(document.createElement("div"))
if not definePropertyWorksOnObject or not definePropertyWorksOnDom
definePropertyFallback = Object.defineProperty
definePropertiesFallback = Object.defineProperties
if not Object.defineProperty or definePropertyFallback
ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "
ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"
Object.defineProperty = defineProperty = (object, property, descriptor) ->
throw new TypeError(ERR_NON_OBJECT_TARGET + object) if (typeof object isnt "object" and typeof object isnt "function") or object is null
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor) if (typeof descriptor isnt "object" and typeof descriptor isnt "function") or descriptor is null
# make a valiant attempt to use the real defineProperty
# for I8's DOM elements.
if definePropertyFallback
try
return definePropertyFallback.call(Object, object, property, descriptor)
# try the shim if the real one doesn't work
# If it's a data property.
if owns(descriptor, "value")
# fail silently if "writable", "enumerable", or "configurable"
# are requested but not supported
#
# // alternate approach:
# if ( // can't implement these features; allow false but not true
# !(owns(descriptor, "writable") ? descriptor.writable : true) ||
# !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
# !(owns(descriptor, "configurable") ? descriptor.configurable : true)
# )
# throw new RangeError(
# "This implementation of Object.defineProperty does not " +
# "support configurable, enumerable, or writable."
# );
#
if supportsAccessors and (lookupGetter(object, property) or lookupSetter(object, property))
# As accessors are supported only on engines implementing
# `__proto__` we can safely override `__proto__` while defining
# a property to make sure that we don't hit an inherited
# accessor.
prototype = object.__proto__
object.__proto__ = prototypeOfObject
# Deleting a property anyway since getter / setter may be
# defined on object itself.
delete object[property]
object[property] = descriptor.value
# Setting original `__proto__` back now.
object.__proto__ = prototype
else
object[property] = descriptor.value
else
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED) unless supportsAccessors
# If we got that far then getters and setters can be defined !!
defineGetter object, property, descriptor.get if owns(descriptor, "get")
defineSetter object, property, descriptor.set if owns(descriptor, "set")
object
# ES5 15.2.3.7
# http://es5.github.com/#x15.2.3.7
if not Object.defineProperties or definePropertiesFallback
Object.defineProperties = defineProperties = (object, properties) ->
# make a valiant attempt to use the real defineProperties
if definePropertiesFallback
try
return definePropertiesFallback.call(Object, object, properties)
# try the shim if the real one doesn't work
for property of properties
Object.defineProperty object, property, properties[property] if owns(properties, property) and property isnt "__proto__"
object
# ES5 15.2.3.8
# http://es5.github.com/#x15.2.3.8
unless Object.seal
Object.seal = seal = (object) ->
# this is misleading and breaks feature-detection, but
# allows "securable" code to "gracefully" degrade to working
# but insecure code.
object
# ES5 15.2.3.9
# http://es5.github.com/#x15.2.3.9
unless Object.freeze
Object.freeze = freeze = (object) ->
# this is misleading and breaks feature-detection, but
# allows "securable" code to "gracefully" degrade to working
# but insecure code.
object
# detect a Rhino bug and patch it
try
Object.freeze ->
catch exception
Object.freeze = (freeze = (freezeObject) ->
freeze = (object) ->
if typeof object is "function"
object
else
freezeObject object
)(Object.freeze)
# ES5 172.16.58.3
# http://es5.github.com/#x15.2.3.10
unless Object.preventExtensions
Object.preventExtensions = preventExtensions = (object) ->
# this is misleading and breaks feature-detection, but
# allows "securable" code to "gracefully" degrade to working
# but insecure code.
object
# ES5 192.168.3.11
# http://es5.github.com/#x15.2.3.11
unless Object.isSealed
Object.isSealed = isSealed = (object) ->
false
# ES5 15.2.3.12
# http://es5.github.com/#x15.2.3.12
unless Object.isFrozen
Object.isFrozen = isFrozen = (object) ->
false
# ES5 15.2.3.13
# http://es5.github.com/#x15.2.3.13
unless Object.isExtensible
Object.isExtensible = isExtensible = (object) ->
# 1. If Type(O) is not Object throw a TypeError exception.
throw new TypeError() if Object(object) isnt object # TODO message
# 2. Return the Boolean value of the [[Extensible]] internal property of O.
name = ""
name += "?" while owns(object, name)
object[name] = true
returnValue = owns(object, name)
delete object[name]
returnValue
| true | # Copyright 2009-2012 by contributors, MIT License
# vim: ts=4 sts=4 sw=4 expandtab
# Module systems magic dance
((definition) ->
# RequireJS
if typeof define is "function"
define definition
# YUI3
else if typeof YUI is "function"
YUI.add "es5-sham", definition
# CommonJS and <script>
else
definition()
) ->
# If JS engine supports accessors creating shortcuts.
# ES5 15.2.3.2
# http://es5.github.com/#x15.2.3.2
# https://github.com/kriskowal/es5-shim/issues#issue/2
# http://ejohn.org/blog/objectgetprototypeof/
# recommended by fschaefer on github
#ES5 1PI:IP_ADDRESS:172.16.58.3END_PI
#http://es5.github.com/#x15.2.3.3
doesGetOwnPropertyDescriptorWork = (object) ->
try
object.sentinel = 0
return Object.getOwnPropertyDescriptor(object, "sentinel").value is 0
# returns falsy
#check whether getOwnPropertyDescriptor works if it's given. Otherwise,
#shim partially.
# make a valiant attempt to use the real getOwnPropertyDescriptor
# for I8's DOM elements.
# try the shim if the real one doesn't work
# If object does not owns property return undefined immediately.
# If object has a property then it's for sure both `enumerable` and
# `configurable`.
# If JS engine supports accessor properties then property may be a
# getter or setter.
# Unfortunately `__lookupGetter__` will return a getter even
# if object has own non getter property along with a same named
# inherited getter. To avoid misbehavior we temporary remove
# `__proto__` so that `__lookupGetter__` will return getter only
# if it's owned by an object.
# Once we have getter and setter we can put values back.
# If it was accessor property we're done and return here
# in order to avoid adding `value` to the descriptor.
# If we got this far we know that object has an own property that is
# not an accessor so we set it as a value and return descriptor.
# ES5 15.2.3.4
# http://es5.github.com/#x15.2.3.4
# ES5 15.2.3.5
# http://es5.github.com/#x15.2.3.5
# Contributed by PI:NAME:<NAME>END_PI, October, 2012
# In old IE __proto__ can't be used to manually set `null`, nor does
# any other method exist to make an object that inherits from nothing,
# aside from Object.prototype itself. Instead, create a new global
# object and *steal* its Object.prototype and strip it bare. This is
# used as the prototype to create nullary objects.
# short-circuit future calls
# An empty constructor.
# In the native implementation `parent` can be `null`
# OR *any* `instanceof Object` (Object|Function|Array|RegExp|etc)
# Use `typeof` tho, b/c in old IE, DOM elements are not `instanceof Object`
# like they are in modern browsers. Using `Object.create` on DOM elements
# is...err...probably inappropriate, but the native version allows for it.
# same msg as Chrome
# IE has no built-in implementation of `Object.getPrototypeOf`
# neither `__proto__`, but this manually setting `__proto__` will
# guarantee that `Object.getPrototypeOf` will work as expected with
# objects created using `Object.create`
# ES5 15.2.3.6
# http://es5.github.com/#x15.2.3.6
# Patch for WebKit and IE8 standard mode
# Designed by hax <hax.github.com>
# related issue: https://github.com/kriskowal/es5-shim/issues#issue/5
# IE8 Reference:
# http://msdn.microsoft.com/en-us/library/dd282900.aspx
# http://msdn.microsoft.com/en-us/library/dd229916.aspx
# WebKit Bugs:
# https://bugs.webkit.org/show_bug.cgi?id=36423
doesDefinePropertyWork = (object) ->
try
Object.defineProperty object, "sentinel", {}
return "sentinel" of object
call = Function::call
prototypeOfObject = Object::
owns = call.bind(prototypeOfObject.hasOwnProperty)
defineGetter = undefined
defineSetter = undefined
lookupGetter = undefined
lookupSetter = undefined
supportsAccessors = undefined
if supportsAccessors = owns(prototypeOfObject, "__defineGetter__")
defineGetter = call.bind(prototypeOfObject.__defineGetter__)
defineSetter = call.bind(prototypeOfObject.__defineSetter__)
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__)
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__)
unless Object.getPrototypeOf
Object.getPrototypeOf = getPrototypeOf = (object) ->
object.__proto__ or ((if object.constructor then object.constructor:: else prototypeOfObject))
if Object.defineProperty
getOwnPropertyDescriptorWorksOnObject = doesGetOwnPropertyDescriptorWork({})
getOwnPropertyDescriptorWorksOnDom = typeof document is "undefined" or doesGetOwnPropertyDescriptorWork(document.createElement("div"))
getOwnPropertyDescriptorFallback = Object.getOwnPropertyDescriptor if not getOwnPropertyDescriptorWorksOnDom or not getOwnPropertyDescriptorWorksOnObject
if not Object.getOwnPropertyDescriptor or getOwnPropertyDescriptorFallback
ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a non-object: "
Object.getOwnPropertyDescriptor = getOwnPropertyDescriptor = (object, property) ->
throw new TypeError(ERR_NON_OBJECT + object) if (typeof object isnt "object" and typeof object isnt "function") or object is null
if getOwnPropertyDescriptorFallback
try
return getOwnPropertyDescriptorFallback.call(Object, object, property)
return unless owns(object, property)
descriptor =
enumerable: true
configurable: true
if supportsAccessors
prototype = object.__proto__
object.__proto__ = prototypeOfObject
getter = lookupGetter(object, property)
setter = lookupSetter(object, property)
object.__proto__ = prototype
if getter or setter
descriptor.get = getter if getter
descriptor.set = setter if setter
return descriptor
descriptor.value = object[property]
descriptor.writable = true
descriptor
unless Object.getOwnPropertyNames
Object.getOwnPropertyNames = getOwnPropertyNames = (object) ->
Object.keys object
unless Object.create
createEmpty = undefined
supportsProto = Object::__proto__ is null
if supportsProto or typeof document is "undefined"
createEmpty = ->
__proto__: null
else
createEmpty = ->
Empty = ->
iframe = document.createElement("iframe")
parent = document.body or document.documentElement
iframe.style.display = "none"
parent.appendChild iframe
iframe.src = "javascript:"
empty = iframe.contentWindow.Object::
parent.removeChild iframe
iframe = null
delete empty.constructor
delete empty.hasOwnProperty
delete empty.propertyIsEnumerable
delete empty.isPrototypeOf
delete empty.toLocaleString
delete empty.toString
delete empty.valueOf
empty.__proto__ = null
Empty:: = empty
createEmpty = ->
new Empty()
new Empty()
Object.create = create = (prototype, properties) ->
Type = ->
object = undefined
if prototype is null
object = createEmpty()
else
throw new TypeError("Object prototype may only be an Object or null") if typeof prototype isnt "object" and typeof prototype isnt "function"
Type:: = prototype
object = new Type()
object.__proto__ = prototype
Object.defineProperties object, properties if properties isnt undefined
object
# returns falsy
# check whether defineProperty works if it's given. Otherwise,
# shim partially.
if Object.defineProperty
definePropertyWorksOnObject = doesDefinePropertyWork({})
definePropertyWorksOnDom = typeof document is "undefined" or doesDefinePropertyWork(document.createElement("div"))
if not definePropertyWorksOnObject or not definePropertyWorksOnDom
definePropertyFallback = Object.defineProperty
definePropertiesFallback = Object.defineProperties
if not Object.defineProperty or definePropertyFallback
ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "
ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"
Object.defineProperty = defineProperty = (object, property, descriptor) ->
throw new TypeError(ERR_NON_OBJECT_TARGET + object) if (typeof object isnt "object" and typeof object isnt "function") or object is null
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor) if (typeof descriptor isnt "object" and typeof descriptor isnt "function") or descriptor is null
# make a valiant attempt to use the real defineProperty
# for I8's DOM elements.
if definePropertyFallback
try
return definePropertyFallback.call(Object, object, property, descriptor)
# try the shim if the real one doesn't work
# If it's a data property.
if owns(descriptor, "value")
# fail silently if "writable", "enumerable", or "configurable"
# are requested but not supported
#
# // alternate approach:
# if ( // can't implement these features; allow false but not true
# !(owns(descriptor, "writable") ? descriptor.writable : true) ||
# !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
# !(owns(descriptor, "configurable") ? descriptor.configurable : true)
# )
# throw new RangeError(
# "This implementation of Object.defineProperty does not " +
# "support configurable, enumerable, or writable."
# );
#
if supportsAccessors and (lookupGetter(object, property) or lookupSetter(object, property))
# As accessors are supported only on engines implementing
# `__proto__` we can safely override `__proto__` while defining
# a property to make sure that we don't hit an inherited
# accessor.
prototype = object.__proto__
object.__proto__ = prototypeOfObject
# Deleting a property anyway since getter / setter may be
# defined on object itself.
delete object[property]
object[property] = descriptor.value
# Setting original `__proto__` back now.
object.__proto__ = prototype
else
object[property] = descriptor.value
else
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED) unless supportsAccessors
# If we got that far then getters and setters can be defined !!
defineGetter object, property, descriptor.get if owns(descriptor, "get")
defineSetter object, property, descriptor.set if owns(descriptor, "set")
object
# ES5 15.2.3.7
# http://es5.github.com/#x15.2.3.7
if not Object.defineProperties or definePropertiesFallback
Object.defineProperties = defineProperties = (object, properties) ->
# make a valiant attempt to use the real defineProperties
if definePropertiesFallback
try
return definePropertiesFallback.call(Object, object, properties)
# try the shim if the real one doesn't work
for property of properties
Object.defineProperty object, property, properties[property] if owns(properties, property) and property isnt "__proto__"
object
# ES5 15.2.3.8
# http://es5.github.com/#x15.2.3.8
unless Object.seal
Object.seal = seal = (object) ->
# this is misleading and breaks feature-detection, but
# allows "securable" code to "gracefully" degrade to working
# but insecure code.
object
# ES5 15.2.3.9
# http://es5.github.com/#x15.2.3.9
unless Object.freeze
Object.freeze = freeze = (object) ->
# this is misleading and breaks feature-detection, but
# allows "securable" code to "gracefully" degrade to working
# but insecure code.
object
# detect a Rhino bug and patch it
try
Object.freeze ->
catch exception
Object.freeze = (freeze = (freezeObject) ->
freeze = (object) ->
if typeof object is "function"
object
else
freezeObject object
)(Object.freeze)
# ES5 PI:IP_ADDRESS:172.16.58.3END_PI
# http://es5.github.com/#x15.2.3.10
unless Object.preventExtensions
Object.preventExtensions = preventExtensions = (object) ->
# this is misleading and breaks feature-detection, but
# allows "securable" code to "gracefully" degrade to working
# but insecure code.
object
# ES5 PI:IP_ADDRESS:192.168.3.11END_PI
# http://es5.github.com/#x15.2.3.11
unless Object.isSealed
Object.isSealed = isSealed = (object) ->
false
# ES5 15.2.3.12
# http://es5.github.com/#x15.2.3.12
unless Object.isFrozen
Object.isFrozen = isFrozen = (object) ->
false
# ES5 15.2.3.13
# http://es5.github.com/#x15.2.3.13
unless Object.isExtensible
Object.isExtensible = isExtensible = (object) ->
# 1. If Type(O) is not Object throw a TypeError exception.
throw new TypeError() if Object(object) isnt object # TODO message
# 2. Return the Boolean value of the [[Extensible]] internal property of O.
name = ""
name += "?" while owns(object, name)
object[name] = true
returnValue = owns(object, name)
delete object[name]
returnValue
|
[
{
"context": " p = @map.latLngToLayerPoint(ll)\n key = \"#{Math.round(p.x / @clusterWidth)}_#{Math.round(p.y / @clusterHe",
"end": 4069,
"score": 0.7874150276184082,
"start": 4057,
"tag": "KEY",
"value": "Math.round(p"
},
{
"context": "\n key = \"#{Math.round(p.x / @clusterWidth)}_#{Math.round(p.y / @clusterHeight)}\"\n cells[key] ",
"end": 4096,
"score": 0.6447857618331909,
"start": 4090,
"tag": "KEY",
"value": "#{Math"
},
{
"context": " key = \"#{Math.round(p.x / @clusterWidth)}_#{Math.round(p.y / @clusterHeight)}\"\n cells[key] = st i",
"end": 4102,
"score": 0.876275360584259,
"start": 4097,
"tag": "KEY",
"value": "round"
},
{
"context": "nt('script')\n el.src = 'https://raw.github.com/mourner/suncalc/master/suncalc.js'\n el.type = 'text/ja",
"end": 8168,
"score": 0.9623907208442688,
"start": 8161,
"tag": "USERNAME",
"value": "mourner"
}
] | src/weather/leaflet-layer.coffee | idress4weather/m | 9 | Icon = L.Icon.extend
options:
popupAnchor: new L.Point(0, -25)
initialize: (options) ->
L.Util.setOptions(this, options)
createIcon: ->
div = document.createElement('div')
div.className = 'leaflet-marker-icon weather-icon'
div.style['margin'] = '-30px 0px 0px -30px'
div.style['width'] = '60px'
div.style['height'] = '20px'
div.style['padding'] = "#{@options.textOffset}px 0px 0px 0px"
div.style['background'] = "url(#{@options.image}) no-repeat center top"
div.style['textAlign'] = 'center'
span = document.createElement('span')
span.innerHTML = @options.text
div.appendChild(span)
div
createShadow: -> null
UnitFormatters =
metric:
temperature: (k, digits) ->
p = Math.pow(10, digits)
c = k - 273.15 # Convert kelvin degrees to celsius
"#{Math.round(c * p) / p} °C"
speed: (v) ->
"#{v} m/s"
height: (v) ->
"#{v} mm"
imperial:
temperature: (k, digits) ->
p = Math.pow(10, digits)
f = (k - 273.15) * 1.8 + 32 # Convert kelvin degrees to fahrenheit
"#{Math.round(f * p) / p} °F"
speed: (v) ->
v = Math.round(v*2.237) # Convert m/s to mph
"#{v} mph"
height: (v) ->
v = Math.round(v/1.27) / 20 # Convert mm to inches
"#{v} in"
Layer = L.Class.extend
defaultI18n:
en:
currentTemperature: "Temperature"
maximumTemperature: "Max. temp"
minimumTemperature: "Min. temp"
humidity: "Humidity"
wind: "Wind"
snow: "Snow"
snow_possible: "Snow possible"
rain: "Rain"
rain_possible: "Rain possible"
icerain: "Ice rain"
rime: "Rime"
rime_possible: "Rime"
clear: "Clear"
updateDate: "Updated at"
ru:
currentTemperature: "Температура"
maximumTemperature: "Макс. темп"
minimumTemperature: "Мин. темп"
humidity: "Влажность"
wind: "Ветер"
snow: "Снег"
snow_possible: "Возможен снег"
rain: "Дождь"
rain_possible: "Возможен дождь"
icerain: "Ледяной дождь"
rime: "Гололед"
rime_possible: "Возможен гололед"
clear: "Ясно"
updateDate: "Дата обновления"
includes: L.Mixin.Events
initialize: (@options = {})->
@layer = new L.LayerGroup()
@sourceUrl = "http://openweathermap.org/data/getrect?type={type}&lat1={minlat}&lat2={maxlat}&lng1={minlon}&lng2={maxlon}"
@sourceRequests = {}
@clusterWidth = @options.clusterWidth or 150
@clusterHeight = @options.clusterHeight or 150
@unitFormatter = UnitFormatters[@options.units or 'metric']
@type = @options.type or 'city'
@i18n = @options.i18n or @defaultI18n[@options.lang or 'en']
@stationsIcon = if @options.hasOwnProperty('stationsIcon') then @options.stationsIcon else true
@temperatureDigits = @options.temperatureDigits
@temperatureDigits = 2 unless @temperatureDigits?
Layer.Utils.checkSunCal()
onAdd: (map) ->
@map = map
@map.addLayer(@layer)
@map.on('moveend', @update, @)
@update()
onRemove: (map) ->
return unless @map == map
@map.off('moveend', @update, @)
@map.removeLayer(@layer)
@map = undefined
getAttribution: ->
'Weather data provided by <a href="http://openweathermap.org/">OpenWeatherMap</a>.'
update: ->
for url, req of @sourceRequests
req.abort()
@sourceRequests = {}
@updateType @type
updateType: (type) ->
bounds = @map.getBounds()
sw = bounds.getSouthWest()
ne = bounds.getNorthEast()
url = @sourceUrl
.replace('{type}', type)
.replace('{minlat}', sw.lat)
.replace('{maxlat}', ne.lat)
.replace('{minlon}', sw.lng)
.replace('{maxlon}', ne.lng)
@sourceRequests[type] = Layer.Utils.requestJsonp url, (data) =>
delete @sourceRequests[type]
@map.removeLayer(@layer)
@layer.clearLayers()
cells = {}
for st in data.list
ll = new L.LatLng(st.lat, st.lng)
p = @map.latLngToLayerPoint(ll)
key = "#{Math.round(p.x / @clusterWidth)}_#{Math.round(p.y / @clusterHeight)}"
cells[key] = st if not cells[key] or parseInt(cells[key].rang) < parseInt(st.rang)
for key, st of cells
@layer.addLayer(@buildMarker(st, new L.LatLng(st.lat, st.lng)))
@map.addLayer(@layer)
buildMarker: (st, ll) ->
weatherText = @weatherText(st)
weatherIcon = @weatherIcon(st)
popupContent = "<div class=\"weather-place\">"
popupContent += "<img height=\"38\" width=\"45\" style=\"border: none; float: right;\" alt=\"#{weatherText}\" src=\"#{weatherIcon}\" />"
popupContent += "<h3><a href=\"#{@buildUrl(st)}\" target=\"_blank\">#{st.name}</a></h3>"
popupContent += "<p>#{weatherText}</p>"
popupContent += "<p>"
popupContent += "#{@i18n.currentTemperature}: #{@unitFormatter.temperature(st.temp, @temperatureDigits)}<br />"
popupContent += "#{@i18n.maximumTemperature}: #{@unitFormatter.temperature(st.temp_max, @temperatureDigits)}<br />" if st.temp_max
popupContent += "#{@i18n.minimumTemperature}: #{@unitFormatter.temperature(st.temp_min, @temperatureDigits)}<br />" if st.temp_min
popupContent += "#{@i18n.humidity}: #{st.humidity}<br />" if st.humidity
popupContent += "#{@i18n.wind}: #{@unitFormatter.speed(st.wind_ms)}<br />"
popupContent += "#{@i18n.updateDate}: #{@formatTimestamp(st.dt)}<br />" if st.dt
popupContent += "</p>"
popupContent += "</div>"
typeIcon = @typeIcon(st)
markerIcon = if @stationsIcon and typeIcon
new Icon image: typeIcon, text: "#{@unitFormatter.temperature(st.temp, @temperatureDigits)}", textOffset: 30
else
new Icon image: weatherIcon, text: "#{@unitFormatter.temperature(st.temp, @temperatureDigits)}", textOffset: 45
marker = new L.Marker ll, icon: markerIcon
marker.bindPopup(popupContent)
marker
formatTimestamp: (ts) ->
date = new Date(ts * 1000)
m = date.getMonth()+1
m = '0' + m if m < 10
d = date.getDate()
d = '0' + d if d < 10
hh = date.getHours()
mm = date.getMinutes()
mm = '0' + mm if mm < 10
"#{date.getFullYear()}-#{m}-#{d} #{hh}:#{mm}"
buildUrl: (st) ->
if st.datatype == 'station'
"http://openweathermap.org/station/#{st.id}"
else
"http://openweathermap.org/city/#{st.id}"
weatherIcon: (st) ->
day = @dayTime(st)
cl = st.cloud
img = 'transparent'
if cl < 25 and cl >= 0
img = '01' + day
if cl < 50 and cl >= 25
img = '02' + day
if cl < 75 and cl >= 50
img = '03' + day
if cl >= 75
img = '04'
if st.prsp_type == '1' and st.prcp > 0
img = '13'
if st.prsp_type == '4' and st.prcp > 0
img = '09'
for i in ['23','24','26','27','28','29','33','38','42']
if st.prsp_type == i
img = '09'
"http://openweathermap.org/images/icons60/#{img}.png"
typeIcon: (st) ->
if st.datatype == 'station'
if st.type == '1'
"http://openweathermap.org/images/list-icon-3.png"
else if st.type == '2'
"http://openweathermap.org/images/list-icon-2.png"
weatherText: (st) ->
if st.prsp_type == '1'
if st.prcp!=0 and st.prcp > 0
"#{@i18n.snow} (#{@unitFormatter.height(st.prcp)})"
else
@i18n.snow_possible
else if st.prsp_type == '2'
if st.prcp!=0 and st.prcp > 0
"#{@i18n.rime} (#{@unitFormatter.height(st.prcp)})"
else
@i18n.rime_possible
else if st.prsp_type == '3'
@i18n.icerain
else if st.prsp_type == '4'
if st.prcp!=0 and st.prcp > 0
"#{@i18n.rain} (#{@unitFormatter.height(st.prcp)})"
else
@i18n.rain_possible
else
@i18n.clear
dayTime: (st) ->
return 'd' unless SunCalc?
dt = new Date()
times = SunCalc.getTimes(dt, st.lat, st.lng)
if dt > times.sunrise && dt < times.sunset
'd'
else
'n'
Layer.Utils =
callbacks: {}
callbackCounter: 0
checkSunCal: ->
return if SunCalc?
el = document.createElement('script')
el.src = 'https://raw.github.com/mourner/suncalc/master/suncalc.js'
el.type = 'text/javascript'
document.getElementsByTagName('body')[0].appendChild(el)
requestJsonp: (url, cb) ->
el = document.createElement('script')
counter = (@callbackCounter += 1)
callback = "OsmJs.Weather.LeafletLayer.Utils.callbacks[#{counter}]"
abort = ->
el.parentNode.removeChild(el) if el.parentNode
@callbacks[counter] = (data) =>
# el.parentNode.removeChild(el) if el.parentNode
delete @callbacks[counter]
cb(data)
delim = if url.indexOf('?') >= 0
'&'
else
'?'
el.src = "#{url}#{delim}callback=#{callback}"
el.type = 'text/javascript'
document.getElementsByTagName('body')[0].appendChild(el)
{abort: abort}
@OsmJs = {} unless @OsmJs
@OsmJs.Weather = {} unless @OsmJs.Weather
@OsmJs.Weather.LeafletLayer = Layer
| 83496 | Icon = L.Icon.extend
options:
popupAnchor: new L.Point(0, -25)
initialize: (options) ->
L.Util.setOptions(this, options)
createIcon: ->
div = document.createElement('div')
div.className = 'leaflet-marker-icon weather-icon'
div.style['margin'] = '-30px 0px 0px -30px'
div.style['width'] = '60px'
div.style['height'] = '20px'
div.style['padding'] = "#{@options.textOffset}px 0px 0px 0px"
div.style['background'] = "url(#{@options.image}) no-repeat center top"
div.style['textAlign'] = 'center'
span = document.createElement('span')
span.innerHTML = @options.text
div.appendChild(span)
div
createShadow: -> null
UnitFormatters =
metric:
temperature: (k, digits) ->
p = Math.pow(10, digits)
c = k - 273.15 # Convert kelvin degrees to celsius
"#{Math.round(c * p) / p} °C"
speed: (v) ->
"#{v} m/s"
height: (v) ->
"#{v} mm"
imperial:
temperature: (k, digits) ->
p = Math.pow(10, digits)
f = (k - 273.15) * 1.8 + 32 # Convert kelvin degrees to fahrenheit
"#{Math.round(f * p) / p} °F"
speed: (v) ->
v = Math.round(v*2.237) # Convert m/s to mph
"#{v} mph"
height: (v) ->
v = Math.round(v/1.27) / 20 # Convert mm to inches
"#{v} in"
Layer = L.Class.extend
defaultI18n:
en:
currentTemperature: "Temperature"
maximumTemperature: "Max. temp"
minimumTemperature: "Min. temp"
humidity: "Humidity"
wind: "Wind"
snow: "Snow"
snow_possible: "Snow possible"
rain: "Rain"
rain_possible: "Rain possible"
icerain: "Ice rain"
rime: "Rime"
rime_possible: "Rime"
clear: "Clear"
updateDate: "Updated at"
ru:
currentTemperature: "Температура"
maximumTemperature: "Макс. темп"
minimumTemperature: "Мин. темп"
humidity: "Влажность"
wind: "Ветер"
snow: "Снег"
snow_possible: "Возможен снег"
rain: "Дождь"
rain_possible: "Возможен дождь"
icerain: "Ледяной дождь"
rime: "Гололед"
rime_possible: "Возможен гололед"
clear: "Ясно"
updateDate: "Дата обновления"
includes: L.Mixin.Events
initialize: (@options = {})->
@layer = new L.LayerGroup()
@sourceUrl = "http://openweathermap.org/data/getrect?type={type}&lat1={minlat}&lat2={maxlat}&lng1={minlon}&lng2={maxlon}"
@sourceRequests = {}
@clusterWidth = @options.clusterWidth or 150
@clusterHeight = @options.clusterHeight or 150
@unitFormatter = UnitFormatters[@options.units or 'metric']
@type = @options.type or 'city'
@i18n = @options.i18n or @defaultI18n[@options.lang or 'en']
@stationsIcon = if @options.hasOwnProperty('stationsIcon') then @options.stationsIcon else true
@temperatureDigits = @options.temperatureDigits
@temperatureDigits = 2 unless @temperatureDigits?
Layer.Utils.checkSunCal()
onAdd: (map) ->
@map = map
@map.addLayer(@layer)
@map.on('moveend', @update, @)
@update()
onRemove: (map) ->
return unless @map == map
@map.off('moveend', @update, @)
@map.removeLayer(@layer)
@map = undefined
getAttribution: ->
'Weather data provided by <a href="http://openweathermap.org/">OpenWeatherMap</a>.'
update: ->
for url, req of @sourceRequests
req.abort()
@sourceRequests = {}
@updateType @type
updateType: (type) ->
bounds = @map.getBounds()
sw = bounds.getSouthWest()
ne = bounds.getNorthEast()
url = @sourceUrl
.replace('{type}', type)
.replace('{minlat}', sw.lat)
.replace('{maxlat}', ne.lat)
.replace('{minlon}', sw.lng)
.replace('{maxlon}', ne.lng)
@sourceRequests[type] = Layer.Utils.requestJsonp url, (data) =>
delete @sourceRequests[type]
@map.removeLayer(@layer)
@layer.clearLayers()
cells = {}
for st in data.list
ll = new L.LatLng(st.lat, st.lng)
p = @map.latLngToLayerPoint(ll)
key = "#{<KEY>.x / @clusterWidth)}_<KEY>.<KEY>(p.y / @clusterHeight)}"
cells[key] = st if not cells[key] or parseInt(cells[key].rang) < parseInt(st.rang)
for key, st of cells
@layer.addLayer(@buildMarker(st, new L.LatLng(st.lat, st.lng)))
@map.addLayer(@layer)
buildMarker: (st, ll) ->
weatherText = @weatherText(st)
weatherIcon = @weatherIcon(st)
popupContent = "<div class=\"weather-place\">"
popupContent += "<img height=\"38\" width=\"45\" style=\"border: none; float: right;\" alt=\"#{weatherText}\" src=\"#{weatherIcon}\" />"
popupContent += "<h3><a href=\"#{@buildUrl(st)}\" target=\"_blank\">#{st.name}</a></h3>"
popupContent += "<p>#{weatherText}</p>"
popupContent += "<p>"
popupContent += "#{@i18n.currentTemperature}: #{@unitFormatter.temperature(st.temp, @temperatureDigits)}<br />"
popupContent += "#{@i18n.maximumTemperature}: #{@unitFormatter.temperature(st.temp_max, @temperatureDigits)}<br />" if st.temp_max
popupContent += "#{@i18n.minimumTemperature}: #{@unitFormatter.temperature(st.temp_min, @temperatureDigits)}<br />" if st.temp_min
popupContent += "#{@i18n.humidity}: #{st.humidity}<br />" if st.humidity
popupContent += "#{@i18n.wind}: #{@unitFormatter.speed(st.wind_ms)}<br />"
popupContent += "#{@i18n.updateDate}: #{@formatTimestamp(st.dt)}<br />" if st.dt
popupContent += "</p>"
popupContent += "</div>"
typeIcon = @typeIcon(st)
markerIcon = if @stationsIcon and typeIcon
new Icon image: typeIcon, text: "#{@unitFormatter.temperature(st.temp, @temperatureDigits)}", textOffset: 30
else
new Icon image: weatherIcon, text: "#{@unitFormatter.temperature(st.temp, @temperatureDigits)}", textOffset: 45
marker = new L.Marker ll, icon: markerIcon
marker.bindPopup(popupContent)
marker
formatTimestamp: (ts) ->
date = new Date(ts * 1000)
m = date.getMonth()+1
m = '0' + m if m < 10
d = date.getDate()
d = '0' + d if d < 10
hh = date.getHours()
mm = date.getMinutes()
mm = '0' + mm if mm < 10
"#{date.getFullYear()}-#{m}-#{d} #{hh}:#{mm}"
buildUrl: (st) ->
if st.datatype == 'station'
"http://openweathermap.org/station/#{st.id}"
else
"http://openweathermap.org/city/#{st.id}"
weatherIcon: (st) ->
day = @dayTime(st)
cl = st.cloud
img = 'transparent'
if cl < 25 and cl >= 0
img = '01' + day
if cl < 50 and cl >= 25
img = '02' + day
if cl < 75 and cl >= 50
img = '03' + day
if cl >= 75
img = '04'
if st.prsp_type == '1' and st.prcp > 0
img = '13'
if st.prsp_type == '4' and st.prcp > 0
img = '09'
for i in ['23','24','26','27','28','29','33','38','42']
if st.prsp_type == i
img = '09'
"http://openweathermap.org/images/icons60/#{img}.png"
typeIcon: (st) ->
if st.datatype == 'station'
if st.type == '1'
"http://openweathermap.org/images/list-icon-3.png"
else if st.type == '2'
"http://openweathermap.org/images/list-icon-2.png"
weatherText: (st) ->
if st.prsp_type == '1'
if st.prcp!=0 and st.prcp > 0
"#{@i18n.snow} (#{@unitFormatter.height(st.prcp)})"
else
@i18n.snow_possible
else if st.prsp_type == '2'
if st.prcp!=0 and st.prcp > 0
"#{@i18n.rime} (#{@unitFormatter.height(st.prcp)})"
else
@i18n.rime_possible
else if st.prsp_type == '3'
@i18n.icerain
else if st.prsp_type == '4'
if st.prcp!=0 and st.prcp > 0
"#{@i18n.rain} (#{@unitFormatter.height(st.prcp)})"
else
@i18n.rain_possible
else
@i18n.clear
dayTime: (st) ->
return 'd' unless SunCalc?
dt = new Date()
times = SunCalc.getTimes(dt, st.lat, st.lng)
if dt > times.sunrise && dt < times.sunset
'd'
else
'n'
Layer.Utils =
callbacks: {}
callbackCounter: 0
checkSunCal: ->
return if SunCalc?
el = document.createElement('script')
el.src = 'https://raw.github.com/mourner/suncalc/master/suncalc.js'
el.type = 'text/javascript'
document.getElementsByTagName('body')[0].appendChild(el)
requestJsonp: (url, cb) ->
el = document.createElement('script')
counter = (@callbackCounter += 1)
callback = "OsmJs.Weather.LeafletLayer.Utils.callbacks[#{counter}]"
abort = ->
el.parentNode.removeChild(el) if el.parentNode
@callbacks[counter] = (data) =>
# el.parentNode.removeChild(el) if el.parentNode
delete @callbacks[counter]
cb(data)
delim = if url.indexOf('?') >= 0
'&'
else
'?'
el.src = "#{url}#{delim}callback=#{callback}"
el.type = 'text/javascript'
document.getElementsByTagName('body')[0].appendChild(el)
{abort: abort}
@OsmJs = {} unless @OsmJs
@OsmJs.Weather = {} unless @OsmJs.Weather
@OsmJs.Weather.LeafletLayer = Layer
| true | Icon = L.Icon.extend
options:
popupAnchor: new L.Point(0, -25)
initialize: (options) ->
L.Util.setOptions(this, options)
createIcon: ->
div = document.createElement('div')
div.className = 'leaflet-marker-icon weather-icon'
div.style['margin'] = '-30px 0px 0px -30px'
div.style['width'] = '60px'
div.style['height'] = '20px'
div.style['padding'] = "#{@options.textOffset}px 0px 0px 0px"
div.style['background'] = "url(#{@options.image}) no-repeat center top"
div.style['textAlign'] = 'center'
span = document.createElement('span')
span.innerHTML = @options.text
div.appendChild(span)
div
createShadow: -> null
UnitFormatters =
metric:
temperature: (k, digits) ->
p = Math.pow(10, digits)
c = k - 273.15 # Convert kelvin degrees to celsius
"#{Math.round(c * p) / p} °C"
speed: (v) ->
"#{v} m/s"
height: (v) ->
"#{v} mm"
imperial:
temperature: (k, digits) ->
p = Math.pow(10, digits)
f = (k - 273.15) * 1.8 + 32 # Convert kelvin degrees to fahrenheit
"#{Math.round(f * p) / p} °F"
speed: (v) ->
v = Math.round(v*2.237) # Convert m/s to mph
"#{v} mph"
height: (v) ->
v = Math.round(v/1.27) / 20 # Convert mm to inches
"#{v} in"
Layer = L.Class.extend
defaultI18n:
en:
currentTemperature: "Temperature"
maximumTemperature: "Max. temp"
minimumTemperature: "Min. temp"
humidity: "Humidity"
wind: "Wind"
snow: "Snow"
snow_possible: "Snow possible"
rain: "Rain"
rain_possible: "Rain possible"
icerain: "Ice rain"
rime: "Rime"
rime_possible: "Rime"
clear: "Clear"
updateDate: "Updated at"
ru:
currentTemperature: "Температура"
maximumTemperature: "Макс. темп"
minimumTemperature: "Мин. темп"
humidity: "Влажность"
wind: "Ветер"
snow: "Снег"
snow_possible: "Возможен снег"
rain: "Дождь"
rain_possible: "Возможен дождь"
icerain: "Ледяной дождь"
rime: "Гололед"
rime_possible: "Возможен гололед"
clear: "Ясно"
updateDate: "Дата обновления"
includes: L.Mixin.Events
initialize: (@options = {})->
@layer = new L.LayerGroup()
@sourceUrl = "http://openweathermap.org/data/getrect?type={type}&lat1={minlat}&lat2={maxlat}&lng1={minlon}&lng2={maxlon}"
@sourceRequests = {}
@clusterWidth = @options.clusterWidth or 150
@clusterHeight = @options.clusterHeight or 150
@unitFormatter = UnitFormatters[@options.units or 'metric']
@type = @options.type or 'city'
@i18n = @options.i18n or @defaultI18n[@options.lang or 'en']
@stationsIcon = if @options.hasOwnProperty('stationsIcon') then @options.stationsIcon else true
@temperatureDigits = @options.temperatureDigits
@temperatureDigits = 2 unless @temperatureDigits?
Layer.Utils.checkSunCal()
onAdd: (map) ->
@map = map
@map.addLayer(@layer)
@map.on('moveend', @update, @)
@update()
onRemove: (map) ->
return unless @map == map
@map.off('moveend', @update, @)
@map.removeLayer(@layer)
@map = undefined
getAttribution: ->
'Weather data provided by <a href="http://openweathermap.org/">OpenWeatherMap</a>.'
update: ->
for url, req of @sourceRequests
req.abort()
@sourceRequests = {}
@updateType @type
updateType: (type) ->
bounds = @map.getBounds()
sw = bounds.getSouthWest()
ne = bounds.getNorthEast()
url = @sourceUrl
.replace('{type}', type)
.replace('{minlat}', sw.lat)
.replace('{maxlat}', ne.lat)
.replace('{minlon}', sw.lng)
.replace('{maxlon}', ne.lng)
@sourceRequests[type] = Layer.Utils.requestJsonp url, (data) =>
delete @sourceRequests[type]
@map.removeLayer(@layer)
@layer.clearLayers()
cells = {}
for st in data.list
ll = new L.LatLng(st.lat, st.lng)
p = @map.latLngToLayerPoint(ll)
key = "#{PI:KEY:<KEY>END_PI.x / @clusterWidth)}_PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI(p.y / @clusterHeight)}"
cells[key] = st if not cells[key] or parseInt(cells[key].rang) < parseInt(st.rang)
for key, st of cells
@layer.addLayer(@buildMarker(st, new L.LatLng(st.lat, st.lng)))
@map.addLayer(@layer)
buildMarker: (st, ll) ->
weatherText = @weatherText(st)
weatherIcon = @weatherIcon(st)
popupContent = "<div class=\"weather-place\">"
popupContent += "<img height=\"38\" width=\"45\" style=\"border: none; float: right;\" alt=\"#{weatherText}\" src=\"#{weatherIcon}\" />"
popupContent += "<h3><a href=\"#{@buildUrl(st)}\" target=\"_blank\">#{st.name}</a></h3>"
popupContent += "<p>#{weatherText}</p>"
popupContent += "<p>"
popupContent += "#{@i18n.currentTemperature}: #{@unitFormatter.temperature(st.temp, @temperatureDigits)}<br />"
popupContent += "#{@i18n.maximumTemperature}: #{@unitFormatter.temperature(st.temp_max, @temperatureDigits)}<br />" if st.temp_max
popupContent += "#{@i18n.minimumTemperature}: #{@unitFormatter.temperature(st.temp_min, @temperatureDigits)}<br />" if st.temp_min
popupContent += "#{@i18n.humidity}: #{st.humidity}<br />" if st.humidity
popupContent += "#{@i18n.wind}: #{@unitFormatter.speed(st.wind_ms)}<br />"
popupContent += "#{@i18n.updateDate}: #{@formatTimestamp(st.dt)}<br />" if st.dt
popupContent += "</p>"
popupContent += "</div>"
typeIcon = @typeIcon(st)
markerIcon = if @stationsIcon and typeIcon
new Icon image: typeIcon, text: "#{@unitFormatter.temperature(st.temp, @temperatureDigits)}", textOffset: 30
else
new Icon image: weatherIcon, text: "#{@unitFormatter.temperature(st.temp, @temperatureDigits)}", textOffset: 45
marker = new L.Marker ll, icon: markerIcon
marker.bindPopup(popupContent)
marker
formatTimestamp: (ts) ->
date = new Date(ts * 1000)
m = date.getMonth()+1
m = '0' + m if m < 10
d = date.getDate()
d = '0' + d if d < 10
hh = date.getHours()
mm = date.getMinutes()
mm = '0' + mm if mm < 10
"#{date.getFullYear()}-#{m}-#{d} #{hh}:#{mm}"
buildUrl: (st) ->
if st.datatype == 'station'
"http://openweathermap.org/station/#{st.id}"
else
"http://openweathermap.org/city/#{st.id}"
weatherIcon: (st) ->
day = @dayTime(st)
cl = st.cloud
img = 'transparent'
if cl < 25 and cl >= 0
img = '01' + day
if cl < 50 and cl >= 25
img = '02' + day
if cl < 75 and cl >= 50
img = '03' + day
if cl >= 75
img = '04'
if st.prsp_type == '1' and st.prcp > 0
img = '13'
if st.prsp_type == '4' and st.prcp > 0
img = '09'
for i in ['23','24','26','27','28','29','33','38','42']
if st.prsp_type == i
img = '09'
"http://openweathermap.org/images/icons60/#{img}.png"
typeIcon: (st) ->
if st.datatype == 'station'
if st.type == '1'
"http://openweathermap.org/images/list-icon-3.png"
else if st.type == '2'
"http://openweathermap.org/images/list-icon-2.png"
weatherText: (st) ->
if st.prsp_type == '1'
if st.prcp!=0 and st.prcp > 0
"#{@i18n.snow} (#{@unitFormatter.height(st.prcp)})"
else
@i18n.snow_possible
else if st.prsp_type == '2'
if st.prcp!=0 and st.prcp > 0
"#{@i18n.rime} (#{@unitFormatter.height(st.prcp)})"
else
@i18n.rime_possible
else if st.prsp_type == '3'
@i18n.icerain
else if st.prsp_type == '4'
if st.prcp!=0 and st.prcp > 0
"#{@i18n.rain} (#{@unitFormatter.height(st.prcp)})"
else
@i18n.rain_possible
else
@i18n.clear
dayTime: (st) ->
return 'd' unless SunCalc?
dt = new Date()
times = SunCalc.getTimes(dt, st.lat, st.lng)
if dt > times.sunrise && dt < times.sunset
'd'
else
'n'
Layer.Utils =
callbacks: {}
callbackCounter: 0
checkSunCal: ->
return if SunCalc?
el = document.createElement('script')
el.src = 'https://raw.github.com/mourner/suncalc/master/suncalc.js'
el.type = 'text/javascript'
document.getElementsByTagName('body')[0].appendChild(el)
requestJsonp: (url, cb) ->
el = document.createElement('script')
counter = (@callbackCounter += 1)
callback = "OsmJs.Weather.LeafletLayer.Utils.callbacks[#{counter}]"
abort = ->
el.parentNode.removeChild(el) if el.parentNode
@callbacks[counter] = (data) =>
# el.parentNode.removeChild(el) if el.parentNode
delete @callbacks[counter]
cb(data)
delim = if url.indexOf('?') >= 0
'&'
else
'?'
el.src = "#{url}#{delim}callback=#{callback}"
el.type = 'text/javascript'
document.getElementsByTagName('body')[0].appendChild(el)
{abort: abort}
@OsmJs = {} unless @OsmJs
@OsmJs.Weather = {} unless @OsmJs.Weather
@OsmJs.Weather.LeafletLayer = Layer
|
[
{
"context": "#\n# Copyright (c) 2011 Hidden\n# Copyright (c) 2012 Marc René Arns\n# Released under the MIT, BSD, and GPL Licenses.\n",
"end": 133,
"score": 0.9998798370361328,
"start": 119,
"tag": "NAME",
"value": "Marc René Arns"
}
] | node_modules/EVE/src/eve.coffee | NUDelta/guide | 4 | # EVE
#
# A JavaScript object schema, processor and validation lib.
#
# Copyright (c) 2011 Hidden
# Copyright (c) 2012 Marc René Arns
# Released under the MIT, BSD, and GPL Licenses.
eve = {}
validator = require "./validator"
type = require "./type"
require "./number"
require "./string"
require "./date"
require "./object"
require "./array"
require "./or"
require "./and"
require "./bool"
# Library version.
#eve.version = require(__dirname + "./../package.json")['version']
eve.version = '0.0.5-metakeule'
# Basic validator
eve.validator = validator
# Schema type
eve.type = type
# Error message
eve.message = require "./message"
# Error object
eve.error = require "./error"
exports = module.exports = eve | 16745 | # EVE
#
# A JavaScript object schema, processor and validation lib.
#
# Copyright (c) 2011 Hidden
# Copyright (c) 2012 <NAME>
# Released under the MIT, BSD, and GPL Licenses.
eve = {}
validator = require "./validator"
type = require "./type"
require "./number"
require "./string"
require "./date"
require "./object"
require "./array"
require "./or"
require "./and"
require "./bool"
# Library version.
#eve.version = require(__dirname + "./../package.json")['version']
eve.version = '0.0.5-metakeule'
# Basic validator
eve.validator = validator
# Schema type
eve.type = type
# Error message
eve.message = require "./message"
# Error object
eve.error = require "./error"
exports = module.exports = eve | true | # EVE
#
# A JavaScript object schema, processor and validation lib.
#
# Copyright (c) 2011 Hidden
# Copyright (c) 2012 PI:NAME:<NAME>END_PI
# Released under the MIT, BSD, and GPL Licenses.
eve = {}
validator = require "./validator"
type = require "./type"
require "./number"
require "./string"
require "./date"
require "./object"
require "./array"
require "./or"
require "./and"
require "./bool"
# Library version.
#eve.version = require(__dirname + "./../package.json")['version']
eve.version = '0.0.5-metakeule'
# Basic validator
eve.validator = validator
# Schema type
eve.type = type
# Error message
eve.message = require "./message"
# Error object
eve.error = require "./error"
exports = module.exports = eve |
[
{
"context": "> users: {client_id: user.clientId, id: 1, name: \"wes\"}\n @server.r 'POST:/groups', (xhr) ->\n ",
"end": 595,
"score": 0.9981207847595215,
"start": 592,
"tag": "NAME",
"value": "wes"
},
{
"context": "groups: {client_id: group.clientId, id: 2, name: \"brogrammers\", members: [{client_id: member.clientId, id: 3, r",
"end": 816,
"score": 0.7530309557914734,
"start": 805,
"tag": "USERNAME",
"value": "brogrammers"
},
{
"context": ")\n user = childSession.create 'user', name: 'wes'\n group = null\n member = null\n chi",
"end": 1005,
"score": 0.9970237016677856,
"start": 1002,
"tag": "NAME",
"value": "wes"
},
{
"context": " group = childSession.create 'group', name: 'brogrammers', user: user\n member = childSession.cr",
"end": 1322,
"score": 0.5100120306015015,
"start": 1318,
"tag": "USERNAME",
"value": "gram"
},
{
"context": "groups: {client_id: group.clientId, id: 2, name: \"brogrammers\", members: [], user: 1}\n childSession.fl",
"end": 2269,
"score": 0.8674588203430176,
"start": 2258,
"tag": "USERNAME",
"value": "brogrammers"
},
{
"context": "oups', groups: [{client_id: null, id: \"1\", name: \"brogrammers\", user: \"1\"}]\n\n @session.query(\"group\").then",
"end": 2782,
"score": 0.8018314242362976,
"start": 2771,
"tag": "USERNAME",
"value": "brogrammers"
},
{
"context": "h).to.eq(1)\n expect(result[0].name).to.eq(\"brogrammers\")\n expect(result[0].groups).to.be.undefine",
"end": 2983,
"score": 0.8046345710754395,
"start": 2972,
"tag": "USERNAME",
"value": "brogrammers"
},
{
"context": "d: 1, name: \"employees\", members: [{id: 2, name: \"kinz\", group: 1, user: 3}]}, users: {id: 3, name: \"wtf",
"end": 3185,
"score": 0.7070075273513794,
"start": 3181,
"tag": "USERNAME",
"value": "kinz"
},
{
"context": "inz\", group: 1, user: 3}]}, users: {id: 3, name: \"wtf\", members: [2], groups: [1]}\n\n @session.lo",
"end": 3233,
"score": 0.31295400857925415,
"start": 3232,
"tag": "NAME",
"value": "w"
},
{
"context": "nz\", group: 1, user: 3}]}, users: {id: 3, name: \"wtf\", members: [2], groups: [1]}\n\n @session.load",
"end": 3235,
"score": 0.7380955815315247,
"start": 3233,
"tag": "USERNAME",
"value": "tf"
},
{
"context": " member = childSession.create('member', {name: \"mollie\"})\n childGroup.members.addObject(member",
"end": 3674,
"score": 0.7045107483863831,
"start": 3671,
"tag": "NAME",
"value": "mol"
},
{
"context": "member = childSession.create('member', {name: \"mollie\"})\n childGroup.members.addObject(member)\n\n",
"end": 3677,
"score": 0.7701769471168518,
"start": 3674,
"tag": "USERNAME",
"value": "lie"
},
{
"context": "d: 1, name: \"employees\", members: [{id: 2, name: \"kinz\", group: 1}, {id: 3, client_id: member.clientId,",
"end": 3926,
"score": 0.6845043897628784,
"start": 3923,
"tag": "NAME",
"value": "kin"
},
{
"context": "1, name: \"employees\", members: [{id: 2, name: \"kinz\", group: 1}, {id: 3, client_id: member.clientId, ",
"end": 3927,
"score": 0.5300869941711426,
"start": 3926,
"tag": "USERNAME",
"value": "z"
},
{
"context": "p: 1}, {id: 3, client_id: member.clientId, name: \"mollie\", group: 1}]}\n promise = childSession.flus",
"end": 3990,
"score": 0.9818217754364014,
"start": 3984,
"tag": "NAME",
"value": "mollie"
},
{
"context": "merge @User.create\n id: '1'\n name: 'abby'\n profile: @Profile.create\n id: '",
"end": 6474,
"score": 0.9993516802787781,
"start": 6470,
"tag": "NAME",
"value": "abby"
},
{
"context": "n.merge @session.build 'campaign',\n name: 'old name'\n id: 1\n campaignSteps: []\n\n s",
"end": 13095,
"score": 0.948327898979187,
"start": 13087,
"tag": "NAME",
"value": "old name"
},
{
"context": "tact: {id: 1, client_id: contact.clientId, name: \"test contact\", account: 2}\n @server.r 'POST:/acco",
"end": 14499,
"score": 0.9785691499710083,
"start": 14495,
"tag": "NAME",
"value": "test"
},
{
"context": "d: 2, client_id: contact.account.clientId, name: \"test account\"}\n \n contact = @session.create ",
"end": 14624,
"score": 0.5360689759254456,
"start": 14620,
"tag": "NAME",
"value": "test"
},
{
"context": " contact = @session.create 'contact', name: 'test contact'\n contact.account = @session.create 'account",
"end": 14704,
"score": 0.8720550537109375,
"start": 14692,
"tag": "NAME",
"value": "test contact"
},
{
"context": "ntact.account = @session.create 'account', name: 'test account'\n \n @session.flush().then =>\n ",
"end": 14768,
"score": 0.6109654903411865,
"start": 14764,
"tag": "NAME",
"value": "test"
}
] | test/rest/rest.acceptance.coffee | travisperson/coalesce | 18 | `import Model from 'coalesce/model/model'`
`import Context from 'coalesce/rest/context'`
`import {postWithComments, groupWithMembersWithUsers} from '../support/configs'`
`import {delay} from '../support/async'`
describe "rest acceptance scenarios", ->
lazy 'context', -> new Context
lazy 'session', -> @context.newSession()
describe "managing groups with embedded members", ->
lazy 'context', -> new Context(groupWithMembersWithUsers())
it 'creates new group and then deletes a member', ->
@server.r 'POST:/users', -> users: {client_id: user.clientId, id: 1, name: "wes"}
@server.r 'POST:/groups', (xhr) ->
data = JSON.parse(xhr.requestBody)
expect(data.group.members[0].role).to.eq('chief')
return groups: {client_id: group.clientId, id: 2, name: "brogrammers", members: [{client_id: member.clientId, id: 3, role: "chief", group: 2, user: 1}], user: 1}
childSession = @session.newSession()
user = childSession.create 'user', name: 'wes'
group = null
member = null
childSession.flushIntoParent().then =>
expect(user.id).to.not.be.null
expect(@server.h).to.eql(['POST:/users'])
childSession = @session.newSession()
user = childSession.add(user)
group = childSession.create 'group', name: 'brogrammers', user: user
member = childSession.create 'member', role: 'chief', user: user, group: group
childSession.flushIntoParent().then =>
expect(@server.h).to.eql(['POST:/users', 'POST:/groups'])
expect(user.id).to.not.be.null
expect(group.id).to.not.be.null
expect(group.members.length).to.eq(1)
expect(user.groups.length).to.eq(1)
expect(user.members.length).to.eq(1)
expect(member.id).to.not.be.null
childSession = @session.newSession()
member = childSession.add(member)
user = childSession.add(user)
group = childSession.add(group)
childSession.deleteModel(member)
expect(user.members.length).to.eq(0)
expect(group.members.length).to.eq(0)
expect(user.groups.length).to.eq(1)
@server.r 'PUT:/groups/2', -> groups: {client_id: group.clientId, id: 2, name: "brogrammers", members: [], user: 1}
childSession.flushIntoParent().then =>
expect(member.isDeleted).to.be.true
expect(group.members.length).to.eq(0)
expect(user.members.length).to.eq(0)
expect(user.groups.length).to.eq(1)
expect(@server.h).to.eql(['POST:/users', 'POST:/groups', 'PUT:/groups/2'])
it "doesn't choke when loading a group without a members key", ->
@server.r 'GET:/groups', groups: [{client_id: null, id: "1", name: "brogrammers", user: "1"}]
@session.query("group").then (result) =>
expect(@server.h).to.eql(['GET:/groups'])
expect(result.length).to.eq(1)
expect(result[0].name).to.eq("brogrammers")
expect(result[0].groups).to.be.undefined
it 'adds a member to an existing group', ->
@server.r 'GET:/groups/1', -> groups: {id: 1, name: "employees", members: [{id: 2, name: "kinz", group: 1, user: 3}]}, users: {id: 3, name: "wtf", members: [2], groups: [1]}
@session.load("group", 1).then (group) =>
expect(@server.h).to.eql(['GET:/groups/1'])
childSession = @session.newSession()
childGroup = childSession.add(group)
existingMember = childGroup.members[0]
expect(existingMember.user).to.not.be.null
expect(existingMember.user.isDetached).to.be.false
member = childSession.create('member', {name: "mollie"})
childGroup.members.addObject(member)
expect(childGroup.members.length).to.eq(2)
expect(group.members.length).to.eq(1)
@server.r 'PUT:/groups/1', -> groups: {id: 1, name: "employees", members: [{id: 2, name: "kinz", group: 1}, {id: 3, client_id: member.clientId, name: "mollie", group: 1}]}
promise = childSession.flushIntoParent().then =>
expect(childGroup.members.length).to.eq(2)
expect(group.members.length).to.eq(2)
expect(@server.h).to.eql(['GET:/groups/1', 'PUT:/groups/1'])
expect(group.members.length).to.eq(2)
promise
describe "managing comments", ->
lazy 'context', -> new Context(postWithComments())
lazy 'Post', -> @context.typeFor('post')
lazy 'Comment', -> @context.typeFor('comment')
it 'creates a new comment within a child session', ->
@server.r 'POST:/comments', -> comment: {client_id: comment.clientId, id: "3", message: "#2", post: "1"}
post = @session.merge @Post.create(id: "1", title: "brogrammer's guide to beer pong", comments: [])
@session.merge @Comment.create(id: "2", message: "yo", post: post)
childSession = @session.newSession()
childPost = childSession.add(post)
comment = childSession.create 'comment',
message: '#2',
post: childPost
expect(childPost.comments.length).to.eq(2)
promise = childSession.flushIntoParent().then =>
expect(childPost.comments.length).to.eq(2)
expect(post.comments.length).to.eq(2)
expect(childPost.comments.length).to.eq(2)
expect(post.comments.length).to.eq(2)
promise
describe "two levels of embedded", ->
lazy 'context', ->
`class User extends Model {}`
User.defineSchema
attributes:
name: {type: 'string'}
relationships:
profile: {kind: 'belongsTo', type: 'profile', embedded: 'always'}
`class Profile extends Model {}`
Profile.defineSchema
attributes:
bio: {type: 'string'}
relationships:
user: {kind: 'belongsTo', type: 'user'}
tags: {kind: 'hasMany', type: 'tag', embedded: 'always'}
`class Tag extends Model {}`
Tag.defineSchema
attributes:
name: {type: 'string'}
relationships:
profile: {kind: 'belongsTo', type: 'profile'}
new Context
types:
user: User
profile: Profile
tag: Tag
lazy 'User', -> @context.typeFor('user')
lazy 'Profile', -> @context.typeFor('profile')
lazy 'Tag', -> @context.typeFor('tag')
it 'deletes root', ->
@server.r 'DELETE:/users/1', {}
@User.create id: '1'
user = @session.merge @User.create
id: '1'
name: 'abby'
profile: @Profile.create
id: '2'
bio: 'asd'
tags: [@Tag.create(id: '3', name: 'java')]
@session.deleteModel(user)
@session.flush().then =>
expect(@server.h).to.eql(['DELETE:/users/1'])
expect(user.isDeleted).to.be.true
describe 'multiple belongsTo', ->
lazy 'context', ->
`class Foo extends Model {}`
Foo.defineSchema
typeKey: 'foo',
relationships:
bar: {kind: 'belongsTo', type: 'bar'}
baz: {kind: 'belongsTo', type: 'baz'}
`class Bar extends Model {}`
Bar.defineSchema
typeKey: 'bar'
relationships:
foos: {kind: 'hasMany', type: 'foo'}
`class Baz extends Model {}`
Baz.defineSchema
typeKey: 'baz'
relationships:
foos: {kind: 'hasMany', type: 'foo'}
new Context
types:
foo: Foo
bar: Bar
baz: Baz
it 'sets ids properly', ->
@server.r 'POST:/bars', -> bar: {client_id: bar.clientId, id: "1"}
@server.r 'POST:/bazs', -> baz: {client_id: baz.clientId, id: "1"}
@server.r 'POST:/foos', (xhr) ->
data = JSON.parse(xhr.requestBody)
expect(data.foo.bar).to.eq 1
expect(data.foo.baz).to.eq 1
foo: {client_id: foo.clientId, id: "1", bar: "1", baz: "1"}
childSession = @session.newSession()
foo = childSession.create 'foo'
bar = childSession.create 'bar'
baz = childSession.create 'baz'
foo.bar = bar
foo.baz = baz
childSession.flushIntoParent().then =>
expect(@server.h.length).to.eq(3)
expect(@server.h[@server.h.length-1]).to.eq('POST:/foos')
expect(@server.h).to.include('POST:/bars')
expect(@server.h).to.include('POST:/bazs')
expect(foo.id).to.not.be.null
expect(bar.id).to.not.be.null
expect(baz.id).to.not.be.null
expect(foo.bar).to.not.be.null
expect(foo.baz).to.not.be.null
expect(bar.foos.length).to.eq 1
expect(baz.foos.length).to.eq 1
describe 'deep embedded relationship with leaf referencing a model without an inverse', ->
lazy 'context', ->
`class Template extends Model {}`
Template.defineSchema
attributes:
subject: {type: 'string'}
`class Campaign extends Model {}`
Campaign.defineSchema
attributes:
name: {type: 'string'}
relationships:
campaignSteps: {kind: 'hasMany', type: 'campaign_step', embedded: 'always'}
`class CampaignStep extends Model {}`
CampaignStep.defineSchema
relationships:
campaign: {kind: 'belongsTo', type: 'campaign'}
campaignTemplates: {kind: 'hasMany', type: 'campaign_template', embedded: 'always'}
`class CampaignTemplate extends Model {}`
CampaignTemplate.defineSchema
relationships:
campaignStep: {kind: 'belongsTo', type: 'campaign_step'}
template: {kind: 'belongsTo', type: 'template'}
new Context
types:
template: Template
campaign: Campaign
campaign_template: CampaignTemplate
campaign_step: CampaignStep
it 'creates new embedded children with reference to new hasMany', ->
calls = 0
delaySequence = (fn) ->
delayAmount = calls * 100
calls++
delay delayAmount, fn
@server.r 'POST:/templates', (xhr) ->
data = JSON.parse(xhr.requestBody)
delaySequence =>
if data.template.client_id == template.clientId
{templates: {client_id: template.clientId, id: 2, subject: 'topological sort'}}
else
{templates: {client_id: template2.clientId, id: 5, subject: 'do you speak it?'}}
@server.r 'PUT:/campaigns/1', (xhr) ->
data = JSON.parse(xhr.requestBody)
expect(data.campaign.campaign_steps[0].campaign_templates[0].template).to.eq(2)
expect(data.campaign.campaign_steps[1].campaign_templates[0].template).to.eq(5)
delaySequence ->
return campaigns:
id: 1
client_id: campaign.clientId
campaign_steps: [
{
client_id: campaignStep.clientId
id: 3
campaign_templates: [
{id: 4, client_id: campaignTemplate.clientId, template: 2, campaign_step: 3}
]
},
{
client_id: campaignStep2.clientId
id: 6
campaign_templates: [
{id: 7, client_id: campaignTemplate2.clientId, template: 5, campaign_step: 6}
]
}
]
campaign = @session.merge @session.build('campaign', id: 1, campaignSteps:[])
childSession = @session.newSession()
campaign = childSession.add campaign
campaignStep = childSession.create('campaign_step', campaign: campaign)
campaignTemplate = childSession.create 'campaign_template'
campaignStep.campaignTemplates.pushObject(campaignTemplate)
template = childSession.create 'template'
template.subject = 'topological sort'
campaignTemplate.template = template
campaignStep2 = childSession.create('campaign_step', campaign: campaign)
campaignTemplate2 = childSession.create 'campaign_template'
campaignStep2.campaignTemplates.pushObject(campaignTemplate2)
template2 = childSession.create 'template'
template2.subject = 'do you speak it?'
campaignTemplate2.template = template2
childSession.flush().then =>
expect(template.id).to.eq("2")
expect(template.isNew).to.be.false
expect(template.subject).to.eq('topological sort')
expect(campaignTemplate.id).to.not.be.null
expect(campaignTemplate.template).to.eq(template)
expect(campaignTemplate.campaignStep).to.eq(campaignStep)
expect(template2.id).to.eq("5")
expect(template2.isNew).to.be.false
expect(template2.subject).to.eq('do you speak it?')
expect(campaignTemplate2.id).to.not.be.null
expect(campaignTemplate2.template).to.eq(template2)
expect(campaignTemplate2.campaignStep).to.eq(campaignStep2)
expect(@server.h).to.eql(['POST:/templates', 'POST:/templates', 'PUT:/campaigns/1'])
it 'save changes to parent when children not loaded in child session', ->
@server.r 'PUT:/campaigns/1', (xhr) ->
data = JSON.parse(xhr.requestBody)
campaign = @session.merge @session.build 'campaign',
name: 'old name'
id: 1
campaignSteps: []
step = @session.merge @session.build 'campaign_step',
id: 2
campaign: campaign
campaignTemplates: []
step2 = @session.merge @session.build 'campaign_step',
id: 4
campaign: campaign
campaignTemplates: []
@session.merge @session.build 'campaign_template',
id: 3
campaignStep: step
expect(campaign.campaignSteps[0]).to.eq(step)
childSession = @session.newSession()
campaign = childSession.add campaign
campaign.name = 'new name'
childSession.flush().then =>
expect(campaign.name).to.eq('new name')
expect(@server.h).to.eql(['PUT:/campaigns/1'])
describe 'belongsTo without inverse', ->
lazy 'context', ->
`class Contact extends Model {}`
Contact.defineSchema
attributes:
name: {type: 'string'}
relationships:
account: {kind: 'belongsTo', type: 'account'}
`class Account extends Model {}`
Account.defineSchema
attributes:
name: {type: 'string'}
new Context
types:
contact: Contact
account: Account
lazy 'session', ->
@context.newSession()
it 'creates hierarchy', ->
@server.r 'POST:/contacts', -> contact: {id: 1, client_id: contact.clientId, name: "test contact", account: 2}
@server.r 'POST:/accounts', -> account: {id: 2, client_id: contact.account.clientId, name: "test account"}
contact = @session.create 'contact', name: 'test contact'
contact.account = @session.create 'account', name: 'test account'
@session.flush().then =>
expect(@server.h).to.eql(['POST:/accounts', 'POST:/contacts'])
expect(contact.account.id).to.eq("2")
| 144565 | `import Model from 'coalesce/model/model'`
`import Context from 'coalesce/rest/context'`
`import {postWithComments, groupWithMembersWithUsers} from '../support/configs'`
`import {delay} from '../support/async'`
describe "rest acceptance scenarios", ->
lazy 'context', -> new Context
lazy 'session', -> @context.newSession()
describe "managing groups with embedded members", ->
lazy 'context', -> new Context(groupWithMembersWithUsers())
it 'creates new group and then deletes a member', ->
@server.r 'POST:/users', -> users: {client_id: user.clientId, id: 1, name: "<NAME>"}
@server.r 'POST:/groups', (xhr) ->
data = JSON.parse(xhr.requestBody)
expect(data.group.members[0].role).to.eq('chief')
return groups: {client_id: group.clientId, id: 2, name: "brogrammers", members: [{client_id: member.clientId, id: 3, role: "chief", group: 2, user: 1}], user: 1}
childSession = @session.newSession()
user = childSession.create 'user', name: '<NAME>'
group = null
member = null
childSession.flushIntoParent().then =>
expect(user.id).to.not.be.null
expect(@server.h).to.eql(['POST:/users'])
childSession = @session.newSession()
user = childSession.add(user)
group = childSession.create 'group', name: 'brogrammers', user: user
member = childSession.create 'member', role: 'chief', user: user, group: group
childSession.flushIntoParent().then =>
expect(@server.h).to.eql(['POST:/users', 'POST:/groups'])
expect(user.id).to.not.be.null
expect(group.id).to.not.be.null
expect(group.members.length).to.eq(1)
expect(user.groups.length).to.eq(1)
expect(user.members.length).to.eq(1)
expect(member.id).to.not.be.null
childSession = @session.newSession()
member = childSession.add(member)
user = childSession.add(user)
group = childSession.add(group)
childSession.deleteModel(member)
expect(user.members.length).to.eq(0)
expect(group.members.length).to.eq(0)
expect(user.groups.length).to.eq(1)
@server.r 'PUT:/groups/2', -> groups: {client_id: group.clientId, id: 2, name: "brogrammers", members: [], user: 1}
childSession.flushIntoParent().then =>
expect(member.isDeleted).to.be.true
expect(group.members.length).to.eq(0)
expect(user.members.length).to.eq(0)
expect(user.groups.length).to.eq(1)
expect(@server.h).to.eql(['POST:/users', 'POST:/groups', 'PUT:/groups/2'])
it "doesn't choke when loading a group without a members key", ->
@server.r 'GET:/groups', groups: [{client_id: null, id: "1", name: "brogrammers", user: "1"}]
@session.query("group").then (result) =>
expect(@server.h).to.eql(['GET:/groups'])
expect(result.length).to.eq(1)
expect(result[0].name).to.eq("brogrammers")
expect(result[0].groups).to.be.undefined
it 'adds a member to an existing group', ->
@server.r 'GET:/groups/1', -> groups: {id: 1, name: "employees", members: [{id: 2, name: "kinz", group: 1, user: 3}]}, users: {id: 3, name: "<NAME>tf", members: [2], groups: [1]}
@session.load("group", 1).then (group) =>
expect(@server.h).to.eql(['GET:/groups/1'])
childSession = @session.newSession()
childGroup = childSession.add(group)
existingMember = childGroup.members[0]
expect(existingMember.user).to.not.be.null
expect(existingMember.user.isDetached).to.be.false
member = childSession.create('member', {name: "<NAME>lie"})
childGroup.members.addObject(member)
expect(childGroup.members.length).to.eq(2)
expect(group.members.length).to.eq(1)
@server.r 'PUT:/groups/1', -> groups: {id: 1, name: "employees", members: [{id: 2, name: "<NAME>z", group: 1}, {id: 3, client_id: member.clientId, name: "<NAME>", group: 1}]}
promise = childSession.flushIntoParent().then =>
expect(childGroup.members.length).to.eq(2)
expect(group.members.length).to.eq(2)
expect(@server.h).to.eql(['GET:/groups/1', 'PUT:/groups/1'])
expect(group.members.length).to.eq(2)
promise
describe "managing comments", ->
lazy 'context', -> new Context(postWithComments())
lazy 'Post', -> @context.typeFor('post')
lazy 'Comment', -> @context.typeFor('comment')
it 'creates a new comment within a child session', ->
@server.r 'POST:/comments', -> comment: {client_id: comment.clientId, id: "3", message: "#2", post: "1"}
post = @session.merge @Post.create(id: "1", title: "brogrammer's guide to beer pong", comments: [])
@session.merge @Comment.create(id: "2", message: "yo", post: post)
childSession = @session.newSession()
childPost = childSession.add(post)
comment = childSession.create 'comment',
message: '#2',
post: childPost
expect(childPost.comments.length).to.eq(2)
promise = childSession.flushIntoParent().then =>
expect(childPost.comments.length).to.eq(2)
expect(post.comments.length).to.eq(2)
expect(childPost.comments.length).to.eq(2)
expect(post.comments.length).to.eq(2)
promise
describe "two levels of embedded", ->
lazy 'context', ->
`class User extends Model {}`
User.defineSchema
attributes:
name: {type: 'string'}
relationships:
profile: {kind: 'belongsTo', type: 'profile', embedded: 'always'}
`class Profile extends Model {}`
Profile.defineSchema
attributes:
bio: {type: 'string'}
relationships:
user: {kind: 'belongsTo', type: 'user'}
tags: {kind: 'hasMany', type: 'tag', embedded: 'always'}
`class Tag extends Model {}`
Tag.defineSchema
attributes:
name: {type: 'string'}
relationships:
profile: {kind: 'belongsTo', type: 'profile'}
new Context
types:
user: User
profile: Profile
tag: Tag
lazy 'User', -> @context.typeFor('user')
lazy 'Profile', -> @context.typeFor('profile')
lazy 'Tag', -> @context.typeFor('tag')
it 'deletes root', ->
@server.r 'DELETE:/users/1', {}
@User.create id: '1'
user = @session.merge @User.create
id: '1'
name: '<NAME>'
profile: @Profile.create
id: '2'
bio: 'asd'
tags: [@Tag.create(id: '3', name: 'java')]
@session.deleteModel(user)
@session.flush().then =>
expect(@server.h).to.eql(['DELETE:/users/1'])
expect(user.isDeleted).to.be.true
describe 'multiple belongsTo', ->
lazy 'context', ->
`class Foo extends Model {}`
Foo.defineSchema
typeKey: 'foo',
relationships:
bar: {kind: 'belongsTo', type: 'bar'}
baz: {kind: 'belongsTo', type: 'baz'}
`class Bar extends Model {}`
Bar.defineSchema
typeKey: 'bar'
relationships:
foos: {kind: 'hasMany', type: 'foo'}
`class Baz extends Model {}`
Baz.defineSchema
typeKey: 'baz'
relationships:
foos: {kind: 'hasMany', type: 'foo'}
new Context
types:
foo: Foo
bar: Bar
baz: Baz
it 'sets ids properly', ->
@server.r 'POST:/bars', -> bar: {client_id: bar.clientId, id: "1"}
@server.r 'POST:/bazs', -> baz: {client_id: baz.clientId, id: "1"}
@server.r 'POST:/foos', (xhr) ->
data = JSON.parse(xhr.requestBody)
expect(data.foo.bar).to.eq 1
expect(data.foo.baz).to.eq 1
foo: {client_id: foo.clientId, id: "1", bar: "1", baz: "1"}
childSession = @session.newSession()
foo = childSession.create 'foo'
bar = childSession.create 'bar'
baz = childSession.create 'baz'
foo.bar = bar
foo.baz = baz
childSession.flushIntoParent().then =>
expect(@server.h.length).to.eq(3)
expect(@server.h[@server.h.length-1]).to.eq('POST:/foos')
expect(@server.h).to.include('POST:/bars')
expect(@server.h).to.include('POST:/bazs')
expect(foo.id).to.not.be.null
expect(bar.id).to.not.be.null
expect(baz.id).to.not.be.null
expect(foo.bar).to.not.be.null
expect(foo.baz).to.not.be.null
expect(bar.foos.length).to.eq 1
expect(baz.foos.length).to.eq 1
describe 'deep embedded relationship with leaf referencing a model without an inverse', ->
lazy 'context', ->
`class Template extends Model {}`
Template.defineSchema
attributes:
subject: {type: 'string'}
`class Campaign extends Model {}`
Campaign.defineSchema
attributes:
name: {type: 'string'}
relationships:
campaignSteps: {kind: 'hasMany', type: 'campaign_step', embedded: 'always'}
`class CampaignStep extends Model {}`
CampaignStep.defineSchema
relationships:
campaign: {kind: 'belongsTo', type: 'campaign'}
campaignTemplates: {kind: 'hasMany', type: 'campaign_template', embedded: 'always'}
`class CampaignTemplate extends Model {}`
CampaignTemplate.defineSchema
relationships:
campaignStep: {kind: 'belongsTo', type: 'campaign_step'}
template: {kind: 'belongsTo', type: 'template'}
new Context
types:
template: Template
campaign: Campaign
campaign_template: CampaignTemplate
campaign_step: CampaignStep
it 'creates new embedded children with reference to new hasMany', ->
calls = 0
delaySequence = (fn) ->
delayAmount = calls * 100
calls++
delay delayAmount, fn
@server.r 'POST:/templates', (xhr) ->
data = JSON.parse(xhr.requestBody)
delaySequence =>
if data.template.client_id == template.clientId
{templates: {client_id: template.clientId, id: 2, subject: 'topological sort'}}
else
{templates: {client_id: template2.clientId, id: 5, subject: 'do you speak it?'}}
@server.r 'PUT:/campaigns/1', (xhr) ->
data = JSON.parse(xhr.requestBody)
expect(data.campaign.campaign_steps[0].campaign_templates[0].template).to.eq(2)
expect(data.campaign.campaign_steps[1].campaign_templates[0].template).to.eq(5)
delaySequence ->
return campaigns:
id: 1
client_id: campaign.clientId
campaign_steps: [
{
client_id: campaignStep.clientId
id: 3
campaign_templates: [
{id: 4, client_id: campaignTemplate.clientId, template: 2, campaign_step: 3}
]
},
{
client_id: campaignStep2.clientId
id: 6
campaign_templates: [
{id: 7, client_id: campaignTemplate2.clientId, template: 5, campaign_step: 6}
]
}
]
campaign = @session.merge @session.build('campaign', id: 1, campaignSteps:[])
childSession = @session.newSession()
campaign = childSession.add campaign
campaignStep = childSession.create('campaign_step', campaign: campaign)
campaignTemplate = childSession.create 'campaign_template'
campaignStep.campaignTemplates.pushObject(campaignTemplate)
template = childSession.create 'template'
template.subject = 'topological sort'
campaignTemplate.template = template
campaignStep2 = childSession.create('campaign_step', campaign: campaign)
campaignTemplate2 = childSession.create 'campaign_template'
campaignStep2.campaignTemplates.pushObject(campaignTemplate2)
template2 = childSession.create 'template'
template2.subject = 'do you speak it?'
campaignTemplate2.template = template2
childSession.flush().then =>
expect(template.id).to.eq("2")
expect(template.isNew).to.be.false
expect(template.subject).to.eq('topological sort')
expect(campaignTemplate.id).to.not.be.null
expect(campaignTemplate.template).to.eq(template)
expect(campaignTemplate.campaignStep).to.eq(campaignStep)
expect(template2.id).to.eq("5")
expect(template2.isNew).to.be.false
expect(template2.subject).to.eq('do you speak it?')
expect(campaignTemplate2.id).to.not.be.null
expect(campaignTemplate2.template).to.eq(template2)
expect(campaignTemplate2.campaignStep).to.eq(campaignStep2)
expect(@server.h).to.eql(['POST:/templates', 'POST:/templates', 'PUT:/campaigns/1'])
it 'save changes to parent when children not loaded in child session', ->
@server.r 'PUT:/campaigns/1', (xhr) ->
data = JSON.parse(xhr.requestBody)
campaign = @session.merge @session.build 'campaign',
name: '<NAME>'
id: 1
campaignSteps: []
step = @session.merge @session.build 'campaign_step',
id: 2
campaign: campaign
campaignTemplates: []
step2 = @session.merge @session.build 'campaign_step',
id: 4
campaign: campaign
campaignTemplates: []
@session.merge @session.build 'campaign_template',
id: 3
campaignStep: step
expect(campaign.campaignSteps[0]).to.eq(step)
childSession = @session.newSession()
campaign = childSession.add campaign
campaign.name = 'new name'
childSession.flush().then =>
expect(campaign.name).to.eq('new name')
expect(@server.h).to.eql(['PUT:/campaigns/1'])
describe 'belongsTo without inverse', ->
lazy 'context', ->
`class Contact extends Model {}`
Contact.defineSchema
attributes:
name: {type: 'string'}
relationships:
account: {kind: 'belongsTo', type: 'account'}
`class Account extends Model {}`
Account.defineSchema
attributes:
name: {type: 'string'}
new Context
types:
contact: Contact
account: Account
lazy 'session', ->
@context.newSession()
it 'creates hierarchy', ->
@server.r 'POST:/contacts', -> contact: {id: 1, client_id: contact.clientId, name: "<NAME> contact", account: 2}
@server.r 'POST:/accounts', -> account: {id: 2, client_id: contact.account.clientId, name: "<NAME> account"}
contact = @session.create 'contact', name: '<NAME>'
contact.account = @session.create 'account', name: '<NAME> account'
@session.flush().then =>
expect(@server.h).to.eql(['POST:/accounts', 'POST:/contacts'])
expect(contact.account.id).to.eq("2")
| true | `import Model from 'coalesce/model/model'`
`import Context from 'coalesce/rest/context'`
`import {postWithComments, groupWithMembersWithUsers} from '../support/configs'`
`import {delay} from '../support/async'`
describe "rest acceptance scenarios", ->
lazy 'context', -> new Context
lazy 'session', -> @context.newSession()
describe "managing groups with embedded members", ->
lazy 'context', -> new Context(groupWithMembersWithUsers())
it 'creates new group and then deletes a member', ->
@server.r 'POST:/users', -> users: {client_id: user.clientId, id: 1, name: "PI:NAME:<NAME>END_PI"}
@server.r 'POST:/groups', (xhr) ->
data = JSON.parse(xhr.requestBody)
expect(data.group.members[0].role).to.eq('chief')
return groups: {client_id: group.clientId, id: 2, name: "brogrammers", members: [{client_id: member.clientId, id: 3, role: "chief", group: 2, user: 1}], user: 1}
childSession = @session.newSession()
user = childSession.create 'user', name: 'PI:NAME:<NAME>END_PI'
group = null
member = null
childSession.flushIntoParent().then =>
expect(user.id).to.not.be.null
expect(@server.h).to.eql(['POST:/users'])
childSession = @session.newSession()
user = childSession.add(user)
group = childSession.create 'group', name: 'brogrammers', user: user
member = childSession.create 'member', role: 'chief', user: user, group: group
childSession.flushIntoParent().then =>
expect(@server.h).to.eql(['POST:/users', 'POST:/groups'])
expect(user.id).to.not.be.null
expect(group.id).to.not.be.null
expect(group.members.length).to.eq(1)
expect(user.groups.length).to.eq(1)
expect(user.members.length).to.eq(1)
expect(member.id).to.not.be.null
childSession = @session.newSession()
member = childSession.add(member)
user = childSession.add(user)
group = childSession.add(group)
childSession.deleteModel(member)
expect(user.members.length).to.eq(0)
expect(group.members.length).to.eq(0)
expect(user.groups.length).to.eq(1)
@server.r 'PUT:/groups/2', -> groups: {client_id: group.clientId, id: 2, name: "brogrammers", members: [], user: 1}
childSession.flushIntoParent().then =>
expect(member.isDeleted).to.be.true
expect(group.members.length).to.eq(0)
expect(user.members.length).to.eq(0)
expect(user.groups.length).to.eq(1)
expect(@server.h).to.eql(['POST:/users', 'POST:/groups', 'PUT:/groups/2'])
it "doesn't choke when loading a group without a members key", ->
@server.r 'GET:/groups', groups: [{client_id: null, id: "1", name: "brogrammers", user: "1"}]
@session.query("group").then (result) =>
expect(@server.h).to.eql(['GET:/groups'])
expect(result.length).to.eq(1)
expect(result[0].name).to.eq("brogrammers")
expect(result[0].groups).to.be.undefined
it 'adds a member to an existing group', ->
@server.r 'GET:/groups/1', -> groups: {id: 1, name: "employees", members: [{id: 2, name: "kinz", group: 1, user: 3}]}, users: {id: 3, name: "PI:NAME:<NAME>END_PItf", members: [2], groups: [1]}
@session.load("group", 1).then (group) =>
expect(@server.h).to.eql(['GET:/groups/1'])
childSession = @session.newSession()
childGroup = childSession.add(group)
existingMember = childGroup.members[0]
expect(existingMember.user).to.not.be.null
expect(existingMember.user.isDetached).to.be.false
member = childSession.create('member', {name: "PI:NAME:<NAME>END_PIlie"})
childGroup.members.addObject(member)
expect(childGroup.members.length).to.eq(2)
expect(group.members.length).to.eq(1)
@server.r 'PUT:/groups/1', -> groups: {id: 1, name: "employees", members: [{id: 2, name: "PI:NAME:<NAME>END_PIz", group: 1}, {id: 3, client_id: member.clientId, name: "PI:NAME:<NAME>END_PI", group: 1}]}
promise = childSession.flushIntoParent().then =>
expect(childGroup.members.length).to.eq(2)
expect(group.members.length).to.eq(2)
expect(@server.h).to.eql(['GET:/groups/1', 'PUT:/groups/1'])
expect(group.members.length).to.eq(2)
promise
describe "managing comments", ->
lazy 'context', -> new Context(postWithComments())
lazy 'Post', -> @context.typeFor('post')
lazy 'Comment', -> @context.typeFor('comment')
it 'creates a new comment within a child session', ->
@server.r 'POST:/comments', -> comment: {client_id: comment.clientId, id: "3", message: "#2", post: "1"}
post = @session.merge @Post.create(id: "1", title: "brogrammer's guide to beer pong", comments: [])
@session.merge @Comment.create(id: "2", message: "yo", post: post)
childSession = @session.newSession()
childPost = childSession.add(post)
comment = childSession.create 'comment',
message: '#2',
post: childPost
expect(childPost.comments.length).to.eq(2)
promise = childSession.flushIntoParent().then =>
expect(childPost.comments.length).to.eq(2)
expect(post.comments.length).to.eq(2)
expect(childPost.comments.length).to.eq(2)
expect(post.comments.length).to.eq(2)
promise
describe "two levels of embedded", ->
lazy 'context', ->
`class User extends Model {}`
User.defineSchema
attributes:
name: {type: 'string'}
relationships:
profile: {kind: 'belongsTo', type: 'profile', embedded: 'always'}
`class Profile extends Model {}`
Profile.defineSchema
attributes:
bio: {type: 'string'}
relationships:
user: {kind: 'belongsTo', type: 'user'}
tags: {kind: 'hasMany', type: 'tag', embedded: 'always'}
`class Tag extends Model {}`
Tag.defineSchema
attributes:
name: {type: 'string'}
relationships:
profile: {kind: 'belongsTo', type: 'profile'}
new Context
types:
user: User
profile: Profile
tag: Tag
lazy 'User', -> @context.typeFor('user')
lazy 'Profile', -> @context.typeFor('profile')
lazy 'Tag', -> @context.typeFor('tag')
it 'deletes root', ->
@server.r 'DELETE:/users/1', {}
@User.create id: '1'
user = @session.merge @User.create
id: '1'
name: 'PI:NAME:<NAME>END_PI'
profile: @Profile.create
id: '2'
bio: 'asd'
tags: [@Tag.create(id: '3', name: 'java')]
@session.deleteModel(user)
@session.flush().then =>
expect(@server.h).to.eql(['DELETE:/users/1'])
expect(user.isDeleted).to.be.true
describe 'multiple belongsTo', ->
lazy 'context', ->
`class Foo extends Model {}`
Foo.defineSchema
typeKey: 'foo',
relationships:
bar: {kind: 'belongsTo', type: 'bar'}
baz: {kind: 'belongsTo', type: 'baz'}
`class Bar extends Model {}`
Bar.defineSchema
typeKey: 'bar'
relationships:
foos: {kind: 'hasMany', type: 'foo'}
`class Baz extends Model {}`
Baz.defineSchema
typeKey: 'baz'
relationships:
foos: {kind: 'hasMany', type: 'foo'}
new Context
types:
foo: Foo
bar: Bar
baz: Baz
it 'sets ids properly', ->
@server.r 'POST:/bars', -> bar: {client_id: bar.clientId, id: "1"}
@server.r 'POST:/bazs', -> baz: {client_id: baz.clientId, id: "1"}
@server.r 'POST:/foos', (xhr) ->
data = JSON.parse(xhr.requestBody)
expect(data.foo.bar).to.eq 1
expect(data.foo.baz).to.eq 1
foo: {client_id: foo.clientId, id: "1", bar: "1", baz: "1"}
childSession = @session.newSession()
foo = childSession.create 'foo'
bar = childSession.create 'bar'
baz = childSession.create 'baz'
foo.bar = bar
foo.baz = baz
childSession.flushIntoParent().then =>
expect(@server.h.length).to.eq(3)
expect(@server.h[@server.h.length-1]).to.eq('POST:/foos')
expect(@server.h).to.include('POST:/bars')
expect(@server.h).to.include('POST:/bazs')
expect(foo.id).to.not.be.null
expect(bar.id).to.not.be.null
expect(baz.id).to.not.be.null
expect(foo.bar).to.not.be.null
expect(foo.baz).to.not.be.null
expect(bar.foos.length).to.eq 1
expect(baz.foos.length).to.eq 1
describe 'deep embedded relationship with leaf referencing a model without an inverse', ->
lazy 'context', ->
`class Template extends Model {}`
Template.defineSchema
attributes:
subject: {type: 'string'}
`class Campaign extends Model {}`
Campaign.defineSchema
attributes:
name: {type: 'string'}
relationships:
campaignSteps: {kind: 'hasMany', type: 'campaign_step', embedded: 'always'}
`class CampaignStep extends Model {}`
CampaignStep.defineSchema
relationships:
campaign: {kind: 'belongsTo', type: 'campaign'}
campaignTemplates: {kind: 'hasMany', type: 'campaign_template', embedded: 'always'}
`class CampaignTemplate extends Model {}`
CampaignTemplate.defineSchema
relationships:
campaignStep: {kind: 'belongsTo', type: 'campaign_step'}
template: {kind: 'belongsTo', type: 'template'}
new Context
types:
template: Template
campaign: Campaign
campaign_template: CampaignTemplate
campaign_step: CampaignStep
it 'creates new embedded children with reference to new hasMany', ->
calls = 0
delaySequence = (fn) ->
delayAmount = calls * 100
calls++
delay delayAmount, fn
@server.r 'POST:/templates', (xhr) ->
data = JSON.parse(xhr.requestBody)
delaySequence =>
if data.template.client_id == template.clientId
{templates: {client_id: template.clientId, id: 2, subject: 'topological sort'}}
else
{templates: {client_id: template2.clientId, id: 5, subject: 'do you speak it?'}}
@server.r 'PUT:/campaigns/1', (xhr) ->
data = JSON.parse(xhr.requestBody)
expect(data.campaign.campaign_steps[0].campaign_templates[0].template).to.eq(2)
expect(data.campaign.campaign_steps[1].campaign_templates[0].template).to.eq(5)
delaySequence ->
return campaigns:
id: 1
client_id: campaign.clientId
campaign_steps: [
{
client_id: campaignStep.clientId
id: 3
campaign_templates: [
{id: 4, client_id: campaignTemplate.clientId, template: 2, campaign_step: 3}
]
},
{
client_id: campaignStep2.clientId
id: 6
campaign_templates: [
{id: 7, client_id: campaignTemplate2.clientId, template: 5, campaign_step: 6}
]
}
]
campaign = @session.merge @session.build('campaign', id: 1, campaignSteps:[])
childSession = @session.newSession()
campaign = childSession.add campaign
campaignStep = childSession.create('campaign_step', campaign: campaign)
campaignTemplate = childSession.create 'campaign_template'
campaignStep.campaignTemplates.pushObject(campaignTemplate)
template = childSession.create 'template'
template.subject = 'topological sort'
campaignTemplate.template = template
campaignStep2 = childSession.create('campaign_step', campaign: campaign)
campaignTemplate2 = childSession.create 'campaign_template'
campaignStep2.campaignTemplates.pushObject(campaignTemplate2)
template2 = childSession.create 'template'
template2.subject = 'do you speak it?'
campaignTemplate2.template = template2
childSession.flush().then =>
expect(template.id).to.eq("2")
expect(template.isNew).to.be.false
expect(template.subject).to.eq('topological sort')
expect(campaignTemplate.id).to.not.be.null
expect(campaignTemplate.template).to.eq(template)
expect(campaignTemplate.campaignStep).to.eq(campaignStep)
expect(template2.id).to.eq("5")
expect(template2.isNew).to.be.false
expect(template2.subject).to.eq('do you speak it?')
expect(campaignTemplate2.id).to.not.be.null
expect(campaignTemplate2.template).to.eq(template2)
expect(campaignTemplate2.campaignStep).to.eq(campaignStep2)
expect(@server.h).to.eql(['POST:/templates', 'POST:/templates', 'PUT:/campaigns/1'])
it 'save changes to parent when children not loaded in child session', ->
@server.r 'PUT:/campaigns/1', (xhr) ->
data = JSON.parse(xhr.requestBody)
campaign = @session.merge @session.build 'campaign',
name: 'PI:NAME:<NAME>END_PI'
id: 1
campaignSteps: []
step = @session.merge @session.build 'campaign_step',
id: 2
campaign: campaign
campaignTemplates: []
step2 = @session.merge @session.build 'campaign_step',
id: 4
campaign: campaign
campaignTemplates: []
@session.merge @session.build 'campaign_template',
id: 3
campaignStep: step
expect(campaign.campaignSteps[0]).to.eq(step)
childSession = @session.newSession()
campaign = childSession.add campaign
campaign.name = 'new name'
childSession.flush().then =>
expect(campaign.name).to.eq('new name')
expect(@server.h).to.eql(['PUT:/campaigns/1'])
describe 'belongsTo without inverse', ->
lazy 'context', ->
`class Contact extends Model {}`
Contact.defineSchema
attributes:
name: {type: 'string'}
relationships:
account: {kind: 'belongsTo', type: 'account'}
`class Account extends Model {}`
Account.defineSchema
attributes:
name: {type: 'string'}
new Context
types:
contact: Contact
account: Account
lazy 'session', ->
@context.newSession()
it 'creates hierarchy', ->
@server.r 'POST:/contacts', -> contact: {id: 1, client_id: contact.clientId, name: "PI:NAME:<NAME>END_PI contact", account: 2}
@server.r 'POST:/accounts', -> account: {id: 2, client_id: contact.account.clientId, name: "PI:NAME:<NAME>END_PI account"}
contact = @session.create 'contact', name: 'PI:NAME:<NAME>END_PI'
contact.account = @session.create 'account', name: 'PI:NAME:<NAME>END_PI account'
@session.flush().then =>
expect(@server.h).to.eql(['POST:/accounts', 'POST:/contacts'])
expect(contact.account.id).to.eq("2")
|
[
{
"context": "###\n * bag\n * getbag.io\n *\n * Copyright (c) 2015 Ryan Gaus\n * Licensed under the MIT license.\n###\nuuid = req",
"end": 58,
"score": 0.9998376369476318,
"start": 49,
"tag": "NAME",
"value": "Ryan Gaus"
}
] | src/controllers/bag_controller.coffee | 1egoman/bag-node | 0 | ###
* bag
* getbag.io
*
* Copyright (c) 2015 Ryan Gaus
* Licensed under the MIT license.
###
uuid = require "uuid"
Bag = require "../models/bag_model"
# get a bag of all lists
# GET /bag
exports.index = (req, res) ->
Bag.findOne user: req.user._id, (err, data) ->
if err
res.send
status: "bag.error.bag.index"
error: err
else if not data
res.send
status: "bag.error.bag.index"
data: null
else
res.send
status: "bag.success.bag.index"
data: data
exports.new = (req, res) -> res.send "Not supported."
# create a new bag
exports.create = (req, res) -> res.send "Not supported."
# get a bag with the specified id
# GET /bag/:bag
exports.show = (req, res) ->
res.send "Not supported."
# Bag.findOne
# user: req.user._id,
# req.params.bag
# , (err, data) ->
# if err
# res.send
# status: "bag.error.bag.show"
# error: err
# else
# res.send
# status: "bag.success.bag.show"
# data: data
exports.edit = (req, res) -> res.send "Not supported."
# update a bag
# PUT /bag/:bag
exports.update = (req, res) ->
Bag.findOne _id: req.params.bag or req?.body?._id, (err, data) ->
if err or not data
res.send
status: "bag.error.bag.update"
error: err
else
data[k] = v for k, v of req.body?.bag
# make sure custom prices have only been used if we can.
for i in data?.contents or []
i.stores.custom = {} if i.store is "custom" and req.user.plan isnt 2
i.store = "nope" if i.store is "custom" and req.user.plan isnt 2
data.save (err) ->
if err
res.send
status: "bag.error.bag.update"
data: err
all: req.body?.bag
else
# Bag.find {}, (err, all) ->
res.send
status: "bag.success.bag.update"
data: data
# all: all
# update a store within a bag
# given req.body.user, req.body.item, and req.body.store
exports.update_store = (req, res) ->
Bag.findOne user: req.user._id or req.body.user, (err, data) ->
if err
res.send
status: "bag.error.bag.update"
error: err
else if data and req.body.item and req.body.store
# for each matching item (recipe's don't have stores), update the
# store to the specified one
contents = data.contents.filter (i) ->
i._id is req.body.item
.forEach (i) ->
i.store = req.body.store
data.save (err) ->
if err
res.send
status: "bag.error.bag.update.store"
data: err
else
res.send
status: "bag.success.bag.update.store"
data: data
else
res.send
status: "bag.error.bag.index"
data: null
# delete a bag
# DELETE /bag/:bag
exports.destroy = (req, res) -> res.send "Not supported."
| 103564 | ###
* bag
* getbag.io
*
* Copyright (c) 2015 <NAME>
* Licensed under the MIT license.
###
uuid = require "uuid"
Bag = require "../models/bag_model"
# get a bag of all lists
# GET /bag
exports.index = (req, res) ->
Bag.findOne user: req.user._id, (err, data) ->
if err
res.send
status: "bag.error.bag.index"
error: err
else if not data
res.send
status: "bag.error.bag.index"
data: null
else
res.send
status: "bag.success.bag.index"
data: data
exports.new = (req, res) -> res.send "Not supported."
# create a new bag
exports.create = (req, res) -> res.send "Not supported."
# get a bag with the specified id
# GET /bag/:bag
exports.show = (req, res) ->
res.send "Not supported."
# Bag.findOne
# user: req.user._id,
# req.params.bag
# , (err, data) ->
# if err
# res.send
# status: "bag.error.bag.show"
# error: err
# else
# res.send
# status: "bag.success.bag.show"
# data: data
exports.edit = (req, res) -> res.send "Not supported."
# update a bag
# PUT /bag/:bag
exports.update = (req, res) ->
Bag.findOne _id: req.params.bag or req?.body?._id, (err, data) ->
if err or not data
res.send
status: "bag.error.bag.update"
error: err
else
data[k] = v for k, v of req.body?.bag
# make sure custom prices have only been used if we can.
for i in data?.contents or []
i.stores.custom = {} if i.store is "custom" and req.user.plan isnt 2
i.store = "nope" if i.store is "custom" and req.user.plan isnt 2
data.save (err) ->
if err
res.send
status: "bag.error.bag.update"
data: err
all: req.body?.bag
else
# Bag.find {}, (err, all) ->
res.send
status: "bag.success.bag.update"
data: data
# all: all
# update a store within a bag
# given req.body.user, req.body.item, and req.body.store
exports.update_store = (req, res) ->
Bag.findOne user: req.user._id or req.body.user, (err, data) ->
if err
res.send
status: "bag.error.bag.update"
error: err
else if data and req.body.item and req.body.store
# for each matching item (recipe's don't have stores), update the
# store to the specified one
contents = data.contents.filter (i) ->
i._id is req.body.item
.forEach (i) ->
i.store = req.body.store
data.save (err) ->
if err
res.send
status: "bag.error.bag.update.store"
data: err
else
res.send
status: "bag.success.bag.update.store"
data: data
else
res.send
status: "bag.error.bag.index"
data: null
# delete a bag
# DELETE /bag/:bag
exports.destroy = (req, res) -> res.send "Not supported."
| true | ###
* bag
* getbag.io
*
* Copyright (c) 2015 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
uuid = require "uuid"
Bag = require "../models/bag_model"
# get a bag of all lists
# GET /bag
exports.index = (req, res) ->
Bag.findOne user: req.user._id, (err, data) ->
if err
res.send
status: "bag.error.bag.index"
error: err
else if not data
res.send
status: "bag.error.bag.index"
data: null
else
res.send
status: "bag.success.bag.index"
data: data
exports.new = (req, res) -> res.send "Not supported."
# create a new bag
exports.create = (req, res) -> res.send "Not supported."
# get a bag with the specified id
# GET /bag/:bag
exports.show = (req, res) ->
res.send "Not supported."
# Bag.findOne
# user: req.user._id,
# req.params.bag
# , (err, data) ->
# if err
# res.send
# status: "bag.error.bag.show"
# error: err
# else
# res.send
# status: "bag.success.bag.show"
# data: data
exports.edit = (req, res) -> res.send "Not supported."
# update a bag
# PUT /bag/:bag
exports.update = (req, res) ->
Bag.findOne _id: req.params.bag or req?.body?._id, (err, data) ->
if err or not data
res.send
status: "bag.error.bag.update"
error: err
else
data[k] = v for k, v of req.body?.bag
# make sure custom prices have only been used if we can.
for i in data?.contents or []
i.stores.custom = {} if i.store is "custom" and req.user.plan isnt 2
i.store = "nope" if i.store is "custom" and req.user.plan isnt 2
data.save (err) ->
if err
res.send
status: "bag.error.bag.update"
data: err
all: req.body?.bag
else
# Bag.find {}, (err, all) ->
res.send
status: "bag.success.bag.update"
data: data
# all: all
# update a store within a bag
# given req.body.user, req.body.item, and req.body.store
exports.update_store = (req, res) ->
Bag.findOne user: req.user._id or req.body.user, (err, data) ->
if err
res.send
status: "bag.error.bag.update"
error: err
else if data and req.body.item and req.body.store
# for each matching item (recipe's don't have stores), update the
# store to the specified one
contents = data.contents.filter (i) ->
i._id is req.body.item
.forEach (i) ->
i.store = req.body.store
data.save (err) ->
if err
res.send
status: "bag.error.bag.update.store"
data: err
else
res.send
status: "bag.success.bag.update.store"
data: data
else
res.send
status: "bag.error.bag.index"
data: null
# delete a bag
# DELETE /bag/:bag
exports.destroy = (req, res) -> res.send "Not supported."
|
[
{
"context": " проставим имя пользователя\n\tusername = $.cookie('username')\t\n\t$('#username').html username\n\n\n# Установление",
"end": 902,
"score": 0.9087540507316589,
"start": 894,
"tag": "USERNAME",
"value": "username"
},
{
"context": " JSON.stringify\n\t\t\tfilename: filename\n\t\t\tusername: username\n\t\t$.post(\"share\",data,serverShareSuccess,'json')\n",
"end": 3216,
"score": 0.9986640214920044,
"start": 3208,
"tag": "USERNAME",
"value": "username"
},
{
"context": "tStatus is on\n\t\tdata = JSON.stringify\n\t\t\tusername:username\n\t\t\tsideaid:sidea.id\n\t\tcometClient.publish cometFo",
"end": 5188,
"score": 0.999069094657898,
"start": 5180,
"tag": "USERNAME",
"value": "username"
},
{
"context": " Сам клиент\n\ncometStart =->\n\tusername = $.cookie('username')\t\n\t$('#username').html username\n\treturn # Пока н",
"end": 5654,
"score": 0.9643362760543823,
"start": 5646,
"tag": "USERNAME",
"value": "username"
},
{
"context": "tStatus is on\n\t\tdata = JSON.stringify\n\t\t\tusername:username\n\t\t\tsideaid:sidea.id\n\t\tcometClient.publish focusCh",
"end": 6703,
"score": 0.999520480632782,
"start": 6695,
"tag": "USERNAME",
"value": "username"
},
{
"context": "->\n\t$.get(\"\",successGetAll,\"json\")\n\n\n\n\nmy.user = \"dpetrov@gmail.com\"\nalien.lock = {}\nmy.lock = {}\ndirty = []\nlastsync",
"end": 8475,
"score": 0.9999000430107117,
"start": 8458,
"tag": "EMAIL",
"value": "dpetrov@gmail.com"
}
] | server.coffee | agershun/minday | 0 | ##################################
# Minday 0.009 Lykia
# server.coffee
# Реализация кооперативной работы
#################################
username = ""
filename = "minday.mdy"
cometStatus = off
# Устанавливаем меню
setMenuServer =->
$(".server_changeuser").click serverChangeUser
$(".server_open").click serverOpen
$(".server_refresh").click serverRefresh
$(".server_save").click serverSave
$(".server_saveas").click serverSaveAs
$(".server_share").click serverShare
$(".server_subscribe").click serverSubscribe
$(".server_unsubscribe").click serverUnsubscribe
# $("#server_getall").click getAll
# $("#server_postall").click postAll
# $("#server_checkdirty").click checkDirty
# $("#server_getdirty").click getDirty
# $("#server_postdirty").click postDirty
# $("#server_cometpublish").click cometAllPublish
cometStart =->
# Заодно проставим имя пользователя
username = $.cookie('username')
$('#username').html username
# Установление пользователя
serverChangeUser = ->
username = prompt "Введите имя пользователя",username
$.cookie 'username',username
$('#username').html username
#############################
# Открытие файла из сервера
#############################
serverOpen = ->
$.get('dir',serverOpenSuccess,'json')
serverOpenSuccess = (data) ->
s = "<p><b>Открыть файл</b></p>"
s += "<p>Выберите файл на сервере для работы:</p>"
for fi in data
s+="<div>"
s+="<a id='"+fi+"' class='open_file' href='#'>"
s+=fi
s+="</a>"
s+="</div>"
$("#dialog_open").html s
$(".open_file").click clickServerOpenFile
clickServerOpenFile = (eo) ->
$("#dialog_open").html ""
filename = eo.srcElement.id
serverRefresh()
serverRefresh = () ->
$.get("open="+filename,serverOpenFileSuccess,"json")
serverOpenFileSuccess = (data) ->
deleteIdea()
b = data # JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[-b.sideaid].upperFrame().fhtml()
alert "Загружен файл с сервера"
#############################
# Тихая загрузка файла
#############################
serverLoad = (fname) ->
$.get("open="+fname,serverLoadFileSuccess,"json")
serverLoadFileSuccess = (data) ->
b = data # JSON.parse data
updateModel()
selectModel(b.filename)
deleteIdea()
initIdea(b.length)
for io in b.idea
cloneIdea(io)
updateModel(b.filename)
selectModel()
# idea[-b.sideaid].upperFrame().fhtml()
# alert "Загружен файл с сервера"
#############################
# Сохранение файла на сервер
#############################
serverSaveAs = ->
filename = prompt "Введите имя файла для сохранения", "minday.mdy"
serverSave()
serverSave = ->
data = JSON.stringify
filename: filename
length:idea.length
idea:idea
sideaid:sidea.id
$.post("save="+filename,data,serverSaveSuccess,"json")
serverSaveSuccess = ->
alert "Файл передан"
#############################
# Открыть файл для редактирования другими пользователями
#############################
channel = ""
cometClient = null
cometAllChannel = null
cometDirtyChannel = null
cometFocusChannel = null
cometStatus = off
shareStatus = off
serverShare =->
if cometStatus is off
cometClient = new Faye.Client('http://localhost:8000/faye')
data = JSON.stringify
filename: filename
username: username
$.post("share",data,serverShareSuccess,'json')
serverShareSuccess =->
shareStatus = on
shareChannelName = filename+"-"+username
alert "Файл "+filename+" доступен другим пользователям на канале "+filename+"-"+username
serverSubscribe = ->
$.get('sharedir',serverShareDirSuccess,'json')
serverShareDirSuccess = (data) ->
s = "<p><b>Поключиться к редактированию</b></p>"
s += "<p>Выберите файл на сервере для работы:</p>"
for fi in data
s+="<div>"
s+="<a id='"+fi.filename+"-"+fi.username+"' class='open_file' href='#'>"
s+=fi.filename+"-"+fi.username
s+="</a>"
s+="</div>"
$("#dialog_open").html s
$(".open_file").click clickServerSubscribe
clickServerSubscribe = (eo) ->
$("#dialog_open").html ""
channelName = eo.srcElement.id
if cometStatus is off
cometClient = new Faye.Client('http://localhost:8000/faye')
channel = cometClient.subscribe channelName,channelArrive
serverRefresh()
channelArrive = (data) ->
alert "changes come"
serverUnsubscribe = ->
channel.cancel()
cometStatus = off
# channel = filename
# comerStatus = on
# cometClient = new Faye.Client('http://localhost:8000/faye')
# cometAllChannel = cometClient.subscribe "/all",cometAllArrive
# cometFocusChannel = cometClient.subscribe "/focus/"+channel,cometFocusArrive
# cometDirtyChannel = cometClient.subscribe "/dirty/"+channel,cometDirtyArrive
#############################
# Канал фокуса
#############################
cursor = {}
cometFocusArrive = (data) ->
b = JSON.parse data
if b.username isnt username
if cursor[b.username]?.sideaid?
cursor[b.username].oldid = cursor[b.username].sideaid
else
cursor[b.username] = {}
cursor[b.user].sideaid = b.sideaid # Сохраняем текущую позицию фокуса
setFocus cursor[b.username]
setFocus = (f) ->
if f?.oldid?
$("#txt"+f.oldid).removeClass 'cursor'
if f?.sideaid?
$("#txt"+f.sideaid).addClass 'cursor'
cometFocusPublish = ->
if cometStatus is on
data = JSON.stringify
username:username
sideaid:sidea.id
cometClient.publish cometFocusChannel,data
###
# Процедуры для работы с Faye
comet = {}
allChannel = "/all" # Полное обновление
dirtyChannel = "/dirty" # Частичное обновление
focusChannel = "/focus" # Передача курсора
lockChannel = "/lock" # Канал блокировки
problemChannel = "/problem" # Канал для проблем и оповещений
chatChannel = "/chat" # Канал для чата
cometClient = null # Сам клиент
cometStart =->
username = $.cookie('username')
$('#username').html username
return # Пока ничего не делаем
cometClient = new Faye.Client('http://localhost:8000/faye');
cometClient.subscribe allChannel,cometAllArrive
cometClient.subscribe dirtyChannel,cometDirtyArrive
cometClient.subscribe focusChannel,cometFocusArrive
cometStatus = on
cometFinish =->
cometClient = new Faye.Client('http://localhost:8000/faye');
cometClient.subscribe allChannel,cometAllArrive
cometClient.subscribe dirtyChannel,cometDirtyArrive
cometClient.subscribe focusChannel,cometFocusArrive
cometStatus = off
cometFocusArrive = (data) ->
b = JSON.parse data
if cursor[b.username]?.sideaid?
cursor[b.username].oldid = cursor[b.username].sideaid
else
cursor[b.username] = {}
cursor[b.user].sideaid = b.sideaid # Сохраняем текущую позицию фокуса
setFocus cursor[b.username]
setFocus = (f) ->
if f?.oldid?
$("#txt"+f.oldid).removeClass 'cursor'
if f?.sideaid?
$("#txt"+f.sideaid).addClass 'cursor'
cometFocusPublish = ->
if cometStatus is on
data = JSON.stringify
username:username
sideaid:sidea.id
cometClient.publish focusChannel,data
cometAllArrive = (data) ->
deleteIdea()
b = JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[-b.fideaid].fhtml(idea[-b.sideaid])
cometAllPublish = ->
data = JSON.stringify
length:idea.length
idea:idea
sideaid:sidea.id
fideaid:fidea.id
cometClient.publish dirtyChannel,data
cometDirtyArrive = (data) ->
# deleteIdea()
b = JSON.parse data
# initIdea(b.length)
for io in b.idea
cloneIdea(io)
# idea[-b.fideaid].fhtml(idea[-b.sideaid])
# Публиковать грязные данные
cometDirtyPublish = ->
data = JSON.stringify
length:idea.length
idea:idea
sideaid:sidea.id
fideaid:fidea.id
cometClient.publish dirtyChannel,data
#
# Константы
#
dirty = []
# Передача всей модели на сервер
successPostAll = ->
alert "Файл передан"
postAll = ->
data = JSON.stringify
length:idea.length
idea:idea
sideaid:sidea.id
$.post("all",data,successPostAll,"json")
# Получение всей модели с сервера
successGetAll = (data) ->
deleteIdea()
console.log data
b = data # JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[b.sideaid].upperFrame().fhtml()
alert "Файл загружен"
getAll = ->
$.get("all",successGetAll,"json")
# Передать часть грязных данных
successPostDirty = ->
alert "Файл передан"
checkDirty = ->
alert dirty
postDirty = ->
data = JSON.stringify
dirty:dirty
$.post("dirty",data,successPostAll,"json")
# Получение грязных данных с сервера
successGetDirty = (data) ->
deleteIdea()
console.log data
b = data # JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[b.sideaid].upperFrame().fhtml()
alert "Файл загружен"
getDirty = ->
$.get("",successGetAll,"json")
my.user = "dpetrov@gmail.com"
alien.lock = {}
my.lock = {}
dirty = []
lastsync = null
lasttouch = null
Idea::touch = ->
if dirty.indexOf(@id) is -1
dirty.push @id
@dirtytime = now
Idea::lock = ->
lck=alien.lock.indexOf(fidea.id)
if lck > -1
return
else
locky.push
yes
| 69038 | ##################################
# Minday 0.009 Lykia
# server.coffee
# Реализация кооперативной работы
#################################
username = ""
filename = "minday.mdy"
cometStatus = off
# Устанавливаем меню
setMenuServer =->
$(".server_changeuser").click serverChangeUser
$(".server_open").click serverOpen
$(".server_refresh").click serverRefresh
$(".server_save").click serverSave
$(".server_saveas").click serverSaveAs
$(".server_share").click serverShare
$(".server_subscribe").click serverSubscribe
$(".server_unsubscribe").click serverUnsubscribe
# $("#server_getall").click getAll
# $("#server_postall").click postAll
# $("#server_checkdirty").click checkDirty
# $("#server_getdirty").click getDirty
# $("#server_postdirty").click postDirty
# $("#server_cometpublish").click cometAllPublish
cometStart =->
# Заодно проставим имя пользователя
username = $.cookie('username')
$('#username').html username
# Установление пользователя
serverChangeUser = ->
username = prompt "Введите имя пользователя",username
$.cookie 'username',username
$('#username').html username
#############################
# Открытие файла из сервера
#############################
serverOpen = ->
$.get('dir',serverOpenSuccess,'json')
serverOpenSuccess = (data) ->
s = "<p><b>Открыть файл</b></p>"
s += "<p>Выберите файл на сервере для работы:</p>"
for fi in data
s+="<div>"
s+="<a id='"+fi+"' class='open_file' href='#'>"
s+=fi
s+="</a>"
s+="</div>"
$("#dialog_open").html s
$(".open_file").click clickServerOpenFile
clickServerOpenFile = (eo) ->
$("#dialog_open").html ""
filename = eo.srcElement.id
serverRefresh()
serverRefresh = () ->
$.get("open="+filename,serverOpenFileSuccess,"json")
serverOpenFileSuccess = (data) ->
deleteIdea()
b = data # JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[-b.sideaid].upperFrame().fhtml()
alert "Загружен файл с сервера"
#############################
# Тихая загрузка файла
#############################
serverLoad = (fname) ->
$.get("open="+fname,serverLoadFileSuccess,"json")
serverLoadFileSuccess = (data) ->
b = data # JSON.parse data
updateModel()
selectModel(b.filename)
deleteIdea()
initIdea(b.length)
for io in b.idea
cloneIdea(io)
updateModel(b.filename)
selectModel()
# idea[-b.sideaid].upperFrame().fhtml()
# alert "Загружен файл с сервера"
#############################
# Сохранение файла на сервер
#############################
serverSaveAs = ->
filename = prompt "Введите имя файла для сохранения", "minday.mdy"
serverSave()
serverSave = ->
data = JSON.stringify
filename: filename
length:idea.length
idea:idea
sideaid:sidea.id
$.post("save="+filename,data,serverSaveSuccess,"json")
serverSaveSuccess = ->
alert "Файл передан"
#############################
# Открыть файл для редактирования другими пользователями
#############################
channel = ""
cometClient = null
cometAllChannel = null
cometDirtyChannel = null
cometFocusChannel = null
cometStatus = off
shareStatus = off
serverShare =->
if cometStatus is off
cometClient = new Faye.Client('http://localhost:8000/faye')
data = JSON.stringify
filename: filename
username: username
$.post("share",data,serverShareSuccess,'json')
serverShareSuccess =->
shareStatus = on
shareChannelName = filename+"-"+username
alert "Файл "+filename+" доступен другим пользователям на канале "+filename+"-"+username
serverSubscribe = ->
$.get('sharedir',serverShareDirSuccess,'json')
serverShareDirSuccess = (data) ->
s = "<p><b>Поключиться к редактированию</b></p>"
s += "<p>Выберите файл на сервере для работы:</p>"
for fi in data
s+="<div>"
s+="<a id='"+fi.filename+"-"+fi.username+"' class='open_file' href='#'>"
s+=fi.filename+"-"+fi.username
s+="</a>"
s+="</div>"
$("#dialog_open").html s
$(".open_file").click clickServerSubscribe
clickServerSubscribe = (eo) ->
$("#dialog_open").html ""
channelName = eo.srcElement.id
if cometStatus is off
cometClient = new Faye.Client('http://localhost:8000/faye')
channel = cometClient.subscribe channelName,channelArrive
serverRefresh()
channelArrive = (data) ->
alert "changes come"
serverUnsubscribe = ->
channel.cancel()
cometStatus = off
# channel = filename
# comerStatus = on
# cometClient = new Faye.Client('http://localhost:8000/faye')
# cometAllChannel = cometClient.subscribe "/all",cometAllArrive
# cometFocusChannel = cometClient.subscribe "/focus/"+channel,cometFocusArrive
# cometDirtyChannel = cometClient.subscribe "/dirty/"+channel,cometDirtyArrive
#############################
# Канал фокуса
#############################
cursor = {}
cometFocusArrive = (data) ->
b = JSON.parse data
if b.username isnt username
if cursor[b.username]?.sideaid?
cursor[b.username].oldid = cursor[b.username].sideaid
else
cursor[b.username] = {}
cursor[b.user].sideaid = b.sideaid # Сохраняем текущую позицию фокуса
setFocus cursor[b.username]
setFocus = (f) ->
if f?.oldid?
$("#txt"+f.oldid).removeClass 'cursor'
if f?.sideaid?
$("#txt"+f.sideaid).addClass 'cursor'
cometFocusPublish = ->
if cometStatus is on
data = JSON.stringify
username:username
sideaid:sidea.id
cometClient.publish cometFocusChannel,data
###
# Процедуры для работы с Faye
comet = {}
allChannel = "/all" # Полное обновление
dirtyChannel = "/dirty" # Частичное обновление
focusChannel = "/focus" # Передача курсора
lockChannel = "/lock" # Канал блокировки
problemChannel = "/problem" # Канал для проблем и оповещений
chatChannel = "/chat" # Канал для чата
cometClient = null # Сам клиент
cometStart =->
username = $.cookie('username')
$('#username').html username
return # Пока ничего не делаем
cometClient = new Faye.Client('http://localhost:8000/faye');
cometClient.subscribe allChannel,cometAllArrive
cometClient.subscribe dirtyChannel,cometDirtyArrive
cometClient.subscribe focusChannel,cometFocusArrive
cometStatus = on
cometFinish =->
cometClient = new Faye.Client('http://localhost:8000/faye');
cometClient.subscribe allChannel,cometAllArrive
cometClient.subscribe dirtyChannel,cometDirtyArrive
cometClient.subscribe focusChannel,cometFocusArrive
cometStatus = off
cometFocusArrive = (data) ->
b = JSON.parse data
if cursor[b.username]?.sideaid?
cursor[b.username].oldid = cursor[b.username].sideaid
else
cursor[b.username] = {}
cursor[b.user].sideaid = b.sideaid # Сохраняем текущую позицию фокуса
setFocus cursor[b.username]
setFocus = (f) ->
if f?.oldid?
$("#txt"+f.oldid).removeClass 'cursor'
if f?.sideaid?
$("#txt"+f.sideaid).addClass 'cursor'
cometFocusPublish = ->
if cometStatus is on
data = JSON.stringify
username:username
sideaid:sidea.id
cometClient.publish focusChannel,data
cometAllArrive = (data) ->
deleteIdea()
b = JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[-b.fideaid].fhtml(idea[-b.sideaid])
cometAllPublish = ->
data = JSON.stringify
length:idea.length
idea:idea
sideaid:sidea.id
fideaid:fidea.id
cometClient.publish dirtyChannel,data
cometDirtyArrive = (data) ->
# deleteIdea()
b = JSON.parse data
# initIdea(b.length)
for io in b.idea
cloneIdea(io)
# idea[-b.fideaid].fhtml(idea[-b.sideaid])
# Публиковать грязные данные
cometDirtyPublish = ->
data = JSON.stringify
length:idea.length
idea:idea
sideaid:sidea.id
fideaid:fidea.id
cometClient.publish dirtyChannel,data
#
# Константы
#
dirty = []
# Передача всей модели на сервер
successPostAll = ->
alert "Файл передан"
postAll = ->
data = JSON.stringify
length:idea.length
idea:idea
sideaid:sidea.id
$.post("all",data,successPostAll,"json")
# Получение всей модели с сервера
successGetAll = (data) ->
deleteIdea()
console.log data
b = data # JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[b.sideaid].upperFrame().fhtml()
alert "Файл загружен"
getAll = ->
$.get("all",successGetAll,"json")
# Передать часть грязных данных
successPostDirty = ->
alert "Файл передан"
checkDirty = ->
alert dirty
postDirty = ->
data = JSON.stringify
dirty:dirty
$.post("dirty",data,successPostAll,"json")
# Получение грязных данных с сервера
successGetDirty = (data) ->
deleteIdea()
console.log data
b = data # JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[b.sideaid].upperFrame().fhtml()
alert "Файл загружен"
getDirty = ->
$.get("",successGetAll,"json")
my.user = "<EMAIL>"
alien.lock = {}
my.lock = {}
dirty = []
lastsync = null
lasttouch = null
Idea::touch = ->
if dirty.indexOf(@id) is -1
dirty.push @id
@dirtytime = now
Idea::lock = ->
lck=alien.lock.indexOf(fidea.id)
if lck > -1
return
else
locky.push
yes
| true | ##################################
# Minday 0.009 Lykia
# server.coffee
# Реализация кооперативной работы
#################################
username = ""
filename = "minday.mdy"
cometStatus = off
# Устанавливаем меню
setMenuServer =->
$(".server_changeuser").click serverChangeUser
$(".server_open").click serverOpen
$(".server_refresh").click serverRefresh
$(".server_save").click serverSave
$(".server_saveas").click serverSaveAs
$(".server_share").click serverShare
$(".server_subscribe").click serverSubscribe
$(".server_unsubscribe").click serverUnsubscribe
# $("#server_getall").click getAll
# $("#server_postall").click postAll
# $("#server_checkdirty").click checkDirty
# $("#server_getdirty").click getDirty
# $("#server_postdirty").click postDirty
# $("#server_cometpublish").click cometAllPublish
cometStart =->
# Заодно проставим имя пользователя
username = $.cookie('username')
$('#username').html username
# Установление пользователя
serverChangeUser = ->
username = prompt "Введите имя пользователя",username
$.cookie 'username',username
$('#username').html username
#############################
# Открытие файла из сервера
#############################
serverOpen = ->
$.get('dir',serverOpenSuccess,'json')
serverOpenSuccess = (data) ->
s = "<p><b>Открыть файл</b></p>"
s += "<p>Выберите файл на сервере для работы:</p>"
for fi in data
s+="<div>"
s+="<a id='"+fi+"' class='open_file' href='#'>"
s+=fi
s+="</a>"
s+="</div>"
$("#dialog_open").html s
$(".open_file").click clickServerOpenFile
clickServerOpenFile = (eo) ->
$("#dialog_open").html ""
filename = eo.srcElement.id
serverRefresh()
serverRefresh = () ->
$.get("open="+filename,serverOpenFileSuccess,"json")
serverOpenFileSuccess = (data) ->
deleteIdea()
b = data # JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[-b.sideaid].upperFrame().fhtml()
alert "Загружен файл с сервера"
#############################
# Тихая загрузка файла
#############################
serverLoad = (fname) ->
$.get("open="+fname,serverLoadFileSuccess,"json")
serverLoadFileSuccess = (data) ->
b = data # JSON.parse data
updateModel()
selectModel(b.filename)
deleteIdea()
initIdea(b.length)
for io in b.idea
cloneIdea(io)
updateModel(b.filename)
selectModel()
# idea[-b.sideaid].upperFrame().fhtml()
# alert "Загружен файл с сервера"
#############################
# Сохранение файла на сервер
#############################
serverSaveAs = ->
filename = prompt "Введите имя файла для сохранения", "minday.mdy"
serverSave()
serverSave = ->
data = JSON.stringify
filename: filename
length:idea.length
idea:idea
sideaid:sidea.id
$.post("save="+filename,data,serverSaveSuccess,"json")
serverSaveSuccess = ->
alert "Файл передан"
#############################
# Открыть файл для редактирования другими пользователями
#############################
channel = ""
cometClient = null
cometAllChannel = null
cometDirtyChannel = null
cometFocusChannel = null
cometStatus = off
shareStatus = off
serverShare =->
if cometStatus is off
cometClient = new Faye.Client('http://localhost:8000/faye')
data = JSON.stringify
filename: filename
username: username
$.post("share",data,serverShareSuccess,'json')
serverShareSuccess =->
shareStatus = on
shareChannelName = filename+"-"+username
alert "Файл "+filename+" доступен другим пользователям на канале "+filename+"-"+username
serverSubscribe = ->
$.get('sharedir',serverShareDirSuccess,'json')
serverShareDirSuccess = (data) ->
s = "<p><b>Поключиться к редактированию</b></p>"
s += "<p>Выберите файл на сервере для работы:</p>"
for fi in data
s+="<div>"
s+="<a id='"+fi.filename+"-"+fi.username+"' class='open_file' href='#'>"
s+=fi.filename+"-"+fi.username
s+="</a>"
s+="</div>"
$("#dialog_open").html s
$(".open_file").click clickServerSubscribe
clickServerSubscribe = (eo) ->
$("#dialog_open").html ""
channelName = eo.srcElement.id
if cometStatus is off
cometClient = new Faye.Client('http://localhost:8000/faye')
channel = cometClient.subscribe channelName,channelArrive
serverRefresh()
channelArrive = (data) ->
alert "changes come"
serverUnsubscribe = ->
channel.cancel()
cometStatus = off
# channel = filename
# comerStatus = on
# cometClient = new Faye.Client('http://localhost:8000/faye')
# cometAllChannel = cometClient.subscribe "/all",cometAllArrive
# cometFocusChannel = cometClient.subscribe "/focus/"+channel,cometFocusArrive
# cometDirtyChannel = cometClient.subscribe "/dirty/"+channel,cometDirtyArrive
#############################
# Канал фокуса
#############################
cursor = {}
cometFocusArrive = (data) ->
b = JSON.parse data
if b.username isnt username
if cursor[b.username]?.sideaid?
cursor[b.username].oldid = cursor[b.username].sideaid
else
cursor[b.username] = {}
cursor[b.user].sideaid = b.sideaid # Сохраняем текущую позицию фокуса
setFocus cursor[b.username]
setFocus = (f) ->
if f?.oldid?
$("#txt"+f.oldid).removeClass 'cursor'
if f?.sideaid?
$("#txt"+f.sideaid).addClass 'cursor'
cometFocusPublish = ->
if cometStatus is on
data = JSON.stringify
username:username
sideaid:sidea.id
cometClient.publish cometFocusChannel,data
###
# Процедуры для работы с Faye
comet = {}
allChannel = "/all" # Полное обновление
dirtyChannel = "/dirty" # Частичное обновление
focusChannel = "/focus" # Передача курсора
lockChannel = "/lock" # Канал блокировки
problemChannel = "/problem" # Канал для проблем и оповещений
chatChannel = "/chat" # Канал для чата
cometClient = null # Сам клиент
cometStart =->
username = $.cookie('username')
$('#username').html username
return # Пока ничего не делаем
cometClient = new Faye.Client('http://localhost:8000/faye');
cometClient.subscribe allChannel,cometAllArrive
cometClient.subscribe dirtyChannel,cometDirtyArrive
cometClient.subscribe focusChannel,cometFocusArrive
cometStatus = on
cometFinish =->
cometClient = new Faye.Client('http://localhost:8000/faye');
cometClient.subscribe allChannel,cometAllArrive
cometClient.subscribe dirtyChannel,cometDirtyArrive
cometClient.subscribe focusChannel,cometFocusArrive
cometStatus = off
cometFocusArrive = (data) ->
b = JSON.parse data
if cursor[b.username]?.sideaid?
cursor[b.username].oldid = cursor[b.username].sideaid
else
cursor[b.username] = {}
cursor[b.user].sideaid = b.sideaid # Сохраняем текущую позицию фокуса
setFocus cursor[b.username]
setFocus = (f) ->
if f?.oldid?
$("#txt"+f.oldid).removeClass 'cursor'
if f?.sideaid?
$("#txt"+f.sideaid).addClass 'cursor'
cometFocusPublish = ->
if cometStatus is on
data = JSON.stringify
username:username
sideaid:sidea.id
cometClient.publish focusChannel,data
cometAllArrive = (data) ->
deleteIdea()
b = JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[-b.fideaid].fhtml(idea[-b.sideaid])
cometAllPublish = ->
data = JSON.stringify
length:idea.length
idea:idea
sideaid:sidea.id
fideaid:fidea.id
cometClient.publish dirtyChannel,data
cometDirtyArrive = (data) ->
# deleteIdea()
b = JSON.parse data
# initIdea(b.length)
for io in b.idea
cloneIdea(io)
# idea[-b.fideaid].fhtml(idea[-b.sideaid])
# Публиковать грязные данные
cometDirtyPublish = ->
data = JSON.stringify
length:idea.length
idea:idea
sideaid:sidea.id
fideaid:fidea.id
cometClient.publish dirtyChannel,data
#
# Константы
#
dirty = []
# Передача всей модели на сервер
successPostAll = ->
alert "Файл передан"
postAll = ->
data = JSON.stringify
length:idea.length
idea:idea
sideaid:sidea.id
$.post("all",data,successPostAll,"json")
# Получение всей модели с сервера
successGetAll = (data) ->
deleteIdea()
console.log data
b = data # JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[b.sideaid].upperFrame().fhtml()
alert "Файл загружен"
getAll = ->
$.get("all",successGetAll,"json")
# Передать часть грязных данных
successPostDirty = ->
alert "Файл передан"
checkDirty = ->
alert dirty
postDirty = ->
data = JSON.stringify
dirty:dirty
$.post("dirty",data,successPostAll,"json")
# Получение грязных данных с сервера
successGetDirty = (data) ->
deleteIdea()
console.log data
b = data # JSON.parse data
initIdea(b.length)
for io in b.idea
cloneIdea(io)
idea[b.sideaid].upperFrame().fhtml()
alert "Файл загружен"
getDirty = ->
$.get("",successGetAll,"json")
my.user = "PI:EMAIL:<EMAIL>END_PI"
alien.lock = {}
my.lock = {}
dirty = []
lastsync = null
lasttouch = null
Idea::touch = ->
if dirty.indexOf(@id) is -1
dirty.push @id
@dirtytime = now
Idea::lock = ->
lck=alien.lock.indexOf(fidea.id)
if lck > -1
return
else
locky.push
yes
|
[
{
"context": "ates a new user', ->\n Users.insert { email: 'craigspaeth@gmail.com', password: 'footothebar' }, (err, user) ->\n ",
"end": 523,
"score": 0.9999246597290039,
"start": 502,
"tag": "EMAIL",
"value": "craigspaeth@gmail.com"
},
{
"context": "sert { email: 'craigspaeth@gmail.com', password: 'footothebar' }, (err, user) ->\n Users.collection.insert.",
"end": 548,
"score": 0.9994680285453796,
"start": 537,
"tag": "PASSWORD",
"value": "footothebar"
},
{
"context": ".collection.insert.args[0][0].email.should.equal 'craigspaeth@gmail.com'\n\n it 'validates email', (done) ->\n Users",
"end": 650,
"score": 0.9999179840087891,
"start": 629,
"tag": "EMAIL",
"value": "craigspaeth@gmail.com"
},
{
"context": "es email', (done) ->\n Users.insert { email: 'craigspaeth', password: 'footothebar' }, (err) ->\n err",
"end": 729,
"score": 0.9975166320800781,
"start": 718,
"tag": "USERNAME",
"value": "craigspaeth"
},
{
"context": " Users.insert { email: 'craigspaeth', password: 'footothebar' }, (err) ->\n err.toString().should.contai",
"end": 754,
"score": 0.9994823932647705,
"start": 743,
"tag": "PASSWORD",
"value": "footothebar"
},
{
"context": "asswords', (done) ->\n Users.insert { email: 'craigspaeth@gmail.com', password: 'foo' }, (err) ->\n err.toStrin",
"end": 937,
"score": 0.9999196529388428,
"start": 916,
"tag": "EMAIL",
"value": "craigspaeth@gmail.com"
},
{
"context": "sert { email: 'craigspaeth@gmail.com', password: 'foo' }, (err) ->\n err.toString().should.contai",
"end": 954,
"score": 0.9994410872459412,
"start": 951,
"tag": "PASSWORD",
"value": "foo"
},
{
"context": "es the password', ->\n Users.insert { email: 'craigspaeth@gmail.com', password: 'foobarbaz' }\n Users.collection.",
"end": 1129,
"score": 0.9999222159385681,
"start": 1108,
"tag": "EMAIL",
"value": "craigspaeth@gmail.com"
},
{
"context": "sert { email: 'craigspaeth@gmail.com', password: 'foobarbaz' }\n Users.collection.insert.args[0][0].passw",
"end": 1152,
"score": 0.9994723796844482,
"start": 1143,
"tag": "PASSWORD",
"value": "foobarbaz"
},
{
"context": "llection.insert.args[0][0].password.should.equal 'foohash'\n\n it 'throws user already exists if the same ",
"end": 1227,
"score": 0.9692728519439697,
"start": 1220,
"tag": "PASSWORD",
"value": "foohash"
},
{
"context": "sArgWith 1, null, {}\n Users.insert { email: 'craigspaeth@gmail.com', password: 'footothebar' }, (err) ->\n err",
"end": 1401,
"score": 0.9999242424964905,
"start": 1380,
"tag": "EMAIL",
"value": "craigspaeth@gmail.com"
},
{
"context": "sert { email: 'craigspaeth@gmail.com', password: 'footothebar' }, (err) ->\n err.toString().should.contai",
"end": 1426,
"score": 0.9994809031486511,
"start": 1415,
"tag": "PASSWORD",
"value": "footothebar"
},
{
"context": "collection.findOne.args[0][0].email.should.equal 'craigspaeth@gmail.com'\n\n describe '#sanitize', ->\n\n it 'does not se",
"end": 1589,
"score": 0.9999258518218994,
"start": 1568,
"tag": "EMAIL",
"value": "craigspaeth@gmail.com"
}
] | test/dal/user.coffee | craigspaeth/nfd-api | 0 | _ = require 'underscore'
rewire = require 'rewire'
Users = rewire '../../dal/users'
sinon = require 'sinon'
collectionStub = require '../helpers/collection-stub'
describe 'users', ->
beforeEach ->
Users.__set__ 'bcrypt', hash: (pwd, len, cb) -> cb null, 'foohash'
Users.collection = collectionStub()
Users.collection.findOne = sinon.stub()
Users.collection.findOne.callsArgWith 1, null, null
describe "#insert", ->
it 'creates a new user', ->
Users.insert { email: 'craigspaeth@gmail.com', password: 'footothebar' }, (err, user) ->
Users.collection.insert.args[0][0].email.should.equal 'craigspaeth@gmail.com'
it 'validates email', (done) ->
Users.insert { email: 'craigspaeth', password: 'footothebar' }, (err) ->
err.toString().should.containEql 'Invalid email'
done()
it 'validates short passwords', (done) ->
Users.insert { email: 'craigspaeth@gmail.com', password: 'foo' }, (err) ->
err.toString().should.containEql 'Password too short'
done()
it 'hashes the password', ->
Users.insert { email: 'craigspaeth@gmail.com', password: 'foobarbaz' }
Users.collection.insert.args[0][0].password.should.equal 'foohash'
it 'throws user already exists if the same email', (done) ->
Users.collection.findOne.callsArgWith 1, null, {}
Users.insert { email: 'craigspaeth@gmail.com', password: 'footothebar' }, (err) ->
err.toString().should.containEql 'already'
done()
Users.collection.findOne.args[0][0].email.should.equal 'craigspaeth@gmail.com'
describe '#sanitize', ->
it 'does not set an empty alerts array if not passed', (done) ->
Users.sanitize { accessToken: 'foo' }, (err, data) ->
(data.alerts?).should.not.be.ok
done()
| 106460 | _ = require 'underscore'
rewire = require 'rewire'
Users = rewire '../../dal/users'
sinon = require 'sinon'
collectionStub = require '../helpers/collection-stub'
describe 'users', ->
beforeEach ->
Users.__set__ 'bcrypt', hash: (pwd, len, cb) -> cb null, 'foohash'
Users.collection = collectionStub()
Users.collection.findOne = sinon.stub()
Users.collection.findOne.callsArgWith 1, null, null
describe "#insert", ->
it 'creates a new user', ->
Users.insert { email: '<EMAIL>', password: '<PASSWORD>' }, (err, user) ->
Users.collection.insert.args[0][0].email.should.equal '<EMAIL>'
it 'validates email', (done) ->
Users.insert { email: 'craigspaeth', password: '<PASSWORD>' }, (err) ->
err.toString().should.containEql 'Invalid email'
done()
it 'validates short passwords', (done) ->
Users.insert { email: '<EMAIL>', password: '<PASSWORD>' }, (err) ->
err.toString().should.containEql 'Password too short'
done()
it 'hashes the password', ->
Users.insert { email: '<EMAIL>', password: '<PASSWORD>' }
Users.collection.insert.args[0][0].password.should.equal '<PASSWORD>'
it 'throws user already exists if the same email', (done) ->
Users.collection.findOne.callsArgWith 1, null, {}
Users.insert { email: '<EMAIL>', password: '<PASSWORD>' }, (err) ->
err.toString().should.containEql 'already'
done()
Users.collection.findOne.args[0][0].email.should.equal '<EMAIL>'
describe '#sanitize', ->
it 'does not set an empty alerts array if not passed', (done) ->
Users.sanitize { accessToken: 'foo' }, (err, data) ->
(data.alerts?).should.not.be.ok
done()
| true | _ = require 'underscore'
rewire = require 'rewire'
Users = rewire '../../dal/users'
sinon = require 'sinon'
collectionStub = require '../helpers/collection-stub'
describe 'users', ->
beforeEach ->
Users.__set__ 'bcrypt', hash: (pwd, len, cb) -> cb null, 'foohash'
Users.collection = collectionStub()
Users.collection.findOne = sinon.stub()
Users.collection.findOne.callsArgWith 1, null, null
describe "#insert", ->
it 'creates a new user', ->
Users.insert { email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' }, (err, user) ->
Users.collection.insert.args[0][0].email.should.equal 'PI:EMAIL:<EMAIL>END_PI'
it 'validates email', (done) ->
Users.insert { email: 'craigspaeth', password: 'PI:PASSWORD:<PASSWORD>END_PI' }, (err) ->
err.toString().should.containEql 'Invalid email'
done()
it 'validates short passwords', (done) ->
Users.insert { email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' }, (err) ->
err.toString().should.containEql 'Password too short'
done()
it 'hashes the password', ->
Users.insert { email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' }
Users.collection.insert.args[0][0].password.should.equal 'PI:PASSWORD:<PASSWORD>END_PI'
it 'throws user already exists if the same email', (done) ->
Users.collection.findOne.callsArgWith 1, null, {}
Users.insert { email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' }, (err) ->
err.toString().should.containEql 'already'
done()
Users.collection.findOne.args[0][0].email.should.equal 'PI:EMAIL:<EMAIL>END_PI'
describe '#sanitize', ->
it 'does not set an empty alerts array if not passed', (done) ->
Users.sanitize { accessToken: 'foo' }, (err, data) ->
(data.alerts?).should.not.be.ok
done()
|
[
{
"context": " host: 'data123.mongolab.com'\n username: 'heroku_user'\n password: 'asdfasdfasdf'\n\n result = Tow",
"end": 471,
"score": 0.9996210932731628,
"start": 460,
"tag": "USERNAME",
"value": "heroku_user"
},
{
"context": "m'\n username: 'heroku_user'\n password: 'asdfasdfasdf'\n\n result = Tower.StoreMongodb.parseEnv()\n\n ",
"end": 502,
"score": 0.999361515045166,
"start": 490,
"tag": "PASSWORD",
"value": "asdfasdfasdf"
}
] | test/cases/store/server/mongodbTest.coffee | jivagoalves/tower | 1 | describe 'Tower.StoreMongodb', ->
__config = null
config = null
beforeEach ->
__config = Tower.StoreMongodb.config
config = Tower.StoreMongodb.config = {}
afterEach ->
Tower.StoreMongodb.config = __config
test 'url', ->
config.url = 'mongodb://heroku_user:asdfasdfasdf@data123.mongolab.com:29197/heroku_app'
expected =
name: 'heroku_app'
port: 29197
host: 'data123.mongolab.com'
username: 'heroku_user'
password: 'asdfasdfasdf'
result = Tower.StoreMongodb.parseEnv()
for key, value of expected
assert.equal result[key], value | 114038 | describe 'Tower.StoreMongodb', ->
__config = null
config = null
beforeEach ->
__config = Tower.StoreMongodb.config
config = Tower.StoreMongodb.config = {}
afterEach ->
Tower.StoreMongodb.config = __config
test 'url', ->
config.url = 'mongodb://heroku_user:asdfasdfasdf@data123.mongolab.com:29197/heroku_app'
expected =
name: 'heroku_app'
port: 29197
host: 'data123.mongolab.com'
username: 'heroku_user'
password: '<PASSWORD>'
result = Tower.StoreMongodb.parseEnv()
for key, value of expected
assert.equal result[key], value | true | describe 'Tower.StoreMongodb', ->
__config = null
config = null
beforeEach ->
__config = Tower.StoreMongodb.config
config = Tower.StoreMongodb.config = {}
afterEach ->
Tower.StoreMongodb.config = __config
test 'url', ->
config.url = 'mongodb://heroku_user:asdfasdfasdf@data123.mongolab.com:29197/heroku_app'
expected =
name: 'heroku_app'
port: 29197
host: 'data123.mongolab.com'
username: 'heroku_user'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
result = Tower.StoreMongodb.parseEnv()
for key, value of expected
assert.equal result[key], value |
[
{
"context": "lert \"Galloping...\"\n super 45\n\nsam: new Snake \"Sammy the Python\"\ntom: new Horse \"Tommy the Palomino\"\n\nsam.move()\n",
"end": 348,
"score": 0.9982207417488098,
"start": 332,
"tag": "NAME",
"value": "Sammy the Python"
},
{
"context": "sam: new Snake \"Sammy the Python\"\ntom: new Horse \"Tommy the Palomino\"\n\nsam.move()\ntom.move()\n\n\n\n\n",
"end": 384,
"score": 0.999235212802887,
"start": 366,
"tag": "NAME",
"value": "Tommy the Palomino"
}
] | lib/coffee/lib/coffee-script/documentation/coffee/classes.coffee | InfinitelLoop/website-3 | 2 | class Animal
move: (meters) ->
alert @name + " moved " + meters + "m."
class Snake extends Animal
constructor: (name) ->
@name: name
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
constructor: (name) ->
@name: name
move: ->
alert "Galloping..."
super 45
sam: new Snake "Sammy the Python"
tom: new Horse "Tommy the Palomino"
sam.move()
tom.move()
| 171955 | class Animal
move: (meters) ->
alert @name + " moved " + meters + "m."
class Snake extends Animal
constructor: (name) ->
@name: name
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
constructor: (name) ->
@name: name
move: ->
alert "Galloping..."
super 45
sam: new Snake "<NAME>"
tom: new Horse "<NAME>"
sam.move()
tom.move()
| true | class Animal
move: (meters) ->
alert @name + " moved " + meters + "m."
class Snake extends Animal
constructor: (name) ->
@name: name
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
constructor: (name) ->
@name: name
move: ->
alert "Galloping..."
super 45
sam: new Snake "PI:NAME:<NAME>END_PI"
tom: new Horse "PI:NAME:<NAME>END_PI"
sam.move()
tom.move()
|
[
{
"context": "esources\n username: params?.u\n password: params?.p\n returnroute: params?.returnroute\n applic",
"end": 1820,
"score": 0.9945248961448669,
"start": 1811,
"tag": "PASSWORD",
"value": "params?.p"
},
{
"context": " userToken = new UserToken.Model\n userName: username\n password: password\n userToken.save null,",
"end": 2898,
"score": 0.999494194984436,
"start": 2890,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ken.Model\n userName: username\n password: password\n userToken.save null, # POST\n success: (",
"end": 2923,
"score": 0.9987745881080627,
"start": 2915,
"tag": "PASSWORD",
"value": "password"
}
] | Web.App/app/modules/common/controller.coffee | vip32/eventfeedback | 0 | application = require 'application'
Controller = require '../../lib/base/controller'
UserProfile = require '../../models/userprofile'
UserToken = require '../../models/usertoken'
vent = require 'vent'
settings = require 'settings'
user = require 'user'
config = require 'config'
module.exports = class Controller extends Controller
constructor: (options) ->
log 'common controller init'
application.addInitializer (options) =>
vent.on 'view:signin:do', (data) =>
if not _.isEmpty(data.username) and not _.isEmpty(data.password)
user.reset()
user.name(data.username) if data.remember
user.remember(data.remember)
@doSignin(data.username, data.password, data.returnroute)
vent.on 'message:success:show', (data) =>
@showMessage data, 'success'
vent.on 'message:error:show', (data) =>
@showMessage data, 'danger'
showMessage: (data, type) ->
$('#messagebox').append('<div id="currentmessage" class="alert alert-' + type + '"><a class="close" data-dismiss="alert"> ×</a><span>'+data+'</span></div>')
setTimeout ->
$("#currentmessage").remove();
, 3000
showHome: ->
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'home:index', '', 'glyphicon-home'
View = require './views/home-view'
view = new View(resources: application.resources)
application.layout.content.show(view)
showSignin: (params) ->
params = @parseParams(params)
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'signin:index', application.resources.key('Title_SignIn'), 'glyphicon-user'
View = require './views/signin-view'
view = new View
resources: application.resources
username: params?.u
password: params?.p
returnroute: params?.returnroute
application.layout.content.show(view)
showAbout: ->
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'about:index', application.resources.key('Title_About'), 'glyphicon-info-sign'
View = require './views/about-view'
view = new View(resources: application.resources)
application.layout.content.show(view)
showDebug: ->
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'debug:index', application.resources.key('Title_Debug'), 'glyphicon-cog'
View = require './views/debug-view'
view = new View(resources: application.resources)
application.layout.content.show(view)
doSignout: ->
user.reset()
vent.trigger 'header:refresh'
vent.trigger config.hometrigger
appInsights.trackEvent('event/signout')
doSignin: (username, password, returnroute) ->
# get the accesstoken
vent.trigger 'fetch:start' # because save() does not trigger block
userToken = new UserToken.Model
userName: username
password: password
userToken.save null, # POST
success: (model, response, options) =>
appInsights.trackEvent('event/signin/success')
user.token(userToken.get('accessToken'))
user.tokenexpires(userToken.get('expires'))
# get the userprofile
profile = new UserProfile.Model()
profile.fetch
success: (model, response, options) =>
appInsights.trackEvent('event/profile/success')
user.set('api_userroles', model.get('roles'))
vent.trigger 'message:success:show', 'signed in ' + username
vent.trigger 'header:refresh'
if _.isEmpty(returnroute)
vent.trigger config.startuptrigger
else
application.navigate returnroute
error: (model, xhr, options) ->
# vent.trigger 'message:error:show', 'profile fetch failed'
appInsights.trackEvent('event/profile/failed')
vent.trigger 'header:refresh'
error: (model, xhr, options) ->
appInsights.trackEvent('event/signin/failed')
vent.trigger 'message:error:show', 'sign in failed'
vent.trigger 'header:refresh'
vent.trigger 'fetch:fail' # stop save() spinner | 185729 | application = require 'application'
Controller = require '../../lib/base/controller'
UserProfile = require '../../models/userprofile'
UserToken = require '../../models/usertoken'
vent = require 'vent'
settings = require 'settings'
user = require 'user'
config = require 'config'
module.exports = class Controller extends Controller
constructor: (options) ->
log 'common controller init'
application.addInitializer (options) =>
vent.on 'view:signin:do', (data) =>
if not _.isEmpty(data.username) and not _.isEmpty(data.password)
user.reset()
user.name(data.username) if data.remember
user.remember(data.remember)
@doSignin(data.username, data.password, data.returnroute)
vent.on 'message:success:show', (data) =>
@showMessage data, 'success'
vent.on 'message:error:show', (data) =>
@showMessage data, 'danger'
showMessage: (data, type) ->
$('#messagebox').append('<div id="currentmessage" class="alert alert-' + type + '"><a class="close" data-dismiss="alert"> ×</a><span>'+data+'</span></div>')
setTimeout ->
$("#currentmessage").remove();
, 3000
showHome: ->
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'home:index', '', 'glyphicon-home'
View = require './views/home-view'
view = new View(resources: application.resources)
application.layout.content.show(view)
showSignin: (params) ->
params = @parseParams(params)
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'signin:index', application.resources.key('Title_SignIn'), 'glyphicon-user'
View = require './views/signin-view'
view = new View
resources: application.resources
username: params?.u
password: <PASSWORD>
returnroute: params?.returnroute
application.layout.content.show(view)
showAbout: ->
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'about:index', application.resources.key('Title_About'), 'glyphicon-info-sign'
View = require './views/about-view'
view = new View(resources: application.resources)
application.layout.content.show(view)
showDebug: ->
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'debug:index', application.resources.key('Title_Debug'), 'glyphicon-cog'
View = require './views/debug-view'
view = new View(resources: application.resources)
application.layout.content.show(view)
doSignout: ->
user.reset()
vent.trigger 'header:refresh'
vent.trigger config.hometrigger
appInsights.trackEvent('event/signout')
doSignin: (username, password, returnroute) ->
# get the accesstoken
vent.trigger 'fetch:start' # because save() does not trigger block
userToken = new UserToken.Model
userName: username
password: <PASSWORD>
userToken.save null, # POST
success: (model, response, options) =>
appInsights.trackEvent('event/signin/success')
user.token(userToken.get('accessToken'))
user.tokenexpires(userToken.get('expires'))
# get the userprofile
profile = new UserProfile.Model()
profile.fetch
success: (model, response, options) =>
appInsights.trackEvent('event/profile/success')
user.set('api_userroles', model.get('roles'))
vent.trigger 'message:success:show', 'signed in ' + username
vent.trigger 'header:refresh'
if _.isEmpty(returnroute)
vent.trigger config.startuptrigger
else
application.navigate returnroute
error: (model, xhr, options) ->
# vent.trigger 'message:error:show', 'profile fetch failed'
appInsights.trackEvent('event/profile/failed')
vent.trigger 'header:refresh'
error: (model, xhr, options) ->
appInsights.trackEvent('event/signin/failed')
vent.trigger 'message:error:show', 'sign in failed'
vent.trigger 'header:refresh'
vent.trigger 'fetch:fail' # stop save() spinner | true | application = require 'application'
Controller = require '../../lib/base/controller'
UserProfile = require '../../models/userprofile'
UserToken = require '../../models/usertoken'
vent = require 'vent'
settings = require 'settings'
user = require 'user'
config = require 'config'
module.exports = class Controller extends Controller
constructor: (options) ->
log 'common controller init'
application.addInitializer (options) =>
vent.on 'view:signin:do', (data) =>
if not _.isEmpty(data.username) and not _.isEmpty(data.password)
user.reset()
user.name(data.username) if data.remember
user.remember(data.remember)
@doSignin(data.username, data.password, data.returnroute)
vent.on 'message:success:show', (data) =>
@showMessage data, 'success'
vent.on 'message:error:show', (data) =>
@showMessage data, 'danger'
showMessage: (data, type) ->
$('#messagebox').append('<div id="currentmessage" class="alert alert-' + type + '"><a class="close" data-dismiss="alert"> ×</a><span>'+data+'</span></div>')
setTimeout ->
$("#currentmessage").remove();
, 3000
showHome: ->
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'home:index', '', 'glyphicon-home'
View = require './views/home-view'
view = new View(resources: application.resources)
application.layout.content.show(view)
showSignin: (params) ->
params = @parseParams(params)
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'signin:index', application.resources.key('Title_SignIn'), 'glyphicon-user'
View = require './views/signin-view'
view = new View
resources: application.resources
username: params?.u
password: PI:PASSWORD:<PASSWORD>END_PI
returnroute: params?.returnroute
application.layout.content.show(view)
showAbout: ->
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'about:index', application.resources.key('Title_About'), 'glyphicon-info-sign'
View = require './views/about-view'
view = new View(resources: application.resources)
application.layout.content.show(view)
showDebug: ->
vent.trigger 'fetch:done' # switch off block
vent.trigger 'set:active:header', 'debug:index', application.resources.key('Title_Debug'), 'glyphicon-cog'
View = require './views/debug-view'
view = new View(resources: application.resources)
application.layout.content.show(view)
doSignout: ->
user.reset()
vent.trigger 'header:refresh'
vent.trigger config.hometrigger
appInsights.trackEvent('event/signout')
doSignin: (username, password, returnroute) ->
# get the accesstoken
vent.trigger 'fetch:start' # because save() does not trigger block
userToken = new UserToken.Model
userName: username
password: PI:PASSWORD:<PASSWORD>END_PI
userToken.save null, # POST
success: (model, response, options) =>
appInsights.trackEvent('event/signin/success')
user.token(userToken.get('accessToken'))
user.tokenexpires(userToken.get('expires'))
# get the userprofile
profile = new UserProfile.Model()
profile.fetch
success: (model, response, options) =>
appInsights.trackEvent('event/profile/success')
user.set('api_userroles', model.get('roles'))
vent.trigger 'message:success:show', 'signed in ' + username
vent.trigger 'header:refresh'
if _.isEmpty(returnroute)
vent.trigger config.startuptrigger
else
application.navigate returnroute
error: (model, xhr, options) ->
# vent.trigger 'message:error:show', 'profile fetch failed'
appInsights.trackEvent('event/profile/failed')
vent.trigger 'header:refresh'
error: (model, xhr, options) ->
appInsights.trackEvent('event/signin/failed')
vent.trigger 'message:error:show', 'sign in failed'
vent.trigger 'header:refresh'
vent.trigger 'fetch:fail' # stop save() spinner |
[
{
"context": "=\n username: null\n email: null\n password: null\n code: null\n\n link: (scope, elem, attr, ctrl)",
"end": 82,
"score": 0.9988679885864258,
"start": 78,
"tag": "PASSWORD",
"value": "null"
}
] | h/js/directives.coffee | balupton/h | 0 | authentication = ->
base =
username: null
email: null
password: null
code: null
link: (scope, elem, attr, ctrl) ->
angular.extend scope, base
controller: [
'$scope', 'authentication',
($scope, authentication) ->
$scope.$on '$reset', => angular.extend $scope, base
$scope.submit = (form) ->
return unless form.$valid
authentication["$#{form.$name}"] ->
$scope.$emit 'success', form.$name
]
scope:
model: '=authentication'
markdown = ['$filter', '$timeout', ($filter, $timeout) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
input = elem.find('textarea')
output = elem.find('div')
# Re-render the markdown when the view needs updating.
ctrl.$render = ->
input.val (ctrl.$viewValue or '')
scope.rendered = ($filter 'converter') (ctrl.$viewValue or '')
# React to the changes to the text area
input.bind 'blur change keyup', ->
ctrl.$setViewValue input.val()
scope.$digest()
# Auto-focus the input box when the widget becomes editable.
# Re-render when it becomes uneditable.
scope.$watch 'readonly', (readonly) ->
ctrl.$render()
unless readonly then $timeout -> input.focus()
require: '?ngModel'
restrict: 'E'
scope:
readonly: '@'
required: '@'
templateUrl: 'markdown.html'
]
privacy = ->
levels = ['Public', 'Private']
link: (scope, elem, attrs, controller) ->
return unless controller?
controller.$formatters.push (permissions) ->
return unless permissions?
if 'group:__world__' in (permissions.read or [])
'Public'
else
'Private'
controller.$parsers.push (privacy) ->
return unless privacy?
permissions = controller.$modelValue
if privacy is 'Public'
if permissions.read
unless 'group:__world__' in permissions.read
permissions.read.push 'group:__world__'
else
permissions.read = ['group:__world__']
else
read = permissions.read or []
read = (role for role in read when role isnt 'group:__world__')
permissions.read = read
permissions
scope.model = controller
scope.levels = levels
require: '?ngModel'
restrict: 'E'
scope: true
templateUrl: 'privacy.html'
recursive = ['$compile', '$timeout', ($compile, $timeout) ->
compile: (tElement, tAttrs, transclude) ->
placeholder = angular.element '<!-- recursive -->'
attachQueue = []
tick = false
template = tElement.contents().clone()
tElement.html ''
transclude = $compile template, (scope, cloneAttachFn) ->
clone = placeholder.clone()
cloneAttachFn clone
$timeout ->
transclude scope, (el, scope) -> attachQueue.push [clone, el]
unless tick
tick = true
requestAnimationFrame ->
tick = false
for [clone, el] in attachQueue
clone.after el
clone.bind '$destroy', -> el.remove()
attachQueue = []
clone
post: (scope, iElement, iAttrs, controller) ->
transclude scope, (contents) -> iElement.append contents
restrict: 'A'
terminal: true
]
resettable = ->
compile: (tElement, tAttrs, transclude) ->
post: (scope, iElement, iAttrs) ->
reset = ->
transclude scope, (el) ->
iElement.replaceWith el
iElement = el
reset()
scope.$on '$reset', reset
priority: 5000
restrict: 'A'
transclude: 'element'
###
# The slow validation directive ties an to a model controller and hides
# it while the model is being edited. This behavior improves the user
# experience of filling out forms by delaying validation messages until
# after the user has made a mistake.
###
slowValidate = ['$parse', '$timeout', ($parse, $timeout) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
promise = null
elem.addClass 'slow-validate'
ctrl[attr.slowValidate]?.$viewChangeListeners?.push (value) ->
elem.removeClass 'slow-validate-show'
if promise
$timeout.cancel promise
promise = null
promise = $timeout -> elem.addClass 'slow-validate-show'
require: '^form'
restrict: 'A'
]
tabReveal = ['$parse', ($parse) ->
compile: (tElement, tAttrs, transclude) ->
panes = []
hiddenPanesGet = $parse tAttrs.tabReveal
pre: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) ->
# Hijack the tabbable controller's addPane so that the visibility of the
# secret ones can be managed. This avoids traversing the DOM to find
# the tab panes.
addPane = tabbable.addPane
tabbable.addPane = (element, attr) =>
removePane = addPane.call tabbable, element, attr
panes.push
element: element
attr: attr
=>
for i in [0..panes.length]
if panes[i].element is element
panes.splice i, 1
break
removePane()
post: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) ->
tabs = angular.element(iElement.children()[0].childNodes)
render = angular.bind ngModel, ngModel.$render
ngModel.$render = ->
render()
hiddenPanes = hiddenPanesGet scope
return unless angular.isArray hiddenPanes
for i in [0..panes.length-1]
pane = panes[i]
value = pane.attr.value || pane.attr.title
if value == ngModel.$viewValue
pane.element.css 'display', ''
angular.element(tabs[i]).css 'display', ''
else if value in hiddenPanes
pane.element.css 'display', 'none'
angular.element(tabs[i]).css 'display', 'none'
require: ['ngModel', 'tabbable']
]
thread = ['$timeout', ($timeout) ->
link: (scope, elem, attr, ctrl) ->
childrenEditing = {}
sel = window.getSelection()
scope.toggleCollapsedDown = (event) ->
event.stopPropagation()
scope.oldSelection = sel.toString()
scope.toggleCollapsed = (event) ->
event.stopPropagation()
# If we have selected something, then don't bother
return unless sel.toString() is scope.oldSelection
$timeout ->
return unless Object.keys(childrenEditing).length is 0
scope.collapsed = !scope.collapsed
scope.openDetails scope.annotation unless scope.collapsed
, 10
scope.$on 'toggleEditing', (event) ->
{$id, editing} = event.targetScope
if editing
scope.collapsed = false
unless childrenEditing[$id]
event.targetScope.$on '$destroy', ->
$timeout (-> delete childrenEditing[$id]), 100
childrenEditing[$id] = true
else
$timeout (-> delete childrenEditing[$id]), 100
restrict: 'C'
]
userPicker = ->
restrict: 'ACE'
scope:
model: '=userPickerModel'
options: '=userPickerOptions'
templateUrl: 'userPicker.html'
#Directive will be removed once the angularjs official version will have this directive
ngBlur = ['$parse', ($parse) ->
(scope, element, attr) ->
fn = $parse attr['ngBlur']
element.bind 'blur', (event) ->
scope.$apply ->
fn scope,
$event: event
]
repeatAnim = ->
restrict: 'A'
scope:
array: '='
template: '<div ng-init="runAnimOnLast()"><div ng-transclude></div></div>'
transclude: true
controller: ($scope, $element, $attrs) ->
$scope.runAnimOnLast = ->
#Run anim on the item's element
#(which will be last child of directive element)
item=$scope.array[0]
itemElm = jQuery($element)
.children()
.first()
.children()
unless item._anim?
return
if item._anim is 'fade'
itemElm
.css({ opacity: 0 })
.animate({ opacity: 1 }, 1500)
else
if item._anim is 'slide'
itemElm
.css({ 'margin-left': itemElm.width() })
.animate({ 'margin-left': '0px' }, 1500)
# Directive to edit/display a tag list.
tags = ['$window', ($window) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
elem.tagit
caseSensitive: false
placeholderText: attr.placeholder
keepPlaceholder: true
preprocessTag: (val) ->
val.replace /[^a-zA-Z0-9\-\_\s]/g, ''
afterTagAdded: (evt, ui) ->
ctrl.$setViewValue elem.tagit 'assignedTags'
afterTagRemoved: (evt, ui) ->
ctrl.$setViewValue elem.tagit 'assignedTags'
autocomplete:
source: []
onTagClicked: (evt, ui) ->
evt.stopPropagation()
tag = ui.tagLabel
$window.open "/t/" + tag
ctrl.$formatters.push (tags=[]) ->
assigned = elem.tagit 'assignedTags'
for t in assigned when t not in tags
elem.tagit 'removeTagByLabel', t
for t in tags when t not in assigned
elem.tagit 'createTag', t
if assigned.length or not attr.readOnly then elem.show() else elem.hide()
attr.$observe 'readonly', (readonly) ->
tagInput = elem.find('input').last()
assigned = elem.tagit 'assignedTags'
if readonly
tagInput.attr('disabled', true)
tagInput.removeAttr('placeholder')
if assigned.length then elem.show() else elem.hide()
else
tagInput.removeAttr('disabled')
tagInput.attr('placeholder', attr['placeholder'])
elem.show()
require: '?ngModel'
restrict: 'C'
]
notification = ['$filter', ($filter) ->
link: (scope, elem, attrs, controller) ->
return unless controller?
# Publish the controller
scope.model = controller
controller: 'NotificationController'
priority: 100 # Must run before ngModel
require: '?ngModel'
restrict: 'C'
scope: {}
templateUrl: 'notification.html'
]
username = ['$filter', '$window', ($filter, $window) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
ctrl.$render = ->
scope.uname = ($filter 'userName') ctrl.$viewValue
scope.uclick = (event) ->
event.stopPropagation()
$window.open "/u/" + scope.uname
require: '?ngModel'
restrict: 'E'
template: '<span class="user" ng-click="uclick($event)">{{uname}}</span>'
]
fuzzytime = ['$filter', '$window', ($filter, $window) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
ctrl.$render = ->
scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue
timefunct = ->
$window.setInterval =>
scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue
scope.$digest()
, 5000
scope.timer = timefunct()
scope.$on '$destroy', ->
$window.clearInterval scope.timer
require: '?ngModel'
restrict: 'E'
template: '<span class="small">{{ftime | date:mediumDate}}</span>'
]
angular.module('h.directives', ['ngSanitize'])
.directive('authentication', authentication)
.directive('fuzzytime', fuzzytime)
.directive('markdown', markdown)
.directive('privacy', privacy)
.directive('recursive', recursive)
.directive('resettable', resettable)
.directive('slowValidate', slowValidate)
.directive('tabReveal', tabReveal)
.directive('tags', tags)
.directive('thread', thread)
.directive('username', username)
.directive('userPicker', userPicker)
.directive('ngBlur', ngBlur)
.directive('repeatAnim', repeatAnim)
.directive('notification', notification)
| 144730 | authentication = ->
base =
username: null
email: null
password: <PASSWORD>
code: null
link: (scope, elem, attr, ctrl) ->
angular.extend scope, base
controller: [
'$scope', 'authentication',
($scope, authentication) ->
$scope.$on '$reset', => angular.extend $scope, base
$scope.submit = (form) ->
return unless form.$valid
authentication["$#{form.$name}"] ->
$scope.$emit 'success', form.$name
]
scope:
model: '=authentication'
markdown = ['$filter', '$timeout', ($filter, $timeout) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
input = elem.find('textarea')
output = elem.find('div')
# Re-render the markdown when the view needs updating.
ctrl.$render = ->
input.val (ctrl.$viewValue or '')
scope.rendered = ($filter 'converter') (ctrl.$viewValue or '')
# React to the changes to the text area
input.bind 'blur change keyup', ->
ctrl.$setViewValue input.val()
scope.$digest()
# Auto-focus the input box when the widget becomes editable.
# Re-render when it becomes uneditable.
scope.$watch 'readonly', (readonly) ->
ctrl.$render()
unless readonly then $timeout -> input.focus()
require: '?ngModel'
restrict: 'E'
scope:
readonly: '@'
required: '@'
templateUrl: 'markdown.html'
]
privacy = ->
levels = ['Public', 'Private']
link: (scope, elem, attrs, controller) ->
return unless controller?
controller.$formatters.push (permissions) ->
return unless permissions?
if 'group:__world__' in (permissions.read or [])
'Public'
else
'Private'
controller.$parsers.push (privacy) ->
return unless privacy?
permissions = controller.$modelValue
if privacy is 'Public'
if permissions.read
unless 'group:__world__' in permissions.read
permissions.read.push 'group:__world__'
else
permissions.read = ['group:__world__']
else
read = permissions.read or []
read = (role for role in read when role isnt 'group:__world__')
permissions.read = read
permissions
scope.model = controller
scope.levels = levels
require: '?ngModel'
restrict: 'E'
scope: true
templateUrl: 'privacy.html'
recursive = ['$compile', '$timeout', ($compile, $timeout) ->
compile: (tElement, tAttrs, transclude) ->
placeholder = angular.element '<!-- recursive -->'
attachQueue = []
tick = false
template = tElement.contents().clone()
tElement.html ''
transclude = $compile template, (scope, cloneAttachFn) ->
clone = placeholder.clone()
cloneAttachFn clone
$timeout ->
transclude scope, (el, scope) -> attachQueue.push [clone, el]
unless tick
tick = true
requestAnimationFrame ->
tick = false
for [clone, el] in attachQueue
clone.after el
clone.bind '$destroy', -> el.remove()
attachQueue = []
clone
post: (scope, iElement, iAttrs, controller) ->
transclude scope, (contents) -> iElement.append contents
restrict: 'A'
terminal: true
]
resettable = ->
compile: (tElement, tAttrs, transclude) ->
post: (scope, iElement, iAttrs) ->
reset = ->
transclude scope, (el) ->
iElement.replaceWith el
iElement = el
reset()
scope.$on '$reset', reset
priority: 5000
restrict: 'A'
transclude: 'element'
###
# The slow validation directive ties an to a model controller and hides
# it while the model is being edited. This behavior improves the user
# experience of filling out forms by delaying validation messages until
# after the user has made a mistake.
###
slowValidate = ['$parse', '$timeout', ($parse, $timeout) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
promise = null
elem.addClass 'slow-validate'
ctrl[attr.slowValidate]?.$viewChangeListeners?.push (value) ->
elem.removeClass 'slow-validate-show'
if promise
$timeout.cancel promise
promise = null
promise = $timeout -> elem.addClass 'slow-validate-show'
require: '^form'
restrict: 'A'
]
tabReveal = ['$parse', ($parse) ->
compile: (tElement, tAttrs, transclude) ->
panes = []
hiddenPanesGet = $parse tAttrs.tabReveal
pre: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) ->
# Hijack the tabbable controller's addPane so that the visibility of the
# secret ones can be managed. This avoids traversing the DOM to find
# the tab panes.
addPane = tabbable.addPane
tabbable.addPane = (element, attr) =>
removePane = addPane.call tabbable, element, attr
panes.push
element: element
attr: attr
=>
for i in [0..panes.length]
if panes[i].element is element
panes.splice i, 1
break
removePane()
post: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) ->
tabs = angular.element(iElement.children()[0].childNodes)
render = angular.bind ngModel, ngModel.$render
ngModel.$render = ->
render()
hiddenPanes = hiddenPanesGet scope
return unless angular.isArray hiddenPanes
for i in [0..panes.length-1]
pane = panes[i]
value = pane.attr.value || pane.attr.title
if value == ngModel.$viewValue
pane.element.css 'display', ''
angular.element(tabs[i]).css 'display', ''
else if value in hiddenPanes
pane.element.css 'display', 'none'
angular.element(tabs[i]).css 'display', 'none'
require: ['ngModel', 'tabbable']
]
thread = ['$timeout', ($timeout) ->
link: (scope, elem, attr, ctrl) ->
childrenEditing = {}
sel = window.getSelection()
scope.toggleCollapsedDown = (event) ->
event.stopPropagation()
scope.oldSelection = sel.toString()
scope.toggleCollapsed = (event) ->
event.stopPropagation()
# If we have selected something, then don't bother
return unless sel.toString() is scope.oldSelection
$timeout ->
return unless Object.keys(childrenEditing).length is 0
scope.collapsed = !scope.collapsed
scope.openDetails scope.annotation unless scope.collapsed
, 10
scope.$on 'toggleEditing', (event) ->
{$id, editing} = event.targetScope
if editing
scope.collapsed = false
unless childrenEditing[$id]
event.targetScope.$on '$destroy', ->
$timeout (-> delete childrenEditing[$id]), 100
childrenEditing[$id] = true
else
$timeout (-> delete childrenEditing[$id]), 100
restrict: 'C'
]
userPicker = ->
restrict: 'ACE'
scope:
model: '=userPickerModel'
options: '=userPickerOptions'
templateUrl: 'userPicker.html'
#Directive will be removed once the angularjs official version will have this directive
ngBlur = ['$parse', ($parse) ->
(scope, element, attr) ->
fn = $parse attr['ngBlur']
element.bind 'blur', (event) ->
scope.$apply ->
fn scope,
$event: event
]
repeatAnim = ->
restrict: 'A'
scope:
array: '='
template: '<div ng-init="runAnimOnLast()"><div ng-transclude></div></div>'
transclude: true
controller: ($scope, $element, $attrs) ->
$scope.runAnimOnLast = ->
#Run anim on the item's element
#(which will be last child of directive element)
item=$scope.array[0]
itemElm = jQuery($element)
.children()
.first()
.children()
unless item._anim?
return
if item._anim is 'fade'
itemElm
.css({ opacity: 0 })
.animate({ opacity: 1 }, 1500)
else
if item._anim is 'slide'
itemElm
.css({ 'margin-left': itemElm.width() })
.animate({ 'margin-left': '0px' }, 1500)
# Directive to edit/display a tag list.
tags = ['$window', ($window) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
elem.tagit
caseSensitive: false
placeholderText: attr.placeholder
keepPlaceholder: true
preprocessTag: (val) ->
val.replace /[^a-zA-Z0-9\-\_\s]/g, ''
afterTagAdded: (evt, ui) ->
ctrl.$setViewValue elem.tagit 'assignedTags'
afterTagRemoved: (evt, ui) ->
ctrl.$setViewValue elem.tagit 'assignedTags'
autocomplete:
source: []
onTagClicked: (evt, ui) ->
evt.stopPropagation()
tag = ui.tagLabel
$window.open "/t/" + tag
ctrl.$formatters.push (tags=[]) ->
assigned = elem.tagit 'assignedTags'
for t in assigned when t not in tags
elem.tagit 'removeTagByLabel', t
for t in tags when t not in assigned
elem.tagit 'createTag', t
if assigned.length or not attr.readOnly then elem.show() else elem.hide()
attr.$observe 'readonly', (readonly) ->
tagInput = elem.find('input').last()
assigned = elem.tagit 'assignedTags'
if readonly
tagInput.attr('disabled', true)
tagInput.removeAttr('placeholder')
if assigned.length then elem.show() else elem.hide()
else
tagInput.removeAttr('disabled')
tagInput.attr('placeholder', attr['placeholder'])
elem.show()
require: '?ngModel'
restrict: 'C'
]
notification = ['$filter', ($filter) ->
link: (scope, elem, attrs, controller) ->
return unless controller?
# Publish the controller
scope.model = controller
controller: 'NotificationController'
priority: 100 # Must run before ngModel
require: '?ngModel'
restrict: 'C'
scope: {}
templateUrl: 'notification.html'
]
username = ['$filter', '$window', ($filter, $window) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
ctrl.$render = ->
scope.uname = ($filter 'userName') ctrl.$viewValue
scope.uclick = (event) ->
event.stopPropagation()
$window.open "/u/" + scope.uname
require: '?ngModel'
restrict: 'E'
template: '<span class="user" ng-click="uclick($event)">{{uname}}</span>'
]
fuzzytime = ['$filter', '$window', ($filter, $window) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
ctrl.$render = ->
scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue
timefunct = ->
$window.setInterval =>
scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue
scope.$digest()
, 5000
scope.timer = timefunct()
scope.$on '$destroy', ->
$window.clearInterval scope.timer
require: '?ngModel'
restrict: 'E'
template: '<span class="small">{{ftime | date:mediumDate}}</span>'
]
angular.module('h.directives', ['ngSanitize'])
.directive('authentication', authentication)
.directive('fuzzytime', fuzzytime)
.directive('markdown', markdown)
.directive('privacy', privacy)
.directive('recursive', recursive)
.directive('resettable', resettable)
.directive('slowValidate', slowValidate)
.directive('tabReveal', tabReveal)
.directive('tags', tags)
.directive('thread', thread)
.directive('username', username)
.directive('userPicker', userPicker)
.directive('ngBlur', ngBlur)
.directive('repeatAnim', repeatAnim)
.directive('notification', notification)
| true | authentication = ->
base =
username: null
email: null
password: PI:PASSWORD:<PASSWORD>END_PI
code: null
link: (scope, elem, attr, ctrl) ->
angular.extend scope, base
controller: [
'$scope', 'authentication',
($scope, authentication) ->
$scope.$on '$reset', => angular.extend $scope, base
$scope.submit = (form) ->
return unless form.$valid
authentication["$#{form.$name}"] ->
$scope.$emit 'success', form.$name
]
scope:
model: '=authentication'
markdown = ['$filter', '$timeout', ($filter, $timeout) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
input = elem.find('textarea')
output = elem.find('div')
# Re-render the markdown when the view needs updating.
ctrl.$render = ->
input.val (ctrl.$viewValue or '')
scope.rendered = ($filter 'converter') (ctrl.$viewValue or '')
# React to the changes to the text area
input.bind 'blur change keyup', ->
ctrl.$setViewValue input.val()
scope.$digest()
# Auto-focus the input box when the widget becomes editable.
# Re-render when it becomes uneditable.
scope.$watch 'readonly', (readonly) ->
ctrl.$render()
unless readonly then $timeout -> input.focus()
require: '?ngModel'
restrict: 'E'
scope:
readonly: '@'
required: '@'
templateUrl: 'markdown.html'
]
privacy = ->
levels = ['Public', 'Private']
link: (scope, elem, attrs, controller) ->
return unless controller?
controller.$formatters.push (permissions) ->
return unless permissions?
if 'group:__world__' in (permissions.read or [])
'Public'
else
'Private'
controller.$parsers.push (privacy) ->
return unless privacy?
permissions = controller.$modelValue
if privacy is 'Public'
if permissions.read
unless 'group:__world__' in permissions.read
permissions.read.push 'group:__world__'
else
permissions.read = ['group:__world__']
else
read = permissions.read or []
read = (role for role in read when role isnt 'group:__world__')
permissions.read = read
permissions
scope.model = controller
scope.levels = levels
require: '?ngModel'
restrict: 'E'
scope: true
templateUrl: 'privacy.html'
recursive = ['$compile', '$timeout', ($compile, $timeout) ->
compile: (tElement, tAttrs, transclude) ->
placeholder = angular.element '<!-- recursive -->'
attachQueue = []
tick = false
template = tElement.contents().clone()
tElement.html ''
transclude = $compile template, (scope, cloneAttachFn) ->
clone = placeholder.clone()
cloneAttachFn clone
$timeout ->
transclude scope, (el, scope) -> attachQueue.push [clone, el]
unless tick
tick = true
requestAnimationFrame ->
tick = false
for [clone, el] in attachQueue
clone.after el
clone.bind '$destroy', -> el.remove()
attachQueue = []
clone
post: (scope, iElement, iAttrs, controller) ->
transclude scope, (contents) -> iElement.append contents
restrict: 'A'
terminal: true
]
resettable = ->
compile: (tElement, tAttrs, transclude) ->
post: (scope, iElement, iAttrs) ->
reset = ->
transclude scope, (el) ->
iElement.replaceWith el
iElement = el
reset()
scope.$on '$reset', reset
priority: 5000
restrict: 'A'
transclude: 'element'
###
# The slow validation directive ties an to a model controller and hides
# it while the model is being edited. This behavior improves the user
# experience of filling out forms by delaying validation messages until
# after the user has made a mistake.
###
slowValidate = ['$parse', '$timeout', ($parse, $timeout) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
promise = null
elem.addClass 'slow-validate'
ctrl[attr.slowValidate]?.$viewChangeListeners?.push (value) ->
elem.removeClass 'slow-validate-show'
if promise
$timeout.cancel promise
promise = null
promise = $timeout -> elem.addClass 'slow-validate-show'
require: '^form'
restrict: 'A'
]
tabReveal = ['$parse', ($parse) ->
compile: (tElement, tAttrs, transclude) ->
panes = []
hiddenPanesGet = $parse tAttrs.tabReveal
pre: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) ->
# Hijack the tabbable controller's addPane so that the visibility of the
# secret ones can be managed. This avoids traversing the DOM to find
# the tab panes.
addPane = tabbable.addPane
tabbable.addPane = (element, attr) =>
removePane = addPane.call tabbable, element, attr
panes.push
element: element
attr: attr
=>
for i in [0..panes.length]
if panes[i].element is element
panes.splice i, 1
break
removePane()
post: (scope, iElement, iAttrs, [ngModel, tabbable] = controller) ->
tabs = angular.element(iElement.children()[0].childNodes)
render = angular.bind ngModel, ngModel.$render
ngModel.$render = ->
render()
hiddenPanes = hiddenPanesGet scope
return unless angular.isArray hiddenPanes
for i in [0..panes.length-1]
pane = panes[i]
value = pane.attr.value || pane.attr.title
if value == ngModel.$viewValue
pane.element.css 'display', ''
angular.element(tabs[i]).css 'display', ''
else if value in hiddenPanes
pane.element.css 'display', 'none'
angular.element(tabs[i]).css 'display', 'none'
require: ['ngModel', 'tabbable']
]
thread = ['$timeout', ($timeout) ->
link: (scope, elem, attr, ctrl) ->
childrenEditing = {}
sel = window.getSelection()
scope.toggleCollapsedDown = (event) ->
event.stopPropagation()
scope.oldSelection = sel.toString()
scope.toggleCollapsed = (event) ->
event.stopPropagation()
# If we have selected something, then don't bother
return unless sel.toString() is scope.oldSelection
$timeout ->
return unless Object.keys(childrenEditing).length is 0
scope.collapsed = !scope.collapsed
scope.openDetails scope.annotation unless scope.collapsed
, 10
scope.$on 'toggleEditing', (event) ->
{$id, editing} = event.targetScope
if editing
scope.collapsed = false
unless childrenEditing[$id]
event.targetScope.$on '$destroy', ->
$timeout (-> delete childrenEditing[$id]), 100
childrenEditing[$id] = true
else
$timeout (-> delete childrenEditing[$id]), 100
restrict: 'C'
]
userPicker = ->
restrict: 'ACE'
scope:
model: '=userPickerModel'
options: '=userPickerOptions'
templateUrl: 'userPicker.html'
#Directive will be removed once the angularjs official version will have this directive
ngBlur = ['$parse', ($parse) ->
(scope, element, attr) ->
fn = $parse attr['ngBlur']
element.bind 'blur', (event) ->
scope.$apply ->
fn scope,
$event: event
]
repeatAnim = ->
restrict: 'A'
scope:
array: '='
template: '<div ng-init="runAnimOnLast()"><div ng-transclude></div></div>'
transclude: true
controller: ($scope, $element, $attrs) ->
$scope.runAnimOnLast = ->
#Run anim on the item's element
#(which will be last child of directive element)
item=$scope.array[0]
itemElm = jQuery($element)
.children()
.first()
.children()
unless item._anim?
return
if item._anim is 'fade'
itemElm
.css({ opacity: 0 })
.animate({ opacity: 1 }, 1500)
else
if item._anim is 'slide'
itemElm
.css({ 'margin-left': itemElm.width() })
.animate({ 'margin-left': '0px' }, 1500)
# Directive to edit/display a tag list.
tags = ['$window', ($window) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
elem.tagit
caseSensitive: false
placeholderText: attr.placeholder
keepPlaceholder: true
preprocessTag: (val) ->
val.replace /[^a-zA-Z0-9\-\_\s]/g, ''
afterTagAdded: (evt, ui) ->
ctrl.$setViewValue elem.tagit 'assignedTags'
afterTagRemoved: (evt, ui) ->
ctrl.$setViewValue elem.tagit 'assignedTags'
autocomplete:
source: []
onTagClicked: (evt, ui) ->
evt.stopPropagation()
tag = ui.tagLabel
$window.open "/t/" + tag
ctrl.$formatters.push (tags=[]) ->
assigned = elem.tagit 'assignedTags'
for t in assigned when t not in tags
elem.tagit 'removeTagByLabel', t
for t in tags when t not in assigned
elem.tagit 'createTag', t
if assigned.length or not attr.readOnly then elem.show() else elem.hide()
attr.$observe 'readonly', (readonly) ->
tagInput = elem.find('input').last()
assigned = elem.tagit 'assignedTags'
if readonly
tagInput.attr('disabled', true)
tagInput.removeAttr('placeholder')
if assigned.length then elem.show() else elem.hide()
else
tagInput.removeAttr('disabled')
tagInput.attr('placeholder', attr['placeholder'])
elem.show()
require: '?ngModel'
restrict: 'C'
]
notification = ['$filter', ($filter) ->
link: (scope, elem, attrs, controller) ->
return unless controller?
# Publish the controller
scope.model = controller
controller: 'NotificationController'
priority: 100 # Must run before ngModel
require: '?ngModel'
restrict: 'C'
scope: {}
templateUrl: 'notification.html'
]
username = ['$filter', '$window', ($filter, $window) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
ctrl.$render = ->
scope.uname = ($filter 'userName') ctrl.$viewValue
scope.uclick = (event) ->
event.stopPropagation()
$window.open "/u/" + scope.uname
require: '?ngModel'
restrict: 'E'
template: '<span class="user" ng-click="uclick($event)">{{uname}}</span>'
]
fuzzytime = ['$filter', '$window', ($filter, $window) ->
link: (scope, elem, attr, ctrl) ->
return unless ctrl?
ctrl.$render = ->
scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue
timefunct = ->
$window.setInterval =>
scope.ftime = ($filter 'fuzzyTime') ctrl.$viewValue
scope.$digest()
, 5000
scope.timer = timefunct()
scope.$on '$destroy', ->
$window.clearInterval scope.timer
require: '?ngModel'
restrict: 'E'
template: '<span class="small">{{ftime | date:mediumDate}}</span>'
]
angular.module('h.directives', ['ngSanitize'])
.directive('authentication', authentication)
.directive('fuzzytime', fuzzytime)
.directive('markdown', markdown)
.directive('privacy', privacy)
.directive('recursive', recursive)
.directive('resettable', resettable)
.directive('slowValidate', slowValidate)
.directive('tabReveal', tabReveal)
.directive('tags', tags)
.directive('thread', thread)
.directive('username', username)
.directive('userPicker', userPicker)
.directive('ngBlur', ngBlur)
.directive('repeatAnim', repeatAnim)
.directive('notification', notification)
|
[
{
"context": ">\n yield [\n new User(username: 'bogus').validate().should.be.fulfilled\n new ",
"end": 861,
"score": 0.999636709690094,
"start": 856,
"tag": "USERNAME",
"value": "bogus"
},
{
"context": "ould.be.fulfilled\n new User(username: 'bogus', email: 'foobar').validate().should.be.rejected\n",
"end": 932,
"score": 0.9996393322944641,
"start": 927,
"tag": "USERNAME",
"value": "bogus"
},
{
"context": "pe, 'validate'\n user = new User(username: 'alice')\n yield user.save()\n user.validate",
"end": 1122,
"score": 0.9993744492530823,
"start": 1117,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "pe, 'validate'\n user = new User(username: 'alice')\n yield user.save()\n user.validate",
"end": 1551,
"score": 0.9995155930519104,
"start": 1546,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "\n ]\n user = new User(username: 'alice')\n yield user.save(null, validation: false",
"end": 1994,
"score": 0.9977680444717407,
"start": 1989,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " ]\n\n user = yield User.forge(username: 'alice').save(null, validation: false)\n user.emai",
"end": 2581,
"score": 0.98435378074646,
"start": 2576,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "l = 'foobar'\n\n yield user.save({username: 'annie', password: 'secret'}, {patch: true})\n\n f.",
"end": 2686,
"score": 0.9995275735855103,
"start": 2681,
"tag": "USERNAME",
"value": "annie"
},
{
"context": " yield user.save({username: 'annie', password: 'secret'}, {patch: true})\n\n f.should.have.been.cal",
"end": 2706,
"score": 0.9991136193275452,
"start": 2700,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": " try\n yield user.save({username: 'annie', password: 'secret'}, {patch: false})\n ca",
"end": 2933,
"score": 0.9994473457336426,
"start": 2928,
"tag": "USERNAME",
"value": "annie"
},
{
"context": " yield user.save({username: 'annie', password: 'secret'}, {patch: false})\n catch\n # pa",
"end": 2953,
"score": 0.9992095828056335,
"start": 2947,
"tag": "PASSWORD",
"value": "secret"
}
] | test/validation.coffee | bgaeddert/bookshelf-schema | 44 | Bookshelf = require 'bookshelf'
CheckIt = require 'checkit'
Schema = require '../src/'
init = require './init'
Fields = require '../src/fields'
{StringField, IntField, EmailField} = Fields
describe "Validation", ->
this.timeout 3000
db = null
User = null
before ->
db = init.init()
init.users()
beforeEach ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', minLength: 3, maxLength: 15
EmailField 'email'
]
it 'should create array of validations', ->
User.__bookshelf_schema.validations.should.deep.equal
username: ['string', 'minLength:3', 'maxLength:15']
email: ['string', 'email']
it 'should validate models', co ->
yield [
new User(username: 'bogus').validate().should.be.fulfilled
new User(username: 'bogus', email: 'foobar').validate().should.be.rejected
]
it 'should run validations on save', co ->
spy.on User.prototype, 'validate'
user = new User(username: 'alice')
yield user.save()
user.validate.should.have.been.called()
it "shouldn't apply validation if plugin initialized with option validation: false", co ->
db2 = Bookshelf db.knex
db2.plugin Schema(validation: false)
class User extends db2.Model
tableName: 'users', validations: [ -> false ]
spy.on User.prototype, 'validate'
user = new User(username: 'alice')
yield user.save()
user.validate.should.not.have.been.called()
yield user.validate().should.be.fulfilled
it "shouldn't apply validation when saved with option validation: false", co ->
f = spy -> false
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', validations: [ f ]
]
user = new User(username: 'alice')
yield user.save(null, validation: false)
f.should.not.have.been.called()
it "when patching should accept validation to passed attributes only", co ->
f = spy -> true
g = spy -> true
h = spy -> false
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', validations: [ f ]
StringField 'password', validations: [g]
StringField 'email', validations: [ h ], required: true
]
user = yield User.forge(username: 'alice').save(null, validation: false)
user.email = 'foobar'
yield user.save({username: 'annie', password: 'secret'}, {patch: true})
f.should.have.been.called()
g.should.have.been.called()
h.should.not.have.been.called()
f.reset()
g.reset()
try
yield user.save({username: 'annie', password: 'secret'}, {patch: false})
catch
# pass
f.should.have.been.called()
g.should.have.been.called()
h.should.have.been.called()
it 'accepts custom validation rules like Checkit do', co ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', validations: [{
rule: 'minLength:5',
message: '{{label}}: foo',
label: 'foo'
}]
]
e = yield new User(username: 'bar').validate().should.be.rejected
e.get('username').message.should.equal 'foo: foo'
describe 'Custom error messages', ->
it 'uses provided messages', co ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'foo', min_length: {value: 10, message: 'foo'}
]
e = yield new User(foo: 'bar').validate().should.be.rejected
e.get('foo').message.should.equal 'foo'
it 'uses field default error message and label', co ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', min_length: 10, message: '{{label}}: foo', label: 'foo'
]
e = yield new User(username: 'bar').validate().should.be.rejected
e.get('username').message.should.equal 'foo: foo'
it 'user field error message and label for field type validation', co ->
class User extends db.Model
tableName: 'users'
@schema [
EmailField 'email', message: '{{label}}: foo', label: 'foo'
]
e = yield new User(email: 'bar').validate().should.be.rejected
e.get('email').message.should.equal 'foo: foo'
it 'can use i18n for messages', co ->
db2 = Bookshelf db.knex
db2.plugin Schema(
language: 'ru',
messages: {email: 'Поле {{label}} должно содержать email-адрес'}
)
class User extends db2.Model
tableName: 'users'
@schema [
EmailField 'email'
]
e = yield new User(email: 'bar').validate().should.be.rejected
e.get('email').message.should.equal 'Поле email должно содержать email-адрес'
| 11733 | Bookshelf = require 'bookshelf'
CheckIt = require 'checkit'
Schema = require '../src/'
init = require './init'
Fields = require '../src/fields'
{StringField, IntField, EmailField} = Fields
describe "Validation", ->
this.timeout 3000
db = null
User = null
before ->
db = init.init()
init.users()
beforeEach ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', minLength: 3, maxLength: 15
EmailField 'email'
]
it 'should create array of validations', ->
User.__bookshelf_schema.validations.should.deep.equal
username: ['string', 'minLength:3', 'maxLength:15']
email: ['string', 'email']
it 'should validate models', co ->
yield [
new User(username: 'bogus').validate().should.be.fulfilled
new User(username: 'bogus', email: 'foobar').validate().should.be.rejected
]
it 'should run validations on save', co ->
spy.on User.prototype, 'validate'
user = new User(username: 'alice')
yield user.save()
user.validate.should.have.been.called()
it "shouldn't apply validation if plugin initialized with option validation: false", co ->
db2 = Bookshelf db.knex
db2.plugin Schema(validation: false)
class User extends db2.Model
tableName: 'users', validations: [ -> false ]
spy.on User.prototype, 'validate'
user = new User(username: 'alice')
yield user.save()
user.validate.should.not.have.been.called()
yield user.validate().should.be.fulfilled
it "shouldn't apply validation when saved with option validation: false", co ->
f = spy -> false
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', validations: [ f ]
]
user = new User(username: 'alice')
yield user.save(null, validation: false)
f.should.not.have.been.called()
it "when patching should accept validation to passed attributes only", co ->
f = spy -> true
g = spy -> true
h = spy -> false
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', validations: [ f ]
StringField 'password', validations: [g]
StringField 'email', validations: [ h ], required: true
]
user = yield User.forge(username: 'alice').save(null, validation: false)
user.email = 'foobar'
yield user.save({username: 'annie', password: '<PASSWORD>'}, {patch: true})
f.should.have.been.called()
g.should.have.been.called()
h.should.not.have.been.called()
f.reset()
g.reset()
try
yield user.save({username: 'annie', password: '<PASSWORD>'}, {patch: false})
catch
# pass
f.should.have.been.called()
g.should.have.been.called()
h.should.have.been.called()
it 'accepts custom validation rules like Checkit do', co ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', validations: [{
rule: 'minLength:5',
message: '{{label}}: foo',
label: 'foo'
}]
]
e = yield new User(username: 'bar').validate().should.be.rejected
e.get('username').message.should.equal 'foo: foo'
describe 'Custom error messages', ->
it 'uses provided messages', co ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'foo', min_length: {value: 10, message: 'foo'}
]
e = yield new User(foo: 'bar').validate().should.be.rejected
e.get('foo').message.should.equal 'foo'
it 'uses field default error message and label', co ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', min_length: 10, message: '{{label}}: foo', label: 'foo'
]
e = yield new User(username: 'bar').validate().should.be.rejected
e.get('username').message.should.equal 'foo: foo'
it 'user field error message and label for field type validation', co ->
class User extends db.Model
tableName: 'users'
@schema [
EmailField 'email', message: '{{label}}: foo', label: 'foo'
]
e = yield new User(email: 'bar').validate().should.be.rejected
e.get('email').message.should.equal 'foo: foo'
it 'can use i18n for messages', co ->
db2 = Bookshelf db.knex
db2.plugin Schema(
language: 'ru',
messages: {email: 'Поле {{label}} должно содержать email-адрес'}
)
class User extends db2.Model
tableName: 'users'
@schema [
EmailField 'email'
]
e = yield new User(email: 'bar').validate().should.be.rejected
e.get('email').message.should.equal 'Поле email должно содержать email-адрес'
| true | Bookshelf = require 'bookshelf'
CheckIt = require 'checkit'
Schema = require '../src/'
init = require './init'
Fields = require '../src/fields'
{StringField, IntField, EmailField} = Fields
describe "Validation", ->
this.timeout 3000
db = null
User = null
before ->
db = init.init()
init.users()
beforeEach ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', minLength: 3, maxLength: 15
EmailField 'email'
]
it 'should create array of validations', ->
User.__bookshelf_schema.validations.should.deep.equal
username: ['string', 'minLength:3', 'maxLength:15']
email: ['string', 'email']
it 'should validate models', co ->
yield [
new User(username: 'bogus').validate().should.be.fulfilled
new User(username: 'bogus', email: 'foobar').validate().should.be.rejected
]
it 'should run validations on save', co ->
spy.on User.prototype, 'validate'
user = new User(username: 'alice')
yield user.save()
user.validate.should.have.been.called()
it "shouldn't apply validation if plugin initialized with option validation: false", co ->
db2 = Bookshelf db.knex
db2.plugin Schema(validation: false)
class User extends db2.Model
tableName: 'users', validations: [ -> false ]
spy.on User.prototype, 'validate'
user = new User(username: 'alice')
yield user.save()
user.validate.should.not.have.been.called()
yield user.validate().should.be.fulfilled
it "shouldn't apply validation when saved with option validation: false", co ->
f = spy -> false
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', validations: [ f ]
]
user = new User(username: 'alice')
yield user.save(null, validation: false)
f.should.not.have.been.called()
it "when patching should accept validation to passed attributes only", co ->
f = spy -> true
g = spy -> true
h = spy -> false
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', validations: [ f ]
StringField 'password', validations: [g]
StringField 'email', validations: [ h ], required: true
]
user = yield User.forge(username: 'alice').save(null, validation: false)
user.email = 'foobar'
yield user.save({username: 'annie', password: 'PI:PASSWORD:<PASSWORD>END_PI'}, {patch: true})
f.should.have.been.called()
g.should.have.been.called()
h.should.not.have.been.called()
f.reset()
g.reset()
try
yield user.save({username: 'annie', password: 'PI:PASSWORD:<PASSWORD>END_PI'}, {patch: false})
catch
# pass
f.should.have.been.called()
g.should.have.been.called()
h.should.have.been.called()
it 'accepts custom validation rules like Checkit do', co ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', validations: [{
rule: 'minLength:5',
message: '{{label}}: foo',
label: 'foo'
}]
]
e = yield new User(username: 'bar').validate().should.be.rejected
e.get('username').message.should.equal 'foo: foo'
describe 'Custom error messages', ->
it 'uses provided messages', co ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'foo', min_length: {value: 10, message: 'foo'}
]
e = yield new User(foo: 'bar').validate().should.be.rejected
e.get('foo').message.should.equal 'foo'
it 'uses field default error message and label', co ->
class User extends db.Model
tableName: 'users'
@schema [
StringField 'username', min_length: 10, message: '{{label}}: foo', label: 'foo'
]
e = yield new User(username: 'bar').validate().should.be.rejected
e.get('username').message.should.equal 'foo: foo'
it 'user field error message and label for field type validation', co ->
class User extends db.Model
tableName: 'users'
@schema [
EmailField 'email', message: '{{label}}: foo', label: 'foo'
]
e = yield new User(email: 'bar').validate().should.be.rejected
e.get('email').message.should.equal 'foo: foo'
it 'can use i18n for messages', co ->
db2 = Bookshelf db.knex
db2.plugin Schema(
language: 'ru',
messages: {email: 'Поле {{label}} должно содержать email-адрес'}
)
class User extends db2.Model
tableName: 'users'
@schema [
EmailField 'email'
]
e = yield new User(email: 'bar').validate().should.be.rejected
e.get('email').message.should.equal 'Поле email должно содержать email-адрес'
|
[
{
"context": "idth]']\n ],\n [[\n key: '.box$12322', values: {'::window[width]': document.documentEl",
"end": 8104,
"score": 0.9984109401702881,
"start": 8093,
"tag": "KEY",
"value": "'.box$12322"
}
] | spec/command.coffee | kevinSuttle/engine | 1,203 | Engine = GSS.Engine #require 'gss-engine/lib/Engine.js'
remove = (el) ->
el.parentNode.removeChild(el)
stringify = JSON.stringify
stringify = (o) -> o
expect = chai.expect
assert = chai.assert
describe 'GSS commands', ->
scope = null
engine = null
beforeEach ->
fixtures = document.getElementById 'fixtures'
scope = document.createElement 'div'
fixtures.appendChild scope
engine = new GSS(scope)
afterEach (done) ->
remove(scope)
engine.destroy()
done()
describe 'when initialized', ->
it 'should be bound to the DOM scope', ->
chai.expect(engine.scope).to.eql scope
describe 'command transformations -', ->
it 'stay with class & static ids', ->
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
engine.solve [
['stay', ['get', ['.','box'], 'x']]
]
chai.expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['stay', ['get', '$12322[x]']]]]
[[key: '.box$34222', ['stay', ['get', '$34222[x]']]]]
]
it 'multiple stays', ->
scope.innerHTML = """
<div class="box block" id="12322">One</div>
<div class="box block" id="34222">One</div>
"""
engine
engine.solve [
['stay', ['get', ['.','box'] , 'x' ]]
['stay', ['get', ['.','box'] , 'y' ]]
['stay', ['get', ['.','block'], 'width']]
]
chai.expect(engine.updated.getProblems()).to.eql [
# break up stays to allow multiple plural queries
[[key: '.box$12322' , ['stay', ['get', '$12322[x]' ]]]]
[[key: '.box$34222' , ['stay', ['get', '$34222[x]' ]]]]
[[key: '.box$12322' , ['stay', ['get', '$12322[y]' ]]]]
[[key: '.box$34222' , ['stay', ['get', '$34222[y]' ]]]]
[[key: '.block$12322', ['stay', ['get', '$12322[width]']]]]
[[key: '.block$34222', ['stay', ['get', '$34222[width]']]]]
]
it 'eq with class and tracker', ->
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
engine.solve [
['==', ['get', ['.','box'], 'width'],['get','grid-col']]
['==', 100,['get','grid-col']]
], '%'
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [[
[key: '%.box$12322', ['==', ['get','$12322[width]'],['get', 'grid-col']]]
[key: '%.box$34222', ['==', ['get','$34222[width]'],['get', 'grid-col']]]
[key: '%', ['==', 100, ['get', 'grid-col']]]
]]
it 'eq with class', ->
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
engine.solve [
['==', ['get',['.','box'],'width'], ['get','grid-col']]
['==', 100, ['get','grid-col']]
]
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [[
[key: '.box$12322', ['==', ['get','$12322[width]'],['get', 'grid-col']]]
[key: '.box$34222', ['==', ['get','$34222[width]'],['get', 'grid-col']]]
[key: '', ['==', 100, ['get', 'grid-col']]]
]]
it 'lte for class & id selectors', (done) ->
window.$engine = engine
engine.solve [
['<=',['get',['.','box'],'width'],['get',['#','box1'],'width']]
], (solution) ->
expect(engine.updated.getProblems()).to.eql [[
[key: '.box$box1→#box1$box1' , ['<=',['get', '$box1[width]' ],['get','$box1[width]']]]
[key: '.box$34222→#box1$box1', ['<=',['get', '$34222[width]'],['get','$box1[width]']]]
[key: '.box$35346→#box1$box1', ['<=',['get', '$35346[width]'],['get','$box1[width]']]]
]]
box2 = engine.id("34222")
box2.parentNode.removeChild(box2)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [
[['remove', '.box$34222'], ['remove', '.box$34222→#box1$box1']]
[['remove', '.box$34222→#box1$box1']]
]
scope.appendChild(box2)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [
[[key: '.box$34222→#box1$box1', ['<=',['get', '$34222[width]'],['get','$box1[width]']]]]
]
box1 = engine.id("box1")
box1.parentNode.removeChild(box1)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [
[
['remove', '#box1'],
['remove', '.box$box1'],
['remove', '.box$box1→#box1$box1'],
['remove', '.box$35346→#box1$box1'],
['remove', '.box$34222→#box1$box1']
]
[['remove', '.box$box1→#box1$box1', '.box$35346→#box1$box1', '.box$34222→#box1$box1']]
]
scope.appendChild(box1)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [[
[key: '.box$35346→#box1$box1', ['<=',['get', '$35346[width]'],['get','$box1[width]']]]
[key: '.box$34222→#box1$box1', ['<=',['get', '$34222[width]'],['get','$box1[width]']]]
[key: '.box$box1→#box1$box1', ['<=',['get', '$box1[width]'],['get','$box1[width]']]]
]]
done()
scope.innerHTML = """
<div class="box" id="box1">One</div>
<div class="box" id="34222">One</div>
<div class="box" id="35346">One</div>
"""
it 'intrinsic-width with class', (done) ->
engine.once 'solve', (solution) ->
engine.solve [
['==',
['get', ['.','box'], 'width'],
['get', ['.','box'], 'intrinsic-width']]
], (solution) ->
chai.expect(stringify engine.updated.getProblems()).to.eql stringify [
[
['get','$12322[intrinsic-width]']
['get','$34222[intrinsic-width]']
['get','$35346[intrinsic-width]']
],
[[
key: '.box$12322', values: {'$12322[intrinsic-width]': 111}
['==',
['get','$12322[width]'],
['get','$12322[intrinsic-width]']
]
]],
[[
key: '.box$34222', values: {'$34222[intrinsic-width]': 222}
['==',
['get','$34222[width]'],
['get','$34222[intrinsic-width]']
]
]],
[[
key: '.box$35346', values: {'$35346[intrinsic-width]': 333}
['==',
['get','$35346[width]'],
['get','$35346[intrinsic-width]']
]
]]
]
expect(solution).to.eql
"$12322[intrinsic-width]": 111
"$12322[width]": 111
"$12322[width]": 111
"$34222[intrinsic-width]": 222
"$34222[width]": 222
"$34222[width]": 222
"$35346[intrinsic-width]": 333
"$35346[width]": 333
"$35346[width]": 333
box0 = scope.getElementsByClassName('box')[0]
box0.parentNode.removeChild(box0)
engine.once 'solve', ->
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [
[["remove",".box$12322"]],
[["remove",".box$12322"]]
]
done()
scope.innerHTML = """
<div style="width:111px;" class="box" id="12322">One</div>
<div style="width:222px;" class="box" id="34222">One</div>
<div style="width:333px;" class="box" id="35346">One</div>
"""
it '.box[width] == ::window[width]', (done) ->
engine.solve [
['==', ['get', ['.','box'], 'width'],['get', ['::window'], 'width']]
]
engine.then ->
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [
[
['get','::window[width]']
],
[[
key: '.box$12322', values: {'::window[width]': document.documentElement.clientWidth}
['==',
['get', '$12322[width]'],
['get', '::window[width]']
]
]]
]
done()
scope.innerHTML = """
<div style="width:111px;" class="box" id="12322">One</div>
"""
it '::window props', ->
scope.innerHTML = """
"""
engine.solve [
['==', ['get', 'xxx'], ['get', ['::window'], 'x' ]]
['<=', ['get', 'yyy'], ['get', ['::window'], 'y' ]]
['<=', ['get', 'yay'], ['get', ['::window'], 'y' ]]
['>=', ['get', 'hhh'], ['get', ['::window'], 'height']]
['>=', ['get', 'hah'], ['get', ['::window'], 'height']]
['<=', ['get', 'www'], ['get', ['::window'], 'width' ]]
]
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [
[
["get", "::window[x]"]
["get", "::window[y]"]
["get", "::window[y]"]
["get", "::window[height]"]
["get", "::window[height]"]
["get", "::window[width]"]
],
[[
key: '', values: {'::window[x]': 0}
['==', ['get', 'xxx'],
['get', '::window[x]']]
]],
[[
key: '', values: {'::window[y]': 0}
['<=', ['get', 'yyy'],
['get', '::window[y]']],
]],
[[
key: '', values: {'::window[y]': 0}
['<=', ['get', 'yay'],
['get', '::window[y]']],
]],
[[
key: '', values: {'::window[height]': Math.min(window.innerHeight, document.documentElement.clientHeight)}
['>=', ['get', 'hhh'],
['get', '::window[height]']]
]],
[[
key: '', values: {'::window[height]': Math.min(window.innerHeight, document.documentElement.clientHeight)}
['>=', ['get', 'hah']
['get', '::window[height]']]
]],
[[
key: '', values: {'::window[width]': document.documentElement.clientWidth}
['<=', ['get', 'www'],
['get', '::window[width]']]
]]
]
#
#
#
describe 'live command spawning -', ->
describe 'adds & removes -', ->
it 'add to class', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['==', ['get','$12322[x]'], 100]]]
[[key: '.box$34222', ['==', ['get','$34222[x]'], 100]]]
]
scope.insertAdjacentHTML('beforeend', '<div class="box" id="35346">One</div>')
else if count is 2
expect(engine.updated.getProblems()).to.eql [
[[key: '.box$35346', ['==', ['get','$35346[x]'], 100]]]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'x'], 100]
]
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
it 'removed from dom', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
chai.expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['==', ['get','$12322[x]'], 100]]]
[[key: '.box$34222', ['==', ['get','$34222[x]'], 100]]]
]
res = engine.id('34222')
res.parentNode.removeChild res
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
[['remove', '.box$34222']]
[['remove', '.box$34222']]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'x'], 100]
]
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
it 'removed from selector', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
chai.expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['==', ['get','$12322[x]',], 100]]]
[[key: '.box$34222', ['==', ['get','$34222[x]',], 100]]]
]
el = engine.id('34222')
el.setAttribute('class', '')
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
[['remove', '.box$34222']]
[['remove', '.box$34222']]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'x'], 100]
]
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
#
#
describe 'resizing -', ->
it 'element resized by style change', (done) ->
count = 0
el = null
listener = (e) ->
count++
if count is 1
el = engine.id('box1')
el.setAttribute('style', "width:1110px")
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1[intrinsic-width]"]
# ["get", "$box1[intrinsic-width]"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 1110},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 1110},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
#chai.expect(engine.values['$box1[intrinsic-width]']).to.equal 1110
chai.expect(engine.values['$box2[height]']).to.equal 1110
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'height'],['get',['#','box1'],'intrinsic-width']]
]
scope.innerHTML = """
<div style="width:111px;" id="box1" class="box" >One</div>
<div style="width:222px;" id="box2" class="box" >One</div>
"""
it 'element resized by inserting child', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
engine.id('box1').innerHTML = "<div style=\"width:111px;\"></div>"
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1", "intrinsic-width", ".box$box1→#box1"]
# ["get", "$box1", "intrinsic-width", ".box$box2→#box1"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'height'],['get',['#','box1'],'intrinsic-width']]
]
scope.innerHTML = """
<div style="display:inline-block;" id="box1" class="box">One</div>
<div style="width:222px;" id="box2" class="box">One</div>
"""
it 'element resized by changing text', (done) ->
count = 0
el = null
listener = (e) ->
count++
if count is 1
el = engine.id('box1')
el.innerHTML = "<div style=\"width:111px;\"></div>"
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1", "intrinsic-width", ".box$box1→#box1"]
# ["get", "$box1", "intrinsic-width", ".box$box2→#box1"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
el.innerHTML = ""
else if count is 3
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1", "intrinsic-width", ".box$box1→#box1"]
# ["get", "$box1", "intrinsic-width", ".box$box2→#box1"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 0},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 0},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'height'],['get',['#','box1'],'intrinsic-width']]
]
scope.innerHTML = """
<div style="display:inline-block" id="box1" class="box" >One</div>
<div style="width:222px;" id="box2" class="box" >One</div>
"""
describe "text measuring", ->
it 'text measuring', (done) ->
count = 0
el = null
listener = (e) ->
count++
if count is 1
# don't set height b/c intrinsic-height was used
expect(engine.id("p-text").style.height).to.eql ""
expect(engine.values["$p-text[width]"]).to.eql 100
expect(engine.values["$p-text[x-height]"] > 400).to.eql true
expect(engine.values["$p-text[x-height]"] % 16).to.eql 0
expect(engine.values["$p-text[x-height]"] % 16).to.eql 0
engine.id("p-text").innerHTML = "Booyaka"
else if count is 2
expect(engine.values["$p-text[width]"]).to.eql 100
expect(engine.values["$p-text[x-height]"]).to.eql(16)
expect(engine.values["$p-text[x-height]"]).to.eql(16)
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['#','p-text'],'width'], 100]
['==', ['get',['#','p-text'],'x-height'], ['get',['#','p-text'],'intrinsic-height']]
]
scope.innerHTML = """
<p id="p-text" style="font-size:16px; line-height:16px; font-family:Helvetica;">Among the sectors most profoundly affected by digitization is the creative sector, which, by the definition of this study, encompasses the industries of book publishing, print publishing, film and television, music, and gaming. The objective of this report is to provide a comprehensive view of the impact digitization has had on the creative sector as a whole, with analyses of its effect on consumers, creators, distributors, and publishers</p>
"""
describe "Chain", ->
it '@chain .box width(+[hgap]*2)', (done) ->
el = null
window.$engine = engine
engine.solve [
['==', ['get','hgap'], 20]
['==', ['get',['#','thing1'],'width'], 100]
[
'rule',
['.', 'thing'],
['=='
['get'
['&'],
'width'],
['+',
['get'
[':previous'],
'width']
['*'
['get', ['^'], 'hgap'],
2
]
]
]
]
]
engine.once 'solve', ->
chai.expect(engine.values["$thing1[width]"]).to.eql 100
chai.expect(engine.values["$thing2[width]"]).to.eql 140
chai.expect(engine.values["$thing3[width]"]).to.eql 180
done()
scope.innerHTML = """
<div id="thing1" class="thing"></div>
<div id="thing2" class="thing"></div>
<div id="thing3" class="thing"></div>
"""
it '@chain .thing right()left', (done) ->
engine.once 'solve', ->
chai.expect(engine.values["$thing1[width]"]).to.eql 100
done()
engine.solve [
['==', ['get',['#','thing1'],'x'], 10]
['==', ['get',['#','thing2'],'x'], 110]
['rule'
['.','thing'],
['=='
['get'
[':previous', ['&']],
'right']
['get'
['&'],
'x']
]
]
]
scope.innerHTML = """
<div id="thing1" class="thing"></div>
<div id="thing2" class="thing"></div>
"""
el = null
| 199064 | Engine = GSS.Engine #require 'gss-engine/lib/Engine.js'
remove = (el) ->
el.parentNode.removeChild(el)
stringify = JSON.stringify
stringify = (o) -> o
expect = chai.expect
assert = chai.assert
describe 'GSS commands', ->
scope = null
engine = null
beforeEach ->
fixtures = document.getElementById 'fixtures'
scope = document.createElement 'div'
fixtures.appendChild scope
engine = new GSS(scope)
afterEach (done) ->
remove(scope)
engine.destroy()
done()
describe 'when initialized', ->
it 'should be bound to the DOM scope', ->
chai.expect(engine.scope).to.eql scope
describe 'command transformations -', ->
it 'stay with class & static ids', ->
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
engine.solve [
['stay', ['get', ['.','box'], 'x']]
]
chai.expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['stay', ['get', '$12322[x]']]]]
[[key: '.box$34222', ['stay', ['get', '$34222[x]']]]]
]
it 'multiple stays', ->
scope.innerHTML = """
<div class="box block" id="12322">One</div>
<div class="box block" id="34222">One</div>
"""
engine
engine.solve [
['stay', ['get', ['.','box'] , 'x' ]]
['stay', ['get', ['.','box'] , 'y' ]]
['stay', ['get', ['.','block'], 'width']]
]
chai.expect(engine.updated.getProblems()).to.eql [
# break up stays to allow multiple plural queries
[[key: '.box$12322' , ['stay', ['get', '$12322[x]' ]]]]
[[key: '.box$34222' , ['stay', ['get', '$34222[x]' ]]]]
[[key: '.box$12322' , ['stay', ['get', '$12322[y]' ]]]]
[[key: '.box$34222' , ['stay', ['get', '$34222[y]' ]]]]
[[key: '.block$12322', ['stay', ['get', '$12322[width]']]]]
[[key: '.block$34222', ['stay', ['get', '$34222[width]']]]]
]
it 'eq with class and tracker', ->
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
engine.solve [
['==', ['get', ['.','box'], 'width'],['get','grid-col']]
['==', 100,['get','grid-col']]
], '%'
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [[
[key: '%.box$12322', ['==', ['get','$12322[width]'],['get', 'grid-col']]]
[key: '%.box$34222', ['==', ['get','$34222[width]'],['get', 'grid-col']]]
[key: '%', ['==', 100, ['get', 'grid-col']]]
]]
it 'eq with class', ->
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
engine.solve [
['==', ['get',['.','box'],'width'], ['get','grid-col']]
['==', 100, ['get','grid-col']]
]
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [[
[key: '.box$12322', ['==', ['get','$12322[width]'],['get', 'grid-col']]]
[key: '.box$34222', ['==', ['get','$34222[width]'],['get', 'grid-col']]]
[key: '', ['==', 100, ['get', 'grid-col']]]
]]
it 'lte for class & id selectors', (done) ->
window.$engine = engine
engine.solve [
['<=',['get',['.','box'],'width'],['get',['#','box1'],'width']]
], (solution) ->
expect(engine.updated.getProblems()).to.eql [[
[key: '.box$box1→#box1$box1' , ['<=',['get', '$box1[width]' ],['get','$box1[width]']]]
[key: '.box$34222→#box1$box1', ['<=',['get', '$34222[width]'],['get','$box1[width]']]]
[key: '.box$35346→#box1$box1', ['<=',['get', '$35346[width]'],['get','$box1[width]']]]
]]
box2 = engine.id("34222")
box2.parentNode.removeChild(box2)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [
[['remove', '.box$34222'], ['remove', '.box$34222→#box1$box1']]
[['remove', '.box$34222→#box1$box1']]
]
scope.appendChild(box2)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [
[[key: '.box$34222→#box1$box1', ['<=',['get', '$34222[width]'],['get','$box1[width]']]]]
]
box1 = engine.id("box1")
box1.parentNode.removeChild(box1)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [
[
['remove', '#box1'],
['remove', '.box$box1'],
['remove', '.box$box1→#box1$box1'],
['remove', '.box$35346→#box1$box1'],
['remove', '.box$34222→#box1$box1']
]
[['remove', '.box$box1→#box1$box1', '.box$35346→#box1$box1', '.box$34222→#box1$box1']]
]
scope.appendChild(box1)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [[
[key: '.box$35346→#box1$box1', ['<=',['get', '$35346[width]'],['get','$box1[width]']]]
[key: '.box$34222→#box1$box1', ['<=',['get', '$34222[width]'],['get','$box1[width]']]]
[key: '.box$box1→#box1$box1', ['<=',['get', '$box1[width]'],['get','$box1[width]']]]
]]
done()
scope.innerHTML = """
<div class="box" id="box1">One</div>
<div class="box" id="34222">One</div>
<div class="box" id="35346">One</div>
"""
it 'intrinsic-width with class', (done) ->
engine.once 'solve', (solution) ->
engine.solve [
['==',
['get', ['.','box'], 'width'],
['get', ['.','box'], 'intrinsic-width']]
], (solution) ->
chai.expect(stringify engine.updated.getProblems()).to.eql stringify [
[
['get','$12322[intrinsic-width]']
['get','$34222[intrinsic-width]']
['get','$35346[intrinsic-width]']
],
[[
key: '.box$12322', values: {'$12322[intrinsic-width]': 111}
['==',
['get','$12322[width]'],
['get','$12322[intrinsic-width]']
]
]],
[[
key: '.box$34222', values: {'$34222[intrinsic-width]': 222}
['==',
['get','$34222[width]'],
['get','$34222[intrinsic-width]']
]
]],
[[
key: '.box$35346', values: {'$35346[intrinsic-width]': 333}
['==',
['get','$35346[width]'],
['get','$35346[intrinsic-width]']
]
]]
]
expect(solution).to.eql
"$12322[intrinsic-width]": 111
"$12322[width]": 111
"$12322[width]": 111
"$34222[intrinsic-width]": 222
"$34222[width]": 222
"$34222[width]": 222
"$35346[intrinsic-width]": 333
"$35346[width]": 333
"$35346[width]": 333
box0 = scope.getElementsByClassName('box')[0]
box0.parentNode.removeChild(box0)
engine.once 'solve', ->
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [
[["remove",".box$12322"]],
[["remove",".box$12322"]]
]
done()
scope.innerHTML = """
<div style="width:111px;" class="box" id="12322">One</div>
<div style="width:222px;" class="box" id="34222">One</div>
<div style="width:333px;" class="box" id="35346">One</div>
"""
it '.box[width] == ::window[width]', (done) ->
engine.solve [
['==', ['get', ['.','box'], 'width'],['get', ['::window'], 'width']]
]
engine.then ->
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [
[
['get','::window[width]']
],
[[
key: <KEY>', values: {'::window[width]': document.documentElement.clientWidth}
['==',
['get', '$12322[width]'],
['get', '::window[width]']
]
]]
]
done()
scope.innerHTML = """
<div style="width:111px;" class="box" id="12322">One</div>
"""
it '::window props', ->
scope.innerHTML = """
"""
engine.solve [
['==', ['get', 'xxx'], ['get', ['::window'], 'x' ]]
['<=', ['get', 'yyy'], ['get', ['::window'], 'y' ]]
['<=', ['get', 'yay'], ['get', ['::window'], 'y' ]]
['>=', ['get', 'hhh'], ['get', ['::window'], 'height']]
['>=', ['get', 'hah'], ['get', ['::window'], 'height']]
['<=', ['get', 'www'], ['get', ['::window'], 'width' ]]
]
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [
[
["get", "::window[x]"]
["get", "::window[y]"]
["get", "::window[y]"]
["get", "::window[height]"]
["get", "::window[height]"]
["get", "::window[width]"]
],
[[
key: '', values: {'::window[x]': 0}
['==', ['get', 'xxx'],
['get', '::window[x]']]
]],
[[
key: '', values: {'::window[y]': 0}
['<=', ['get', 'yyy'],
['get', '::window[y]']],
]],
[[
key: '', values: {'::window[y]': 0}
['<=', ['get', 'yay'],
['get', '::window[y]']],
]],
[[
key: '', values: {'::window[height]': Math.min(window.innerHeight, document.documentElement.clientHeight)}
['>=', ['get', 'hhh'],
['get', '::window[height]']]
]],
[[
key: '', values: {'::window[height]': Math.min(window.innerHeight, document.documentElement.clientHeight)}
['>=', ['get', 'hah']
['get', '::window[height]']]
]],
[[
key: '', values: {'::window[width]': document.documentElement.clientWidth}
['<=', ['get', 'www'],
['get', '::window[width]']]
]]
]
#
#
#
describe 'live command spawning -', ->
describe 'adds & removes -', ->
it 'add to class', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['==', ['get','$12322[x]'], 100]]]
[[key: '.box$34222', ['==', ['get','$34222[x]'], 100]]]
]
scope.insertAdjacentHTML('beforeend', '<div class="box" id="35346">One</div>')
else if count is 2
expect(engine.updated.getProblems()).to.eql [
[[key: '.box$35346', ['==', ['get','$35346[x]'], 100]]]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'x'], 100]
]
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
it 'removed from dom', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
chai.expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['==', ['get','$12322[x]'], 100]]]
[[key: '.box$34222', ['==', ['get','$34222[x]'], 100]]]
]
res = engine.id('34222')
res.parentNode.removeChild res
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
[['remove', '.box$34222']]
[['remove', '.box$34222']]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'x'], 100]
]
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
it 'removed from selector', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
chai.expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['==', ['get','$12322[x]',], 100]]]
[[key: '.box$34222', ['==', ['get','$34222[x]',], 100]]]
]
el = engine.id('34222')
el.setAttribute('class', '')
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
[['remove', '.box$34222']]
[['remove', '.box$34222']]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'x'], 100]
]
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
#
#
describe 'resizing -', ->
it 'element resized by style change', (done) ->
count = 0
el = null
listener = (e) ->
count++
if count is 1
el = engine.id('box1')
el.setAttribute('style', "width:1110px")
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1[intrinsic-width]"]
# ["get", "$box1[intrinsic-width]"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 1110},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 1110},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
#chai.expect(engine.values['$box1[intrinsic-width]']).to.equal 1110
chai.expect(engine.values['$box2[height]']).to.equal 1110
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'height'],['get',['#','box1'],'intrinsic-width']]
]
scope.innerHTML = """
<div style="width:111px;" id="box1" class="box" >One</div>
<div style="width:222px;" id="box2" class="box" >One</div>
"""
it 'element resized by inserting child', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
engine.id('box1').innerHTML = "<div style=\"width:111px;\"></div>"
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1", "intrinsic-width", ".box$box1→#box1"]
# ["get", "$box1", "intrinsic-width", ".box$box2→#box1"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'height'],['get',['#','box1'],'intrinsic-width']]
]
scope.innerHTML = """
<div style="display:inline-block;" id="box1" class="box">One</div>
<div style="width:222px;" id="box2" class="box">One</div>
"""
it 'element resized by changing text', (done) ->
count = 0
el = null
listener = (e) ->
count++
if count is 1
el = engine.id('box1')
el.innerHTML = "<div style=\"width:111px;\"></div>"
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1", "intrinsic-width", ".box$box1→#box1"]
# ["get", "$box1", "intrinsic-width", ".box$box2→#box1"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
el.innerHTML = ""
else if count is 3
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1", "intrinsic-width", ".box$box1→#box1"]
# ["get", "$box1", "intrinsic-width", ".box$box2→#box1"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 0},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 0},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'height'],['get',['#','box1'],'intrinsic-width']]
]
scope.innerHTML = """
<div style="display:inline-block" id="box1" class="box" >One</div>
<div style="width:222px;" id="box2" class="box" >One</div>
"""
describe "text measuring", ->
it 'text measuring', (done) ->
count = 0
el = null
listener = (e) ->
count++
if count is 1
# don't set height b/c intrinsic-height was used
expect(engine.id("p-text").style.height).to.eql ""
expect(engine.values["$p-text[width]"]).to.eql 100
expect(engine.values["$p-text[x-height]"] > 400).to.eql true
expect(engine.values["$p-text[x-height]"] % 16).to.eql 0
expect(engine.values["$p-text[x-height]"] % 16).to.eql 0
engine.id("p-text").innerHTML = "Booyaka"
else if count is 2
expect(engine.values["$p-text[width]"]).to.eql 100
expect(engine.values["$p-text[x-height]"]).to.eql(16)
expect(engine.values["$p-text[x-height]"]).to.eql(16)
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['#','p-text'],'width'], 100]
['==', ['get',['#','p-text'],'x-height'], ['get',['#','p-text'],'intrinsic-height']]
]
scope.innerHTML = """
<p id="p-text" style="font-size:16px; line-height:16px; font-family:Helvetica;">Among the sectors most profoundly affected by digitization is the creative sector, which, by the definition of this study, encompasses the industries of book publishing, print publishing, film and television, music, and gaming. The objective of this report is to provide a comprehensive view of the impact digitization has had on the creative sector as a whole, with analyses of its effect on consumers, creators, distributors, and publishers</p>
"""
describe "Chain", ->
it '@chain .box width(+[hgap]*2)', (done) ->
el = null
window.$engine = engine
engine.solve [
['==', ['get','hgap'], 20]
['==', ['get',['#','thing1'],'width'], 100]
[
'rule',
['.', 'thing'],
['=='
['get'
['&'],
'width'],
['+',
['get'
[':previous'],
'width']
['*'
['get', ['^'], 'hgap'],
2
]
]
]
]
]
engine.once 'solve', ->
chai.expect(engine.values["$thing1[width]"]).to.eql 100
chai.expect(engine.values["$thing2[width]"]).to.eql 140
chai.expect(engine.values["$thing3[width]"]).to.eql 180
done()
scope.innerHTML = """
<div id="thing1" class="thing"></div>
<div id="thing2" class="thing"></div>
<div id="thing3" class="thing"></div>
"""
it '@chain .thing right()left', (done) ->
engine.once 'solve', ->
chai.expect(engine.values["$thing1[width]"]).to.eql 100
done()
engine.solve [
['==', ['get',['#','thing1'],'x'], 10]
['==', ['get',['#','thing2'],'x'], 110]
['rule'
['.','thing'],
['=='
['get'
[':previous', ['&']],
'right']
['get'
['&'],
'x']
]
]
]
scope.innerHTML = """
<div id="thing1" class="thing"></div>
<div id="thing2" class="thing"></div>
"""
el = null
| true | Engine = GSS.Engine #require 'gss-engine/lib/Engine.js'
remove = (el) ->
el.parentNode.removeChild(el)
stringify = JSON.stringify
stringify = (o) -> o
expect = chai.expect
assert = chai.assert
describe 'GSS commands', ->
scope = null
engine = null
beforeEach ->
fixtures = document.getElementById 'fixtures'
scope = document.createElement 'div'
fixtures.appendChild scope
engine = new GSS(scope)
afterEach (done) ->
remove(scope)
engine.destroy()
done()
describe 'when initialized', ->
it 'should be bound to the DOM scope', ->
chai.expect(engine.scope).to.eql scope
describe 'command transformations -', ->
it 'stay with class & static ids', ->
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
engine.solve [
['stay', ['get', ['.','box'], 'x']]
]
chai.expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['stay', ['get', '$12322[x]']]]]
[[key: '.box$34222', ['stay', ['get', '$34222[x]']]]]
]
it 'multiple stays', ->
scope.innerHTML = """
<div class="box block" id="12322">One</div>
<div class="box block" id="34222">One</div>
"""
engine
engine.solve [
['stay', ['get', ['.','box'] , 'x' ]]
['stay', ['get', ['.','box'] , 'y' ]]
['stay', ['get', ['.','block'], 'width']]
]
chai.expect(engine.updated.getProblems()).to.eql [
# break up stays to allow multiple plural queries
[[key: '.box$12322' , ['stay', ['get', '$12322[x]' ]]]]
[[key: '.box$34222' , ['stay', ['get', '$34222[x]' ]]]]
[[key: '.box$12322' , ['stay', ['get', '$12322[y]' ]]]]
[[key: '.box$34222' , ['stay', ['get', '$34222[y]' ]]]]
[[key: '.block$12322', ['stay', ['get', '$12322[width]']]]]
[[key: '.block$34222', ['stay', ['get', '$34222[width]']]]]
]
it 'eq with class and tracker', ->
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
engine.solve [
['==', ['get', ['.','box'], 'width'],['get','grid-col']]
['==', 100,['get','grid-col']]
], '%'
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [[
[key: '%.box$12322', ['==', ['get','$12322[width]'],['get', 'grid-col']]]
[key: '%.box$34222', ['==', ['get','$34222[width]'],['get', 'grid-col']]]
[key: '%', ['==', 100, ['get', 'grid-col']]]
]]
it 'eq with class', ->
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
engine.solve [
['==', ['get',['.','box'],'width'], ['get','grid-col']]
['==', 100, ['get','grid-col']]
]
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [[
[key: '.box$12322', ['==', ['get','$12322[width]'],['get', 'grid-col']]]
[key: '.box$34222', ['==', ['get','$34222[width]'],['get', 'grid-col']]]
[key: '', ['==', 100, ['get', 'grid-col']]]
]]
it 'lte for class & id selectors', (done) ->
window.$engine = engine
engine.solve [
['<=',['get',['.','box'],'width'],['get',['#','box1'],'width']]
], (solution) ->
expect(engine.updated.getProblems()).to.eql [[
[key: '.box$box1→#box1$box1' , ['<=',['get', '$box1[width]' ],['get','$box1[width]']]]
[key: '.box$34222→#box1$box1', ['<=',['get', '$34222[width]'],['get','$box1[width]']]]
[key: '.box$35346→#box1$box1', ['<=',['get', '$35346[width]'],['get','$box1[width]']]]
]]
box2 = engine.id("34222")
box2.parentNode.removeChild(box2)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [
[['remove', '.box$34222'], ['remove', '.box$34222→#box1$box1']]
[['remove', '.box$34222→#box1$box1']]
]
scope.appendChild(box2)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [
[[key: '.box$34222→#box1$box1', ['<=',['get', '$34222[width]'],['get','$box1[width]']]]]
]
box1 = engine.id("box1")
box1.parentNode.removeChild(box1)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [
[
['remove', '#box1'],
['remove', '.box$box1'],
['remove', '.box$box1→#box1$box1'],
['remove', '.box$35346→#box1$box1'],
['remove', '.box$34222→#box1$box1']
]
[['remove', '.box$box1→#box1$box1', '.box$35346→#box1$box1', '.box$34222→#box1$box1']]
]
scope.appendChild(box1)
engine.then (solution) ->
expect(engine.updated.getProblems()).to.eql [[
[key: '.box$35346→#box1$box1', ['<=',['get', '$35346[width]'],['get','$box1[width]']]]
[key: '.box$34222→#box1$box1', ['<=',['get', '$34222[width]'],['get','$box1[width]']]]
[key: '.box$box1→#box1$box1', ['<=',['get', '$box1[width]'],['get','$box1[width]']]]
]]
done()
scope.innerHTML = """
<div class="box" id="box1">One</div>
<div class="box" id="34222">One</div>
<div class="box" id="35346">One</div>
"""
it 'intrinsic-width with class', (done) ->
engine.once 'solve', (solution) ->
engine.solve [
['==',
['get', ['.','box'], 'width'],
['get', ['.','box'], 'intrinsic-width']]
], (solution) ->
chai.expect(stringify engine.updated.getProblems()).to.eql stringify [
[
['get','$12322[intrinsic-width]']
['get','$34222[intrinsic-width]']
['get','$35346[intrinsic-width]']
],
[[
key: '.box$12322', values: {'$12322[intrinsic-width]': 111}
['==',
['get','$12322[width]'],
['get','$12322[intrinsic-width]']
]
]],
[[
key: '.box$34222', values: {'$34222[intrinsic-width]': 222}
['==',
['get','$34222[width]'],
['get','$34222[intrinsic-width]']
]
]],
[[
key: '.box$35346', values: {'$35346[intrinsic-width]': 333}
['==',
['get','$35346[width]'],
['get','$35346[intrinsic-width]']
]
]]
]
expect(solution).to.eql
"$12322[intrinsic-width]": 111
"$12322[width]": 111
"$12322[width]": 111
"$34222[intrinsic-width]": 222
"$34222[width]": 222
"$34222[width]": 222
"$35346[intrinsic-width]": 333
"$35346[width]": 333
"$35346[width]": 333
box0 = scope.getElementsByClassName('box')[0]
box0.parentNode.removeChild(box0)
engine.once 'solve', ->
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [
[["remove",".box$12322"]],
[["remove",".box$12322"]]
]
done()
scope.innerHTML = """
<div style="width:111px;" class="box" id="12322">One</div>
<div style="width:222px;" class="box" id="34222">One</div>
<div style="width:333px;" class="box" id="35346">One</div>
"""
it '.box[width] == ::window[width]', (done) ->
engine.solve [
['==', ['get', ['.','box'], 'width'],['get', ['::window'], 'width']]
]
engine.then ->
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [
[
['get','::window[width]']
],
[[
key: PI:KEY:<KEY>END_PI', values: {'::window[width]': document.documentElement.clientWidth}
['==',
['get', '$12322[width]'],
['get', '::window[width]']
]
]]
]
done()
scope.innerHTML = """
<div style="width:111px;" class="box" id="12322">One</div>
"""
it '::window props', ->
scope.innerHTML = """
"""
engine.solve [
['==', ['get', 'xxx'], ['get', ['::window'], 'x' ]]
['<=', ['get', 'yyy'], ['get', ['::window'], 'y' ]]
['<=', ['get', 'yay'], ['get', ['::window'], 'y' ]]
['>=', ['get', 'hhh'], ['get', ['::window'], 'height']]
['>=', ['get', 'hah'], ['get', ['::window'], 'height']]
['<=', ['get', 'www'], ['get', ['::window'], 'width' ]]
]
chai.expect(stringify(engine.updated.getProblems())).to.eql stringify [
[
["get", "::window[x]"]
["get", "::window[y]"]
["get", "::window[y]"]
["get", "::window[height]"]
["get", "::window[height]"]
["get", "::window[width]"]
],
[[
key: '', values: {'::window[x]': 0}
['==', ['get', 'xxx'],
['get', '::window[x]']]
]],
[[
key: '', values: {'::window[y]': 0}
['<=', ['get', 'yyy'],
['get', '::window[y]']],
]],
[[
key: '', values: {'::window[y]': 0}
['<=', ['get', 'yay'],
['get', '::window[y]']],
]],
[[
key: '', values: {'::window[height]': Math.min(window.innerHeight, document.documentElement.clientHeight)}
['>=', ['get', 'hhh'],
['get', '::window[height]']]
]],
[[
key: '', values: {'::window[height]': Math.min(window.innerHeight, document.documentElement.clientHeight)}
['>=', ['get', 'hah']
['get', '::window[height]']]
]],
[[
key: '', values: {'::window[width]': document.documentElement.clientWidth}
['<=', ['get', 'www'],
['get', '::window[width]']]
]]
]
#
#
#
describe 'live command spawning -', ->
describe 'adds & removes -', ->
it 'add to class', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['==', ['get','$12322[x]'], 100]]]
[[key: '.box$34222', ['==', ['get','$34222[x]'], 100]]]
]
scope.insertAdjacentHTML('beforeend', '<div class="box" id="35346">One</div>')
else if count is 2
expect(engine.updated.getProblems()).to.eql [
[[key: '.box$35346', ['==', ['get','$35346[x]'], 100]]]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'x'], 100]
]
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
it 'removed from dom', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
chai.expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['==', ['get','$12322[x]'], 100]]]
[[key: '.box$34222', ['==', ['get','$34222[x]'], 100]]]
]
res = engine.id('34222')
res.parentNode.removeChild res
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
[['remove', '.box$34222']]
[['remove', '.box$34222']]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'x'], 100]
]
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
it 'removed from selector', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
chai.expect(engine.updated.getProblems()).to.eql [
[[key: '.box$12322', ['==', ['get','$12322[x]',], 100]]]
[[key: '.box$34222', ['==', ['get','$34222[x]',], 100]]]
]
el = engine.id('34222')
el.setAttribute('class', '')
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
[['remove', '.box$34222']]
[['remove', '.box$34222']]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'x'], 100]
]
scope.innerHTML = """
<div class="box" id="12322">One</div>
<div class="box" id="34222">One</div>
"""
#
#
describe 'resizing -', ->
it 'element resized by style change', (done) ->
count = 0
el = null
listener = (e) ->
count++
if count is 1
el = engine.id('box1')
el.setAttribute('style', "width:1110px")
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1[intrinsic-width]"]
# ["get", "$box1[intrinsic-width]"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 1110},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 1110},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
#chai.expect(engine.values['$box1[intrinsic-width]']).to.equal 1110
chai.expect(engine.values['$box2[height]']).to.equal 1110
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'height'],['get',['#','box1'],'intrinsic-width']]
]
scope.innerHTML = """
<div style="width:111px;" id="box1" class="box" >One</div>
<div style="width:222px;" id="box2" class="box" >One</div>
"""
it 'element resized by inserting child', (done) ->
count = 0
listener = (e) ->
count++
if count is 1
engine.id('box1').innerHTML = "<div style=\"width:111px;\"></div>"
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1", "intrinsic-width", ".box$box1→#box1"]
# ["get", "$box1", "intrinsic-width", ".box$box2→#box1"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'height'],['get',['#','box1'],'intrinsic-width']]
]
scope.innerHTML = """
<div style="display:inline-block;" id="box1" class="box">One</div>
<div style="width:222px;" id="box2" class="box">One</div>
"""
it 'element resized by changing text', (done) ->
count = 0
el = null
listener = (e) ->
count++
if count is 1
el = engine.id('box1')
el.innerHTML = "<div style=\"width:111px;\"></div>"
else if count is 2
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1", "intrinsic-width", ".box$box1→#box1"]
# ["get", "$box1", "intrinsic-width", ".box$box2→#box1"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 111},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
el.innerHTML = ""
else if count is 3
chai.expect(engine.updated.getProblems()).to.eql [
#[
# ["get", "$box1", "intrinsic-width", ".box$box1→#box1"]
# ["get", "$box1", "intrinsic-width", ".box$box2→#box1"]
#],
[[
key: ".box$box1→#box1$box1", values: {"$box1[intrinsic-width]": 0},
["==",
["get", "$box1[height]"]
["get", "$box1[intrinsic-width]"]
]
]],
[[
key: ".box$box2→#box1$box1", values: {"$box1[intrinsic-width]": 0},
["==",
["get", "$box2[height]"]
["get", "$box1[intrinsic-width]"]
]
]]
]
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['.','box'],'height'],['get',['#','box1'],'intrinsic-width']]
]
scope.innerHTML = """
<div style="display:inline-block" id="box1" class="box" >One</div>
<div style="width:222px;" id="box2" class="box" >One</div>
"""
describe "text measuring", ->
it 'text measuring', (done) ->
count = 0
el = null
listener = (e) ->
count++
if count is 1
# don't set height b/c intrinsic-height was used
expect(engine.id("p-text").style.height).to.eql ""
expect(engine.values["$p-text[width]"]).to.eql 100
expect(engine.values["$p-text[x-height]"] > 400).to.eql true
expect(engine.values["$p-text[x-height]"] % 16).to.eql 0
expect(engine.values["$p-text[x-height]"] % 16).to.eql 0
engine.id("p-text").innerHTML = "Booyaka"
else if count is 2
expect(engine.values["$p-text[width]"]).to.eql 100
expect(engine.values["$p-text[x-height]"]).to.eql(16)
expect(engine.values["$p-text[x-height]"]).to.eql(16)
engine.removeEventListener 'solve', listener
done()
engine.addEventListener 'solve', listener
engine.solve [
['==', ['get',['#','p-text'],'width'], 100]
['==', ['get',['#','p-text'],'x-height'], ['get',['#','p-text'],'intrinsic-height']]
]
scope.innerHTML = """
<p id="p-text" style="font-size:16px; line-height:16px; font-family:Helvetica;">Among the sectors most profoundly affected by digitization is the creative sector, which, by the definition of this study, encompasses the industries of book publishing, print publishing, film and television, music, and gaming. The objective of this report is to provide a comprehensive view of the impact digitization has had on the creative sector as a whole, with analyses of its effect on consumers, creators, distributors, and publishers</p>
"""
describe "Chain", ->
it '@chain .box width(+[hgap]*2)', (done) ->
el = null
window.$engine = engine
engine.solve [
['==', ['get','hgap'], 20]
['==', ['get',['#','thing1'],'width'], 100]
[
'rule',
['.', 'thing'],
['=='
['get'
['&'],
'width'],
['+',
['get'
[':previous'],
'width']
['*'
['get', ['^'], 'hgap'],
2
]
]
]
]
]
engine.once 'solve', ->
chai.expect(engine.values["$thing1[width]"]).to.eql 100
chai.expect(engine.values["$thing2[width]"]).to.eql 140
chai.expect(engine.values["$thing3[width]"]).to.eql 180
done()
scope.innerHTML = """
<div id="thing1" class="thing"></div>
<div id="thing2" class="thing"></div>
<div id="thing3" class="thing"></div>
"""
it '@chain .thing right()left', (done) ->
engine.once 'solve', ->
chai.expect(engine.values["$thing1[width]"]).to.eql 100
done()
engine.solve [
['==', ['get',['#','thing1'],'x'], 10]
['==', ['get',['#','thing2'],'x'], 110]
['rule'
['.','thing'],
['=='
['get'
[':previous', ['&']],
'right']
['get'
['&'],
'x']
]
]
]
scope.innerHTML = """
<div id="thing1" class="thing"></div>
<div id="thing2" class="thing"></div>
"""
el = null
|
[
{
"context": " 5000 if @isIPadApp() # if me.displayName() is 'Nick'\n\n initVolume: ->\n volume = me.get('volume')\n",
"end": 11147,
"score": 0.986789882183075,
"start": 11143,
"tag": "NAME",
"value": "Nick"
},
{
"context": "ion.get('team')] = session.get('creatorName') or 'Anoner'\n playerNames\n\n # Once Surface is Loaded ",
"end": 15197,
"score": 0.6587435007095337,
"start": 15195,
"tag": "USERNAME",
"value": "An"
},
{
"context": "n.get('team')] = session.get('creatorName') or 'Anoner'\n playerNames\n\n # Once Surface is Loaded ####",
"end": 15201,
"score": 0.6915502548217773,
"start": 15197,
"tag": "NAME",
"value": "oner"
},
{
"context": "ID?\n # TODO: Wait for name instead of using 'Anon', or try and update it later?\n name = me.get",
"end": 27641,
"score": 0.9640869498252869,
"start": 27637,
"tag": "NAME",
"value": "Anon"
},
{
"context": " = me.get('name') ? session.get('creatorName') ? 'Anon'\n @realTimePlayerRef.set\n id: me.id #",
"end": 27736,
"score": 0.9930260181427002,
"start": 27732,
"tag": "NAME",
"value": "Anon"
}
] | app/views/play/level/PlayLevelView.coffee | pougounias/codecombat | 0 | RootView = require 'views/core/RootView'
template = require 'templates/play/level'
{me} = require 'core/auth'
ThangType = require 'models/ThangType'
utils = require 'core/utils'
storage = require 'core/storage'
{createAetherOptions} = require 'lib/aether_utils'
# tools
Surface = require 'lib/surface/Surface'
God = require 'lib/God'
GoalManager = require 'lib/world/GoalManager'
ScriptManager = require 'lib/scripts/ScriptManager'
LevelBus = require 'lib/LevelBus'
LevelLoader = require 'lib/LevelLoader'
LevelSession = require 'models/LevelSession'
Level = require 'models/Level'
LevelComponent = require 'models/LevelComponent'
Article = require 'models/Article'
Camera = require 'lib/surface/Camera'
AudioPlayer = require 'lib/AudioPlayer'
# subviews
LevelLoadingView = require './LevelLoadingView'
ProblemAlertView = require './tome/ProblemAlertView'
TomeView = require './tome/TomeView'
ChatView = require './LevelChatView'
HUDView = require './LevelHUDView'
LevelDialogueView = require './LevelDialogueView'
ControlBarView = require './ControlBarView'
LevelPlaybackView = require './LevelPlaybackView'
GoalsView = require './LevelGoalsView'
LevelFlagsView = require './LevelFlagsView'
GoldView = require './LevelGoldView'
VictoryModal = require './modal/VictoryModal'
HeroVictoryModal = require './modal/HeroVictoryModal'
InfiniteLoopModal = require './modal/InfiniteLoopModal'
LevelSetupManager = require 'lib/LevelSetupManager'
ContactModal = require 'views/core/ContactModal'
PROFILE_ME = false
module.exports = class PlayLevelView extends RootView
id: 'level-view'
template: template
cache: false
shortcutsEnabled: true
isEditorPreview: false
subscriptions:
'level:set-volume': (e) -> createjs.Sound.setVolume(if e.volume is 1 then 0.6 else e.volume) # Quieter for now until individual sound FX controls work again.
'level:show-victory': 'onShowVictory'
'level:restart': 'onRestartLevel'
'level:highlight-dom': 'onHighlightDOM'
'level:end-highlight-dom': 'onEndHighlight'
'level:focus-dom': 'onFocusDom'
'level:disable-controls': 'onDisableControls'
'level:enable-controls': 'onEnableControls'
'god:world-load-progress-changed': 'onWorldLoadProgressChanged'
'god:new-world-created': 'onNewWorld'
'god:streaming-world-updated': 'onNewWorld'
'god:infinite-loop': 'onInfiniteLoop'
'level:reload-from-data': 'onLevelReloadFromData'
'level:reload-thang-type': 'onLevelReloadThangType'
'level:session-will-save': 'onSessionWillSave'
'level:started': 'onLevelStarted'
'level:loading-view-unveiling': 'onLoadingViewUnveiling'
'level:loading-view-unveiled': 'onLoadingViewUnveiled'
'level:session-loaded': 'onSessionLoaded'
'playback:real-time-playback-waiting': 'onRealTimePlaybackWaiting'
'playback:real-time-playback-started': 'onRealTimePlaybackStarted'
'playback:real-time-playback-ended': 'onRealTimePlaybackEnded'
'real-time-multiplayer:created-game': 'onRealTimeMultiplayerCreatedGame'
'real-time-multiplayer:joined-game': 'onRealTimeMultiplayerJoinedGame'
'real-time-multiplayer:left-game': 'onRealTimeMultiplayerLeftGame'
'real-time-multiplayer:manual-cast': 'onRealTimeMultiplayerCast'
'ipad:memory-warning': 'onIPadMemoryWarning'
'store:item-purchased': 'onItemPurchased'
events:
'click #level-done-button': 'onDonePressed'
'click #stop-real-time-playback-button': -> Backbone.Mediator.publish 'playback:stop-real-time-playback', {}
'click #fullscreen-editor-background-screen': (e) -> Backbone.Mediator.publish 'tome:toggle-maximize', {}
'click .contact-link': 'onContactClicked'
shortcuts:
'ctrl+s': 'onCtrlS'
'esc': 'onEscapePressed'
# Initial Setup #############################################################
constructor: (options, @levelID) ->
console.profile?() if PROFILE_ME
super options
@isEditorPreview = @getQueryVariable 'dev'
@sessionID = @getQueryVariable 'session'
@observing = @getQueryVariable 'observing'
@opponentSessionID = @getQueryVariable('opponent')
@opponentSessionID ?= @options.opponent
$(window).on 'resize', @onWindowResize
@saveScreenshot = _.throttle @saveScreenshot, 30000
if @isEditorPreview
@supermodel.shouldSaveBackups = (model) -> # Make sure to load possibly changed things from localStorage.
model.constructor.className in ['Level', 'LevelComponent', 'LevelSystem', 'ThangType']
f = => @load() unless @levelLoader # Wait to see if it's just given to us through setLevel.
setTimeout f, 100
else
@load()
application.tracker?.trackEvent 'Started Level Load', category: 'Play Level', level: @levelID, label: @levelID unless @observing
setLevel: (@level, givenSupermodel) ->
@supermodel.models = givenSupermodel.models
@supermodel.collections = givenSupermodel.collections
@supermodel.shouldSaveBackups = givenSupermodel.shouldSaveBackups
serializedLevel = @level.serialize @supermodel, @session, @otherSession
@god?.setLevel serializedLevel
if @world
@world.loadFromLevel serializedLevel, false
else
@load()
load: ->
@loadStartTime = new Date()
@god = new God debugWorker: true
@levelLoader = new LevelLoader supermodel: @supermodel, levelID: @levelID, sessionID: @sessionID, opponentSessionID: @opponentSessionID, team: @getQueryVariable('team'), observing: @observing
@listenToOnce @levelLoader, 'world-necessities-loaded', @onWorldNecessitiesLoaded
trackLevelLoadEnd: ->
return if @isEditorPreview
@loadEndTime = new Date()
loadDuration = @loadEndTime - @loadStartTime
console.debug "Level unveiled after #{(loadDuration / 1000).toFixed(2)}s"
unless @observing
application.tracker?.trackEvent 'Finished Level Load', category: 'Play Level', label: @levelID, level: @levelID, loadDuration: loadDuration
application.tracker?.trackTiming loadDuration, 'Level Load Time', @levelID, @levelID
# CocoView overridden methods ###############################################
getRenderData: ->
c = super()
c.world = @world
c
afterRender: ->
super()
window.onPlayLevelViewLoaded? @ # still a hack
@insertSubView @loadingView = new LevelLoadingView autoUnveil: @options.autoUnveil or @observing, level: @levelLoader?.level ? @level # May not have @level loaded yet
@$el.find('#level-done-button').hide()
$('body').addClass('is-playing')
$('body').bind('touchmove', false) if @isIPadApp()
afterInsert: ->
super()
# Partially Loaded Setup ####################################################
onWorldNecessitiesLoaded: ->
# Called when we have enough to build the world, but not everything is loaded
@grabLevelLoaderData()
team = @getQueryVariable('team') ? @session.get('team') ? @world.teamForPlayer(0)
@loadOpponentTeam(team)
@setupGod()
@setTeam team
@initGoalManager()
@insertSubviews()
@initVolume()
@listenTo(@session, 'change:multiplayer', @onMultiplayerChanged)
@originalSessionState = $.extend(true, {}, @session.get('state'))
@register()
@controlBar.setBus(@bus)
@initScriptManager()
grabLevelLoaderData: ->
@session = @levelLoader.session
@world = @levelLoader.world
@level = @levelLoader.level
@$el.addClass 'hero' if @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']
@$el.addClass 'flags' if _.any(@world.thangs, (t) -> (t.programmableProperties and 'findFlags' in t.programmableProperties) or t.inventory?.flag) or @level.get('slug') is 'sky-span'
# TODO: Update terminology to always be opponentSession or otherSession
# TODO: E.g. if it's always opponent right now, then variable names should be opponentSession until we have coop play
@otherSession = @levelLoader.opponentSession
@worldLoadFakeResources = [] # first element (0) is 1%, last (100) is 100%
for percent in [1 .. 100]
@worldLoadFakeResources.push @supermodel.addSomethingResource "world_simulation_#{percent}%", 1
onWorldLoadProgressChanged: (e) ->
return unless @worldLoadFakeResources
@lastWorldLoadPercent ?= 0
worldLoadPercent = Math.floor 100 * e.progress
for percent in [@lastWorldLoadPercent + 1 .. worldLoadPercent] by 1
@worldLoadFakeResources[percent - 1].markLoaded()
@lastWorldLoadPercent = worldLoadPercent
@worldFakeLoadResources = null if worldLoadPercent is 100 # Done, don't need to watch progress any more.
loadOpponentTeam: (myTeam) ->
opponentSpells = []
for spellTeam, spells of @session.get('teamSpells') ? @otherSession?.get('teamSpells') ? {}
continue if spellTeam is myTeam or not myTeam
opponentSpells = opponentSpells.concat spells
if (not @session.get('teamSpells')) and @otherSession?.get('teamSpells')
@session.set('teamSpells', @otherSession.get('teamSpells'))
opponentCode = @otherSession?.get('transpiledCode') or {}
myCode = @session.get('code') or {}
for spell in opponentSpells
[thang, spell] = spell.split '/'
c = opponentCode[thang]?[spell]
myCode[thang] ?= {}
if c then myCode[thang][spell] = c else delete myCode[thang][spell]
@session.set('code', myCode)
if @session.get('multiplayer') and @otherSession?
# For now, ladderGame will disallow multiplayer, because session code combining doesn't play nice yet.
@session.set 'multiplayer', false
setupGod: ->
@god.setLevel @level.serialize @supermodel, @session, @otherSession
@god.setLevelSessionIDs if @otherSession then [@session.id, @otherSession.id] else [@session.id]
@god.setWorldClassMap @world.classMap
setTeam: (team) ->
team = team?.team unless _.isString team
team ?= 'humans'
me.team = team
@session.set 'team', team
Backbone.Mediator.publish 'level:team-set', team: team # Needed for scripts
@team = team
initGoalManager: ->
@goalManager = new GoalManager(@world, @level.get('goals'), @team)
@god.setGoalManager @goalManager
insertSubviews: ->
@insertSubView @tome = new TomeView levelID: @levelID, session: @session, otherSession: @otherSession, thangs: @world.thangs, supermodel: @supermodel, level: @level, observing: @observing
@insertSubView new LevelPlaybackView session: @session, level: @level
@insertSubView new GoalsView {}
@insertSubView new LevelFlagsView levelID: @levelID, world: @world if @$el.hasClass 'flags'
@insertSubView new GoldView {}
@insertSubView new HUDView {level: @level}
@insertSubView new LevelDialogueView {level: @level, sessionID: @session.id}
@insertSubView new ChatView levelID: @levelID, sessionID: @session.id, session: @session
@insertSubView new ProblemAlertView session: @session, level: @level, supermodel: @supermodel
worldName = utils.i18n @level.attributes, 'name'
@controlBar = @insertSubView new ControlBarView {worldName: worldName, session: @session, level: @level, supermodel: @supermodel}
#_.delay (=> Backbone.Mediator.publish('level:set-debug', debug: true)), 5000 if @isIPadApp() # if me.displayName() is 'Nick'
initVolume: ->
volume = me.get('volume')
volume = 1.0 unless volume?
Backbone.Mediator.publish 'level:set-volume', volume: volume
initScriptManager: ->
@scriptManager = new ScriptManager({scripts: @world.scripts or [], view: @, session: @session, levelID: @level.get('slug')})
@scriptManager.loadFromSession()
register: ->
@bus = LevelBus.get(@levelID, @session.id)
@bus.setSession(@session)
@bus.setSpells @tome.spells
if @session.get('multiplayer') and not me.isAdmin()
@session.set 'multiplayer', false # Temp: multiplayer has bugged out some sessions, so ignoring it.
@bus.connect() if @session.get('multiplayer')
# Load Completed Setup ######################################################
onSessionLoaded: (e) ->
Backbone.Mediator.publish "ipad:language-chosen", language: e.session.get('codeLanguage') ? "python"
# Just the level and session have been loaded by the level loader
if e.level.get('slug') is 'zero-sum'
sorcerer = '52fd1524c7e6cf99160e7bc9'
if e.session.get('creator') is '532dbc73a622924444b68ed9' # Wizard Dude gets his own avatar
sorcerer = '53e126a4e06b897606d38bef'
e.session.set 'heroConfig', {"thangType":sorcerer,"inventory":{"misc-0":"53e2396a53457600003e3f0f","programming-book":"546e266e9df4a17d0d449be5","minion":"54eb5dbc49fa2d5c905ddf56","feet":"53e214f153457600003e3eab","right-hand":"54eab7f52b7506e891ca7202","left-hand":"5463758f3839c6e02811d30f","wrists":"54693797a2b1f53ce79443e9","gloves":"5469425ca2b1f53ce7944421","torso":"546d4a549df4a17d0d449a97","neck":"54693274a2b1f53ce79443c9","eyes":"546941fda2b1f53ce794441d","head":"546d4ca19df4a17d0d449abf"}}
else if e.level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop'] and not _.size e.session.get('heroConfig')?.inventory ? {}
@setupManager?.destroy()
@setupManager = new LevelSetupManager({supermodel: @supermodel, levelID: @levelID, parent: @, session: @session})
@setupManager.open()
@onRealTimeMultiplayerLevelLoaded e.session if e.level.get('type') in ['hero-ladder']
onLoaded: ->
_.defer => @onLevelLoaderLoaded()
onLevelLoaderLoaded: ->
# Everything is now loaded
return unless @levelLoader.progress() is 1 # double check, since closing the guide may trigger this early
# Save latest level played.
if not @observing and not (@levelLoader.level.get('type') in ['ladder', 'ladder-tutorial'])
me.set('lastLevel', @levelID)
me.save()
application.tracker?.identify()
@saveRecentMatch() if @otherSession
@levelLoader.destroy()
@levelLoader = null
@initSurface()
saveRecentMatch: ->
allRecentlyPlayedMatches = storage.load('recently-played-matches') ? {}
recentlyPlayedMatches = allRecentlyPlayedMatches[@levelID] ? []
allRecentlyPlayedMatches[@levelID] = recentlyPlayedMatches
recentlyPlayedMatches.unshift yourTeam: me.team, otherSessionID: @otherSession.id, opponentName: @otherSession.get('creatorName') unless _.find recentlyPlayedMatches, otherSessionID: @otherSession.id
recentlyPlayedMatches.splice(8)
storage.save 'recently-played-matches', allRecentlyPlayedMatches
initSurface: ->
webGLSurface = $('canvas#webgl-surface', @$el)
normalSurface = $('canvas#normal-surface', @$el)
@surface = new Surface(@world, normalSurface, webGLSurface, thangTypes: @supermodel.getModels(ThangType), playJingle: not @isEditorPreview, wizards: not (@level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']), observing: @observing, playerNames: @findPlayerNames())
worldBounds = @world.getBounds()
bounds = [{x: worldBounds.left, y: worldBounds.top}, {x: worldBounds.right, y: worldBounds.bottom}]
@surface.camera.setBounds(bounds)
@surface.camera.zoomTo({x: 0, y: 0}, 0.1, 0)
findPlayerNames: ->
return {} unless @observing
playerNames = {}
for session in [@session, @otherSession] when session?.get('team')
playerNames[session.get('team')] = session.get('creatorName') or 'Anoner'
playerNames
# Once Surface is Loaded ####################################################
onLevelStarted: ->
return unless @surface?
@loadingView.showReady()
@trackLevelLoadEnd()
if window.currentModal and not window.currentModal.destroyed and window.currentModal.constructor isnt VictoryModal
return Backbone.Mediator.subscribeOnce 'modal:closed', @onLevelStarted, @
@surface.showLevel()
if @otherSession and not (@level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop'])
# TODO: colorize name and cloud by team, colorize wizard by user's color config
@surface.createOpponentWizard id: @otherSession.get('creator'), name: @otherSession.get('creatorName'), team: @otherSession.get('team'), levelSlug: @level.get('slug'), codeLanguage: @otherSession.get('submittedCodeLanguage')
if @isEditorPreview or @observing
@loadingView.startUnveiling()
@loadingView.unveil()
onLoadingViewUnveiling: (e) ->
@restoreSessionState()
onLoadingViewUnveiled: (e) ->
@loadingView.$el.remove()
@removeSubView @loadingView
@loadingView = null
@playAmbientSound()
if @options.realTimeMultiplayerSessionID?
Backbone.Mediator.publish 'playback:real-time-playback-waiting', {}
@realTimeMultiplayerContinueGame @options.realTimeMultiplayerSessionID
# TODO: Is it possible to create a Mongoose ObjectId for 'ls', instead of the string returned from get()?
application.tracker?.trackEvent 'Started Level', category:'Play Level', levelID: @levelID, ls: @session?.get('_id') unless @observing
$(window).trigger 'resize'
playAmbientSound: ->
return if @destroyed
return if @ambientSound
return unless file = {Dungeon: 'ambient-dungeon', Grass: 'ambient-grass'}[@level.get('terrain')]
src = "/file/interface/#{file}#{AudioPlayer.ext}"
unless AudioPlayer.getStatus(src)?.loaded
AudioPlayer.preloadSound src
Backbone.Mediator.subscribeOnce 'audio-player:loaded', @playAmbientSound, @
return
@ambientSound = createjs.Sound.play src, loop: -1, volume: 0.1
createjs.Tween.get(@ambientSound).to({volume: 1.0}, 10000)
restoreSessionState: ->
return if @alreadyLoadedState
@alreadyLoadedState = true
state = @originalSessionState
if not @level or @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']
Backbone.Mediator.publish 'level:suppress-selection-sounds', suppress: true
Backbone.Mediator.publish 'tome:select-primary-sprite', {}
Backbone.Mediator.publish 'level:suppress-selection-sounds', suppress: false
@surface.focusOnHero()
Backbone.Mediator.publish 'level:set-time', time: 0
Backbone.Mediator.publish 'level:set-playing', playing: true
else
if state.selected
# TODO: Should also restore selected spell here by saving spellName
Backbone.Mediator.publish 'level:select-sprite', thangID: state.selected, spellName: null
# callbacks
onCtrlS: (e) ->
e.preventDefault()
onEscapePressed: (e) ->
return unless @$el.hasClass 'real-time'
Backbone.Mediator.publish 'playback:stop-real-time-playback', {}
onLevelReloadFromData: (e) ->
isReload = Boolean @world
@setLevel e.level, e.supermodel
if isReload
@scriptManager.setScripts(e.level.get('scripts'))
Backbone.Mediator.publish 'tome:cast-spell', {} # a bit hacky
onLevelReloadThangType: (e) ->
tt = e.thangType
for url, model of @supermodel.models
if model.id is tt.id
for key, val of tt.attributes
model.attributes[key] = val
break
Backbone.Mediator.publish 'tome:cast-spell', {}
onWindowResize: (e) => @endHighlight()
onDisableControls: (e) ->
return if e.controls and not ('level' in e.controls)
@shortcutsEnabled = false
@wasFocusedOn = document.activeElement
$('body').focus()
onEnableControls: (e) ->
return if e.controls? and not ('level' in e.controls)
@shortcutsEnabled = true
$(@wasFocusedOn).focus() if @wasFocusedOn
@wasFocusedOn = null
onDonePressed: -> @showVictory()
onShowVictory: (e) ->
$('#level-done-button').show() unless @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']
@showVictory() if e.showModal
return if @victorySeen
@victorySeen = true
victoryTime = (new Date()) - @loadEndTime
if not @observing and victoryTime > 10 * 1000 # Don't track it if we're reloading an already-beaten level
application.tracker?.trackEvent 'Saw Victory',
category: 'Play Level'
level: @level.get('name')
label: @level.get('name')
levelID: @levelID
ls: @session?.get('_id')
application.tracker?.trackTiming victoryTime, 'Level Victory Time', @levelID, @levelID
showVictory: ->
@endHighlight()
options = {level: @level, supermodel: @supermodel, session: @session, hasReceivedMemoryWarning: @hasReceivedMemoryWarning}
ModalClass = if @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop'] then HeroVictoryModal else VictoryModal
victoryModal = new ModalClass(options)
@openModalView(victoryModal)
if me.get('anonymous')
window.nextURL = '/play/' + (@level.get('campaign') ? '') # Signup will go here on completion instead of reloading.
onRestartLevel: ->
@tome.reloadAllCode()
Backbone.Mediator.publish 'level:restarted', {}
$('#level-done-button', @$el).hide()
application.tracker?.trackEvent 'Confirmed Restart', category: 'Play Level', level: @level.get('name'), label: @level.get('name') unless @observing
onInfiniteLoop: (e) ->
return unless e.firstWorld
@openModalView new InfiniteLoopModal nonUserCodeProblem: e.nonUserCodeProblem
application.tracker?.trackEvent 'Saw Initial Infinite Loop', category: 'Play Level', level: @level.get('name'), label: @level.get('name') unless @observing
onHighlightDOM: (e) -> @highlightElement e.selector, delay: e.delay, sides: e.sides, offset: e.offset, rotation: e.rotation
onEndHighlight: -> @endHighlight()
onFocusDom: (e) -> $(e.selector).focus()
onMultiplayerChanged: (e) ->
if @session.get('multiplayer')
@bus.connect()
else
@bus.removeFirebaseData =>
@bus.disconnect()
onSessionWillSave: (e) ->
# Something interesting has happened, so (at a lower frequency), we'll save a screenshot.
#@saveScreenshot e.session
# Throttled
saveScreenshot: (session) =>
return unless screenshot = @surface?.screenshot()
session.save {screenshot: screenshot}, {patch: true, type: 'PUT'}
onContactClicked: (e) ->
@openModalView contactModal = new ContactModal()
screenshot = @surface.screenshot(1, 'image/png', 1.0, 1)
body =
b64png: screenshot.replace 'data:image/png;base64,', ''
filename: "screenshot-#{@levelID}-#{_.string.slugify((new Date()).toString())}.png"
path: "db/user/#{me.id}"
mimetype: 'image/png'
contactModal.screenshotURL = "http://codecombat.com/file/#{body.path}/#{body.filename}"
window.screenshot = screenshot
window.screenshotURL = contactModal.screenshotURL
$.ajax '/file', type: 'POST', data: body, success: (e) ->
contactModal.updateScreenshot?()
# Dynamic sound loading
onNewWorld: (e) ->
return if @headless
scripts = @world.scripts # Since these worlds don't have scripts, preserve them.
@world = e.world
@world.scripts = scripts
thangTypes = @supermodel.getModels(ThangType)
startFrame = @lastWorldFramesLoaded ? 0
finishedLoading = @world.frames.length is @world.totalFrames
if finishedLoading
@lastWorldFramesLoaded = 0
if @waitingForSubmissionComplete
_.defer @onSubmissionComplete # Give it a frame to make sure we have the latest goals
@waitingForSubmissionComplete = false
else
@lastWorldFramesLoaded = @world.frames.length
for [spriteName, message] in @world.thangDialogueSounds startFrame
continue unless thangType = _.find thangTypes, (m) -> m.get('name') is spriteName
continue unless sound = AudioPlayer.soundForDialogue message, thangType.get('soundTriggers')
AudioPlayer.preloadSoundReference sound
# Real-time playback
onRealTimePlaybackWaiting: (e) ->
@$el.addClass('real-time').focus()
@onWindowResize()
onRealTimePlaybackStarted: (e) ->
@$el.addClass('real-time').focus()
@onWindowResize()
onRealTimePlaybackEnded: (e) ->
return unless @$el.hasClass 'real-time'
@$el.removeClass 'real-time'
@onWindowResize()
if @world.frames.length is @world.totalFrames
_.delay @onSubmissionComplete, 750 # Wait for transition to end.
else
@waitingForSubmissionComplete = true
@onRealTimeMultiplayerPlaybackEnded()
onSubmissionComplete: =>
return if @destroyed
# TODO: Show a victory dialog specific to hero-ladder level
if @goalManager.checkOverallStatus() is 'success' and not @options.realTimeMultiplayerSessionID?
showModalFn = -> Backbone.Mediator.publish 'level:show-victory', showModal: true
@session.recordScores @world.scores, @level
if @level.get 'replayable'
@session.increaseDifficulty showModalFn
else
showModalFn()
destroy: ->
@levelLoader?.destroy()
@surface?.destroy()
@god?.destroy()
@goalManager?.destroy()
@scriptManager?.destroy()
@setupManager?.destroy()
if ambientSound = @ambientSound
# Doesn't seem to work; stops immediately.
createjs.Tween.get(ambientSound).to({volume: 0.0}, 1500).call -> ambientSound.stop()
$(window).off 'resize', @onWindowResize
delete window.world # not sure where this is set, but this is one way to clean it up
@bus?.destroy()
#@instance.save() unless @instance.loading
delete window.nextURL
console.profileEnd?() if PROFILE_ME
@onRealTimeMultiplayerLevelUnloaded()
super()
onIPadMemoryWarning: (e) ->
@hasReceivedMemoryWarning = true
onItemPurchased: (e) ->
heroConfig = @session.get('heroConfig') ? {}
inventory = heroConfig.inventory ? {}
slot = e.item.getAllowedSlots()[0]
if slot and not inventory[slot]
# Open up the inventory modal so they can equip the new item
@setupManager?.destroy()
@setupManager = new LevelSetupManager({supermodel: @supermodel, levelID: @levelID, parent: @, session: @session, hadEverChosenHero: true})
@setupManager.open()
# Start Real-time Multiplayer ######################################################
#
# This view acts as a hub for the real-time multiplayer session for the current level.
#
# It performs these actions:
# Player heartbeat
# Publishes player status
# Updates real-time multiplayer session state
# Updates real-time multiplayer player state
# Cleans up old sessions (sets state to 'finished')
# Real-time multiplayer cast handshake
# Swap teams on game joined, if necessary
# Reload PlayLevelView on real-time submit, automatically continue game and real-time playback
#
# It monitors these:
# Real-time multiplayer sessions
# Current real-time multiplayer session
# Internal multiplayer create/joined/left events
#
# Real-time state variables.
# Each Ref is Firebase reference, and may have a matching Data suffixed variable with the latest data received.
# @realTimePlayerRef - User's real-time multiplayer player for this level
# @realTimePlayerGameRef - User's current real-time multiplayer player game session
# @realTimeSessionRef - Current real-time multiplayer game session
# @realTimeOpponentRef - Current real-time multiplayer opponent
# @realTimePlayersRef - Real-time players for current real-time multiplayer game session
# @options.realTimeMultiplayerSessionID - Need to continue an existing real-time multiplayer session
#
# TODO: Move this code to it's own file, or possibly the LevelBus
# TODO: Save settings somewhere reasonable
multiplayerFireHost: 'https://codecombat.firebaseio.com/test/db/'
onRealTimeMultiplayerLevelLoaded: (session) ->
# console.log 'PlayLevelView onRealTimeMultiplayerLevelLoaded'
return if @realTimePlayerRef?
return if me.get('anonymous')
@realTimePlayerRef = new Firebase "#{@multiplayerFireHost}multiplayer_players/#{@levelID}/#{me.id}"
unless @options.realTimeMultiplayerSessionID?
# TODO: Wait for name instead of using 'Anon', or try and update it later?
name = me.get('name') ? session.get('creatorName') ? 'Anon'
@realTimePlayerRef.set
id: me.id # TODO: is this redundant info necessary?
name: name
state: 'playing'
created: new Date().toISOString()
heartbeat: new Date().toISOString()
@timerMultiplayerHeartbeatID = setInterval @onRealTimeMultiplayerHeartbeat, 60 * 1000
@cleanupRealTimeSessions()
cleanupRealTimeSessions: ->
# console.log 'PlayLevelView cleanupRealTimeSessions'
# TODO: Reduce this call, possibly by username and dates
realTimeSessionCollection = new Firebase "#{@multiplayerFireHost}multiplayer_level_sessions/#{@levelID}"
realTimeSessionCollection.once 'value', (collectionSnapshot) =>
for multiplayerSessionID, multiplayerSession of collectionSnapshot.val()
continue if @options.realTimeMultiplayerSessionID? and @options.realTimeMultiplayerSessionID is multiplayerSessionID
continue unless multiplayerSession.state isnt 'finished'
player = realTimeSessionCollection.child "#{multiplayerSession.id}/players/#{me.id}"
player.once 'value', (playerSnapshot) =>
if playerSnapshot.val()
console.info 'Cleaning up previous real-time multiplayer session', multiplayerSessionID
player.update 'state': 'left'
multiplayerSessionRef = realTimeSessionCollection.child "#{multiplayerSessionID}"
multiplayerSessionRef.update 'state': 'finished'
onRealTimeMultiplayerLevelUnloaded: ->
# console.log 'PlayLevelView onRealTimeMultiplayerLevelUnloaded'
if @timerMultiplayerHeartbeatID?
clearInterval @timerMultiplayerHeartbeatID
@timerMultiplayerHeartbeatID = null
# TODO: similar to game ending cleanup
if @realTimeOpponentRef?
@realTimeOpponentRef.off 'value', @onRealTimeOpponentChanged
@realTimeOpponentRef = null
if @realTimePlayersRef?
@realTimePlayersRef.off 'child_added', @onRealTimePlayerAdded
@realTimePlayersRef = null
if @realTimeSessionRef?
@realTimeSessionRef.off 'value', @onRealTimeSessionChanged
@realTimeSessionRef = null
if @realTimePlayerGameRef?
@realTimePlayerGameRef = null
if @realTimePlayerRef?
@realTimePlayerRef = null
onRealTimeMultiplayerHeartbeat: =>
# console.log 'PlayLevelView onRealTimeMultiplayerHeartbeat', @realTimePlayerRef
@realTimePlayerRef.update 'heartbeat': new Date().toISOString() if @realTimePlayerRef?
onRealTimeMultiplayerCreatedGame: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerCreatedGame'
@joinRealTimeMultiplayerGame e
@realTimePlayerGameRef.update 'state': 'coding'
@realTimePlayerRef.update 'state': 'available'
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: 'Waiting for opponent..'
onRealTimeSessionChanged: (snapshot) =>
# console.log 'PlayLevelView onRealTimeSessionChanged', snapshot.val()
@realTimeSessionData = snapshot.val()
if @realTimeSessionData?.state is 'finished'
@realTimeGameEnded()
Backbone.Mediator.publish 'real-time-multiplayer:left-game', {}
onRealTimePlayerAdded: (snapshot) =>
# console.log 'PlayLevelView onRealTimePlayerAdded', snapshot.val()
# Assume game is full, game on
data = snapshot.val()
if data? and data.id isnt me.id
@realTimeOpponentData = data
# console.log 'PlayLevelView onRealTimePlayerAdded opponent', @realTimeOpponentData, @realTimePlayersData
@realTimePlayersData[@realTimeOpponentData.id] = @realTimeOpponentData
if @realTimeSessionData?.state is 'creating'
@realTimeSessionRef.update 'state': 'coding'
@realTimePlayerRef.update 'state': 'unavailable'
@realTimeOpponentRef = @realTimeSessionRef.child "players/#{@realTimeOpponentData.id}"
@realTimeOpponentRef.on 'value', @onRealTimeOpponentChanged
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "Playing against #{@realTimeOpponentData.name}"
onRealTimeOpponentChanged: (snapshot) =>
# console.log 'PlayLevelView onRealTimeOpponentChanged', snapshot.val()
@realTimeOpponentData = snapshot.val()
switch @realTimeOpponentData?.state
when 'left'
console.info 'Real-time multiplayer opponent left the game'
opponentID = @realTimeOpponentData.id
@realTimeGameEnded()
Backbone.Mediator.publish 'real-time-multiplayer:left-game', userID: opponentID
when 'submitted'
# TODO: What should this message say?
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "#{@realTimeOpponentData.name} waiting for your code"
joinRealTimeMultiplayerGame: (e) ->
# console.log 'PlayLevelView joinRealTimeMultiplayerGame', e
unless @realTimeSessionRef?
@session.set('submittedCodeLanguage', @session.get('codeLanguage'))
@session.save()
@realTimeSessionRef = new Firebase "#{@multiplayerFireHost}multiplayer_level_sessions/#{@levelID}/#{e.realTimeSessionID}"
@realTimePlayersRef = @realTimeSessionRef.child 'players'
# Look for opponent
@realTimeSessionRef.once 'value', (multiplayerSessionSnapshot) =>
if @realTimeSessionData = multiplayerSessionSnapshot.val()
@realTimePlayersRef.once 'value', (playsSnapshot) =>
if @realTimePlayersData = playsSnapshot.val()
for id, player of @realTimePlayersData
if id isnt me.id
@realTimeOpponentRef = @realTimeSessionRef.child "players/#{id}"
@realTimeOpponentRef.once 'value', (opponentSnapshot) =>
if @realTimeOpponentData = opponentSnapshot.val()
@updateTeam()
else
console.error 'Could not lookup multiplayer opponent data.'
@realTimeOpponentRef.on 'value', @onRealTimeOpponentChanged
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: 'Playing against ' + player.name
else
console.error 'Could not lookup multiplayer session players data.'
# TODO: need child_removed too?
@realTimePlayersRef.on 'child_added', @onRealTimePlayerAdded
else
console.error 'Could not lookup multiplayer session data.'
@realTimeSessionRef.on 'value', @onRealTimeSessionChanged
@realTimePlayerGameRef = @realTimeSessionRef.child "players/#{me.id}"
# TODO: Follow up in MultiplayerView to see if double joins can be avoided
# else
# console.error 'Joining real-time multiplayer game with an existing @realTimeSessionRef.'
onRealTimeMultiplayerJoinedGame: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerJoinedGame', e
@joinRealTimeMultiplayerGame e
@realTimePlayerGameRef.update 'state': 'coding'
@realTimePlayerRef.update 'state': 'unavailable'
onRealTimeMultiplayerLeftGame: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerLeftGame', e
if e.userID? and e.userID is me.id
@realTimePlayerGameRef.update 'state': 'left'
@realTimeGameEnded()
realTimeMultiplayerContinueGame: (realTimeSessionID) ->
# console.log 'PlayLevelView realTimeMultiplayerContinueGame', realTimeSessionID, me.id
Backbone.Mediator.publish 'real-time-multiplayer:joined-game', realTimeSessionID: realTimeSessionID
console.info 'Setting my game status to ready'
@realTimePlayerGameRef.update 'state': 'ready'
if @realTimeOpponentData.state is 'ready'
@realTimeOpponentIsReady()
else
console.info 'Waiting for opponent to be ready'
@realTimeOpponentRef.on 'value', @realTimeOpponentMaybeReady
realTimeOpponentMaybeReady: (snapshot) =>
# console.log 'PlayLevelView realTimeOpponentMaybeReady'
if @realTimeOpponentData = snapshot.val()
if @realTimeOpponentData.state is 'ready'
@realTimeOpponentRef.off 'value', @realTimeOpponentMaybeReady
@realTimeOpponentIsReady()
realTimeOpponentIsReady: =>
console.info 'All real-time multiplayer players are ready!'
@realTimeSessionRef.update 'state': 'running'
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: 'Battling ' + @realTimeOpponentData.name
Backbone.Mediator.publish 'tome:manual-cast', {realTime: true}
realTimeGameEnded: ->
if @realTimeOpponentRef?
@realTimeOpponentRef.off 'value', @onRealTimeOpponentChanged
@realTimeOpponentRef = null
if @realTimePlayersRef?
@realTimePlayersRef.off 'child_added', @onRealTimePlayerAdded
@realTimePlayersRef = null
if @realTimeSessionRef?
@realTimeSessionRef.off 'value', @onRealTimeSessionChanged
@realTimeSessionRef.update 'state': 'finished'
@realTimeSessionRef = null
if @realTimePlayerGameRef?
@realTimePlayerGameRef = null
if @realTimePlayerRef?
@realTimePlayerRef.update 'state': 'playing'
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: ''
onRealTimeMultiplayerCast: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerCast', @realTimeSessionData, @realTimePlayersData
unless @realTimeSessionRef?
console.error 'Real-time multiplayer cast without multiplayer session.'
return
unless @realTimeSessionData?
console.error 'Real-time multiplayer cast without multiplayer data.'
return
unless @realTimePlayersData?
console.error 'Real-time multiplayer cast without multiplayer players data.'
return
# Set submissionCount for created real-time multiplayer session
if me.id is @realTimeSessionData.creator
sessionState = @session.get('state')
if sessionState?
submissionCount = sessionState.submissionCount ? 0
console.info 'Setting multiplayer submissionCount to', submissionCount
@realTimeSessionRef.update 'submissionCount': submissionCount
else
console.error 'Failed to read sessionState in onRealTimeMultiplayerCast'
console.info 'Submitting my code'
# Transpiling code copied from scripts/transpile.coffee
# TODO: Should this live somewhere else?
transpiledCode = {}
for thang, spells of @session.get('code')
transpiledCode[thang] = {}
for spellID, spell of spells
spellName = thang + '/' + spellID
continue if @session.get('teamSpells') and not (spellName in @session.get('teamSpells')[@session.get('team')])
# console.log "PlayLevelView Transpiling spell #{spellName}"
aetherOptions = createAetherOptions functionName: spellID, codeLanguage: @session.get('submittedCodeLanguage'), includeFlow: true
aether = new Aether aetherOptions
transpiledCode[thang][spellID] = aether.transpile spell
# console.log "PlayLevelView transpiled code", transpiledCode
@session.set 'transpiledCode', transpiledCode
permissions = @session.get 'permissions' ? []
unless _.find(permissions, (p) -> p.target is 'public' and p.access is 'read')
permissions.push target:'public', access:'read'
@session.set 'permissions', permissions
@session.patch()
@realTimePlayerGameRef.update 'state': 'submitted'
console.info 'Other player is', @realTimeOpponentData.state
if @realTimeOpponentData.state in ['submitted', 'ready']
@realTimeOpponentSubmittedCode @realTimeOpponentData, @realTimePlayerGameData
else
# Wait for opponent to submit their code
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "Waiting for code from #{@realTimeOpponentData.name}"
@realTimeOpponentRef.on 'value', @realTimeOpponentMaybeSubmitted
realTimeOpponentMaybeSubmitted: (snapshot) =>
if @realTimeOpponentData = snapshot.val()
if @realTimeOpponentData.state in ['submitted', 'ready']
@realTimeOpponentRef.off 'value', @realTimeOpponentMaybeSubmitted
@realTimeOpponentSubmittedCode @realTimeOpponentData, @realTimePlayerGameData
onRealTimeMultiplayerPlaybackEnded: ->
# console.log 'PlayLevelView onRealTimeMultiplayerPlaybackEnded'
if @realTimeSessionRef?
@realTimeSessionRef.update 'state': 'coding'
@realTimePlayerGameRef.update 'state': 'coding'
if @realTimeOpponentData?
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "Playing against #{@realTimeOpponentData.name}"
realTimeOpponentSubmittedCode: (opponentPlayer, myPlayer) =>
# console.log 'PlayLevelView realTimeOpponentSubmittedCode', @realTimeSessionData.id, opponentPlayer.level_session
# Read submissionCount for joined real-time multiplayer session
if me.id isnt @realTimeSessionData.creator
sessionState = @session.get('state') ? {}
newSubmissionCount = @realTimeSessionData.submissionCount
if newSubmissionCount?
# TODO: This isn't always getting updated where the random seed generation uses it.
sessionState.submissionCount = parseInt newSubmissionCount
console.info 'Got multiplayer submissionCount', sessionState.submissionCount
@session.set 'state', sessionState
@session.patch()
# Reload this level so the opponent session can easily be wired up
Backbone.Mediator.publish 'router:navigate',
route: "/play/level/#{@levelID}"
viewClass: PlayLevelView
viewArgs: [{supermodel: @supermodel, autoUnveil: true, realTimeMultiplayerSessionID: @realTimeSessionData.id, opponent: opponentPlayer.level_session, team: @team}, @levelID]
updateTeam: ->
# If not creator, and same team as creator, then switch teams
# TODO: Assumes there are only 'humans' and 'ogres'
unless @realTimeOpponentData?
console.error 'Tried to switch teams without real-time multiplayer opponent data.'
return
unless @realTimeSessionData?
console.error 'Tried to switch teams without real-time multiplayer session data.'
return
return if me.id is @realTimeSessionData.creator
oldTeam = @realTimeOpponentData.team
return unless oldTeam is @session.get('team')
# Need to switch to other team
newTeam = if oldTeam is 'humans' then 'ogres' else 'humans'
console.info "Switching from team #{oldTeam} to #{newTeam}"
# Move code from old team to new team
# Assumes teamSpells has matching spells for each team
# TODO: Similar to code in loadOpponentTeam, consolidate?
code = @session.get 'code'
teamSpells = @session.get 'teamSpells'
for oldSpellKey in teamSpells[oldTeam]
[oldThang, oldSpell] = oldSpellKey.split '/'
oldCode = code[oldThang]?[oldSpell]
continue unless oldCode?
# Move oldCode to new team under same spell
for newSpellKey in teamSpells[newTeam]
[newThang, newSpell] = newSpellKey.split '/'
if newSpell is oldSpell
# Found spell location under new team
# console.log "Swapping spell=#{oldSpell} from #{oldThang} to #{newThang}"
if code[newThang]?[oldSpell]?
# Option 1: have a new spell to swap
code[oldThang][oldSpell] = code[newThang][oldSpell]
else
# Option 2: no new spell to swap
delete code[oldThang][oldSpell]
code[newThang] = {} unless code[newThang]?
code[newThang][oldSpell] = oldCode
break
@setTeam newTeam # Sets @session 'team'
sessionState = @session.get('state')
if sessionState?
# TODO: Don't hard code thangID
sessionState.selected = if newTeam is 'humans' then 'Hero Placeholder' else 'Hero Placeholder 1'
@session.set 'state', sessionState
@session.set 'code', code
@session.patch()
if sessionState?
# TODO: Don't hardcode spellName
Backbone.Mediator.publish 'level:select-sprite', thangID: sessionState.selected, spellName: 'plan'
# End Real-time Multiplayer ######################################################
| 210286 | RootView = require 'views/core/RootView'
template = require 'templates/play/level'
{me} = require 'core/auth'
ThangType = require 'models/ThangType'
utils = require 'core/utils'
storage = require 'core/storage'
{createAetherOptions} = require 'lib/aether_utils'
# tools
Surface = require 'lib/surface/Surface'
God = require 'lib/God'
GoalManager = require 'lib/world/GoalManager'
ScriptManager = require 'lib/scripts/ScriptManager'
LevelBus = require 'lib/LevelBus'
LevelLoader = require 'lib/LevelLoader'
LevelSession = require 'models/LevelSession'
Level = require 'models/Level'
LevelComponent = require 'models/LevelComponent'
Article = require 'models/Article'
Camera = require 'lib/surface/Camera'
AudioPlayer = require 'lib/AudioPlayer'
# subviews
LevelLoadingView = require './LevelLoadingView'
ProblemAlertView = require './tome/ProblemAlertView'
TomeView = require './tome/TomeView'
ChatView = require './LevelChatView'
HUDView = require './LevelHUDView'
LevelDialogueView = require './LevelDialogueView'
ControlBarView = require './ControlBarView'
LevelPlaybackView = require './LevelPlaybackView'
GoalsView = require './LevelGoalsView'
LevelFlagsView = require './LevelFlagsView'
GoldView = require './LevelGoldView'
VictoryModal = require './modal/VictoryModal'
HeroVictoryModal = require './modal/HeroVictoryModal'
InfiniteLoopModal = require './modal/InfiniteLoopModal'
LevelSetupManager = require 'lib/LevelSetupManager'
ContactModal = require 'views/core/ContactModal'
PROFILE_ME = false
module.exports = class PlayLevelView extends RootView
id: 'level-view'
template: template
cache: false
shortcutsEnabled: true
isEditorPreview: false
subscriptions:
'level:set-volume': (e) -> createjs.Sound.setVolume(if e.volume is 1 then 0.6 else e.volume) # Quieter for now until individual sound FX controls work again.
'level:show-victory': 'onShowVictory'
'level:restart': 'onRestartLevel'
'level:highlight-dom': 'onHighlightDOM'
'level:end-highlight-dom': 'onEndHighlight'
'level:focus-dom': 'onFocusDom'
'level:disable-controls': 'onDisableControls'
'level:enable-controls': 'onEnableControls'
'god:world-load-progress-changed': 'onWorldLoadProgressChanged'
'god:new-world-created': 'onNewWorld'
'god:streaming-world-updated': 'onNewWorld'
'god:infinite-loop': 'onInfiniteLoop'
'level:reload-from-data': 'onLevelReloadFromData'
'level:reload-thang-type': 'onLevelReloadThangType'
'level:session-will-save': 'onSessionWillSave'
'level:started': 'onLevelStarted'
'level:loading-view-unveiling': 'onLoadingViewUnveiling'
'level:loading-view-unveiled': 'onLoadingViewUnveiled'
'level:session-loaded': 'onSessionLoaded'
'playback:real-time-playback-waiting': 'onRealTimePlaybackWaiting'
'playback:real-time-playback-started': 'onRealTimePlaybackStarted'
'playback:real-time-playback-ended': 'onRealTimePlaybackEnded'
'real-time-multiplayer:created-game': 'onRealTimeMultiplayerCreatedGame'
'real-time-multiplayer:joined-game': 'onRealTimeMultiplayerJoinedGame'
'real-time-multiplayer:left-game': 'onRealTimeMultiplayerLeftGame'
'real-time-multiplayer:manual-cast': 'onRealTimeMultiplayerCast'
'ipad:memory-warning': 'onIPadMemoryWarning'
'store:item-purchased': 'onItemPurchased'
events:
'click #level-done-button': 'onDonePressed'
'click #stop-real-time-playback-button': -> Backbone.Mediator.publish 'playback:stop-real-time-playback', {}
'click #fullscreen-editor-background-screen': (e) -> Backbone.Mediator.publish 'tome:toggle-maximize', {}
'click .contact-link': 'onContactClicked'
shortcuts:
'ctrl+s': 'onCtrlS'
'esc': 'onEscapePressed'
# Initial Setup #############################################################
constructor: (options, @levelID) ->
console.profile?() if PROFILE_ME
super options
@isEditorPreview = @getQueryVariable 'dev'
@sessionID = @getQueryVariable 'session'
@observing = @getQueryVariable 'observing'
@opponentSessionID = @getQueryVariable('opponent')
@opponentSessionID ?= @options.opponent
$(window).on 'resize', @onWindowResize
@saveScreenshot = _.throttle @saveScreenshot, 30000
if @isEditorPreview
@supermodel.shouldSaveBackups = (model) -> # Make sure to load possibly changed things from localStorage.
model.constructor.className in ['Level', 'LevelComponent', 'LevelSystem', 'ThangType']
f = => @load() unless @levelLoader # Wait to see if it's just given to us through setLevel.
setTimeout f, 100
else
@load()
application.tracker?.trackEvent 'Started Level Load', category: 'Play Level', level: @levelID, label: @levelID unless @observing
setLevel: (@level, givenSupermodel) ->
@supermodel.models = givenSupermodel.models
@supermodel.collections = givenSupermodel.collections
@supermodel.shouldSaveBackups = givenSupermodel.shouldSaveBackups
serializedLevel = @level.serialize @supermodel, @session, @otherSession
@god?.setLevel serializedLevel
if @world
@world.loadFromLevel serializedLevel, false
else
@load()
load: ->
@loadStartTime = new Date()
@god = new God debugWorker: true
@levelLoader = new LevelLoader supermodel: @supermodel, levelID: @levelID, sessionID: @sessionID, opponentSessionID: @opponentSessionID, team: @getQueryVariable('team'), observing: @observing
@listenToOnce @levelLoader, 'world-necessities-loaded', @onWorldNecessitiesLoaded
trackLevelLoadEnd: ->
return if @isEditorPreview
@loadEndTime = new Date()
loadDuration = @loadEndTime - @loadStartTime
console.debug "Level unveiled after #{(loadDuration / 1000).toFixed(2)}s"
unless @observing
application.tracker?.trackEvent 'Finished Level Load', category: 'Play Level', label: @levelID, level: @levelID, loadDuration: loadDuration
application.tracker?.trackTiming loadDuration, 'Level Load Time', @levelID, @levelID
# CocoView overridden methods ###############################################
getRenderData: ->
c = super()
c.world = @world
c
afterRender: ->
super()
window.onPlayLevelViewLoaded? @ # still a hack
@insertSubView @loadingView = new LevelLoadingView autoUnveil: @options.autoUnveil or @observing, level: @levelLoader?.level ? @level # May not have @level loaded yet
@$el.find('#level-done-button').hide()
$('body').addClass('is-playing')
$('body').bind('touchmove', false) if @isIPadApp()
afterInsert: ->
super()
# Partially Loaded Setup ####################################################
onWorldNecessitiesLoaded: ->
# Called when we have enough to build the world, but not everything is loaded
@grabLevelLoaderData()
team = @getQueryVariable('team') ? @session.get('team') ? @world.teamForPlayer(0)
@loadOpponentTeam(team)
@setupGod()
@setTeam team
@initGoalManager()
@insertSubviews()
@initVolume()
@listenTo(@session, 'change:multiplayer', @onMultiplayerChanged)
@originalSessionState = $.extend(true, {}, @session.get('state'))
@register()
@controlBar.setBus(@bus)
@initScriptManager()
grabLevelLoaderData: ->
@session = @levelLoader.session
@world = @levelLoader.world
@level = @levelLoader.level
@$el.addClass 'hero' if @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']
@$el.addClass 'flags' if _.any(@world.thangs, (t) -> (t.programmableProperties and 'findFlags' in t.programmableProperties) or t.inventory?.flag) or @level.get('slug') is 'sky-span'
# TODO: Update terminology to always be opponentSession or otherSession
# TODO: E.g. if it's always opponent right now, then variable names should be opponentSession until we have coop play
@otherSession = @levelLoader.opponentSession
@worldLoadFakeResources = [] # first element (0) is 1%, last (100) is 100%
for percent in [1 .. 100]
@worldLoadFakeResources.push @supermodel.addSomethingResource "world_simulation_#{percent}%", 1
onWorldLoadProgressChanged: (e) ->
return unless @worldLoadFakeResources
@lastWorldLoadPercent ?= 0
worldLoadPercent = Math.floor 100 * e.progress
for percent in [@lastWorldLoadPercent + 1 .. worldLoadPercent] by 1
@worldLoadFakeResources[percent - 1].markLoaded()
@lastWorldLoadPercent = worldLoadPercent
@worldFakeLoadResources = null if worldLoadPercent is 100 # Done, don't need to watch progress any more.
loadOpponentTeam: (myTeam) ->
opponentSpells = []
for spellTeam, spells of @session.get('teamSpells') ? @otherSession?.get('teamSpells') ? {}
continue if spellTeam is myTeam or not myTeam
opponentSpells = opponentSpells.concat spells
if (not @session.get('teamSpells')) and @otherSession?.get('teamSpells')
@session.set('teamSpells', @otherSession.get('teamSpells'))
opponentCode = @otherSession?.get('transpiledCode') or {}
myCode = @session.get('code') or {}
for spell in opponentSpells
[thang, spell] = spell.split '/'
c = opponentCode[thang]?[spell]
myCode[thang] ?= {}
if c then myCode[thang][spell] = c else delete myCode[thang][spell]
@session.set('code', myCode)
if @session.get('multiplayer') and @otherSession?
# For now, ladderGame will disallow multiplayer, because session code combining doesn't play nice yet.
@session.set 'multiplayer', false
setupGod: ->
@god.setLevel @level.serialize @supermodel, @session, @otherSession
@god.setLevelSessionIDs if @otherSession then [@session.id, @otherSession.id] else [@session.id]
@god.setWorldClassMap @world.classMap
setTeam: (team) ->
team = team?.team unless _.isString team
team ?= 'humans'
me.team = team
@session.set 'team', team
Backbone.Mediator.publish 'level:team-set', team: team # Needed for scripts
@team = team
initGoalManager: ->
@goalManager = new GoalManager(@world, @level.get('goals'), @team)
@god.setGoalManager @goalManager
insertSubviews: ->
@insertSubView @tome = new TomeView levelID: @levelID, session: @session, otherSession: @otherSession, thangs: @world.thangs, supermodel: @supermodel, level: @level, observing: @observing
@insertSubView new LevelPlaybackView session: @session, level: @level
@insertSubView new GoalsView {}
@insertSubView new LevelFlagsView levelID: @levelID, world: @world if @$el.hasClass 'flags'
@insertSubView new GoldView {}
@insertSubView new HUDView {level: @level}
@insertSubView new LevelDialogueView {level: @level, sessionID: @session.id}
@insertSubView new ChatView levelID: @levelID, sessionID: @session.id, session: @session
@insertSubView new ProblemAlertView session: @session, level: @level, supermodel: @supermodel
worldName = utils.i18n @level.attributes, 'name'
@controlBar = @insertSubView new ControlBarView {worldName: worldName, session: @session, level: @level, supermodel: @supermodel}
#_.delay (=> Backbone.Mediator.publish('level:set-debug', debug: true)), 5000 if @isIPadApp() # if me.displayName() is '<NAME>'
initVolume: ->
volume = me.get('volume')
volume = 1.0 unless volume?
Backbone.Mediator.publish 'level:set-volume', volume: volume
initScriptManager: ->
@scriptManager = new ScriptManager({scripts: @world.scripts or [], view: @, session: @session, levelID: @level.get('slug')})
@scriptManager.loadFromSession()
register: ->
@bus = LevelBus.get(@levelID, @session.id)
@bus.setSession(@session)
@bus.setSpells @tome.spells
if @session.get('multiplayer') and not me.isAdmin()
@session.set 'multiplayer', false # Temp: multiplayer has bugged out some sessions, so ignoring it.
@bus.connect() if @session.get('multiplayer')
# Load Completed Setup ######################################################
onSessionLoaded: (e) ->
Backbone.Mediator.publish "ipad:language-chosen", language: e.session.get('codeLanguage') ? "python"
# Just the level and session have been loaded by the level loader
if e.level.get('slug') is 'zero-sum'
sorcerer = '52fd1524c7e6cf99160e7bc9'
if e.session.get('creator') is '532dbc73a622924444b68ed9' # Wizard Dude gets his own avatar
sorcerer = '53e126a4e06b897606d38bef'
e.session.set 'heroConfig', {"thangType":sorcerer,"inventory":{"misc-0":"53e2396a53457600003e3f0f","programming-book":"546e266e9df4a17d0d449be5","minion":"54eb5dbc49fa2d5c905ddf56","feet":"53e214f153457600003e3eab","right-hand":"54eab7f52b7506e891ca7202","left-hand":"5463758f3839c6e02811d30f","wrists":"54693797a2b1f53ce79443e9","gloves":"5469425ca2b1f53ce7944421","torso":"546d4a549df4a17d0d449a97","neck":"54693274a2b1f53ce79443c9","eyes":"546941fda2b1f53ce794441d","head":"546d4ca19df4a17d0d449abf"}}
else if e.level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop'] and not _.size e.session.get('heroConfig')?.inventory ? {}
@setupManager?.destroy()
@setupManager = new LevelSetupManager({supermodel: @supermodel, levelID: @levelID, parent: @, session: @session})
@setupManager.open()
@onRealTimeMultiplayerLevelLoaded e.session if e.level.get('type') in ['hero-ladder']
onLoaded: ->
_.defer => @onLevelLoaderLoaded()
onLevelLoaderLoaded: ->
# Everything is now loaded
return unless @levelLoader.progress() is 1 # double check, since closing the guide may trigger this early
# Save latest level played.
if not @observing and not (@levelLoader.level.get('type') in ['ladder', 'ladder-tutorial'])
me.set('lastLevel', @levelID)
me.save()
application.tracker?.identify()
@saveRecentMatch() if @otherSession
@levelLoader.destroy()
@levelLoader = null
@initSurface()
saveRecentMatch: ->
allRecentlyPlayedMatches = storage.load('recently-played-matches') ? {}
recentlyPlayedMatches = allRecentlyPlayedMatches[@levelID] ? []
allRecentlyPlayedMatches[@levelID] = recentlyPlayedMatches
recentlyPlayedMatches.unshift yourTeam: me.team, otherSessionID: @otherSession.id, opponentName: @otherSession.get('creatorName') unless _.find recentlyPlayedMatches, otherSessionID: @otherSession.id
recentlyPlayedMatches.splice(8)
storage.save 'recently-played-matches', allRecentlyPlayedMatches
initSurface: ->
webGLSurface = $('canvas#webgl-surface', @$el)
normalSurface = $('canvas#normal-surface', @$el)
@surface = new Surface(@world, normalSurface, webGLSurface, thangTypes: @supermodel.getModels(ThangType), playJingle: not @isEditorPreview, wizards: not (@level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']), observing: @observing, playerNames: @findPlayerNames())
worldBounds = @world.getBounds()
bounds = [{x: worldBounds.left, y: worldBounds.top}, {x: worldBounds.right, y: worldBounds.bottom}]
@surface.camera.setBounds(bounds)
@surface.camera.zoomTo({x: 0, y: 0}, 0.1, 0)
findPlayerNames: ->
return {} unless @observing
playerNames = {}
for session in [@session, @otherSession] when session?.get('team')
playerNames[session.get('team')] = session.get('creatorName') or 'An<NAME>'
playerNames
# Once Surface is Loaded ####################################################
onLevelStarted: ->
return unless @surface?
@loadingView.showReady()
@trackLevelLoadEnd()
if window.currentModal and not window.currentModal.destroyed and window.currentModal.constructor isnt VictoryModal
return Backbone.Mediator.subscribeOnce 'modal:closed', @onLevelStarted, @
@surface.showLevel()
if @otherSession and not (@level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop'])
# TODO: colorize name and cloud by team, colorize wizard by user's color config
@surface.createOpponentWizard id: @otherSession.get('creator'), name: @otherSession.get('creatorName'), team: @otherSession.get('team'), levelSlug: @level.get('slug'), codeLanguage: @otherSession.get('submittedCodeLanguage')
if @isEditorPreview or @observing
@loadingView.startUnveiling()
@loadingView.unveil()
onLoadingViewUnveiling: (e) ->
@restoreSessionState()
onLoadingViewUnveiled: (e) ->
@loadingView.$el.remove()
@removeSubView @loadingView
@loadingView = null
@playAmbientSound()
if @options.realTimeMultiplayerSessionID?
Backbone.Mediator.publish 'playback:real-time-playback-waiting', {}
@realTimeMultiplayerContinueGame @options.realTimeMultiplayerSessionID
# TODO: Is it possible to create a Mongoose ObjectId for 'ls', instead of the string returned from get()?
application.tracker?.trackEvent 'Started Level', category:'Play Level', levelID: @levelID, ls: @session?.get('_id') unless @observing
$(window).trigger 'resize'
playAmbientSound: ->
return if @destroyed
return if @ambientSound
return unless file = {Dungeon: 'ambient-dungeon', Grass: 'ambient-grass'}[@level.get('terrain')]
src = "/file/interface/#{file}#{AudioPlayer.ext}"
unless AudioPlayer.getStatus(src)?.loaded
AudioPlayer.preloadSound src
Backbone.Mediator.subscribeOnce 'audio-player:loaded', @playAmbientSound, @
return
@ambientSound = createjs.Sound.play src, loop: -1, volume: 0.1
createjs.Tween.get(@ambientSound).to({volume: 1.0}, 10000)
restoreSessionState: ->
return if @alreadyLoadedState
@alreadyLoadedState = true
state = @originalSessionState
if not @level or @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']
Backbone.Mediator.publish 'level:suppress-selection-sounds', suppress: true
Backbone.Mediator.publish 'tome:select-primary-sprite', {}
Backbone.Mediator.publish 'level:suppress-selection-sounds', suppress: false
@surface.focusOnHero()
Backbone.Mediator.publish 'level:set-time', time: 0
Backbone.Mediator.publish 'level:set-playing', playing: true
else
if state.selected
# TODO: Should also restore selected spell here by saving spellName
Backbone.Mediator.publish 'level:select-sprite', thangID: state.selected, spellName: null
# callbacks
onCtrlS: (e) ->
e.preventDefault()
onEscapePressed: (e) ->
return unless @$el.hasClass 'real-time'
Backbone.Mediator.publish 'playback:stop-real-time-playback', {}
onLevelReloadFromData: (e) ->
isReload = Boolean @world
@setLevel e.level, e.supermodel
if isReload
@scriptManager.setScripts(e.level.get('scripts'))
Backbone.Mediator.publish 'tome:cast-spell', {} # a bit hacky
onLevelReloadThangType: (e) ->
tt = e.thangType
for url, model of @supermodel.models
if model.id is tt.id
for key, val of tt.attributes
model.attributes[key] = val
break
Backbone.Mediator.publish 'tome:cast-spell', {}
onWindowResize: (e) => @endHighlight()
onDisableControls: (e) ->
return if e.controls and not ('level' in e.controls)
@shortcutsEnabled = false
@wasFocusedOn = document.activeElement
$('body').focus()
onEnableControls: (e) ->
return if e.controls? and not ('level' in e.controls)
@shortcutsEnabled = true
$(@wasFocusedOn).focus() if @wasFocusedOn
@wasFocusedOn = null
onDonePressed: -> @showVictory()
onShowVictory: (e) ->
$('#level-done-button').show() unless @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']
@showVictory() if e.showModal
return if @victorySeen
@victorySeen = true
victoryTime = (new Date()) - @loadEndTime
if not @observing and victoryTime > 10 * 1000 # Don't track it if we're reloading an already-beaten level
application.tracker?.trackEvent 'Saw Victory',
category: 'Play Level'
level: @level.get('name')
label: @level.get('name')
levelID: @levelID
ls: @session?.get('_id')
application.tracker?.trackTiming victoryTime, 'Level Victory Time', @levelID, @levelID
showVictory: ->
@endHighlight()
options = {level: @level, supermodel: @supermodel, session: @session, hasReceivedMemoryWarning: @hasReceivedMemoryWarning}
ModalClass = if @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop'] then HeroVictoryModal else VictoryModal
victoryModal = new ModalClass(options)
@openModalView(victoryModal)
if me.get('anonymous')
window.nextURL = '/play/' + (@level.get('campaign') ? '') # Signup will go here on completion instead of reloading.
onRestartLevel: ->
@tome.reloadAllCode()
Backbone.Mediator.publish 'level:restarted', {}
$('#level-done-button', @$el).hide()
application.tracker?.trackEvent 'Confirmed Restart', category: 'Play Level', level: @level.get('name'), label: @level.get('name') unless @observing
onInfiniteLoop: (e) ->
return unless e.firstWorld
@openModalView new InfiniteLoopModal nonUserCodeProblem: e.nonUserCodeProblem
application.tracker?.trackEvent 'Saw Initial Infinite Loop', category: 'Play Level', level: @level.get('name'), label: @level.get('name') unless @observing
onHighlightDOM: (e) -> @highlightElement e.selector, delay: e.delay, sides: e.sides, offset: e.offset, rotation: e.rotation
onEndHighlight: -> @endHighlight()
onFocusDom: (e) -> $(e.selector).focus()
onMultiplayerChanged: (e) ->
if @session.get('multiplayer')
@bus.connect()
else
@bus.removeFirebaseData =>
@bus.disconnect()
onSessionWillSave: (e) ->
# Something interesting has happened, so (at a lower frequency), we'll save a screenshot.
#@saveScreenshot e.session
# Throttled
saveScreenshot: (session) =>
return unless screenshot = @surface?.screenshot()
session.save {screenshot: screenshot}, {patch: true, type: 'PUT'}
onContactClicked: (e) ->
@openModalView contactModal = new ContactModal()
screenshot = @surface.screenshot(1, 'image/png', 1.0, 1)
body =
b64png: screenshot.replace 'data:image/png;base64,', ''
filename: "screenshot-#{@levelID}-#{_.string.slugify((new Date()).toString())}.png"
path: "db/user/#{me.id}"
mimetype: 'image/png'
contactModal.screenshotURL = "http://codecombat.com/file/#{body.path}/#{body.filename}"
window.screenshot = screenshot
window.screenshotURL = contactModal.screenshotURL
$.ajax '/file', type: 'POST', data: body, success: (e) ->
contactModal.updateScreenshot?()
# Dynamic sound loading
onNewWorld: (e) ->
return if @headless
scripts = @world.scripts # Since these worlds don't have scripts, preserve them.
@world = e.world
@world.scripts = scripts
thangTypes = @supermodel.getModels(ThangType)
startFrame = @lastWorldFramesLoaded ? 0
finishedLoading = @world.frames.length is @world.totalFrames
if finishedLoading
@lastWorldFramesLoaded = 0
if @waitingForSubmissionComplete
_.defer @onSubmissionComplete # Give it a frame to make sure we have the latest goals
@waitingForSubmissionComplete = false
else
@lastWorldFramesLoaded = @world.frames.length
for [spriteName, message] in @world.thangDialogueSounds startFrame
continue unless thangType = _.find thangTypes, (m) -> m.get('name') is spriteName
continue unless sound = AudioPlayer.soundForDialogue message, thangType.get('soundTriggers')
AudioPlayer.preloadSoundReference sound
# Real-time playback
onRealTimePlaybackWaiting: (e) ->
@$el.addClass('real-time').focus()
@onWindowResize()
onRealTimePlaybackStarted: (e) ->
@$el.addClass('real-time').focus()
@onWindowResize()
onRealTimePlaybackEnded: (e) ->
return unless @$el.hasClass 'real-time'
@$el.removeClass 'real-time'
@onWindowResize()
if @world.frames.length is @world.totalFrames
_.delay @onSubmissionComplete, 750 # Wait for transition to end.
else
@waitingForSubmissionComplete = true
@onRealTimeMultiplayerPlaybackEnded()
onSubmissionComplete: =>
return if @destroyed
# TODO: Show a victory dialog specific to hero-ladder level
if @goalManager.checkOverallStatus() is 'success' and not @options.realTimeMultiplayerSessionID?
showModalFn = -> Backbone.Mediator.publish 'level:show-victory', showModal: true
@session.recordScores @world.scores, @level
if @level.get 'replayable'
@session.increaseDifficulty showModalFn
else
showModalFn()
destroy: ->
@levelLoader?.destroy()
@surface?.destroy()
@god?.destroy()
@goalManager?.destroy()
@scriptManager?.destroy()
@setupManager?.destroy()
if ambientSound = @ambientSound
# Doesn't seem to work; stops immediately.
createjs.Tween.get(ambientSound).to({volume: 0.0}, 1500).call -> ambientSound.stop()
$(window).off 'resize', @onWindowResize
delete window.world # not sure where this is set, but this is one way to clean it up
@bus?.destroy()
#@instance.save() unless @instance.loading
delete window.nextURL
console.profileEnd?() if PROFILE_ME
@onRealTimeMultiplayerLevelUnloaded()
super()
onIPadMemoryWarning: (e) ->
@hasReceivedMemoryWarning = true
onItemPurchased: (e) ->
heroConfig = @session.get('heroConfig') ? {}
inventory = heroConfig.inventory ? {}
slot = e.item.getAllowedSlots()[0]
if slot and not inventory[slot]
# Open up the inventory modal so they can equip the new item
@setupManager?.destroy()
@setupManager = new LevelSetupManager({supermodel: @supermodel, levelID: @levelID, parent: @, session: @session, hadEverChosenHero: true})
@setupManager.open()
# Start Real-time Multiplayer ######################################################
#
# This view acts as a hub for the real-time multiplayer session for the current level.
#
# It performs these actions:
# Player heartbeat
# Publishes player status
# Updates real-time multiplayer session state
# Updates real-time multiplayer player state
# Cleans up old sessions (sets state to 'finished')
# Real-time multiplayer cast handshake
# Swap teams on game joined, if necessary
# Reload PlayLevelView on real-time submit, automatically continue game and real-time playback
#
# It monitors these:
# Real-time multiplayer sessions
# Current real-time multiplayer session
# Internal multiplayer create/joined/left events
#
# Real-time state variables.
# Each Ref is Firebase reference, and may have a matching Data suffixed variable with the latest data received.
# @realTimePlayerRef - User's real-time multiplayer player for this level
# @realTimePlayerGameRef - User's current real-time multiplayer player game session
# @realTimeSessionRef - Current real-time multiplayer game session
# @realTimeOpponentRef - Current real-time multiplayer opponent
# @realTimePlayersRef - Real-time players for current real-time multiplayer game session
# @options.realTimeMultiplayerSessionID - Need to continue an existing real-time multiplayer session
#
# TODO: Move this code to it's own file, or possibly the LevelBus
# TODO: Save settings somewhere reasonable
multiplayerFireHost: 'https://codecombat.firebaseio.com/test/db/'
onRealTimeMultiplayerLevelLoaded: (session) ->
# console.log 'PlayLevelView onRealTimeMultiplayerLevelLoaded'
return if @realTimePlayerRef?
return if me.get('anonymous')
@realTimePlayerRef = new Firebase "#{@multiplayerFireHost}multiplayer_players/#{@levelID}/#{me.id}"
unless @options.realTimeMultiplayerSessionID?
# TODO: Wait for name instead of using '<NAME>', or try and update it later?
name = me.get('name') ? session.get('creatorName') ? '<NAME>'
@realTimePlayerRef.set
id: me.id # TODO: is this redundant info necessary?
name: name
state: 'playing'
created: new Date().toISOString()
heartbeat: new Date().toISOString()
@timerMultiplayerHeartbeatID = setInterval @onRealTimeMultiplayerHeartbeat, 60 * 1000
@cleanupRealTimeSessions()
cleanupRealTimeSessions: ->
# console.log 'PlayLevelView cleanupRealTimeSessions'
# TODO: Reduce this call, possibly by username and dates
realTimeSessionCollection = new Firebase "#{@multiplayerFireHost}multiplayer_level_sessions/#{@levelID}"
realTimeSessionCollection.once 'value', (collectionSnapshot) =>
for multiplayerSessionID, multiplayerSession of collectionSnapshot.val()
continue if @options.realTimeMultiplayerSessionID? and @options.realTimeMultiplayerSessionID is multiplayerSessionID
continue unless multiplayerSession.state isnt 'finished'
player = realTimeSessionCollection.child "#{multiplayerSession.id}/players/#{me.id}"
player.once 'value', (playerSnapshot) =>
if playerSnapshot.val()
console.info 'Cleaning up previous real-time multiplayer session', multiplayerSessionID
player.update 'state': 'left'
multiplayerSessionRef = realTimeSessionCollection.child "#{multiplayerSessionID}"
multiplayerSessionRef.update 'state': 'finished'
onRealTimeMultiplayerLevelUnloaded: ->
# console.log 'PlayLevelView onRealTimeMultiplayerLevelUnloaded'
if @timerMultiplayerHeartbeatID?
clearInterval @timerMultiplayerHeartbeatID
@timerMultiplayerHeartbeatID = null
# TODO: similar to game ending cleanup
if @realTimeOpponentRef?
@realTimeOpponentRef.off 'value', @onRealTimeOpponentChanged
@realTimeOpponentRef = null
if @realTimePlayersRef?
@realTimePlayersRef.off 'child_added', @onRealTimePlayerAdded
@realTimePlayersRef = null
if @realTimeSessionRef?
@realTimeSessionRef.off 'value', @onRealTimeSessionChanged
@realTimeSessionRef = null
if @realTimePlayerGameRef?
@realTimePlayerGameRef = null
if @realTimePlayerRef?
@realTimePlayerRef = null
onRealTimeMultiplayerHeartbeat: =>
# console.log 'PlayLevelView onRealTimeMultiplayerHeartbeat', @realTimePlayerRef
@realTimePlayerRef.update 'heartbeat': new Date().toISOString() if @realTimePlayerRef?
onRealTimeMultiplayerCreatedGame: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerCreatedGame'
@joinRealTimeMultiplayerGame e
@realTimePlayerGameRef.update 'state': 'coding'
@realTimePlayerRef.update 'state': 'available'
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: 'Waiting for opponent..'
onRealTimeSessionChanged: (snapshot) =>
# console.log 'PlayLevelView onRealTimeSessionChanged', snapshot.val()
@realTimeSessionData = snapshot.val()
if @realTimeSessionData?.state is 'finished'
@realTimeGameEnded()
Backbone.Mediator.publish 'real-time-multiplayer:left-game', {}
onRealTimePlayerAdded: (snapshot) =>
# console.log 'PlayLevelView onRealTimePlayerAdded', snapshot.val()
# Assume game is full, game on
data = snapshot.val()
if data? and data.id isnt me.id
@realTimeOpponentData = data
# console.log 'PlayLevelView onRealTimePlayerAdded opponent', @realTimeOpponentData, @realTimePlayersData
@realTimePlayersData[@realTimeOpponentData.id] = @realTimeOpponentData
if @realTimeSessionData?.state is 'creating'
@realTimeSessionRef.update 'state': 'coding'
@realTimePlayerRef.update 'state': 'unavailable'
@realTimeOpponentRef = @realTimeSessionRef.child "players/#{@realTimeOpponentData.id}"
@realTimeOpponentRef.on 'value', @onRealTimeOpponentChanged
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "Playing against #{@realTimeOpponentData.name}"
onRealTimeOpponentChanged: (snapshot) =>
# console.log 'PlayLevelView onRealTimeOpponentChanged', snapshot.val()
@realTimeOpponentData = snapshot.val()
switch @realTimeOpponentData?.state
when 'left'
console.info 'Real-time multiplayer opponent left the game'
opponentID = @realTimeOpponentData.id
@realTimeGameEnded()
Backbone.Mediator.publish 'real-time-multiplayer:left-game', userID: opponentID
when 'submitted'
# TODO: What should this message say?
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "#{@realTimeOpponentData.name} waiting for your code"
joinRealTimeMultiplayerGame: (e) ->
# console.log 'PlayLevelView joinRealTimeMultiplayerGame', e
unless @realTimeSessionRef?
@session.set('submittedCodeLanguage', @session.get('codeLanguage'))
@session.save()
@realTimeSessionRef = new Firebase "#{@multiplayerFireHost}multiplayer_level_sessions/#{@levelID}/#{e.realTimeSessionID}"
@realTimePlayersRef = @realTimeSessionRef.child 'players'
# Look for opponent
@realTimeSessionRef.once 'value', (multiplayerSessionSnapshot) =>
if @realTimeSessionData = multiplayerSessionSnapshot.val()
@realTimePlayersRef.once 'value', (playsSnapshot) =>
if @realTimePlayersData = playsSnapshot.val()
for id, player of @realTimePlayersData
if id isnt me.id
@realTimeOpponentRef = @realTimeSessionRef.child "players/#{id}"
@realTimeOpponentRef.once 'value', (opponentSnapshot) =>
if @realTimeOpponentData = opponentSnapshot.val()
@updateTeam()
else
console.error 'Could not lookup multiplayer opponent data.'
@realTimeOpponentRef.on 'value', @onRealTimeOpponentChanged
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: 'Playing against ' + player.name
else
console.error 'Could not lookup multiplayer session players data.'
# TODO: need child_removed too?
@realTimePlayersRef.on 'child_added', @onRealTimePlayerAdded
else
console.error 'Could not lookup multiplayer session data.'
@realTimeSessionRef.on 'value', @onRealTimeSessionChanged
@realTimePlayerGameRef = @realTimeSessionRef.child "players/#{me.id}"
# TODO: Follow up in MultiplayerView to see if double joins can be avoided
# else
# console.error 'Joining real-time multiplayer game with an existing @realTimeSessionRef.'
onRealTimeMultiplayerJoinedGame: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerJoinedGame', e
@joinRealTimeMultiplayerGame e
@realTimePlayerGameRef.update 'state': 'coding'
@realTimePlayerRef.update 'state': 'unavailable'
onRealTimeMultiplayerLeftGame: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerLeftGame', e
if e.userID? and e.userID is me.id
@realTimePlayerGameRef.update 'state': 'left'
@realTimeGameEnded()
realTimeMultiplayerContinueGame: (realTimeSessionID) ->
# console.log 'PlayLevelView realTimeMultiplayerContinueGame', realTimeSessionID, me.id
Backbone.Mediator.publish 'real-time-multiplayer:joined-game', realTimeSessionID: realTimeSessionID
console.info 'Setting my game status to ready'
@realTimePlayerGameRef.update 'state': 'ready'
if @realTimeOpponentData.state is 'ready'
@realTimeOpponentIsReady()
else
console.info 'Waiting for opponent to be ready'
@realTimeOpponentRef.on 'value', @realTimeOpponentMaybeReady
realTimeOpponentMaybeReady: (snapshot) =>
# console.log 'PlayLevelView realTimeOpponentMaybeReady'
if @realTimeOpponentData = snapshot.val()
if @realTimeOpponentData.state is 'ready'
@realTimeOpponentRef.off 'value', @realTimeOpponentMaybeReady
@realTimeOpponentIsReady()
realTimeOpponentIsReady: =>
console.info 'All real-time multiplayer players are ready!'
@realTimeSessionRef.update 'state': 'running'
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: 'Battling ' + @realTimeOpponentData.name
Backbone.Mediator.publish 'tome:manual-cast', {realTime: true}
realTimeGameEnded: ->
if @realTimeOpponentRef?
@realTimeOpponentRef.off 'value', @onRealTimeOpponentChanged
@realTimeOpponentRef = null
if @realTimePlayersRef?
@realTimePlayersRef.off 'child_added', @onRealTimePlayerAdded
@realTimePlayersRef = null
if @realTimeSessionRef?
@realTimeSessionRef.off 'value', @onRealTimeSessionChanged
@realTimeSessionRef.update 'state': 'finished'
@realTimeSessionRef = null
if @realTimePlayerGameRef?
@realTimePlayerGameRef = null
if @realTimePlayerRef?
@realTimePlayerRef.update 'state': 'playing'
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: ''
onRealTimeMultiplayerCast: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerCast', @realTimeSessionData, @realTimePlayersData
unless @realTimeSessionRef?
console.error 'Real-time multiplayer cast without multiplayer session.'
return
unless @realTimeSessionData?
console.error 'Real-time multiplayer cast without multiplayer data.'
return
unless @realTimePlayersData?
console.error 'Real-time multiplayer cast without multiplayer players data.'
return
# Set submissionCount for created real-time multiplayer session
if me.id is @realTimeSessionData.creator
sessionState = @session.get('state')
if sessionState?
submissionCount = sessionState.submissionCount ? 0
console.info 'Setting multiplayer submissionCount to', submissionCount
@realTimeSessionRef.update 'submissionCount': submissionCount
else
console.error 'Failed to read sessionState in onRealTimeMultiplayerCast'
console.info 'Submitting my code'
# Transpiling code copied from scripts/transpile.coffee
# TODO: Should this live somewhere else?
transpiledCode = {}
for thang, spells of @session.get('code')
transpiledCode[thang] = {}
for spellID, spell of spells
spellName = thang + '/' + spellID
continue if @session.get('teamSpells') and not (spellName in @session.get('teamSpells')[@session.get('team')])
# console.log "PlayLevelView Transpiling spell #{spellName}"
aetherOptions = createAetherOptions functionName: spellID, codeLanguage: @session.get('submittedCodeLanguage'), includeFlow: true
aether = new Aether aetherOptions
transpiledCode[thang][spellID] = aether.transpile spell
# console.log "PlayLevelView transpiled code", transpiledCode
@session.set 'transpiledCode', transpiledCode
permissions = @session.get 'permissions' ? []
unless _.find(permissions, (p) -> p.target is 'public' and p.access is 'read')
permissions.push target:'public', access:'read'
@session.set 'permissions', permissions
@session.patch()
@realTimePlayerGameRef.update 'state': 'submitted'
console.info 'Other player is', @realTimeOpponentData.state
if @realTimeOpponentData.state in ['submitted', 'ready']
@realTimeOpponentSubmittedCode @realTimeOpponentData, @realTimePlayerGameData
else
# Wait for opponent to submit their code
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "Waiting for code from #{@realTimeOpponentData.name}"
@realTimeOpponentRef.on 'value', @realTimeOpponentMaybeSubmitted
realTimeOpponentMaybeSubmitted: (snapshot) =>
if @realTimeOpponentData = snapshot.val()
if @realTimeOpponentData.state in ['submitted', 'ready']
@realTimeOpponentRef.off 'value', @realTimeOpponentMaybeSubmitted
@realTimeOpponentSubmittedCode @realTimeOpponentData, @realTimePlayerGameData
onRealTimeMultiplayerPlaybackEnded: ->
# console.log 'PlayLevelView onRealTimeMultiplayerPlaybackEnded'
if @realTimeSessionRef?
@realTimeSessionRef.update 'state': 'coding'
@realTimePlayerGameRef.update 'state': 'coding'
if @realTimeOpponentData?
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "Playing against #{@realTimeOpponentData.name}"
realTimeOpponentSubmittedCode: (opponentPlayer, myPlayer) =>
# console.log 'PlayLevelView realTimeOpponentSubmittedCode', @realTimeSessionData.id, opponentPlayer.level_session
# Read submissionCount for joined real-time multiplayer session
if me.id isnt @realTimeSessionData.creator
sessionState = @session.get('state') ? {}
newSubmissionCount = @realTimeSessionData.submissionCount
if newSubmissionCount?
# TODO: This isn't always getting updated where the random seed generation uses it.
sessionState.submissionCount = parseInt newSubmissionCount
console.info 'Got multiplayer submissionCount', sessionState.submissionCount
@session.set 'state', sessionState
@session.patch()
# Reload this level so the opponent session can easily be wired up
Backbone.Mediator.publish 'router:navigate',
route: "/play/level/#{@levelID}"
viewClass: PlayLevelView
viewArgs: [{supermodel: @supermodel, autoUnveil: true, realTimeMultiplayerSessionID: @realTimeSessionData.id, opponent: opponentPlayer.level_session, team: @team}, @levelID]
updateTeam: ->
# If not creator, and same team as creator, then switch teams
# TODO: Assumes there are only 'humans' and 'ogres'
unless @realTimeOpponentData?
console.error 'Tried to switch teams without real-time multiplayer opponent data.'
return
unless @realTimeSessionData?
console.error 'Tried to switch teams without real-time multiplayer session data.'
return
return if me.id is @realTimeSessionData.creator
oldTeam = @realTimeOpponentData.team
return unless oldTeam is @session.get('team')
# Need to switch to other team
newTeam = if oldTeam is 'humans' then 'ogres' else 'humans'
console.info "Switching from team #{oldTeam} to #{newTeam}"
# Move code from old team to new team
# Assumes teamSpells has matching spells for each team
# TODO: Similar to code in loadOpponentTeam, consolidate?
code = @session.get 'code'
teamSpells = @session.get 'teamSpells'
for oldSpellKey in teamSpells[oldTeam]
[oldThang, oldSpell] = oldSpellKey.split '/'
oldCode = code[oldThang]?[oldSpell]
continue unless oldCode?
# Move oldCode to new team under same spell
for newSpellKey in teamSpells[newTeam]
[newThang, newSpell] = newSpellKey.split '/'
if newSpell is oldSpell
# Found spell location under new team
# console.log "Swapping spell=#{oldSpell} from #{oldThang} to #{newThang}"
if code[newThang]?[oldSpell]?
# Option 1: have a new spell to swap
code[oldThang][oldSpell] = code[newThang][oldSpell]
else
# Option 2: no new spell to swap
delete code[oldThang][oldSpell]
code[newThang] = {} unless code[newThang]?
code[newThang][oldSpell] = oldCode
break
@setTeam newTeam # Sets @session 'team'
sessionState = @session.get('state')
if sessionState?
# TODO: Don't hard code thangID
sessionState.selected = if newTeam is 'humans' then 'Hero Placeholder' else 'Hero Placeholder 1'
@session.set 'state', sessionState
@session.set 'code', code
@session.patch()
if sessionState?
# TODO: Don't hardcode spellName
Backbone.Mediator.publish 'level:select-sprite', thangID: sessionState.selected, spellName: 'plan'
# End Real-time Multiplayer ######################################################
| true | RootView = require 'views/core/RootView'
template = require 'templates/play/level'
{me} = require 'core/auth'
ThangType = require 'models/ThangType'
utils = require 'core/utils'
storage = require 'core/storage'
{createAetherOptions} = require 'lib/aether_utils'
# tools
Surface = require 'lib/surface/Surface'
God = require 'lib/God'
GoalManager = require 'lib/world/GoalManager'
ScriptManager = require 'lib/scripts/ScriptManager'
LevelBus = require 'lib/LevelBus'
LevelLoader = require 'lib/LevelLoader'
LevelSession = require 'models/LevelSession'
Level = require 'models/Level'
LevelComponent = require 'models/LevelComponent'
Article = require 'models/Article'
Camera = require 'lib/surface/Camera'
AudioPlayer = require 'lib/AudioPlayer'
# subviews
LevelLoadingView = require './LevelLoadingView'
ProblemAlertView = require './tome/ProblemAlertView'
TomeView = require './tome/TomeView'
ChatView = require './LevelChatView'
HUDView = require './LevelHUDView'
LevelDialogueView = require './LevelDialogueView'
ControlBarView = require './ControlBarView'
LevelPlaybackView = require './LevelPlaybackView'
GoalsView = require './LevelGoalsView'
LevelFlagsView = require './LevelFlagsView'
GoldView = require './LevelGoldView'
VictoryModal = require './modal/VictoryModal'
HeroVictoryModal = require './modal/HeroVictoryModal'
InfiniteLoopModal = require './modal/InfiniteLoopModal'
LevelSetupManager = require 'lib/LevelSetupManager'
ContactModal = require 'views/core/ContactModal'
PROFILE_ME = false
module.exports = class PlayLevelView extends RootView
id: 'level-view'
template: template
cache: false
shortcutsEnabled: true
isEditorPreview: false
subscriptions:
'level:set-volume': (e) -> createjs.Sound.setVolume(if e.volume is 1 then 0.6 else e.volume) # Quieter for now until individual sound FX controls work again.
'level:show-victory': 'onShowVictory'
'level:restart': 'onRestartLevel'
'level:highlight-dom': 'onHighlightDOM'
'level:end-highlight-dom': 'onEndHighlight'
'level:focus-dom': 'onFocusDom'
'level:disable-controls': 'onDisableControls'
'level:enable-controls': 'onEnableControls'
'god:world-load-progress-changed': 'onWorldLoadProgressChanged'
'god:new-world-created': 'onNewWorld'
'god:streaming-world-updated': 'onNewWorld'
'god:infinite-loop': 'onInfiniteLoop'
'level:reload-from-data': 'onLevelReloadFromData'
'level:reload-thang-type': 'onLevelReloadThangType'
'level:session-will-save': 'onSessionWillSave'
'level:started': 'onLevelStarted'
'level:loading-view-unveiling': 'onLoadingViewUnveiling'
'level:loading-view-unveiled': 'onLoadingViewUnveiled'
'level:session-loaded': 'onSessionLoaded'
'playback:real-time-playback-waiting': 'onRealTimePlaybackWaiting'
'playback:real-time-playback-started': 'onRealTimePlaybackStarted'
'playback:real-time-playback-ended': 'onRealTimePlaybackEnded'
'real-time-multiplayer:created-game': 'onRealTimeMultiplayerCreatedGame'
'real-time-multiplayer:joined-game': 'onRealTimeMultiplayerJoinedGame'
'real-time-multiplayer:left-game': 'onRealTimeMultiplayerLeftGame'
'real-time-multiplayer:manual-cast': 'onRealTimeMultiplayerCast'
'ipad:memory-warning': 'onIPadMemoryWarning'
'store:item-purchased': 'onItemPurchased'
events:
'click #level-done-button': 'onDonePressed'
'click #stop-real-time-playback-button': -> Backbone.Mediator.publish 'playback:stop-real-time-playback', {}
'click #fullscreen-editor-background-screen': (e) -> Backbone.Mediator.publish 'tome:toggle-maximize', {}
'click .contact-link': 'onContactClicked'
shortcuts:
'ctrl+s': 'onCtrlS'
'esc': 'onEscapePressed'
# Initial Setup #############################################################
constructor: (options, @levelID) ->
console.profile?() if PROFILE_ME
super options
@isEditorPreview = @getQueryVariable 'dev'
@sessionID = @getQueryVariable 'session'
@observing = @getQueryVariable 'observing'
@opponentSessionID = @getQueryVariable('opponent')
@opponentSessionID ?= @options.opponent
$(window).on 'resize', @onWindowResize
@saveScreenshot = _.throttle @saveScreenshot, 30000
if @isEditorPreview
@supermodel.shouldSaveBackups = (model) -> # Make sure to load possibly changed things from localStorage.
model.constructor.className in ['Level', 'LevelComponent', 'LevelSystem', 'ThangType']
f = => @load() unless @levelLoader # Wait to see if it's just given to us through setLevel.
setTimeout f, 100
else
@load()
application.tracker?.trackEvent 'Started Level Load', category: 'Play Level', level: @levelID, label: @levelID unless @observing
setLevel: (@level, givenSupermodel) ->
@supermodel.models = givenSupermodel.models
@supermodel.collections = givenSupermodel.collections
@supermodel.shouldSaveBackups = givenSupermodel.shouldSaveBackups
serializedLevel = @level.serialize @supermodel, @session, @otherSession
@god?.setLevel serializedLevel
if @world
@world.loadFromLevel serializedLevel, false
else
@load()
load: ->
@loadStartTime = new Date()
@god = new God debugWorker: true
@levelLoader = new LevelLoader supermodel: @supermodel, levelID: @levelID, sessionID: @sessionID, opponentSessionID: @opponentSessionID, team: @getQueryVariable('team'), observing: @observing
@listenToOnce @levelLoader, 'world-necessities-loaded', @onWorldNecessitiesLoaded
trackLevelLoadEnd: ->
return if @isEditorPreview
@loadEndTime = new Date()
loadDuration = @loadEndTime - @loadStartTime
console.debug "Level unveiled after #{(loadDuration / 1000).toFixed(2)}s"
unless @observing
application.tracker?.trackEvent 'Finished Level Load', category: 'Play Level', label: @levelID, level: @levelID, loadDuration: loadDuration
application.tracker?.trackTiming loadDuration, 'Level Load Time', @levelID, @levelID
# CocoView overridden methods ###############################################
getRenderData: ->
c = super()
c.world = @world
c
afterRender: ->
super()
window.onPlayLevelViewLoaded? @ # still a hack
@insertSubView @loadingView = new LevelLoadingView autoUnveil: @options.autoUnveil or @observing, level: @levelLoader?.level ? @level # May not have @level loaded yet
@$el.find('#level-done-button').hide()
$('body').addClass('is-playing')
$('body').bind('touchmove', false) if @isIPadApp()
afterInsert: ->
super()
# Partially Loaded Setup ####################################################
onWorldNecessitiesLoaded: ->
# Called when we have enough to build the world, but not everything is loaded
@grabLevelLoaderData()
team = @getQueryVariable('team') ? @session.get('team') ? @world.teamForPlayer(0)
@loadOpponentTeam(team)
@setupGod()
@setTeam team
@initGoalManager()
@insertSubviews()
@initVolume()
@listenTo(@session, 'change:multiplayer', @onMultiplayerChanged)
@originalSessionState = $.extend(true, {}, @session.get('state'))
@register()
@controlBar.setBus(@bus)
@initScriptManager()
grabLevelLoaderData: ->
@session = @levelLoader.session
@world = @levelLoader.world
@level = @levelLoader.level
@$el.addClass 'hero' if @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']
@$el.addClass 'flags' if _.any(@world.thangs, (t) -> (t.programmableProperties and 'findFlags' in t.programmableProperties) or t.inventory?.flag) or @level.get('slug') is 'sky-span'
# TODO: Update terminology to always be opponentSession or otherSession
# TODO: E.g. if it's always opponent right now, then variable names should be opponentSession until we have coop play
@otherSession = @levelLoader.opponentSession
@worldLoadFakeResources = [] # first element (0) is 1%, last (100) is 100%
for percent in [1 .. 100]
@worldLoadFakeResources.push @supermodel.addSomethingResource "world_simulation_#{percent}%", 1
onWorldLoadProgressChanged: (e) ->
return unless @worldLoadFakeResources
@lastWorldLoadPercent ?= 0
worldLoadPercent = Math.floor 100 * e.progress
for percent in [@lastWorldLoadPercent + 1 .. worldLoadPercent] by 1
@worldLoadFakeResources[percent - 1].markLoaded()
@lastWorldLoadPercent = worldLoadPercent
@worldFakeLoadResources = null if worldLoadPercent is 100 # Done, don't need to watch progress any more.
loadOpponentTeam: (myTeam) ->
opponentSpells = []
for spellTeam, spells of @session.get('teamSpells') ? @otherSession?.get('teamSpells') ? {}
continue if spellTeam is myTeam or not myTeam
opponentSpells = opponentSpells.concat spells
if (not @session.get('teamSpells')) and @otherSession?.get('teamSpells')
@session.set('teamSpells', @otherSession.get('teamSpells'))
opponentCode = @otherSession?.get('transpiledCode') or {}
myCode = @session.get('code') or {}
for spell in opponentSpells
[thang, spell] = spell.split '/'
c = opponentCode[thang]?[spell]
myCode[thang] ?= {}
if c then myCode[thang][spell] = c else delete myCode[thang][spell]
@session.set('code', myCode)
if @session.get('multiplayer') and @otherSession?
# For now, ladderGame will disallow multiplayer, because session code combining doesn't play nice yet.
@session.set 'multiplayer', false
setupGod: ->
@god.setLevel @level.serialize @supermodel, @session, @otherSession
@god.setLevelSessionIDs if @otherSession then [@session.id, @otherSession.id] else [@session.id]
@god.setWorldClassMap @world.classMap
setTeam: (team) ->
team = team?.team unless _.isString team
team ?= 'humans'
me.team = team
@session.set 'team', team
Backbone.Mediator.publish 'level:team-set', team: team # Needed for scripts
@team = team
initGoalManager: ->
@goalManager = new GoalManager(@world, @level.get('goals'), @team)
@god.setGoalManager @goalManager
insertSubviews: ->
@insertSubView @tome = new TomeView levelID: @levelID, session: @session, otherSession: @otherSession, thangs: @world.thangs, supermodel: @supermodel, level: @level, observing: @observing
@insertSubView new LevelPlaybackView session: @session, level: @level
@insertSubView new GoalsView {}
@insertSubView new LevelFlagsView levelID: @levelID, world: @world if @$el.hasClass 'flags'
@insertSubView new GoldView {}
@insertSubView new HUDView {level: @level}
@insertSubView new LevelDialogueView {level: @level, sessionID: @session.id}
@insertSubView new ChatView levelID: @levelID, sessionID: @session.id, session: @session
@insertSubView new ProblemAlertView session: @session, level: @level, supermodel: @supermodel
worldName = utils.i18n @level.attributes, 'name'
@controlBar = @insertSubView new ControlBarView {worldName: worldName, session: @session, level: @level, supermodel: @supermodel}
#_.delay (=> Backbone.Mediator.publish('level:set-debug', debug: true)), 5000 if @isIPadApp() # if me.displayName() is 'PI:NAME:<NAME>END_PI'
initVolume: ->
volume = me.get('volume')
volume = 1.0 unless volume?
Backbone.Mediator.publish 'level:set-volume', volume: volume
initScriptManager: ->
@scriptManager = new ScriptManager({scripts: @world.scripts or [], view: @, session: @session, levelID: @level.get('slug')})
@scriptManager.loadFromSession()
register: ->
@bus = LevelBus.get(@levelID, @session.id)
@bus.setSession(@session)
@bus.setSpells @tome.spells
if @session.get('multiplayer') and not me.isAdmin()
@session.set 'multiplayer', false # Temp: multiplayer has bugged out some sessions, so ignoring it.
@bus.connect() if @session.get('multiplayer')
# Load Completed Setup ######################################################
onSessionLoaded: (e) ->
Backbone.Mediator.publish "ipad:language-chosen", language: e.session.get('codeLanguage') ? "python"
# Just the level and session have been loaded by the level loader
if e.level.get('slug') is 'zero-sum'
sorcerer = '52fd1524c7e6cf99160e7bc9'
if e.session.get('creator') is '532dbc73a622924444b68ed9' # Wizard Dude gets his own avatar
sorcerer = '53e126a4e06b897606d38bef'
e.session.set 'heroConfig', {"thangType":sorcerer,"inventory":{"misc-0":"53e2396a53457600003e3f0f","programming-book":"546e266e9df4a17d0d449be5","minion":"54eb5dbc49fa2d5c905ddf56","feet":"53e214f153457600003e3eab","right-hand":"54eab7f52b7506e891ca7202","left-hand":"5463758f3839c6e02811d30f","wrists":"54693797a2b1f53ce79443e9","gloves":"5469425ca2b1f53ce7944421","torso":"546d4a549df4a17d0d449a97","neck":"54693274a2b1f53ce79443c9","eyes":"546941fda2b1f53ce794441d","head":"546d4ca19df4a17d0d449abf"}}
else if e.level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop'] and not _.size e.session.get('heroConfig')?.inventory ? {}
@setupManager?.destroy()
@setupManager = new LevelSetupManager({supermodel: @supermodel, levelID: @levelID, parent: @, session: @session})
@setupManager.open()
@onRealTimeMultiplayerLevelLoaded e.session if e.level.get('type') in ['hero-ladder']
onLoaded: ->
_.defer => @onLevelLoaderLoaded()
onLevelLoaderLoaded: ->
# Everything is now loaded
return unless @levelLoader.progress() is 1 # double check, since closing the guide may trigger this early
# Save latest level played.
if not @observing and not (@levelLoader.level.get('type') in ['ladder', 'ladder-tutorial'])
me.set('lastLevel', @levelID)
me.save()
application.tracker?.identify()
@saveRecentMatch() if @otherSession
@levelLoader.destroy()
@levelLoader = null
@initSurface()
saveRecentMatch: ->
allRecentlyPlayedMatches = storage.load('recently-played-matches') ? {}
recentlyPlayedMatches = allRecentlyPlayedMatches[@levelID] ? []
allRecentlyPlayedMatches[@levelID] = recentlyPlayedMatches
recentlyPlayedMatches.unshift yourTeam: me.team, otherSessionID: @otherSession.id, opponentName: @otherSession.get('creatorName') unless _.find recentlyPlayedMatches, otherSessionID: @otherSession.id
recentlyPlayedMatches.splice(8)
storage.save 'recently-played-matches', allRecentlyPlayedMatches
initSurface: ->
webGLSurface = $('canvas#webgl-surface', @$el)
normalSurface = $('canvas#normal-surface', @$el)
@surface = new Surface(@world, normalSurface, webGLSurface, thangTypes: @supermodel.getModels(ThangType), playJingle: not @isEditorPreview, wizards: not (@level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']), observing: @observing, playerNames: @findPlayerNames())
worldBounds = @world.getBounds()
bounds = [{x: worldBounds.left, y: worldBounds.top}, {x: worldBounds.right, y: worldBounds.bottom}]
@surface.camera.setBounds(bounds)
@surface.camera.zoomTo({x: 0, y: 0}, 0.1, 0)
findPlayerNames: ->
return {} unless @observing
playerNames = {}
for session in [@session, @otherSession] when session?.get('team')
playerNames[session.get('team')] = session.get('creatorName') or 'AnPI:NAME:<NAME>END_PI'
playerNames
# Once Surface is Loaded ####################################################
onLevelStarted: ->
return unless @surface?
@loadingView.showReady()
@trackLevelLoadEnd()
if window.currentModal and not window.currentModal.destroyed and window.currentModal.constructor isnt VictoryModal
return Backbone.Mediator.subscribeOnce 'modal:closed', @onLevelStarted, @
@surface.showLevel()
if @otherSession and not (@level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop'])
# TODO: colorize name and cloud by team, colorize wizard by user's color config
@surface.createOpponentWizard id: @otherSession.get('creator'), name: @otherSession.get('creatorName'), team: @otherSession.get('team'), levelSlug: @level.get('slug'), codeLanguage: @otherSession.get('submittedCodeLanguage')
if @isEditorPreview or @observing
@loadingView.startUnveiling()
@loadingView.unveil()
onLoadingViewUnveiling: (e) ->
@restoreSessionState()
onLoadingViewUnveiled: (e) ->
@loadingView.$el.remove()
@removeSubView @loadingView
@loadingView = null
@playAmbientSound()
if @options.realTimeMultiplayerSessionID?
Backbone.Mediator.publish 'playback:real-time-playback-waiting', {}
@realTimeMultiplayerContinueGame @options.realTimeMultiplayerSessionID
# TODO: Is it possible to create a Mongoose ObjectId for 'ls', instead of the string returned from get()?
application.tracker?.trackEvent 'Started Level', category:'Play Level', levelID: @levelID, ls: @session?.get('_id') unless @observing
$(window).trigger 'resize'
playAmbientSound: ->
return if @destroyed
return if @ambientSound
return unless file = {Dungeon: 'ambient-dungeon', Grass: 'ambient-grass'}[@level.get('terrain')]
src = "/file/interface/#{file}#{AudioPlayer.ext}"
unless AudioPlayer.getStatus(src)?.loaded
AudioPlayer.preloadSound src
Backbone.Mediator.subscribeOnce 'audio-player:loaded', @playAmbientSound, @
return
@ambientSound = createjs.Sound.play src, loop: -1, volume: 0.1
createjs.Tween.get(@ambientSound).to({volume: 1.0}, 10000)
restoreSessionState: ->
return if @alreadyLoadedState
@alreadyLoadedState = true
state = @originalSessionState
if not @level or @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']
Backbone.Mediator.publish 'level:suppress-selection-sounds', suppress: true
Backbone.Mediator.publish 'tome:select-primary-sprite', {}
Backbone.Mediator.publish 'level:suppress-selection-sounds', suppress: false
@surface.focusOnHero()
Backbone.Mediator.publish 'level:set-time', time: 0
Backbone.Mediator.publish 'level:set-playing', playing: true
else
if state.selected
# TODO: Should also restore selected spell here by saving spellName
Backbone.Mediator.publish 'level:select-sprite', thangID: state.selected, spellName: null
# callbacks
onCtrlS: (e) ->
e.preventDefault()
onEscapePressed: (e) ->
return unless @$el.hasClass 'real-time'
Backbone.Mediator.publish 'playback:stop-real-time-playback', {}
onLevelReloadFromData: (e) ->
isReload = Boolean @world
@setLevel e.level, e.supermodel
if isReload
@scriptManager.setScripts(e.level.get('scripts'))
Backbone.Mediator.publish 'tome:cast-spell', {} # a bit hacky
onLevelReloadThangType: (e) ->
tt = e.thangType
for url, model of @supermodel.models
if model.id is tt.id
for key, val of tt.attributes
model.attributes[key] = val
break
Backbone.Mediator.publish 'tome:cast-spell', {}
onWindowResize: (e) => @endHighlight()
onDisableControls: (e) ->
return if e.controls and not ('level' in e.controls)
@shortcutsEnabled = false
@wasFocusedOn = document.activeElement
$('body').focus()
onEnableControls: (e) ->
return if e.controls? and not ('level' in e.controls)
@shortcutsEnabled = true
$(@wasFocusedOn).focus() if @wasFocusedOn
@wasFocusedOn = null
onDonePressed: -> @showVictory()
onShowVictory: (e) ->
$('#level-done-button').show() unless @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop']
@showVictory() if e.showModal
return if @victorySeen
@victorySeen = true
victoryTime = (new Date()) - @loadEndTime
if not @observing and victoryTime > 10 * 1000 # Don't track it if we're reloading an already-beaten level
application.tracker?.trackEvent 'Saw Victory',
category: 'Play Level'
level: @level.get('name')
label: @level.get('name')
levelID: @levelID
ls: @session?.get('_id')
application.tracker?.trackTiming victoryTime, 'Level Victory Time', @levelID, @levelID
showVictory: ->
@endHighlight()
options = {level: @level, supermodel: @supermodel, session: @session, hasReceivedMemoryWarning: @hasReceivedMemoryWarning}
ModalClass = if @level.get('type', true) in ['hero', 'hero-ladder', 'hero-coop'] then HeroVictoryModal else VictoryModal
victoryModal = new ModalClass(options)
@openModalView(victoryModal)
if me.get('anonymous')
window.nextURL = '/play/' + (@level.get('campaign') ? '') # Signup will go here on completion instead of reloading.
onRestartLevel: ->
@tome.reloadAllCode()
Backbone.Mediator.publish 'level:restarted', {}
$('#level-done-button', @$el).hide()
application.tracker?.trackEvent 'Confirmed Restart', category: 'Play Level', level: @level.get('name'), label: @level.get('name') unless @observing
onInfiniteLoop: (e) ->
return unless e.firstWorld
@openModalView new InfiniteLoopModal nonUserCodeProblem: e.nonUserCodeProblem
application.tracker?.trackEvent 'Saw Initial Infinite Loop', category: 'Play Level', level: @level.get('name'), label: @level.get('name') unless @observing
onHighlightDOM: (e) -> @highlightElement e.selector, delay: e.delay, sides: e.sides, offset: e.offset, rotation: e.rotation
onEndHighlight: -> @endHighlight()
onFocusDom: (e) -> $(e.selector).focus()
onMultiplayerChanged: (e) ->
if @session.get('multiplayer')
@bus.connect()
else
@bus.removeFirebaseData =>
@bus.disconnect()
onSessionWillSave: (e) ->
# Something interesting has happened, so (at a lower frequency), we'll save a screenshot.
#@saveScreenshot e.session
# Throttled
saveScreenshot: (session) =>
return unless screenshot = @surface?.screenshot()
session.save {screenshot: screenshot}, {patch: true, type: 'PUT'}
onContactClicked: (e) ->
@openModalView contactModal = new ContactModal()
screenshot = @surface.screenshot(1, 'image/png', 1.0, 1)
body =
b64png: screenshot.replace 'data:image/png;base64,', ''
filename: "screenshot-#{@levelID}-#{_.string.slugify((new Date()).toString())}.png"
path: "db/user/#{me.id}"
mimetype: 'image/png'
contactModal.screenshotURL = "http://codecombat.com/file/#{body.path}/#{body.filename}"
window.screenshot = screenshot
window.screenshotURL = contactModal.screenshotURL
$.ajax '/file', type: 'POST', data: body, success: (e) ->
contactModal.updateScreenshot?()
# Dynamic sound loading
onNewWorld: (e) ->
return if @headless
scripts = @world.scripts # Since these worlds don't have scripts, preserve them.
@world = e.world
@world.scripts = scripts
thangTypes = @supermodel.getModels(ThangType)
startFrame = @lastWorldFramesLoaded ? 0
finishedLoading = @world.frames.length is @world.totalFrames
if finishedLoading
@lastWorldFramesLoaded = 0
if @waitingForSubmissionComplete
_.defer @onSubmissionComplete # Give it a frame to make sure we have the latest goals
@waitingForSubmissionComplete = false
else
@lastWorldFramesLoaded = @world.frames.length
for [spriteName, message] in @world.thangDialogueSounds startFrame
continue unless thangType = _.find thangTypes, (m) -> m.get('name') is spriteName
continue unless sound = AudioPlayer.soundForDialogue message, thangType.get('soundTriggers')
AudioPlayer.preloadSoundReference sound
# Real-time playback
onRealTimePlaybackWaiting: (e) ->
@$el.addClass('real-time').focus()
@onWindowResize()
onRealTimePlaybackStarted: (e) ->
@$el.addClass('real-time').focus()
@onWindowResize()
onRealTimePlaybackEnded: (e) ->
return unless @$el.hasClass 'real-time'
@$el.removeClass 'real-time'
@onWindowResize()
if @world.frames.length is @world.totalFrames
_.delay @onSubmissionComplete, 750 # Wait for transition to end.
else
@waitingForSubmissionComplete = true
@onRealTimeMultiplayerPlaybackEnded()
onSubmissionComplete: =>
return if @destroyed
# TODO: Show a victory dialog specific to hero-ladder level
if @goalManager.checkOverallStatus() is 'success' and not @options.realTimeMultiplayerSessionID?
showModalFn = -> Backbone.Mediator.publish 'level:show-victory', showModal: true
@session.recordScores @world.scores, @level
if @level.get 'replayable'
@session.increaseDifficulty showModalFn
else
showModalFn()
destroy: ->
@levelLoader?.destroy()
@surface?.destroy()
@god?.destroy()
@goalManager?.destroy()
@scriptManager?.destroy()
@setupManager?.destroy()
if ambientSound = @ambientSound
# Doesn't seem to work; stops immediately.
createjs.Tween.get(ambientSound).to({volume: 0.0}, 1500).call -> ambientSound.stop()
$(window).off 'resize', @onWindowResize
delete window.world # not sure where this is set, but this is one way to clean it up
@bus?.destroy()
#@instance.save() unless @instance.loading
delete window.nextURL
console.profileEnd?() if PROFILE_ME
@onRealTimeMultiplayerLevelUnloaded()
super()
onIPadMemoryWarning: (e) ->
@hasReceivedMemoryWarning = true
onItemPurchased: (e) ->
heroConfig = @session.get('heroConfig') ? {}
inventory = heroConfig.inventory ? {}
slot = e.item.getAllowedSlots()[0]
if slot and not inventory[slot]
# Open up the inventory modal so they can equip the new item
@setupManager?.destroy()
@setupManager = new LevelSetupManager({supermodel: @supermodel, levelID: @levelID, parent: @, session: @session, hadEverChosenHero: true})
@setupManager.open()
# Start Real-time Multiplayer ######################################################
#
# This view acts as a hub for the real-time multiplayer session for the current level.
#
# It performs these actions:
# Player heartbeat
# Publishes player status
# Updates real-time multiplayer session state
# Updates real-time multiplayer player state
# Cleans up old sessions (sets state to 'finished')
# Real-time multiplayer cast handshake
# Swap teams on game joined, if necessary
# Reload PlayLevelView on real-time submit, automatically continue game and real-time playback
#
# It monitors these:
# Real-time multiplayer sessions
# Current real-time multiplayer session
# Internal multiplayer create/joined/left events
#
# Real-time state variables.
# Each Ref is Firebase reference, and may have a matching Data suffixed variable with the latest data received.
# @realTimePlayerRef - User's real-time multiplayer player for this level
# @realTimePlayerGameRef - User's current real-time multiplayer player game session
# @realTimeSessionRef - Current real-time multiplayer game session
# @realTimeOpponentRef - Current real-time multiplayer opponent
# @realTimePlayersRef - Real-time players for current real-time multiplayer game session
# @options.realTimeMultiplayerSessionID - Need to continue an existing real-time multiplayer session
#
# TODO: Move this code to it's own file, or possibly the LevelBus
# TODO: Save settings somewhere reasonable
multiplayerFireHost: 'https://codecombat.firebaseio.com/test/db/'
onRealTimeMultiplayerLevelLoaded: (session) ->
# console.log 'PlayLevelView onRealTimeMultiplayerLevelLoaded'
return if @realTimePlayerRef?
return if me.get('anonymous')
@realTimePlayerRef = new Firebase "#{@multiplayerFireHost}multiplayer_players/#{@levelID}/#{me.id}"
unless @options.realTimeMultiplayerSessionID?
# TODO: Wait for name instead of using 'PI:NAME:<NAME>END_PI', or try and update it later?
name = me.get('name') ? session.get('creatorName') ? 'PI:NAME:<NAME>END_PI'
@realTimePlayerRef.set
id: me.id # TODO: is this redundant info necessary?
name: name
state: 'playing'
created: new Date().toISOString()
heartbeat: new Date().toISOString()
@timerMultiplayerHeartbeatID = setInterval @onRealTimeMultiplayerHeartbeat, 60 * 1000
@cleanupRealTimeSessions()
cleanupRealTimeSessions: ->
# console.log 'PlayLevelView cleanupRealTimeSessions'
# TODO: Reduce this call, possibly by username and dates
realTimeSessionCollection = new Firebase "#{@multiplayerFireHost}multiplayer_level_sessions/#{@levelID}"
realTimeSessionCollection.once 'value', (collectionSnapshot) =>
for multiplayerSessionID, multiplayerSession of collectionSnapshot.val()
continue if @options.realTimeMultiplayerSessionID? and @options.realTimeMultiplayerSessionID is multiplayerSessionID
continue unless multiplayerSession.state isnt 'finished'
player = realTimeSessionCollection.child "#{multiplayerSession.id}/players/#{me.id}"
player.once 'value', (playerSnapshot) =>
if playerSnapshot.val()
console.info 'Cleaning up previous real-time multiplayer session', multiplayerSessionID
player.update 'state': 'left'
multiplayerSessionRef = realTimeSessionCollection.child "#{multiplayerSessionID}"
multiplayerSessionRef.update 'state': 'finished'
onRealTimeMultiplayerLevelUnloaded: ->
# console.log 'PlayLevelView onRealTimeMultiplayerLevelUnloaded'
if @timerMultiplayerHeartbeatID?
clearInterval @timerMultiplayerHeartbeatID
@timerMultiplayerHeartbeatID = null
# TODO: similar to game ending cleanup
if @realTimeOpponentRef?
@realTimeOpponentRef.off 'value', @onRealTimeOpponentChanged
@realTimeOpponentRef = null
if @realTimePlayersRef?
@realTimePlayersRef.off 'child_added', @onRealTimePlayerAdded
@realTimePlayersRef = null
if @realTimeSessionRef?
@realTimeSessionRef.off 'value', @onRealTimeSessionChanged
@realTimeSessionRef = null
if @realTimePlayerGameRef?
@realTimePlayerGameRef = null
if @realTimePlayerRef?
@realTimePlayerRef = null
onRealTimeMultiplayerHeartbeat: =>
# console.log 'PlayLevelView onRealTimeMultiplayerHeartbeat', @realTimePlayerRef
@realTimePlayerRef.update 'heartbeat': new Date().toISOString() if @realTimePlayerRef?
onRealTimeMultiplayerCreatedGame: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerCreatedGame'
@joinRealTimeMultiplayerGame e
@realTimePlayerGameRef.update 'state': 'coding'
@realTimePlayerRef.update 'state': 'available'
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: 'Waiting for opponent..'
onRealTimeSessionChanged: (snapshot) =>
# console.log 'PlayLevelView onRealTimeSessionChanged', snapshot.val()
@realTimeSessionData = snapshot.val()
if @realTimeSessionData?.state is 'finished'
@realTimeGameEnded()
Backbone.Mediator.publish 'real-time-multiplayer:left-game', {}
onRealTimePlayerAdded: (snapshot) =>
# console.log 'PlayLevelView onRealTimePlayerAdded', snapshot.val()
# Assume game is full, game on
data = snapshot.val()
if data? and data.id isnt me.id
@realTimeOpponentData = data
# console.log 'PlayLevelView onRealTimePlayerAdded opponent', @realTimeOpponentData, @realTimePlayersData
@realTimePlayersData[@realTimeOpponentData.id] = @realTimeOpponentData
if @realTimeSessionData?.state is 'creating'
@realTimeSessionRef.update 'state': 'coding'
@realTimePlayerRef.update 'state': 'unavailable'
@realTimeOpponentRef = @realTimeSessionRef.child "players/#{@realTimeOpponentData.id}"
@realTimeOpponentRef.on 'value', @onRealTimeOpponentChanged
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "Playing against #{@realTimeOpponentData.name}"
onRealTimeOpponentChanged: (snapshot) =>
# console.log 'PlayLevelView onRealTimeOpponentChanged', snapshot.val()
@realTimeOpponentData = snapshot.val()
switch @realTimeOpponentData?.state
when 'left'
console.info 'Real-time multiplayer opponent left the game'
opponentID = @realTimeOpponentData.id
@realTimeGameEnded()
Backbone.Mediator.publish 'real-time-multiplayer:left-game', userID: opponentID
when 'submitted'
# TODO: What should this message say?
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "#{@realTimeOpponentData.name} waiting for your code"
joinRealTimeMultiplayerGame: (e) ->
# console.log 'PlayLevelView joinRealTimeMultiplayerGame', e
unless @realTimeSessionRef?
@session.set('submittedCodeLanguage', @session.get('codeLanguage'))
@session.save()
@realTimeSessionRef = new Firebase "#{@multiplayerFireHost}multiplayer_level_sessions/#{@levelID}/#{e.realTimeSessionID}"
@realTimePlayersRef = @realTimeSessionRef.child 'players'
# Look for opponent
@realTimeSessionRef.once 'value', (multiplayerSessionSnapshot) =>
if @realTimeSessionData = multiplayerSessionSnapshot.val()
@realTimePlayersRef.once 'value', (playsSnapshot) =>
if @realTimePlayersData = playsSnapshot.val()
for id, player of @realTimePlayersData
if id isnt me.id
@realTimeOpponentRef = @realTimeSessionRef.child "players/#{id}"
@realTimeOpponentRef.once 'value', (opponentSnapshot) =>
if @realTimeOpponentData = opponentSnapshot.val()
@updateTeam()
else
console.error 'Could not lookup multiplayer opponent data.'
@realTimeOpponentRef.on 'value', @onRealTimeOpponentChanged
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: 'Playing against ' + player.name
else
console.error 'Could not lookup multiplayer session players data.'
# TODO: need child_removed too?
@realTimePlayersRef.on 'child_added', @onRealTimePlayerAdded
else
console.error 'Could not lookup multiplayer session data.'
@realTimeSessionRef.on 'value', @onRealTimeSessionChanged
@realTimePlayerGameRef = @realTimeSessionRef.child "players/#{me.id}"
# TODO: Follow up in MultiplayerView to see if double joins can be avoided
# else
# console.error 'Joining real-time multiplayer game with an existing @realTimeSessionRef.'
onRealTimeMultiplayerJoinedGame: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerJoinedGame', e
@joinRealTimeMultiplayerGame e
@realTimePlayerGameRef.update 'state': 'coding'
@realTimePlayerRef.update 'state': 'unavailable'
onRealTimeMultiplayerLeftGame: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerLeftGame', e
if e.userID? and e.userID is me.id
@realTimePlayerGameRef.update 'state': 'left'
@realTimeGameEnded()
realTimeMultiplayerContinueGame: (realTimeSessionID) ->
# console.log 'PlayLevelView realTimeMultiplayerContinueGame', realTimeSessionID, me.id
Backbone.Mediator.publish 'real-time-multiplayer:joined-game', realTimeSessionID: realTimeSessionID
console.info 'Setting my game status to ready'
@realTimePlayerGameRef.update 'state': 'ready'
if @realTimeOpponentData.state is 'ready'
@realTimeOpponentIsReady()
else
console.info 'Waiting for opponent to be ready'
@realTimeOpponentRef.on 'value', @realTimeOpponentMaybeReady
realTimeOpponentMaybeReady: (snapshot) =>
# console.log 'PlayLevelView realTimeOpponentMaybeReady'
if @realTimeOpponentData = snapshot.val()
if @realTimeOpponentData.state is 'ready'
@realTimeOpponentRef.off 'value', @realTimeOpponentMaybeReady
@realTimeOpponentIsReady()
realTimeOpponentIsReady: =>
console.info 'All real-time multiplayer players are ready!'
@realTimeSessionRef.update 'state': 'running'
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: 'Battling ' + @realTimeOpponentData.name
Backbone.Mediator.publish 'tome:manual-cast', {realTime: true}
realTimeGameEnded: ->
if @realTimeOpponentRef?
@realTimeOpponentRef.off 'value', @onRealTimeOpponentChanged
@realTimeOpponentRef = null
if @realTimePlayersRef?
@realTimePlayersRef.off 'child_added', @onRealTimePlayerAdded
@realTimePlayersRef = null
if @realTimeSessionRef?
@realTimeSessionRef.off 'value', @onRealTimeSessionChanged
@realTimeSessionRef.update 'state': 'finished'
@realTimeSessionRef = null
if @realTimePlayerGameRef?
@realTimePlayerGameRef = null
if @realTimePlayerRef?
@realTimePlayerRef.update 'state': 'playing'
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: ''
onRealTimeMultiplayerCast: (e) ->
# console.log 'PlayLevelView onRealTimeMultiplayerCast', @realTimeSessionData, @realTimePlayersData
unless @realTimeSessionRef?
console.error 'Real-time multiplayer cast without multiplayer session.'
return
unless @realTimeSessionData?
console.error 'Real-time multiplayer cast without multiplayer data.'
return
unless @realTimePlayersData?
console.error 'Real-time multiplayer cast without multiplayer players data.'
return
# Set submissionCount for created real-time multiplayer session
if me.id is @realTimeSessionData.creator
sessionState = @session.get('state')
if sessionState?
submissionCount = sessionState.submissionCount ? 0
console.info 'Setting multiplayer submissionCount to', submissionCount
@realTimeSessionRef.update 'submissionCount': submissionCount
else
console.error 'Failed to read sessionState in onRealTimeMultiplayerCast'
console.info 'Submitting my code'
# Transpiling code copied from scripts/transpile.coffee
# TODO: Should this live somewhere else?
transpiledCode = {}
for thang, spells of @session.get('code')
transpiledCode[thang] = {}
for spellID, spell of spells
spellName = thang + '/' + spellID
continue if @session.get('teamSpells') and not (spellName in @session.get('teamSpells')[@session.get('team')])
# console.log "PlayLevelView Transpiling spell #{spellName}"
aetherOptions = createAetherOptions functionName: spellID, codeLanguage: @session.get('submittedCodeLanguage'), includeFlow: true
aether = new Aether aetherOptions
transpiledCode[thang][spellID] = aether.transpile spell
# console.log "PlayLevelView transpiled code", transpiledCode
@session.set 'transpiledCode', transpiledCode
permissions = @session.get 'permissions' ? []
unless _.find(permissions, (p) -> p.target is 'public' and p.access is 'read')
permissions.push target:'public', access:'read'
@session.set 'permissions', permissions
@session.patch()
@realTimePlayerGameRef.update 'state': 'submitted'
console.info 'Other player is', @realTimeOpponentData.state
if @realTimeOpponentData.state in ['submitted', 'ready']
@realTimeOpponentSubmittedCode @realTimeOpponentData, @realTimePlayerGameData
else
# Wait for opponent to submit their code
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "Waiting for code from #{@realTimeOpponentData.name}"
@realTimeOpponentRef.on 'value', @realTimeOpponentMaybeSubmitted
realTimeOpponentMaybeSubmitted: (snapshot) =>
if @realTimeOpponentData = snapshot.val()
if @realTimeOpponentData.state in ['submitted', 'ready']
@realTimeOpponentRef.off 'value', @realTimeOpponentMaybeSubmitted
@realTimeOpponentSubmittedCode @realTimeOpponentData, @realTimePlayerGameData
onRealTimeMultiplayerPlaybackEnded: ->
# console.log 'PlayLevelView onRealTimeMultiplayerPlaybackEnded'
if @realTimeSessionRef?
@realTimeSessionRef.update 'state': 'coding'
@realTimePlayerGameRef.update 'state': 'coding'
if @realTimeOpponentData?
Backbone.Mediator.publish 'real-time-multiplayer:player-status', status: "Playing against #{@realTimeOpponentData.name}"
realTimeOpponentSubmittedCode: (opponentPlayer, myPlayer) =>
# console.log 'PlayLevelView realTimeOpponentSubmittedCode', @realTimeSessionData.id, opponentPlayer.level_session
# Read submissionCount for joined real-time multiplayer session
if me.id isnt @realTimeSessionData.creator
sessionState = @session.get('state') ? {}
newSubmissionCount = @realTimeSessionData.submissionCount
if newSubmissionCount?
# TODO: This isn't always getting updated where the random seed generation uses it.
sessionState.submissionCount = parseInt newSubmissionCount
console.info 'Got multiplayer submissionCount', sessionState.submissionCount
@session.set 'state', sessionState
@session.patch()
# Reload this level so the opponent session can easily be wired up
Backbone.Mediator.publish 'router:navigate',
route: "/play/level/#{@levelID}"
viewClass: PlayLevelView
viewArgs: [{supermodel: @supermodel, autoUnveil: true, realTimeMultiplayerSessionID: @realTimeSessionData.id, opponent: opponentPlayer.level_session, team: @team}, @levelID]
updateTeam: ->
# If not creator, and same team as creator, then switch teams
# TODO: Assumes there are only 'humans' and 'ogres'
unless @realTimeOpponentData?
console.error 'Tried to switch teams without real-time multiplayer opponent data.'
return
unless @realTimeSessionData?
console.error 'Tried to switch teams without real-time multiplayer session data.'
return
return if me.id is @realTimeSessionData.creator
oldTeam = @realTimeOpponentData.team
return unless oldTeam is @session.get('team')
# Need to switch to other team
newTeam = if oldTeam is 'humans' then 'ogres' else 'humans'
console.info "Switching from team #{oldTeam} to #{newTeam}"
# Move code from old team to new team
# Assumes teamSpells has matching spells for each team
# TODO: Similar to code in loadOpponentTeam, consolidate?
code = @session.get 'code'
teamSpells = @session.get 'teamSpells'
for oldSpellKey in teamSpells[oldTeam]
[oldThang, oldSpell] = oldSpellKey.split '/'
oldCode = code[oldThang]?[oldSpell]
continue unless oldCode?
# Move oldCode to new team under same spell
for newSpellKey in teamSpells[newTeam]
[newThang, newSpell] = newSpellKey.split '/'
if newSpell is oldSpell
# Found spell location under new team
# console.log "Swapping spell=#{oldSpell} from #{oldThang} to #{newThang}"
if code[newThang]?[oldSpell]?
# Option 1: have a new spell to swap
code[oldThang][oldSpell] = code[newThang][oldSpell]
else
# Option 2: no new spell to swap
delete code[oldThang][oldSpell]
code[newThang] = {} unless code[newThang]?
code[newThang][oldSpell] = oldCode
break
@setTeam newTeam # Sets @session 'team'
sessionState = @session.get('state')
if sessionState?
# TODO: Don't hard code thangID
sessionState.selected = if newTeam is 'humans' then 'Hero Placeholder' else 'Hero Placeholder 1'
@session.set 'state', sessionState
@session.set 'code', code
@session.patch()
if sessionState?
# TODO: Don't hardcode spellName
Backbone.Mediator.publish 'level:select-sprite', thangID: sessionState.selected, spellName: 'plan'
# End Real-time Multiplayer ######################################################
|
[
{
"context": "3 Flarebyte.com Ltd. All rights reserved.\nCreator: Olivier Huin\nContributors:\n###\n\n'use strict'\n\nclient = require",
"end": 151,
"score": 0.9998672604560852,
"start": 139,
"tag": "NAME",
"value": "Olivier Huin"
},
{
"context": "UserContext= (req)->\n uctx=\n ownerRef: \"email:magma.test.u1.77225432@flarebyte.com\"\n universeId: \"magma:f/universe/testing\",\n ",
"end": 316,
"score": 0.9996002912521362,
"start": 280,
"tag": "EMAIL",
"value": "magma.test.u1.77225432@flarebyte.com"
}
] | nodejs/flarebyte.net/0.8/node/flaming/routes/api.coffee | flarebyte/wonderful-bazar | 0 | ###
GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT)
Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved.
Creator: Olivier Huin
Contributors:
###
'use strict'
client = require('flaming-magma-client')
getUserContext= (req)->
uctx=
ownerRef: "email:magma.test.u1.77225432@flarebyte.com"
universeId: "magma:f/universe/testing",
verified: true
return uctx
# List all profiles for the current user
exports.doListAllProfile= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all login options for the current user
exports.doListAllLoginOptions= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all compose templates for the current user
exports.doListAllComposeTemplates= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all messages to read for the current user
exports.doListAllMessagesToRead= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all tasks to do for the current user
exports.doListAllTasksToDo= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all important messages for the current user
exports.doListAllImportantMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all recent messages for the current user
exports.doListAllRecentMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all shared messages for the current user
exports.doListAllSharedMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all messages for the current user
exports.doListAllMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all news for the current user
exports.doListAllNews= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all trash for the current user
exports.doListAllTrash= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all dashboards of the current user
exports.doListAllDashboards= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List a selection of contacts of the current user
exports.doListASelectionOfContacts= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all contacts of the current user
exports.doListAllContacts= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all settings of the current user
exports.doListAllSettings= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all help items of the current user
exports.doListAllHelpItems= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all faq items of the current user
exports.doListAllFaqItems= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all privacy items of the current user
exports.doListAllPrivacyItems= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all terms for the current user
exports.doListAllTerms= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
| 94741 | ###
GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT)
Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved.
Creator: <NAME>
Contributors:
###
'use strict'
client = require('flaming-magma-client')
getUserContext= (req)->
uctx=
ownerRef: "email:<EMAIL>"
universeId: "magma:f/universe/testing",
verified: true
return uctx
# List all profiles for the current user
exports.doListAllProfile= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all login options for the current user
exports.doListAllLoginOptions= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all compose templates for the current user
exports.doListAllComposeTemplates= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all messages to read for the current user
exports.doListAllMessagesToRead= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all tasks to do for the current user
exports.doListAllTasksToDo= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all important messages for the current user
exports.doListAllImportantMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all recent messages for the current user
exports.doListAllRecentMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all shared messages for the current user
exports.doListAllSharedMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all messages for the current user
exports.doListAllMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all news for the current user
exports.doListAllNews= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all trash for the current user
exports.doListAllTrash= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all dashboards of the current user
exports.doListAllDashboards= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List a selection of contacts of the current user
exports.doListASelectionOfContacts= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all contacts of the current user
exports.doListAllContacts= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all settings of the current user
exports.doListAllSettings= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all help items of the current user
exports.doListAllHelpItems= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all faq items of the current user
exports.doListAllFaqItems= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all privacy items of the current user
exports.doListAllPrivacyItems= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all terms for the current user
exports.doListAllTerms= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
| true | ###
GENERATED - DO NOT EDIT - Tue Jan 14 2014 22:25:31 GMT+0000 (GMT)
Copyright (c) 2013 Flarebyte.com Ltd. All rights reserved.
Creator: PI:NAME:<NAME>END_PI
Contributors:
###
'use strict'
client = require('flaming-magma-client')
getUserContext= (req)->
uctx=
ownerRef: "email:PI:EMAIL:<EMAIL>END_PI"
universeId: "magma:f/universe/testing",
verified: true
return uctx
# List all profiles for the current user
exports.doListAllProfile= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all login options for the current user
exports.doListAllLoginOptions= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all compose templates for the current user
exports.doListAllComposeTemplates= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all messages to read for the current user
exports.doListAllMessagesToRead= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all tasks to do for the current user
exports.doListAllTasksToDo= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all important messages for the current user
exports.doListAllImportantMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all recent messages for the current user
exports.doListAllRecentMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all shared messages for the current user
exports.doListAllSharedMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all messages for the current user
exports.doListAllMessages= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all news for the current user
exports.doListAllNews= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all trash for the current user
exports.doListAllTrash= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all dashboards of the current user
exports.doListAllDashboards= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List a selection of contacts of the current user
exports.doListASelectionOfContacts= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all contacts of the current user
exports.doListAllContacts= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all settings of the current user
exports.doListAllSettings= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all help items of the current user
exports.doListAllHelpItems= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all faq items of the current user
exports.doListAllFaqItems= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all privacy items of the current user
exports.doListAllPrivacyItems= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
# List all terms for the current user
exports.doListAllTerms= (req, res) ->
viewModel= client.g.lookup('magma:f/view.get/744550486')
ctx=
my: getUserContext req
view: viewModel
qs:
path: "contacts"
client.httpRequest ctx, (err, data)->
res.send data
|
[
{
"context": "Each ->\n @artwork = new Artwork artist: name: 'Foo Bar'\n\n describe 'sans partner', ->\n it 'returns t",
"end": 230,
"score": 0.9986807107925415,
"start": 223,
"tag": "NAME",
"value": "Foo Bar"
}
] | src/desktop/components/contact/test/default_message.coffee | kanaabe/force | 1 | Artwork = require '../../../models/artwork'
Partner = require '../../../models/partner'
defaultMessage = require '../default_message'
describe 'defaultMessage', ->
beforeEach ->
@artwork = new Artwork artist: name: 'Foo Bar'
describe 'sans partner', ->
it 'returns the default message', ->
defaultMessage @artwork
.should.equal 'Hi, I’m interested in purchasing this work. ' +
'Could you please provide more information about the piece?'
describe 'with partner', ->
beforeEach ->
@partner = new Partner
describe 'of Gallery type', ->
beforeEach ->
@partner.set 'type', 'Gallery'
it 'returns the default message', ->
defaultMessage @artwork, @partner
.should.equal 'Hi, I’m interested in purchasing this work. ' +
'Could you please provide more information about the piece?'
it 'returns the similar message when the artwork is sold', ->
@artwork.set availability: 'sold'
defaultMessage @artwork, @partner
.should.equal 'Hi, I’m interested in similar works by this artist. ' +
'Could you please let me know if you have anything available?'
it 'returns the similar message when the artwork is on loan', ->
@artwork.set availability: 'on loan'
defaultMessage @artwork, @partner
.should.equal 'Hi, I’m interested in similar works by this artist. ' +
'Could you please let me know if you have anything available?'
it 'returns nothing when the artwork is not for sale', ->
@artwork.set availability: 'not for sale'
(typeof defaultMessage @artwork, @partner)
.should.equal 'undefined'
describe 'of Auction type', ->
beforeEach ->
@partner.set 'type', 'Auction'
it 'returns the auction-specific message', ->
defaultMessage @artwork, @partner
.should.equal 'Hello, I am interested in placing a bid on this work. ' +
'Please send me more information.'
| 183509 | Artwork = require '../../../models/artwork'
Partner = require '../../../models/partner'
defaultMessage = require '../default_message'
describe 'defaultMessage', ->
beforeEach ->
@artwork = new Artwork artist: name: '<NAME>'
describe 'sans partner', ->
it 'returns the default message', ->
defaultMessage @artwork
.should.equal 'Hi, I’m interested in purchasing this work. ' +
'Could you please provide more information about the piece?'
describe 'with partner', ->
beforeEach ->
@partner = new Partner
describe 'of Gallery type', ->
beforeEach ->
@partner.set 'type', 'Gallery'
it 'returns the default message', ->
defaultMessage @artwork, @partner
.should.equal 'Hi, I’m interested in purchasing this work. ' +
'Could you please provide more information about the piece?'
it 'returns the similar message when the artwork is sold', ->
@artwork.set availability: 'sold'
defaultMessage @artwork, @partner
.should.equal 'Hi, I’m interested in similar works by this artist. ' +
'Could you please let me know if you have anything available?'
it 'returns the similar message when the artwork is on loan', ->
@artwork.set availability: 'on loan'
defaultMessage @artwork, @partner
.should.equal 'Hi, I’m interested in similar works by this artist. ' +
'Could you please let me know if you have anything available?'
it 'returns nothing when the artwork is not for sale', ->
@artwork.set availability: 'not for sale'
(typeof defaultMessage @artwork, @partner)
.should.equal 'undefined'
describe 'of Auction type', ->
beforeEach ->
@partner.set 'type', 'Auction'
it 'returns the auction-specific message', ->
defaultMessage @artwork, @partner
.should.equal 'Hello, I am interested in placing a bid on this work. ' +
'Please send me more information.'
| true | Artwork = require '../../../models/artwork'
Partner = require '../../../models/partner'
defaultMessage = require '../default_message'
describe 'defaultMessage', ->
beforeEach ->
@artwork = new Artwork artist: name: 'PI:NAME:<NAME>END_PI'
describe 'sans partner', ->
it 'returns the default message', ->
defaultMessage @artwork
.should.equal 'Hi, I’m interested in purchasing this work. ' +
'Could you please provide more information about the piece?'
describe 'with partner', ->
beforeEach ->
@partner = new Partner
describe 'of Gallery type', ->
beforeEach ->
@partner.set 'type', 'Gallery'
it 'returns the default message', ->
defaultMessage @artwork, @partner
.should.equal 'Hi, I’m interested in purchasing this work. ' +
'Could you please provide more information about the piece?'
it 'returns the similar message when the artwork is sold', ->
@artwork.set availability: 'sold'
defaultMessage @artwork, @partner
.should.equal 'Hi, I’m interested in similar works by this artist. ' +
'Could you please let me know if you have anything available?'
it 'returns the similar message when the artwork is on loan', ->
@artwork.set availability: 'on loan'
defaultMessage @artwork, @partner
.should.equal 'Hi, I’m interested in similar works by this artist. ' +
'Could you please let me know if you have anything available?'
it 'returns nothing when the artwork is not for sale', ->
@artwork.set availability: 'not for sale'
(typeof defaultMessage @artwork, @partner)
.should.equal 'undefined'
describe 'of Auction type', ->
beforeEach ->
@partner.set 'type', 'Auction'
it 'returns the auction-specific message', ->
defaultMessage @artwork, @partner
.should.equal 'Hello, I am interested in placing a bid on this work. ' +
'Please send me more information.'
|
[
{
"context": "uTube result.'\n version: '0.5'\n authors: [\n 'Tunnecino @ ignitae.com',\n 'Álvaro Cuesta'\n ]\n",
"end": 2000,
"score": 0.8436197638511658,
"start": 1999,
"tag": "USERNAME",
"value": "T"
},
{
"context": "Tube result.'\n version: '0.5'\n authors: [\n 'Tunnecino @ ignitae.com',\n 'Álvaro Cuesta'\n ]\n",
"end": 2008,
"score": 0.9716799259185791,
"start": 2000,
"tag": "NAME",
"value": "unnecino"
},
{
"context": "t.'\n version: '0.5'\n authors: [\n 'Tunnecino @ ignitae.com',\n 'Álvaro Cuesta'\n ]\n",
"end": 2022,
"score": 0.9930536150932312,
"start": 2011,
"tag": "EMAIL",
"value": "ignitae.com"
},
{
"context": "\n authors: [\n 'Tunnecino @ ignitae.com',\n 'Álvaro Cuesta'\n ]\n",
"end": 2043,
"score": 0.99986332654953,
"start": 2030,
"tag": "NAME",
"value": "Álvaro Cuesta"
}
] | plugins/youtube.coffee | Arrogance/nerdobot | 1 | request = require('request')
watchURL = (v) ->
"http://youtu.be/#{v}"
module.exports = ({results, random, options}) ->
results ?= 1
random ?= false
searchURL = (q) ->
q = encodeURIComponent q
if options?
query = '&' + ("#{k}=#{v}" for k, v of options).join '&'
else
query = ''
"http://gdata.youtube.com/feeds/api/videos?q=#{q}&v=2&alt=json#{query}"
banner = (message) =>
"#{@BOLD}You#{@color 'white', 'red'}Tube#{@RESET} - #{message}"
sendMsg = (content, channel) =>
links = JSON.stringify(content.id['$t']).split ':'
[title, link, views] = [
content.title['$t'],
watchURL(links[3].replace '"', ''),
content.yt$statistics['viewCount']
]
@say channel,
banner "#{@BOLD}#{title}#{@RESET} - " +
"#{@UNDERLINE}#{@color 'blue'}#{link}#{@RESET} - " +
"#{@UNDERLINE}#{views}#{@RESET} views"
sendErr = (err, channel) =>
@say channel, banner "#{@BOLD}#{err}#{@RESET}"
@addCommand 'youtube',
args: '<search terms>'
description: 'YouTube search'
(from, query, channel) =>
if not channel?
@notice from.nick, 'That command only works in channels'
return
if not query?
@notice from.nick, 'You should specify a search query!'
return
request
url: searchURL query
json: true
(err, res, data) ->
if err?
sendErr "Couldn't connect...", channel
return
if not data?.feed?
console.log data
sendErr "ERROR: empty feed!", channel
return
if data.feed.openSearch$totalResults['$t'] is 0
sendErr "No results...", channel
return
videos = data.feed.entry
videos = videos.sort -> 0.5 - Math.random() if random
sendMsg video, channel for video in videos[...results]
name: 'Youtube Search'
description: 'Returns the first YouTube result.'
version: '0.5'
authors: [
'Tunnecino @ ignitae.com',
'Álvaro Cuesta'
]
| 172428 | request = require('request')
watchURL = (v) ->
"http://youtu.be/#{v}"
module.exports = ({results, random, options}) ->
results ?= 1
random ?= false
searchURL = (q) ->
q = encodeURIComponent q
if options?
query = '&' + ("#{k}=#{v}" for k, v of options).join '&'
else
query = ''
"http://gdata.youtube.com/feeds/api/videos?q=#{q}&v=2&alt=json#{query}"
banner = (message) =>
"#{@BOLD}You#{@color 'white', 'red'}Tube#{@RESET} - #{message}"
sendMsg = (content, channel) =>
links = JSON.stringify(content.id['$t']).split ':'
[title, link, views] = [
content.title['$t'],
watchURL(links[3].replace '"', ''),
content.yt$statistics['viewCount']
]
@say channel,
banner "#{@BOLD}#{title}#{@RESET} - " +
"#{@UNDERLINE}#{@color 'blue'}#{link}#{@RESET} - " +
"#{@UNDERLINE}#{views}#{@RESET} views"
sendErr = (err, channel) =>
@say channel, banner "#{@BOLD}#{err}#{@RESET}"
@addCommand 'youtube',
args: '<search terms>'
description: 'YouTube search'
(from, query, channel) =>
if not channel?
@notice from.nick, 'That command only works in channels'
return
if not query?
@notice from.nick, 'You should specify a search query!'
return
request
url: searchURL query
json: true
(err, res, data) ->
if err?
sendErr "Couldn't connect...", channel
return
if not data?.feed?
console.log data
sendErr "ERROR: empty feed!", channel
return
if data.feed.openSearch$totalResults['$t'] is 0
sendErr "No results...", channel
return
videos = data.feed.entry
videos = videos.sort -> 0.5 - Math.random() if random
sendMsg video, channel for video in videos[...results]
name: 'Youtube Search'
description: 'Returns the first YouTube result.'
version: '0.5'
authors: [
'T<NAME> @ <EMAIL>',
'<NAME>'
]
| true | request = require('request')
watchURL = (v) ->
"http://youtu.be/#{v}"
module.exports = ({results, random, options}) ->
results ?= 1
random ?= false
searchURL = (q) ->
q = encodeURIComponent q
if options?
query = '&' + ("#{k}=#{v}" for k, v of options).join '&'
else
query = ''
"http://gdata.youtube.com/feeds/api/videos?q=#{q}&v=2&alt=json#{query}"
banner = (message) =>
"#{@BOLD}You#{@color 'white', 'red'}Tube#{@RESET} - #{message}"
sendMsg = (content, channel) =>
links = JSON.stringify(content.id['$t']).split ':'
[title, link, views] = [
content.title['$t'],
watchURL(links[3].replace '"', ''),
content.yt$statistics['viewCount']
]
@say channel,
banner "#{@BOLD}#{title}#{@RESET} - " +
"#{@UNDERLINE}#{@color 'blue'}#{link}#{@RESET} - " +
"#{@UNDERLINE}#{views}#{@RESET} views"
sendErr = (err, channel) =>
@say channel, banner "#{@BOLD}#{err}#{@RESET}"
@addCommand 'youtube',
args: '<search terms>'
description: 'YouTube search'
(from, query, channel) =>
if not channel?
@notice from.nick, 'That command only works in channels'
return
if not query?
@notice from.nick, 'You should specify a search query!'
return
request
url: searchURL query
json: true
(err, res, data) ->
if err?
sendErr "Couldn't connect...", channel
return
if not data?.feed?
console.log data
sendErr "ERROR: empty feed!", channel
return
if data.feed.openSearch$totalResults['$t'] is 0
sendErr "No results...", channel
return
videos = data.feed.entry
videos = videos.sort -> 0.5 - Math.random() if random
sendMsg video, channel for video in videos[...results]
name: 'Youtube Search'
description: 'Returns the first YouTube result.'
version: '0.5'
authors: [
'TPI:NAME:<NAME>END_PI @ PI:EMAIL:<EMAIL>END_PI',
'PI:NAME:<NAME>END_PI'
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.