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": " create features\n# HUBOT_AHA_PASS - password for aha user\n# HUBOT_AHA_ACCOUNTNAME - the name of th",
"end": 199,
"score": 0.7308351397514343,
"start": 198,
"tag": "USERNAME",
"value": "a"
},
{
"context": "ate features\n# HUBOT_AHA_PASS - password for aha user\n#... | src/hubot-aha-idea.coffee | denniswalker/hubot-aha-create-idea | 0 | # Description:
# Command for hubot to create an idea in Aha
#
# Configuration:
# HUBOT_AHA_USER - username of user in Aha who has permission to create features
# HUBOT_AHA_PASS - password for aha user
# HUBOT_AHA_ACCOUNTNAME - the name of the Aha.io account
# HUBOT_AHA_IDEA_VISIBILITY - visibility of the new idea (use 'aha', 'employee', or 'public' - employee is default)
# HUBOT_AHA_PRODUCT - product that the new idea is created under
#
# Dependencies:
# request-promise
#
# Commands:
# hubot create idea <name>: <description> - hubot will create a new idea in Aha with the name <name> and description of <description>
#
# Author:
# Dennis Newel <dennis.newel@newelcorp.com>
#
# Notes:
# The user used for this integration cannot be linked to a single sign-on system; it must be a user with basic username/password
#
aha_api = "https://" + process.env.HUBOT_AHA_ACCOUNTNAME + ".aha.io/api/v1/"
default_release = process.env.HUBOT_AHA_RELEASE ? "P-R-1"
usertoken = new Buffer(process.env.HUBOT_AHA_USER + ":" + process.env.HUBOT_AHA_PASS).toString('base64')
visibility = process.env.HUBOT_AHA_IDEA_VISIBILITY ? "employee"
product = process.env.HUBOT_AHA_PRODUCT ? "P"
rp = require 'request-promise'
req_headers = {
"X-Aha-Account": process.env.HUBOT_AHA_ACCOUNTNAME,
"Content-Type": "application/json",
Accept: "application/json",
Authorization: "Basic " + usertoken,
}
module.exports = (robot) =>
robot.respond /create idea (.*): (.*)/i, (msg) ->
msg.reply "hmm...something's missing from what you're asking me. Try again" unless msg.match[1] && msg.match[2]
options = {
method: 'POST',
uri: aha_api + "products/" + product + "/ideas",
headers: req_headers,
body: {
"idea": {
"name": msg.match[1],
"description": msg.match[2],
"created_by": msg.message.user.slack.profile.email
}
},
json: true
}
rp(options)
.then (parsedBody) ->
msg.reply "The idea '#{msg.match[1]}' has been created in Aha as #{parsedBody.idea.reference_num}: #{parsedBody.idea.url}"
return
.catch (err) ->
msg.reply "Something went wrong when creating the idea: #{err}"
return
| 194067 | # Description:
# Command for hubot to create an idea in Aha
#
# Configuration:
# HUBOT_AHA_USER - username of user in Aha who has permission to create features
# HUBOT_AHA_PASS - password for aha user
# HUBOT_AHA_ACCOUNTNAME - the name of the Aha.io account
# HUBOT_AHA_IDEA_VISIBILITY - visibility of the new idea (use 'aha', 'employee', or 'public' - employee is default)
# HUBOT_AHA_PRODUCT - product that the new idea is created under
#
# Dependencies:
# request-promise
#
# Commands:
# hubot create idea <name>: <description> - hubot will create a new idea in Aha with the name <name> and description of <description>
#
# Author:
# <NAME> <<EMAIL>>
#
# Notes:
# The user used for this integration cannot be linked to a single sign-on system; it must be a user with basic username/password
#
aha_api = "https://" + process.env.HUBOT_AHA_ACCOUNTNAME + ".aha.io/api/v1/"
default_release = process.env.HUBOT_AHA_RELEASE ? "P-R-1"
usertoken = new Buffer(process.env.HUBOT_AHA_USER + ":" + process.env.HUBOT_AHA_PASS).toString('base64')
visibility = process.env.HUBOT_AHA_IDEA_VISIBILITY ? "employee"
product = process.env.HUBOT_AHA_PRODUCT ? "P"
rp = require 'request-promise'
req_headers = {
"X-Aha-Account": process.env.HUBOT_AHA_ACCOUNTNAME,
"Content-Type": "application/json",
Accept: "application/json",
Authorization: "Basic " + usertoken,
}
module.exports = (robot) =>
robot.respond /create idea (.*): (.*)/i, (msg) ->
msg.reply "hmm...something's missing from what you're asking me. Try again" unless msg.match[1] && msg.match[2]
options = {
method: 'POST',
uri: aha_api + "products/" + product + "/ideas",
headers: req_headers,
body: {
"idea": {
"name": msg.match[1],
"description": msg.match[2],
"created_by": msg.message.user.slack.profile.email
}
},
json: true
}
rp(options)
.then (parsedBody) ->
msg.reply "The idea '#{msg.match[1]}' has been created in Aha as #{parsedBody.idea.reference_num}: #{parsedBody.idea.url}"
return
.catch (err) ->
msg.reply "Something went wrong when creating the idea: #{err}"
return
| true | # Description:
# Command for hubot to create an idea in Aha
#
# Configuration:
# HUBOT_AHA_USER - username of user in Aha who has permission to create features
# HUBOT_AHA_PASS - password for aha user
# HUBOT_AHA_ACCOUNTNAME - the name of the Aha.io account
# HUBOT_AHA_IDEA_VISIBILITY - visibility of the new idea (use 'aha', 'employee', or 'public' - employee is default)
# HUBOT_AHA_PRODUCT - product that the new idea is created under
#
# Dependencies:
# request-promise
#
# Commands:
# hubot create idea <name>: <description> - hubot will create a new idea in Aha with the name <name> and description of <description>
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# Notes:
# The user used for this integration cannot be linked to a single sign-on system; it must be a user with basic username/password
#
aha_api = "https://" + process.env.HUBOT_AHA_ACCOUNTNAME + ".aha.io/api/v1/"
default_release = process.env.HUBOT_AHA_RELEASE ? "P-R-1"
usertoken = new Buffer(process.env.HUBOT_AHA_USER + ":" + process.env.HUBOT_AHA_PASS).toString('base64')
visibility = process.env.HUBOT_AHA_IDEA_VISIBILITY ? "employee"
product = process.env.HUBOT_AHA_PRODUCT ? "P"
rp = require 'request-promise'
req_headers = {
"X-Aha-Account": process.env.HUBOT_AHA_ACCOUNTNAME,
"Content-Type": "application/json",
Accept: "application/json",
Authorization: "Basic " + usertoken,
}
module.exports = (robot) =>
robot.respond /create idea (.*): (.*)/i, (msg) ->
msg.reply "hmm...something's missing from what you're asking me. Try again" unless msg.match[1] && msg.match[2]
options = {
method: 'POST',
uri: aha_api + "products/" + product + "/ideas",
headers: req_headers,
body: {
"idea": {
"name": msg.match[1],
"description": msg.match[2],
"created_by": msg.message.user.slack.profile.email
}
},
json: true
}
rp(options)
.then (parsedBody) ->
msg.reply "The idea '#{msg.match[1]}' has been created in Aha as #{parsedBody.idea.reference_num}: #{parsedBody.idea.url}"
return
.catch (err) ->
msg.reply "Something went wrong when creating the idea: #{err}"
return
|
[
{
"context": "---------------------------------\n# Copyright 2013 I.B.M.\n# \n# Licensed under the Apache License, Version 2",
"end": 4266,
"score": 0.9986682534217834,
"start": 4261,
"tag": "NAME",
"value": "I.B.M"
}
] | lib-src/coffee/node/config.coffee | pmuellr/nodprof | 6 | # Licensed under the Apache License. See footer for details.
fs = require "fs"
path = require "path"
nopt = require "nopt"
_ = require "underscore"
pkg = require "../../package.json"
utils = require "../common/utils"
logger = require "../common/logger"
#-------------------------------------------------------------------------------
exports.getConfiguration = (argv) ->
{args, opts} = parseCommandLine argv
cDef = getConfigurationDefault()
cCmd = getConfigurationCommandLine opts
cFile = cCmd.config or cDef.config
cEnv = getConfigurationEnv()
cCfg = getConfigurationConfig cFile
config = _.defaults {}, cCmd, cEnv, cCfg, cDef
delete config.config
data = mkdirp config.data
if !data?
logger.log "data directory not found or not writable: #{config.data}"
process.exit 1
return {args, config}
#-------------------------------------------------------------------------------
mkdirp = (dir) ->
exists = fs.existsSync dir
if exists
stats = fs.statSync dir
return null if !stats.isDirectory()
return dir
parent = path.dirname dir
result = mkdirp parent
return null if !result?
try
fs.mkdirSync dir
catch e
return null
return dir
#-------------------------------------------------------------------------------
getConfigurationDefault = ->
result =
verbose: false
debug: false
serve: false
port: 3000
heap: true
profile: true
data: utils.replaceTilde "~/.#{pkg.name}/data"
config: utils.replaceTilde "~/.#{pkg.name}/config.json"
return result
#-------------------------------------------------------------------------------
getConfigurationConfig = (file) ->
try
contents = fs.readFileSync file, "utf8"
contents = JSON.parse contents
catch e
contents = {}
return contents
#-------------------------------------------------------------------------------
getConfigurationEnv = ->
result = {}
port = process.env.PORT
result.port = port if port?
return result
#-------------------------------------------------------------------------------
getConfigurationCommandLine = (opts) ->
return opts
#-------------------------------------------------------------------------------
parseCommandLine = (argv) ->
optionSpecs =
verbose: Boolean
debug: Boolean
serve: Boolean
heap: Boolean
profile: Boolean
port: Number
data: path
config: path
help: Boolean
shortHands =
v: "--verbose"
d: "--debug"
s: "--serve"
h: "--heap"
r: "--profile"
p: "--port"
d: "--data"
c: "--config"
"?": "--help"
exports.help() if argv[0] == "?"
parsed = nopt(optionSpecs, shortHands, argv, 0)
exports.help() if parsed.help
args = parsed.argv.remain
opts = parsed
delete opts.argv
return {args, opts}
#-------------------------------------------------------------------------------
# print some help and then exit
#-------------------------------------------------------------------------------
exports.help = ->
text = """
#{pkg.name} #{pkg.version}
will run an HTTP server to display profiling results,
or profile the execution of a node module
usage:
#{pkg.name} [options] [arguments]
options:
-c --config path
-v --verbose
-x --debug
-p --port Number
-d --data path
-s --serve
-r --profile boolean
Using the --serve option will run the server, else the remainder
of the command line will be used as the node module to profile.
See the `README.md` file for #{pkg.name} for more information.
"""
console.log text
process.exit()
#-------------------------------------------------------------------------------
# Copyright 2013 I.B.M.
#
# 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.
#-------------------------------------------------------------------------------
| 105171 | # Licensed under the Apache License. See footer for details.
fs = require "fs"
path = require "path"
nopt = require "nopt"
_ = require "underscore"
pkg = require "../../package.json"
utils = require "../common/utils"
logger = require "../common/logger"
#-------------------------------------------------------------------------------
exports.getConfiguration = (argv) ->
{args, opts} = parseCommandLine argv
cDef = getConfigurationDefault()
cCmd = getConfigurationCommandLine opts
cFile = cCmd.config or cDef.config
cEnv = getConfigurationEnv()
cCfg = getConfigurationConfig cFile
config = _.defaults {}, cCmd, cEnv, cCfg, cDef
delete config.config
data = mkdirp config.data
if !data?
logger.log "data directory not found or not writable: #{config.data}"
process.exit 1
return {args, config}
#-------------------------------------------------------------------------------
mkdirp = (dir) ->
exists = fs.existsSync dir
if exists
stats = fs.statSync dir
return null if !stats.isDirectory()
return dir
parent = path.dirname dir
result = mkdirp parent
return null if !result?
try
fs.mkdirSync dir
catch e
return null
return dir
#-------------------------------------------------------------------------------
getConfigurationDefault = ->
result =
verbose: false
debug: false
serve: false
port: 3000
heap: true
profile: true
data: utils.replaceTilde "~/.#{pkg.name}/data"
config: utils.replaceTilde "~/.#{pkg.name}/config.json"
return result
#-------------------------------------------------------------------------------
getConfigurationConfig = (file) ->
try
contents = fs.readFileSync file, "utf8"
contents = JSON.parse contents
catch e
contents = {}
return contents
#-------------------------------------------------------------------------------
getConfigurationEnv = ->
result = {}
port = process.env.PORT
result.port = port if port?
return result
#-------------------------------------------------------------------------------
getConfigurationCommandLine = (opts) ->
return opts
#-------------------------------------------------------------------------------
parseCommandLine = (argv) ->
optionSpecs =
verbose: Boolean
debug: Boolean
serve: Boolean
heap: Boolean
profile: Boolean
port: Number
data: path
config: path
help: Boolean
shortHands =
v: "--verbose"
d: "--debug"
s: "--serve"
h: "--heap"
r: "--profile"
p: "--port"
d: "--data"
c: "--config"
"?": "--help"
exports.help() if argv[0] == "?"
parsed = nopt(optionSpecs, shortHands, argv, 0)
exports.help() if parsed.help
args = parsed.argv.remain
opts = parsed
delete opts.argv
return {args, opts}
#-------------------------------------------------------------------------------
# print some help and then exit
#-------------------------------------------------------------------------------
exports.help = ->
text = """
#{pkg.name} #{pkg.version}
will run an HTTP server to display profiling results,
or profile the execution of a node module
usage:
#{pkg.name} [options] [arguments]
options:
-c --config path
-v --verbose
-x --debug
-p --port Number
-d --data path
-s --serve
-r --profile boolean
Using the --serve option will run the server, else the remainder
of the command line will be used as the node module to profile.
See the `README.md` file for #{pkg.name} for more information.
"""
console.log text
process.exit()
#-------------------------------------------------------------------------------
# Copyright 2013 <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.
#-------------------------------------------------------------------------------
| true | # Licensed under the Apache License. See footer for details.
fs = require "fs"
path = require "path"
nopt = require "nopt"
_ = require "underscore"
pkg = require "../../package.json"
utils = require "../common/utils"
logger = require "../common/logger"
#-------------------------------------------------------------------------------
exports.getConfiguration = (argv) ->
{args, opts} = parseCommandLine argv
cDef = getConfigurationDefault()
cCmd = getConfigurationCommandLine opts
cFile = cCmd.config or cDef.config
cEnv = getConfigurationEnv()
cCfg = getConfigurationConfig cFile
config = _.defaults {}, cCmd, cEnv, cCfg, cDef
delete config.config
data = mkdirp config.data
if !data?
logger.log "data directory not found or not writable: #{config.data}"
process.exit 1
return {args, config}
#-------------------------------------------------------------------------------
mkdirp = (dir) ->
exists = fs.existsSync dir
if exists
stats = fs.statSync dir
return null if !stats.isDirectory()
return dir
parent = path.dirname dir
result = mkdirp parent
return null if !result?
try
fs.mkdirSync dir
catch e
return null
return dir
#-------------------------------------------------------------------------------
getConfigurationDefault = ->
result =
verbose: false
debug: false
serve: false
port: 3000
heap: true
profile: true
data: utils.replaceTilde "~/.#{pkg.name}/data"
config: utils.replaceTilde "~/.#{pkg.name}/config.json"
return result
#-------------------------------------------------------------------------------
getConfigurationConfig = (file) ->
try
contents = fs.readFileSync file, "utf8"
contents = JSON.parse contents
catch e
contents = {}
return contents
#-------------------------------------------------------------------------------
getConfigurationEnv = ->
result = {}
port = process.env.PORT
result.port = port if port?
return result
#-------------------------------------------------------------------------------
getConfigurationCommandLine = (opts) ->
return opts
#-------------------------------------------------------------------------------
parseCommandLine = (argv) ->
optionSpecs =
verbose: Boolean
debug: Boolean
serve: Boolean
heap: Boolean
profile: Boolean
port: Number
data: path
config: path
help: Boolean
shortHands =
v: "--verbose"
d: "--debug"
s: "--serve"
h: "--heap"
r: "--profile"
p: "--port"
d: "--data"
c: "--config"
"?": "--help"
exports.help() if argv[0] == "?"
parsed = nopt(optionSpecs, shortHands, argv, 0)
exports.help() if parsed.help
args = parsed.argv.remain
opts = parsed
delete opts.argv
return {args, opts}
#-------------------------------------------------------------------------------
# print some help and then exit
#-------------------------------------------------------------------------------
exports.help = ->
text = """
#{pkg.name} #{pkg.version}
will run an HTTP server to display profiling results,
or profile the execution of a node module
usage:
#{pkg.name} [options] [arguments]
options:
-c --config path
-v --verbose
-x --debug
-p --port Number
-d --data path
-s --serve
-r --profile boolean
Using the --serve option will run the server, else the remainder
of the command line will be used as the node module to profile.
See the `README.md` file for #{pkg.name} for more information.
"""
console.log text
process.exit()
#-------------------------------------------------------------------------------
# Copyright 2013 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.
#-------------------------------------------------------------------------------
|
[
{
"context": "nge for Bosun -- http://bosun.org.\n#\n# Author:\n# lukas.pustina@gmail.com\n#\n# Todos:\n# (*) Graph queries\n\nrequest = requi",
"end": 1894,
"score": 0.9998924136161804,
"start": 1871,
"tag": "EMAIL",
"value": "lukas.pustina@gmail.com"
},
{
"context": "ta = {\n ... | src/bosun.coffee | lukaspustina/hubot-bosun | 1 | # Description
# Allows hubot to interact with Bosun.
#
# Configuration:
# HUBOT_BOSUN_HOST -- Bosun server URL, e.g., `http://localhost:8070`
# HUBOT_BOSUN_LINK_URL -- If set, this URL will be used for links instead of `HUBOT_BOSUN_HOST`
# HUBOT_BOSUN_ROLE -- If set, auth role required to interact with Bosun. Default is `bosun`
# HUBOT_BOSUN_SLACK -- If `yes` enables rich text formatting for Slack, default is `no`
# HUBOT_BOSUN_LOG_LEVEL -- Log level, default is `info`
# HUBOT_BOSUN_TIMEOUT -- Timeout for Bosun API calls in milliseconds; default is `10000`
# HUBOT_BOSUN_RELATIVE_TIME -- If `yes` all dates and times are presented relative to now, e.g. _2 min ago_
#
# Commands:
# show open bosun incidents -- shows all open incidents, unacked and acked, sorted by incident id
# <ack|close> bosun incident[s] <Id,...> because <message> -- acks or closes bosun incidents with the specific incident ids
# show bosun silences -- shows all active silences
# <set|test> bosun silence for <alert|tagkey>=value[,...] for <duration> because <message> -- sets or tests a new silence, e.g., `set bosun silence for alert=test.lukas,host=muffin for 1h because I want to`. Can also be used with alert or tags only.
# clear bosun silence <id> -- deletes silence with the specific silence id
#
# Events:
# Accepts the following events:
# bosun.set_silence
# bosun.clear_silence
# bosun.check_silence
# Emits the following events:
# bosun.result.set_silence.successful
# bosun.result.set_silence.failed
# bosun.result.clear_silence.successful
# bosun.result.clear_silence.failed
# bosun.result.check_silence.successful
# bosun.result.check_silence.failed
# Please see the event handlers for the specific event formats.
#
# Notes:
# Enjoy and thank Stack Exchange for Bosun -- http://bosun.org.
#
# Author:
# lukas.pustina@gmail.com
#
# Todos:
# (*) Graph queries
request = require 'request'
Log = require 'log'
moment = require 'moment'
config =
host: process.env.HUBOT_BOSUN_HOST
link_url: process.env.HUBOT_BOSUN_LINK_URL or process.env.HUBOT_BOSUN_HOST
role: process.env.HUBOT_BOSUN_ROLE or ""
slack: process.env.HUBOT_BOSUN_SLACK is "yes"
log_level: process.env.HUBOT_BOSUN_LOG_LEVEL or "info"
timeout: if process.env.HUBOT_BOSUN_TIMEOUT then parseInt process.env.HUBOT_BOSUN_TIMEOUT else 10000
relative_time: process.env.HUBOT_BOSUN_RELATIVE_TIME is "yes"
logger = new Log config.log_level
logger.notice "hubot-bosun: Started with Bosun server #{config.host}, link URL #{config.link_url}, Slack #{if config.slack then 'en' else 'dis'}abled, timeout set to #{config.timeout}, and log level #{config.log_level}."
module.exports = (robot) ->
robot.respond /show open bosun incidents/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
logger.info "hubot-bosun: Retrieving Bosun incidents requested by #{user_name}."
res.reply "Retrieving Bosun incidents ..."
req = request.get("#{config.host}/api/incidents/open", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
res.reply "Yippie. Done."
incidents = JSON.parse body
incidents.sort( (a,b) -> parseInt(a.Id) > parseInt(b.Id) )
status =
if incidents.length is 0
then "Oh, no incidents there. Everything is ok."
else "So, there are currently #{incidents.length} open incidents in Bosun."
logger.info "hubot-bosun: #{status}"
unless config.slack
res.reply status
for i in incidents
res.reply "#{i.Id} is #{i.CurrentStatus}: #{i.Subject}."
else
attachments = []
for i in incidents
start = format_date_str(new Date(i.Start * 1000).toISOString())
color = switch i.CurrentStatus
when 'normal' then 'good'
when 'warning' then 'warning'
when 'critical' then 'danger'
else '#439FE0'
acked = if i.NeedAck then '*Unacked*' else 'Acked'
actions = for a in i.Actions
time = format_date_str(new Date(a.Time * 1000).toISOString())
"* #{a.User} #{a.Type.toLowerCase()} this incident at #{time}."
text = "#{acked} and active since #{start} with _#{i.TagsString}_."
text += '\n' if actions.length > 0
text += actions.join('\n')
attachments.push {
fallback: "Incident #{i.Id} is #{i.CurrentStatus}"
color: color
title: "#{i.Id}: #{i.Subject}"
title_link: "#{config.link_url}/incident?id=#{i.Id}"
text: text
mrkdwn_in: ["text"]
}
robot.adapter.customMessage {
channel: res.message.room
text: status
attachments: attachments
}
)
robot.respond /(ack|close) bosun incident[s]* ([\d,]+) because (.+)/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
action = res.match[1].toLowerCase()
ids = (parseInt(incident) for incident in res.match[2].split ',')
message = res.match[3]
logger.info "hubot-bosun: Executing '#{action}' for incident(s) #{ids.join(',')} requested by #{user_name}."
res.reply "Trying to #{action} Bosun incident#{if ids.length > 1 then 's' else ''} #{ids.join(',')} ..."
data = {
Type: "#{action}"
User: "#{user_name}"
Message: "#{message}"
Ids: ids
Notify: true
}
req = request.post("#{config.host}/api/action", {timeout: config.timeout, json: true, body: data}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
logger.info "hubot-buson: Bosun replied with HTTP status code #{response.statusCode}"
answer = switch response.statusCode
when 200 then "Yippie. Done."
when 500 then "Bosun couldn't deal with that; maybe the incident doesn't exists or is still active? I suggest, you list the now open incidents. That's what Bosun told me: ```\n#{body}\n```"
else "Puh, no sure what happened. I asked Bosun politely, but I got a weird answer. Bosun said '#{body}'."
if not config.slack or response.statusCode is 200
res.reply answer
else
robot.adapter.customMessage {
channel: res.message.room
attachments: [ {
fallback: "#{answer}"
color: 'danger'
title: "Argh. Failed to deal with Bosun's answer."
text: answer
mrkdwn_in: ["text"]
} ]
}
)
robot.respond /show bosun silence[s]*/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
logger.info "hubot-bosun: Retrieving Bosun silences requested by #{user_name}."
res.reply "Retrieving Bosun silences ..."
req = request.get("#{config.host}/api/silence/get", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
res.reply "Yippie. Done."
silences = JSON.parse body
status =
if silences.length is 0
then "Oh, no silences there. Everybody is on watch."
else "So, there are currently #{Object.keys(silences).length} active silences in Bosun."
logger.info "hubot-bosun: #{status}"
console.log
unless config.slack
res.reply status
for k in Object.keys silences
s = silences[k]
start = format_date_str s.Start
end = format_date_str s.End
res.reply "Silence #{k} from #{start} until #{end} for tags #{s.TagString} and alert '#{s.Alert}' because #{s.Message}"
else
attachments = []
for id in Object.keys silences
s = silences[id]
start = format_date_str s.Start
end = format_date_str s.End
is_active = moment(s.End).isBefore moment()
color = switch is_active
when true then 'danger'
when false then 'good'
when true then 'danger'
text = "Active from #{start} until #{end}"
text += "\nMessage: _#{s.Message}_"
text += "\nAlert: #{s.Alert}" if s.Alert != ""
text += "\nTags: #{s.TagString}" if s.TagsString != ""
text += "\nId: #{id}"
attachments.push {
fallback: "Slience #{id} is #{if is_active then "active" else "inactive"}."
color: color
title: "Slience is #{if is_active then "active" else "inactive"}."
title_link: "#{config.link_url}/silence"
text: text
mrkdwn_in: ["text"]
}
robot.adapter.customMessage {
channel: res.message.room
text: status
attachments: attachments
}
)
robot.respond /(set|test) bosun silence for (.+) for (.+) because (.+)/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
action = res.match[1].toLowerCase()
alert_tags_str = res.match[2]
alert_tags = (
dict = {}
for alert_tag in alert_tags_str.split ','
[k, v] = alert_tag.split '='
dict[k] = v
dict
)
duration = res.match[3]
message = res.match[4]
logger.info "hubot-bosun: #{action}ing silence for #{alert_tags_str} for #{duration} requested by #{user_name}."
alert = if alert_tags.alert? then alert_tags.alert else ""
delete alert_tags.alert if alert_tags.alert?
tags = alert_tags
answer = switch action
when 'test' then "Trying to test Bosun silence"
when 'set' then "Trying to set Bosun silence"
answer += " for alert '#{alert}'" if alert != ""
answer += if alert !="" and Object.keys(tags).length > 0 then " and" else " for"
tags_str = JSON.stringify(tags).replace(/\"/g,'')
answer += " tags #{tags_str} for" if Object.keys(tags).length > 0
answer += " #{duration}"
res.reply "#{answer} ..."
tag_str = ("#{k}=#{tags[k]}" for k in Object.keys(tags)).join(',')
data = {
duration: "#{duration}"
alert: "#{alert}"
tags: tag_str
user: "#{user_name}"
message: "#{message}"
forget: "true"
}
data.confirm = "true" if action == 'set'
req = request.post("#{config.host}/api/silence/set", {timeout: config.timeout, json: true, body: data}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
logger.info "hubot-buson: Bosun replied with HTTP status code #{response.statusCode}"
answer = switch response.statusCode
when 200
if action == 'set' then "Yippie. Done. Admire your alarm at #{config.host}/silence."
else "Yippie. Done. That alarm will work."
when 500 then "Bosun couldn't deal with that. I suggest, you list the active silences now. That's what Bosun told me: ```\n#{body}\n```"
else "Puh, no sure what happened. I asked Bosun politely, but I got a weird answer. Bosun said '#{body}'."
if not config.slack or response.statusCode is 200
res.reply answer
else
robot.adapter.customMessage {
channel: res.message.room
attachments: [ {
fallback: "#{answer}"
color: 'danger'
title: "Argh. Failed to deal with Bosun's answer."
text: answer
mrkdwn_in: ["text"]
} ]
}
)
robot.respond /clear bosun silence (.+)/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
id = res.match[1]
logger.info "hubot-bosun: Clearing silence '#{id}' requested by #{user_name}."
res.reply "Trying to clear Bosun silence #{id} ..."
req = request.post("#{config.host}/api/silence/clear?id=#{id}", {timeout: config.timeout, json: true, body: {}}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
logger.info "hubot-buson: Bosun replied with HTTP status code #{response.statusCode}"
answer = switch response.statusCode
when 200 then "Yippie. Done."
when 500 then "Bosun couldn't deal with that; maybe the silence doesn't exists? I suggest, you list the open silences now. That's what Bosun told me: ```\n#{body}\n```"
else "Puh, no sure what happened. I asked Bosun politely, but I got a weird answer. Bosun said '#{body}'."
if not config.slack or response.statusCode is 200
res.reply answer
else
robot.adapter.customMessage {
channel: res.message.room
attachments: [ {
fallback: "#{answer}"
color: 'danger'
title: "Argh. Failed to deal with Bosun's answer."
text: answer
mrkdwn_in: ["text"]
} ]
}
)
robot.on 'bosun.set_silence', (event) ->
unless is_authorized robot, event.user
logger.warning "hubot-bosun: #{event.user} tried to run event 'bosun.set_silence' but was not authorized."
else
logger.info "hubot-bosun: setting silence for alert '#{event.alert}' and tags '#{event.tags}' for #{event.duration} requested by #{event.user.name} via event."
data =
duration: event.duration
alert: event.alert
tags: event.tags
message: event.message
forget: event.forget
confirm: "true"
req = request.post("#{config.host}/api/silence/set", {timeout: config.timeout, json: true, body: data}, (err, response, body) ->
if err
handle_bosun_err null, err, response, body
robot.emit 'bosun.result.set_silence.failed', {
user: event.user
room: event.room
message: "Connection to Bosun failed."
}
else if response and response.statusCode != 200
robot.emit 'bosun.result.set_silence.failed', {
user: event.user
room: event.room
message: "API call failed with status code #{response.statusCode}."
}
else
# ARGH: Bosun does not return the ID of the Silence via API, so we have to figure it out with a second call and some heuristics
req = request.get("#{config.host}/api/silence/get", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
robot.emit 'bosun.result.set_silence.failed', {
user: event.user
room: event.room
message: "Cloud not retrieve actives silences after setting your's; status code #{response.statusCode}."
}
else
silences = JSON.parse body
# map silences from object to array and add unix_time_stamp for time based ordering
silences = ({Id: k, start_as_unix_time: moment(v.Start).valueOf(), silence: v} for k,v of silences)
silences.sort( (a,b) -> b.start_as_unix_time - a.start_as_unix_time )
# This should be the younges alarm
silence_id = silences[0].Id
robot.emit 'bosun.result.set_silence.successful',
user: event.user
room: event.room
duration: event.duration
silence_id: silence_id
)
)
robot.on 'bosun.clear_silence', (event) ->
unless is_authorized robot, event.user
logger.warning "hubot-bosun: #{event.user} tried to run event 'bosun.clear_silence' but was not authorized."
else
logger.info "hubot-bosun: clearing silence with id '#{event.silence_id}' equested by #{event.user.name} via event."
req = request.post("#{config.host}/api/silence/clear?id=#{event.silence_id}", {timeout: config.timeout, json: true, body: {}}, (err, response, body) ->
if err
handle_bosun_err null, err, response, body
robot.emit 'bosun.result.clear_silence.failed', {
user: event.user
room: event.room
silence_id: event.silence_id
message: "Connection to Bosun failed."
}
else if response and response.statusCode != 200
robot.emit 'bosun.result.clear_silence.failed', {
user: event.user
room: event.room
silence_id: event.silence_id
message: "API call failed with status code #{response.statusCode}."
}
else
robot.emit 'bosun.result.clear_silence.successful', event
)
robot.on 'bosun.check_silence', (event) ->
unless is_authorized robot, event.user
logger.warning "hubot-bosun: #{event.user} tried to run event 'bosun.check_silence' but was not authorized."
else
logger.info "hubot-bosun: checking silence requested by #{event.user.name} via event."
req = request.get("#{config.host}/api/silence/get", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
robot.emit 'bosun.result.check_silence.failed', {
user: event.user
room: event.room
message: "Cloud not retrieve actives silences; status code #{response.statusCode}."
}
else
silences = JSON.parse body
silences = (k for k,v of silences)
active = event.silence_id in silences
robot.emit 'bosun.result.check_silence.successful',
user: event.user
room: event.room
silence_id: event.silence_id
active: active
)
robot.error (err, res) ->
robot.logger.error "hubot-bosun: DOES NOT COMPUTE"
if res?
res.reply "DOES NOT COMPUTE: #{err}"
is_authorized = (robot, user) ->
logger.debug "Checking authorization for user '#{user.name}' and role '#{config.role}': role is #{config.role is ""}, auth is #{robot.auth.hasRole(user, config.role)}, combined is #{config.role is "" or robot.auth.hasRole(user, config.role)}."
config.role is "" or robot.auth.hasRole(user, config.role)
warn_unauthorized = (res) ->
user = res.envelope.user.name
message = res.message.text
logger.warning "hubot-bosun: #{user} tried to run '#{message}' but was not authorized."
res.reply "Sorry, you're not allowed to do that. You need the '#{config.role}' role."
handle_bosun_err = (res, err, response, body) ->
logger.error "hubot-bosun: Requst to Bosun timed out." if err? and err.code is 'ETIMEDOUT'
logger.error "hubot-bosun: Connection to Bosun failed." if err? and err.connect is true or err.code is 'ECONNREFUSED'
logger.error "hubot-bosun: Failed to retrieve response from Bosun. Error: '#{err}', reponse: '#{response}', body: '#{body}'"
if res
res.reply "Ouuch. I'm sorry, but I couldn't contact Bosun."
format_date_str = (date_str) ->
if config.relative_time
moment(date_str).fromNow()
else
date_str.replace(/T/, ' ').replace(/\..+/, ' UTC')
| 7564 | # Description
# Allows hubot to interact with Bosun.
#
# Configuration:
# HUBOT_BOSUN_HOST -- Bosun server URL, e.g., `http://localhost:8070`
# HUBOT_BOSUN_LINK_URL -- If set, this URL will be used for links instead of `HUBOT_BOSUN_HOST`
# HUBOT_BOSUN_ROLE -- If set, auth role required to interact with Bosun. Default is `bosun`
# HUBOT_BOSUN_SLACK -- If `yes` enables rich text formatting for Slack, default is `no`
# HUBOT_BOSUN_LOG_LEVEL -- Log level, default is `info`
# HUBOT_BOSUN_TIMEOUT -- Timeout for Bosun API calls in milliseconds; default is `10000`
# HUBOT_BOSUN_RELATIVE_TIME -- If `yes` all dates and times are presented relative to now, e.g. _2 min ago_
#
# Commands:
# show open bosun incidents -- shows all open incidents, unacked and acked, sorted by incident id
# <ack|close> bosun incident[s] <Id,...> because <message> -- acks or closes bosun incidents with the specific incident ids
# show bosun silences -- shows all active silences
# <set|test> bosun silence for <alert|tagkey>=value[,...] for <duration> because <message> -- sets or tests a new silence, e.g., `set bosun silence for alert=test.lukas,host=muffin for 1h because I want to`. Can also be used with alert or tags only.
# clear bosun silence <id> -- deletes silence with the specific silence id
#
# Events:
# Accepts the following events:
# bosun.set_silence
# bosun.clear_silence
# bosun.check_silence
# Emits the following events:
# bosun.result.set_silence.successful
# bosun.result.set_silence.failed
# bosun.result.clear_silence.successful
# bosun.result.clear_silence.failed
# bosun.result.check_silence.successful
# bosun.result.check_silence.failed
# Please see the event handlers for the specific event formats.
#
# Notes:
# Enjoy and thank Stack Exchange for Bosun -- http://bosun.org.
#
# Author:
# <EMAIL>
#
# Todos:
# (*) Graph queries
request = require 'request'
Log = require 'log'
moment = require 'moment'
config =
host: process.env.HUBOT_BOSUN_HOST
link_url: process.env.HUBOT_BOSUN_LINK_URL or process.env.HUBOT_BOSUN_HOST
role: process.env.HUBOT_BOSUN_ROLE or ""
slack: process.env.HUBOT_BOSUN_SLACK is "yes"
log_level: process.env.HUBOT_BOSUN_LOG_LEVEL or "info"
timeout: if process.env.HUBOT_BOSUN_TIMEOUT then parseInt process.env.HUBOT_BOSUN_TIMEOUT else 10000
relative_time: process.env.HUBOT_BOSUN_RELATIVE_TIME is "yes"
logger = new Log config.log_level
logger.notice "hubot-bosun: Started with Bosun server #{config.host}, link URL #{config.link_url}, Slack #{if config.slack then 'en' else 'dis'}abled, timeout set to #{config.timeout}, and log level #{config.log_level}."
module.exports = (robot) ->
robot.respond /show open bosun incidents/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
logger.info "hubot-bosun: Retrieving Bosun incidents requested by #{user_name}."
res.reply "Retrieving Bosun incidents ..."
req = request.get("#{config.host}/api/incidents/open", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
res.reply "Yippie. Done."
incidents = JSON.parse body
incidents.sort( (a,b) -> parseInt(a.Id) > parseInt(b.Id) )
status =
if incidents.length is 0
then "Oh, no incidents there. Everything is ok."
else "So, there are currently #{incidents.length} open incidents in Bosun."
logger.info "hubot-bosun: #{status}"
unless config.slack
res.reply status
for i in incidents
res.reply "#{i.Id} is #{i.CurrentStatus}: #{i.Subject}."
else
attachments = []
for i in incidents
start = format_date_str(new Date(i.Start * 1000).toISOString())
color = switch i.CurrentStatus
when 'normal' then 'good'
when 'warning' then 'warning'
when 'critical' then 'danger'
else '#439FE0'
acked = if i.NeedAck then '*Unacked*' else 'Acked'
actions = for a in i.Actions
time = format_date_str(new Date(a.Time * 1000).toISOString())
"* #{a.User} #{a.Type.toLowerCase()} this incident at #{time}."
text = "#{acked} and active since #{start} with _#{i.TagsString}_."
text += '\n' if actions.length > 0
text += actions.join('\n')
attachments.push {
fallback: "Incident #{i.Id} is #{i.CurrentStatus}"
color: color
title: "#{i.Id}: #{i.Subject}"
title_link: "#{config.link_url}/incident?id=#{i.Id}"
text: text
mrkdwn_in: ["text"]
}
robot.adapter.customMessage {
channel: res.message.room
text: status
attachments: attachments
}
)
robot.respond /(ack|close) bosun incident[s]* ([\d,]+) because (.+)/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
action = res.match[1].toLowerCase()
ids = (parseInt(incident) for incident in res.match[2].split ',')
message = res.match[3]
logger.info "hubot-bosun: Executing '#{action}' for incident(s) #{ids.join(',')} requested by #{user_name}."
res.reply "Trying to #{action} Bosun incident#{if ids.length > 1 then 's' else ''} #{ids.join(',')} ..."
data = {
Type: "#{action}"
User: "#{user_name}"
Message: "#{message}"
Ids: ids
Notify: true
}
req = request.post("#{config.host}/api/action", {timeout: config.timeout, json: true, body: data}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
logger.info "hubot-buson: Bosun replied with HTTP status code #{response.statusCode}"
answer = switch response.statusCode
when 200 then "Yippie. Done."
when 500 then "Bosun couldn't deal with that; maybe the incident doesn't exists or is still active? I suggest, you list the now open incidents. That's what Bosun told me: ```\n#{body}\n```"
else "Puh, no sure what happened. I asked Bosun politely, but I got a weird answer. Bosun said '#{body}'."
if not config.slack or response.statusCode is 200
res.reply answer
else
robot.adapter.customMessage {
channel: res.message.room
attachments: [ {
fallback: "#{answer}"
color: 'danger'
title: "Argh. Failed to deal with Bosun's answer."
text: answer
mrkdwn_in: ["text"]
} ]
}
)
robot.respond /show bosun silence[s]*/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
logger.info "hubot-bosun: Retrieving Bosun silences requested by #{user_name}."
res.reply "Retrieving Bosun silences ..."
req = request.get("#{config.host}/api/silence/get", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
res.reply "Yippie. Done."
silences = JSON.parse body
status =
if silences.length is 0
then "Oh, no silences there. Everybody is on watch."
else "So, there are currently #{Object.keys(silences).length} active silences in Bosun."
logger.info "hubot-bosun: #{status}"
console.log
unless config.slack
res.reply status
for k in Object.keys silences
s = silences[k]
start = format_date_str s.Start
end = format_date_str s.End
res.reply "Silence #{k} from #{start} until #{end} for tags #{s.TagString} and alert '#{s.Alert}' because #{s.Message}"
else
attachments = []
for id in Object.keys silences
s = silences[id]
start = format_date_str s.Start
end = format_date_str s.End
is_active = moment(s.End).isBefore moment()
color = switch is_active
when true then 'danger'
when false then 'good'
when true then 'danger'
text = "Active from #{start} until #{end}"
text += "\nMessage: _#{s.Message}_"
text += "\nAlert: #{s.Alert}" if s.Alert != ""
text += "\nTags: #{s.TagString}" if s.TagsString != ""
text += "\nId: #{id}"
attachments.push {
fallback: "Slience #{id} is #{if is_active then "active" else "inactive"}."
color: color
title: "Slience is #{if is_active then "active" else "inactive"}."
title_link: "#{config.link_url}/silence"
text: text
mrkdwn_in: ["text"]
}
robot.adapter.customMessage {
channel: res.message.room
text: status
attachments: attachments
}
)
robot.respond /(set|test) bosun silence for (.+) for (.+) because (.+)/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
action = res.match[1].toLowerCase()
alert_tags_str = res.match[2]
alert_tags = (
dict = {}
for alert_tag in alert_tags_str.split ','
[k, v] = alert_tag.split '='
dict[k] = v
dict
)
duration = res.match[3]
message = res.match[4]
logger.info "hubot-bosun: #{action}ing silence for #{alert_tags_str} for #{duration} requested by #{user_name}."
alert = if alert_tags.alert? then alert_tags.alert else ""
delete alert_tags.alert if alert_tags.alert?
tags = alert_tags
answer = switch action
when 'test' then "Trying to test Bosun silence"
when 'set' then "Trying to set Bosun silence"
answer += " for alert '#{alert}'" if alert != ""
answer += if alert !="" and Object.keys(tags).length > 0 then " and" else " for"
tags_str = JSON.stringify(tags).replace(/\"/g,'')
answer += " tags #{tags_str} for" if Object.keys(tags).length > 0
answer += " #{duration}"
res.reply "#{answer} ..."
tag_str = ("#{k}=#{tags[k]}" for k in Object.keys(tags)).join(',')
data = {
duration: "#{duration}"
alert: "#{alert}"
tags: tag_str
user: "#{user_name}"
message: "#{message}"
forget: "true"
}
data.confirm = "true" if action == 'set'
req = request.post("#{config.host}/api/silence/set", {timeout: config.timeout, json: true, body: data}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
logger.info "hubot-buson: Bosun replied with HTTP status code #{response.statusCode}"
answer = switch response.statusCode
when 200
if action == 'set' then "Yippie. Done. Admire your alarm at #{config.host}/silence."
else "Yippie. Done. That alarm will work."
when 500 then "Bosun couldn't deal with that. I suggest, you list the active silences now. That's what Bosun told me: ```\n#{body}\n```"
else "Puh, no sure what happened. I asked Bosun politely, but I got a weird answer. Bosun said '#{body}'."
if not config.slack or response.statusCode is 200
res.reply answer
else
robot.adapter.customMessage {
channel: res.message.room
attachments: [ {
fallback: "#{answer}"
color: 'danger'
title: "Argh. Failed to deal with Bosun's answer."
text: answer
mrkdwn_in: ["text"]
} ]
}
)
robot.respond /clear bosun silence (.+)/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
id = res.match[1]
logger.info "hubot-bosun: Clearing silence '#{id}' requested by #{user_name}."
res.reply "Trying to clear Bosun silence #{id} ..."
req = request.post("#{config.host}/api/silence/clear?id=#{id}", {timeout: config.timeout, json: true, body: {}}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
logger.info "hubot-buson: Bosun replied with HTTP status code #{response.statusCode}"
answer = switch response.statusCode
when 200 then "Yippie. Done."
when 500 then "Bosun couldn't deal with that; maybe the silence doesn't exists? I suggest, you list the open silences now. That's what Bosun told me: ```\n#{body}\n```"
else "Puh, no sure what happened. I asked Bosun politely, but I got a weird answer. Bosun said '#{body}'."
if not config.slack or response.statusCode is 200
res.reply answer
else
robot.adapter.customMessage {
channel: res.message.room
attachments: [ {
fallback: "#{answer}"
color: 'danger'
title: "Argh. Failed to deal with Bosun's answer."
text: answer
mrkdwn_in: ["text"]
} ]
}
)
robot.on 'bosun.set_silence', (event) ->
unless is_authorized robot, event.user
logger.warning "hubot-bosun: #{event.user} tried to run event 'bosun.set_silence' but was not authorized."
else
logger.info "hubot-bosun: setting silence for alert '#{event.alert}' and tags '#{event.tags}' for #{event.duration} requested by #{event.user.name} via event."
data =
duration: event.duration
alert: event.alert
tags: event.tags
message: event.message
forget: event.forget
confirm: "true"
req = request.post("#{config.host}/api/silence/set", {timeout: config.timeout, json: true, body: data}, (err, response, body) ->
if err
handle_bosun_err null, err, response, body
robot.emit 'bosun.result.set_silence.failed', {
user: event.user
room: event.room
message: "Connection to Bosun failed."
}
else if response and response.statusCode != 200
robot.emit 'bosun.result.set_silence.failed', {
user: event.user
room: event.room
message: "API call failed with status code #{response.statusCode}."
}
else
# ARGH: Bosun does not return the ID of the Silence via API, so we have to figure it out with a second call and some heuristics
req = request.get("#{config.host}/api/silence/get", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
robot.emit 'bosun.result.set_silence.failed', {
user: event.user
room: event.room
message: "Cloud not retrieve actives silences after setting your's; status code #{response.statusCode}."
}
else
silences = JSON.parse body
# map silences from object to array and add unix_time_stamp for time based ordering
silences = ({Id: k, start_as_unix_time: moment(v.Start).valueOf(), silence: v} for k,v of silences)
silences.sort( (a,b) -> b.start_as_unix_time - a.start_as_unix_time )
# This should be the younges alarm
silence_id = silences[0].Id
robot.emit 'bosun.result.set_silence.successful',
user: event.user
room: event.room
duration: event.duration
silence_id: silence_id
)
)
robot.on 'bosun.clear_silence', (event) ->
unless is_authorized robot, event.user
logger.warning "hubot-bosun: #{event.user} tried to run event 'bosun.clear_silence' but was not authorized."
else
logger.info "hubot-bosun: clearing silence with id '#{event.silence_id}' equested by #{event.user.name} via event."
req = request.post("#{config.host}/api/silence/clear?id=#{event.silence_id}", {timeout: config.timeout, json: true, body: {}}, (err, response, body) ->
if err
handle_bosun_err null, err, response, body
robot.emit 'bosun.result.clear_silence.failed', {
user: event.user
room: event.room
silence_id: event.silence_id
message: "Connection to Bosun failed."
}
else if response and response.statusCode != 200
robot.emit 'bosun.result.clear_silence.failed', {
user: event.user
room: event.room
silence_id: event.silence_id
message: "API call failed with status code #{response.statusCode}."
}
else
robot.emit 'bosun.result.clear_silence.successful', event
)
robot.on 'bosun.check_silence', (event) ->
unless is_authorized robot, event.user
logger.warning "hubot-bosun: #{event.user} tried to run event 'bosun.check_silence' but was not authorized."
else
logger.info "hubot-bosun: checking silence requested by #{event.user.name} via event."
req = request.get("#{config.host}/api/silence/get", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
robot.emit 'bosun.result.check_silence.failed', {
user: event.user
room: event.room
message: "Cloud not retrieve actives silences; status code #{response.statusCode}."
}
else
silences = JSON.parse body
silences = (k for k,v of silences)
active = event.silence_id in silences
robot.emit 'bosun.result.check_silence.successful',
user: event.user
room: event.room
silence_id: event.silence_id
active: active
)
robot.error (err, res) ->
robot.logger.error "hubot-bosun: DOES NOT COMPUTE"
if res?
res.reply "DOES NOT COMPUTE: #{err}"
is_authorized = (robot, user) ->
logger.debug "Checking authorization for user '#{user.name}' and role '#{config.role}': role is #{config.role is ""}, auth is #{robot.auth.hasRole(user, config.role)}, combined is #{config.role is "" or robot.auth.hasRole(user, config.role)}."
config.role is "" or robot.auth.hasRole(user, config.role)
warn_unauthorized = (res) ->
user = res.envelope.user.name
message = res.message.text
logger.warning "hubot-bosun: #{user} tried to run '#{message}' but was not authorized."
res.reply "Sorry, you're not allowed to do that. You need the '#{config.role}' role."
handle_bosun_err = (res, err, response, body) ->
logger.error "hubot-bosun: Requst to Bosun timed out." if err? and err.code is 'ETIMEDOUT'
logger.error "hubot-bosun: Connection to Bosun failed." if err? and err.connect is true or err.code is 'ECONNREFUSED'
logger.error "hubot-bosun: Failed to retrieve response from Bosun. Error: '#{err}', reponse: '#{response}', body: '#{body}'"
if res
res.reply "Ouuch. I'm sorry, but I couldn't contact Bosun."
format_date_str = (date_str) ->
if config.relative_time
moment(date_str).fromNow()
else
date_str.replace(/T/, ' ').replace(/\..+/, ' UTC')
| true | # Description
# Allows hubot to interact with Bosun.
#
# Configuration:
# HUBOT_BOSUN_HOST -- Bosun server URL, e.g., `http://localhost:8070`
# HUBOT_BOSUN_LINK_URL -- If set, this URL will be used for links instead of `HUBOT_BOSUN_HOST`
# HUBOT_BOSUN_ROLE -- If set, auth role required to interact with Bosun. Default is `bosun`
# HUBOT_BOSUN_SLACK -- If `yes` enables rich text formatting for Slack, default is `no`
# HUBOT_BOSUN_LOG_LEVEL -- Log level, default is `info`
# HUBOT_BOSUN_TIMEOUT -- Timeout for Bosun API calls in milliseconds; default is `10000`
# HUBOT_BOSUN_RELATIVE_TIME -- If `yes` all dates and times are presented relative to now, e.g. _2 min ago_
#
# Commands:
# show open bosun incidents -- shows all open incidents, unacked and acked, sorted by incident id
# <ack|close> bosun incident[s] <Id,...> because <message> -- acks or closes bosun incidents with the specific incident ids
# show bosun silences -- shows all active silences
# <set|test> bosun silence for <alert|tagkey>=value[,...] for <duration> because <message> -- sets or tests a new silence, e.g., `set bosun silence for alert=test.lukas,host=muffin for 1h because I want to`. Can also be used with alert or tags only.
# clear bosun silence <id> -- deletes silence with the specific silence id
#
# Events:
# Accepts the following events:
# bosun.set_silence
# bosun.clear_silence
# bosun.check_silence
# Emits the following events:
# bosun.result.set_silence.successful
# bosun.result.set_silence.failed
# bosun.result.clear_silence.successful
# bosun.result.clear_silence.failed
# bosun.result.check_silence.successful
# bosun.result.check_silence.failed
# Please see the event handlers for the specific event formats.
#
# Notes:
# Enjoy and thank Stack Exchange for Bosun -- http://bosun.org.
#
# Author:
# PI:EMAIL:<EMAIL>END_PI
#
# Todos:
# (*) Graph queries
request = require 'request'
Log = require 'log'
moment = require 'moment'
config =
host: process.env.HUBOT_BOSUN_HOST
link_url: process.env.HUBOT_BOSUN_LINK_URL or process.env.HUBOT_BOSUN_HOST
role: process.env.HUBOT_BOSUN_ROLE or ""
slack: process.env.HUBOT_BOSUN_SLACK is "yes"
log_level: process.env.HUBOT_BOSUN_LOG_LEVEL or "info"
timeout: if process.env.HUBOT_BOSUN_TIMEOUT then parseInt process.env.HUBOT_BOSUN_TIMEOUT else 10000
relative_time: process.env.HUBOT_BOSUN_RELATIVE_TIME is "yes"
logger = new Log config.log_level
logger.notice "hubot-bosun: Started with Bosun server #{config.host}, link URL #{config.link_url}, Slack #{if config.slack then 'en' else 'dis'}abled, timeout set to #{config.timeout}, and log level #{config.log_level}."
module.exports = (robot) ->
robot.respond /show open bosun incidents/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
logger.info "hubot-bosun: Retrieving Bosun incidents requested by #{user_name}."
res.reply "Retrieving Bosun incidents ..."
req = request.get("#{config.host}/api/incidents/open", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
res.reply "Yippie. Done."
incidents = JSON.parse body
incidents.sort( (a,b) -> parseInt(a.Id) > parseInt(b.Id) )
status =
if incidents.length is 0
then "Oh, no incidents there. Everything is ok."
else "So, there are currently #{incidents.length} open incidents in Bosun."
logger.info "hubot-bosun: #{status}"
unless config.slack
res.reply status
for i in incidents
res.reply "#{i.Id} is #{i.CurrentStatus}: #{i.Subject}."
else
attachments = []
for i in incidents
start = format_date_str(new Date(i.Start * 1000).toISOString())
color = switch i.CurrentStatus
when 'normal' then 'good'
when 'warning' then 'warning'
when 'critical' then 'danger'
else '#439FE0'
acked = if i.NeedAck then '*Unacked*' else 'Acked'
actions = for a in i.Actions
time = format_date_str(new Date(a.Time * 1000).toISOString())
"* #{a.User} #{a.Type.toLowerCase()} this incident at #{time}."
text = "#{acked} and active since #{start} with _#{i.TagsString}_."
text += '\n' if actions.length > 0
text += actions.join('\n')
attachments.push {
fallback: "Incident #{i.Id} is #{i.CurrentStatus}"
color: color
title: "#{i.Id}: #{i.Subject}"
title_link: "#{config.link_url}/incident?id=#{i.Id}"
text: text
mrkdwn_in: ["text"]
}
robot.adapter.customMessage {
channel: res.message.room
text: status
attachments: attachments
}
)
robot.respond /(ack|close) bosun incident[s]* ([\d,]+) because (.+)/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
action = res.match[1].toLowerCase()
ids = (parseInt(incident) for incident in res.match[2].split ',')
message = res.match[3]
logger.info "hubot-bosun: Executing '#{action}' for incident(s) #{ids.join(',')} requested by #{user_name}."
res.reply "Trying to #{action} Bosun incident#{if ids.length > 1 then 's' else ''} #{ids.join(',')} ..."
data = {
Type: "#{action}"
User: "#{user_name}"
Message: "#{message}"
Ids: ids
Notify: true
}
req = request.post("#{config.host}/api/action", {timeout: config.timeout, json: true, body: data}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
logger.info "hubot-buson: Bosun replied with HTTP status code #{response.statusCode}"
answer = switch response.statusCode
when 200 then "Yippie. Done."
when 500 then "Bosun couldn't deal with that; maybe the incident doesn't exists or is still active? I suggest, you list the now open incidents. That's what Bosun told me: ```\n#{body}\n```"
else "Puh, no sure what happened. I asked Bosun politely, but I got a weird answer. Bosun said '#{body}'."
if not config.slack or response.statusCode is 200
res.reply answer
else
robot.adapter.customMessage {
channel: res.message.room
attachments: [ {
fallback: "#{answer}"
color: 'danger'
title: "Argh. Failed to deal with Bosun's answer."
text: answer
mrkdwn_in: ["text"]
} ]
}
)
robot.respond /show bosun silence[s]*/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
logger.info "hubot-bosun: Retrieving Bosun silences requested by #{user_name}."
res.reply "Retrieving Bosun silences ..."
req = request.get("#{config.host}/api/silence/get", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
res.reply "Yippie. Done."
silences = JSON.parse body
status =
if silences.length is 0
then "Oh, no silences there. Everybody is on watch."
else "So, there are currently #{Object.keys(silences).length} active silences in Bosun."
logger.info "hubot-bosun: #{status}"
console.log
unless config.slack
res.reply status
for k in Object.keys silences
s = silences[k]
start = format_date_str s.Start
end = format_date_str s.End
res.reply "Silence #{k} from #{start} until #{end} for tags #{s.TagString} and alert '#{s.Alert}' because #{s.Message}"
else
attachments = []
for id in Object.keys silences
s = silences[id]
start = format_date_str s.Start
end = format_date_str s.End
is_active = moment(s.End).isBefore moment()
color = switch is_active
when true then 'danger'
when false then 'good'
when true then 'danger'
text = "Active from #{start} until #{end}"
text += "\nMessage: _#{s.Message}_"
text += "\nAlert: #{s.Alert}" if s.Alert != ""
text += "\nTags: #{s.TagString}" if s.TagsString != ""
text += "\nId: #{id}"
attachments.push {
fallback: "Slience #{id} is #{if is_active then "active" else "inactive"}."
color: color
title: "Slience is #{if is_active then "active" else "inactive"}."
title_link: "#{config.link_url}/silence"
text: text
mrkdwn_in: ["text"]
}
robot.adapter.customMessage {
channel: res.message.room
text: status
attachments: attachments
}
)
robot.respond /(set|test) bosun silence for (.+) for (.+) because (.+)/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
action = res.match[1].toLowerCase()
alert_tags_str = res.match[2]
alert_tags = (
dict = {}
for alert_tag in alert_tags_str.split ','
[k, v] = alert_tag.split '='
dict[k] = v
dict
)
duration = res.match[3]
message = res.match[4]
logger.info "hubot-bosun: #{action}ing silence for #{alert_tags_str} for #{duration} requested by #{user_name}."
alert = if alert_tags.alert? then alert_tags.alert else ""
delete alert_tags.alert if alert_tags.alert?
tags = alert_tags
answer = switch action
when 'test' then "Trying to test Bosun silence"
when 'set' then "Trying to set Bosun silence"
answer += " for alert '#{alert}'" if alert != ""
answer += if alert !="" and Object.keys(tags).length > 0 then " and" else " for"
tags_str = JSON.stringify(tags).replace(/\"/g,'')
answer += " tags #{tags_str} for" if Object.keys(tags).length > 0
answer += " #{duration}"
res.reply "#{answer} ..."
tag_str = ("#{k}=#{tags[k]}" for k in Object.keys(tags)).join(',')
data = {
duration: "#{duration}"
alert: "#{alert}"
tags: tag_str
user: "#{user_name}"
message: "#{message}"
forget: "true"
}
data.confirm = "true" if action == 'set'
req = request.post("#{config.host}/api/silence/set", {timeout: config.timeout, json: true, body: data}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
logger.info "hubot-buson: Bosun replied with HTTP status code #{response.statusCode}"
answer = switch response.statusCode
when 200
if action == 'set' then "Yippie. Done. Admire your alarm at #{config.host}/silence."
else "Yippie. Done. That alarm will work."
when 500 then "Bosun couldn't deal with that. I suggest, you list the active silences now. That's what Bosun told me: ```\n#{body}\n```"
else "Puh, no sure what happened. I asked Bosun politely, but I got a weird answer. Bosun said '#{body}'."
if not config.slack or response.statusCode is 200
res.reply answer
else
robot.adapter.customMessage {
channel: res.message.room
attachments: [ {
fallback: "#{answer}"
color: 'danger'
title: "Argh. Failed to deal with Bosun's answer."
text: answer
mrkdwn_in: ["text"]
} ]
}
)
robot.respond /clear bosun silence (.+)/i, (res) ->
unless is_authorized robot, res.envelope.user
warn_unauthorized res
else
user_name = res.envelope.user.name
id = res.match[1]
logger.info "hubot-bosun: Clearing silence '#{id}' requested by #{user_name}."
res.reply "Trying to clear Bosun silence #{id} ..."
req = request.post("#{config.host}/api/silence/clear?id=#{id}", {timeout: config.timeout, json: true, body: {}}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
else
logger.info "hubot-buson: Bosun replied with HTTP status code #{response.statusCode}"
answer = switch response.statusCode
when 200 then "Yippie. Done."
when 500 then "Bosun couldn't deal with that; maybe the silence doesn't exists? I suggest, you list the open silences now. That's what Bosun told me: ```\n#{body}\n```"
else "Puh, no sure what happened. I asked Bosun politely, but I got a weird answer. Bosun said '#{body}'."
if not config.slack or response.statusCode is 200
res.reply answer
else
robot.adapter.customMessage {
channel: res.message.room
attachments: [ {
fallback: "#{answer}"
color: 'danger'
title: "Argh. Failed to deal with Bosun's answer."
text: answer
mrkdwn_in: ["text"]
} ]
}
)
robot.on 'bosun.set_silence', (event) ->
unless is_authorized robot, event.user
logger.warning "hubot-bosun: #{event.user} tried to run event 'bosun.set_silence' but was not authorized."
else
logger.info "hubot-bosun: setting silence for alert '#{event.alert}' and tags '#{event.tags}' for #{event.duration} requested by #{event.user.name} via event."
data =
duration: event.duration
alert: event.alert
tags: event.tags
message: event.message
forget: event.forget
confirm: "true"
req = request.post("#{config.host}/api/silence/set", {timeout: config.timeout, json: true, body: data}, (err, response, body) ->
if err
handle_bosun_err null, err, response, body
robot.emit 'bosun.result.set_silence.failed', {
user: event.user
room: event.room
message: "Connection to Bosun failed."
}
else if response and response.statusCode != 200
robot.emit 'bosun.result.set_silence.failed', {
user: event.user
room: event.room
message: "API call failed with status code #{response.statusCode}."
}
else
# ARGH: Bosun does not return the ID of the Silence via API, so we have to figure it out with a second call and some heuristics
req = request.get("#{config.host}/api/silence/get", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
robot.emit 'bosun.result.set_silence.failed', {
user: event.user
room: event.room
message: "Cloud not retrieve actives silences after setting your's; status code #{response.statusCode}."
}
else
silences = JSON.parse body
# map silences from object to array and add unix_time_stamp for time based ordering
silences = ({Id: k, start_as_unix_time: moment(v.Start).valueOf(), silence: v} for k,v of silences)
silences.sort( (a,b) -> b.start_as_unix_time - a.start_as_unix_time )
# This should be the younges alarm
silence_id = silences[0].Id
robot.emit 'bosun.result.set_silence.successful',
user: event.user
room: event.room
duration: event.duration
silence_id: silence_id
)
)
robot.on 'bosun.clear_silence', (event) ->
unless is_authorized robot, event.user
logger.warning "hubot-bosun: #{event.user} tried to run event 'bosun.clear_silence' but was not authorized."
else
logger.info "hubot-bosun: clearing silence with id '#{event.silence_id}' equested by #{event.user.name} via event."
req = request.post("#{config.host}/api/silence/clear?id=#{event.silence_id}", {timeout: config.timeout, json: true, body: {}}, (err, response, body) ->
if err
handle_bosun_err null, err, response, body
robot.emit 'bosun.result.clear_silence.failed', {
user: event.user
room: event.room
silence_id: event.silence_id
message: "Connection to Bosun failed."
}
else if response and response.statusCode != 200
robot.emit 'bosun.result.clear_silence.failed', {
user: event.user
room: event.room
silence_id: event.silence_id
message: "API call failed with status code #{response.statusCode}."
}
else
robot.emit 'bosun.result.clear_silence.successful', event
)
robot.on 'bosun.check_silence', (event) ->
unless is_authorized robot, event.user
logger.warning "hubot-bosun: #{event.user} tried to run event 'bosun.check_silence' but was not authorized."
else
logger.info "hubot-bosun: checking silence requested by #{event.user.name} via event."
req = request.get("#{config.host}/api/silence/get", {timeout: config.timeout}, (err, response, body) ->
if err
handle_bosun_err res, err, response, body
robot.emit 'bosun.result.check_silence.failed', {
user: event.user
room: event.room
message: "Cloud not retrieve actives silences; status code #{response.statusCode}."
}
else
silences = JSON.parse body
silences = (k for k,v of silences)
active = event.silence_id in silences
robot.emit 'bosun.result.check_silence.successful',
user: event.user
room: event.room
silence_id: event.silence_id
active: active
)
robot.error (err, res) ->
robot.logger.error "hubot-bosun: DOES NOT COMPUTE"
if res?
res.reply "DOES NOT COMPUTE: #{err}"
is_authorized = (robot, user) ->
logger.debug "Checking authorization for user '#{user.name}' and role '#{config.role}': role is #{config.role is ""}, auth is #{robot.auth.hasRole(user, config.role)}, combined is #{config.role is "" or robot.auth.hasRole(user, config.role)}."
config.role is "" or robot.auth.hasRole(user, config.role)
warn_unauthorized = (res) ->
user = res.envelope.user.name
message = res.message.text
logger.warning "hubot-bosun: #{user} tried to run '#{message}' but was not authorized."
res.reply "Sorry, you're not allowed to do that. You need the '#{config.role}' role."
handle_bosun_err = (res, err, response, body) ->
logger.error "hubot-bosun: Requst to Bosun timed out." if err? and err.code is 'ETIMEDOUT'
logger.error "hubot-bosun: Connection to Bosun failed." if err? and err.connect is true or err.code is 'ECONNREFUSED'
logger.error "hubot-bosun: Failed to retrieve response from Bosun. Error: '#{err}', reponse: '#{response}', body: '#{body}'"
if res
res.reply "Ouuch. I'm sorry, but I couldn't contact Bosun."
format_date_str = (date_str) ->
if config.relative_time
moment(date_str).fromNow()
else
date_str.replace(/T/, ' ').replace(/\..+/, ' UTC')
|
[
{
"context": "###\n@author alteredq / http://alteredqualia.com/\n\nPort of greggman's T",
"end": 20,
"score": 0.937816858291626,
"start": 12,
"tag": "NAME",
"value": "alteredq"
},
{
"context": "////////////////\n\n# These tables are straight from Paul Bourke's page:\n# http://local.w... | js-src/MarchingCubes.coffee | eccheng/math126 | 0 | ###
@author alteredq / http://alteredqualia.com/
Port of greggman's ThreeD version of marching cubes to Three.js
http://webglsamples.googlecode.com/hg/blob/blob.html
###
THREE.MarchingCubes = (resolution, material, enableUvs, enableColors) ->
THREE.ImmediateRenderObject.call this
@material = material
@enableUvs = (if enableUvs isnt `undefined` then enableUvs else false)
@enableColors = (if enableColors isnt `undefined` then enableColors else false)
# functions have to be object properties
# prototype functions kill performance
# (tested and it was 4x slower !!!)
@init = (resolution) ->
@resolution = resolution
# parameters
@isolation = 80.0
# size of field, 32 is pushing it in Javascript :)
@size = resolution
@size2 = @size * @size
@size3 = @size2 * @size
@halfsize = @size / 2.0
# deltas
@delta = 2.0 / @size
@yd = @size
@zd = @size2
@field = new Float32Array(@size3)
@normal_cache = new Float32Array(@size3 * 3)
# temp buffers used in polygonize
@vlist = new Float32Array(12 * 3)
@nlist = new Float32Array(12 * 3)
@firstDraw = true
# immediate render mode simulator
@maxCount = 4096 # TODO: find the fastest size for this buffer
@count = 0
@hasPositions = false
@hasNormals = false
@hasColors = false
@hasUvs = false
@positionArray = new Float32Array(@maxCount * 3)
@normalArray = new Float32Array(@maxCount * 3)
@uvArray = new Float32Array(@maxCount * 2) if @enableUvs
@colorArray = new Float32Array(@maxCount * 3) if @enableColors
return
#/////////////////////
# Polygonization
#/////////////////////
@lerp = (a, b, t) ->
a + (b - a) * t
@VIntX = (q, pout, nout, offset, isol, x, y, z, valp1, valp2) ->
mu = (isol - valp1) / (valp2 - valp1)
nc = @normal_cache
pout[offset] = x + mu * @delta
pout[offset + 1] = y
pout[offset + 2] = z
nout[offset] = @lerp(nc[q], nc[q + 3], mu)
nout[offset + 1] = @lerp(nc[q + 1], nc[q + 4], mu)
nout[offset + 2] = @lerp(nc[q + 2], nc[q + 5], mu)
return
@VIntY = (q, pout, nout, offset, isol, x, y, z, valp1, valp2) ->
mu = (isol - valp1) / (valp2 - valp1)
nc = @normal_cache
pout[offset] = x
pout[offset + 1] = y + mu * @delta
pout[offset + 2] = z
q2 = q + @yd * 3
nout[offset] = @lerp(nc[q], nc[q2], mu)
nout[offset + 1] = @lerp(nc[q + 1], nc[q2 + 1], mu)
nout[offset + 2] = @lerp(nc[q + 2], nc[q2 + 2], mu)
return
@VIntZ = (q, pout, nout, offset, isol, x, y, z, valp1, valp2) ->
mu = (isol - valp1) / (valp2 - valp1)
nc = @normal_cache
pout[offset] = x
pout[offset + 1] = y
pout[offset + 2] = z + mu * @delta
q2 = q + @zd * 3
nout[offset] = @lerp(nc[q], nc[q2], mu)
nout[offset + 1] = @lerp(nc[q + 1], nc[q2 + 1], mu)
nout[offset + 2] = @lerp(nc[q + 2], nc[q2 + 2], mu)
return
@compNorm = (q) ->
q3 = q * 3
if @normal_cache[q3] is 0.0
@normal_cache[q3] = @field[q - 1] - @field[q + 1]
@normal_cache[q3 + 1] = @field[q - @yd] - @field[q + @yd]
@normal_cache[q3 + 2] = @field[q - @zd] - @field[q + @zd]
return
# Returns total number of triangles. Fills triangles.
# (this is where most of time is spent - it's inner work of O(n3) loop )
@polygonize = (fx, fy, fz, q, isol, renderCallback) ->
# cache indices
q1 = q + 1
qy = q + @yd
qz = q + @zd
q1y = q1 + @yd
q1z = q1 + @zd
qyz = q + @yd + @zd
q1yz = q1 + @yd + @zd
cubeindex = 0
field0 = @field[q]
field1 = @field[q1]
field2 = @field[qy]
field3 = @field[q1y]
field4 = @field[qz]
field5 = @field[q1z]
field6 = @field[qyz]
field7 = @field[q1yz]
cubeindex |= 1 if field0 < isol
cubeindex |= 2 if field1 < isol
cubeindex |= 8 if field2 < isol
cubeindex |= 4 if field3 < isol
cubeindex |= 16 if field4 < isol
cubeindex |= 32 if field5 < isol
cubeindex |= 128 if field6 < isol
cubeindex |= 64 if field7 < isol
# if cube is entirely in/out of the surface - bail, nothing to draw
bits = THREE.edgeTable[cubeindex]
return 0 if bits is 0
d = @delta
fx2 = fx + d
fy2 = fy + d
fz2 = fz + d
# top of the cube
if bits & 1
@compNorm q
@compNorm q1
@VIntX q * 3, @vlist, @nlist, 0, isol, fx, fy, fz, field0, field1
if bits & 2
@compNorm q1
@compNorm q1y
@VIntY q1 * 3, @vlist, @nlist, 3, isol, fx2, fy, fz, field1, field3
if bits & 4
@compNorm qy
@compNorm q1y
@VIntX qy * 3, @vlist, @nlist, 6, isol, fx, fy2, fz, field2, field3
if bits & 8
@compNorm q
@compNorm qy
@VIntY q * 3, @vlist, @nlist, 9, isol, fx, fy, fz, field0, field2
# bottom of the cube
if bits & 16
@compNorm qz
@compNorm q1z
@VIntX qz * 3, @vlist, @nlist, 12, isol, fx, fy, fz2, field4, field5
if bits & 32
@compNorm q1z
@compNorm q1yz
@VIntY q1z * 3, @vlist, @nlist, 15, isol, fx2, fy, fz2, field5, field7
if bits & 64
@compNorm qyz
@compNorm q1yz
@VIntX qyz * 3, @vlist, @nlist, 18, isol, fx, fy2, fz2, field6, field7
if bits & 128
@compNorm qz
@compNorm qyz
@VIntY qz * 3, @vlist, @nlist, 21, isol, fx, fy, fz2, field4, field6
# vertical lines of the cube
if bits & 256
@compNorm q
@compNorm qz
@VIntZ q * 3, @vlist, @nlist, 24, isol, fx, fy, fz, field0, field4
if bits & 512
@compNorm q1
@compNorm q1z
@VIntZ q1 * 3, @vlist, @nlist, 27, isol, fx2, fy, fz, field1, field5
if bits & 1024
@compNorm q1y
@compNorm q1yz
@VIntZ q1y * 3, @vlist, @nlist, 30, isol, fx2, fy2, fz, field3, field7
if bits & 2048
@compNorm qy
@compNorm qyz
@VIntZ qy * 3, @vlist, @nlist, 33, isol, fx, fy2, fz, field2, field6
cubeindex <<= 4 # re-purpose cubeindex into an offset into triTable
o1 = undefined
o2 = undefined
o3 = undefined
numtris = 0
i = 0
# here is where triangles are created
until THREE.triTable[cubeindex + i] is -1
o1 = cubeindex + i
o2 = o1 + 1
o3 = o1 + 2
@posnormtriv @vlist, @nlist, 3 * THREE.triTable[o1], 3 * THREE.triTable[o2], 3 * THREE.triTable[o3], renderCallback
i += 3
numtris++
numtris
#///////////////////////////////////
# Immediate render mode simulator
#///////////////////////////////////
@posnormtriv = (pos, norm, o1, o2, o3, renderCallback) ->
c = @count * 3
# positions
@positionArray[c] = pos[o1]
@positionArray[c + 1] = pos[o1 + 1]
@positionArray[c + 2] = pos[o1 + 2]
@positionArray[c + 3] = pos[o2]
@positionArray[c + 4] = pos[o2 + 1]
@positionArray[c + 5] = pos[o2 + 2]
@positionArray[c + 6] = pos[o3]
@positionArray[c + 7] = pos[o3 + 1]
@positionArray[c + 8] = pos[o3 + 2]
# normals
@normalArray[c] = norm[o1]
@normalArray[c + 1] = norm[o1 + 1]
@normalArray[c + 2] = norm[o1 + 2]
@normalArray[c + 3] = norm[o2]
@normalArray[c + 4] = norm[o2 + 1]
@normalArray[c + 5] = norm[o2 + 2]
@normalArray[c + 6] = norm[o3]
@normalArray[c + 7] = norm[o3 + 1]
@normalArray[c + 8] = norm[o3 + 2]
# uvs
if @enableUvs
d = @count * 2
@uvArray[d] = pos[o1]
@uvArray[d + 1] = pos[o1 + 2]
@uvArray[d + 2] = pos[o2]
@uvArray[d + 3] = pos[o2 + 2]
@uvArray[d + 4] = pos[o3]
@uvArray[d + 5] = pos[o3 + 2]
# colors
if @enableColors
@colorArray[c] = pos[o1]
@colorArray[c + 1] = pos[o1 + 1]
@colorArray[c + 2] = pos[o1 + 2]
@colorArray[c + 3] = pos[o2]
@colorArray[c + 4] = pos[o2 + 1]
@colorArray[c + 5] = pos[o2 + 2]
@colorArray[c + 6] = pos[o3]
@colorArray[c + 7] = pos[o3 + 1]
@colorArray[c + 8] = pos[o3 + 2]
@count += 3
if @count >= @maxCount - 3
@hasPositions = true
@hasNormals = true
@hasUvs = true if @enableUvs
@hasColors = true if @enableColors
renderCallback this
return
@begin = ->
@count = 0
@hasPositions = false
@hasNormals = false
@hasUvs = false
@hasColors = false
return
@end = (renderCallback) ->
return if @count is 0
i = @count * 3
while i < @positionArray.length
@positionArray[i] = 0.0
i++
@hasPositions = true
@hasNormals = true
@hasUvs = true if @enableUvs
@hasColors = true if @enableColors
renderCallback this
return
#///////////////////////////////////
# Metaballs
#///////////////////////////////////
# Adds a reciprocal ball (nice and blobby) that, to be fast, fades to zero after
# a fixed distance, determined by strength and subtract.
@addBall = (ballx, bally, ballz, strength, subtract) ->
# Let's solve the equation to find the radius:
# 1.0 / (0.000001 + radius^2) * strength - subtract = 0
# strength / (radius^2) = subtract
# strength = subtract * radius^2
# radius^2 = strength / subtract
# radius = sqrt(strength / subtract)
radius = @size * Math.sqrt(strength / subtract)
zs = ballz * @size
ys = bally * @size
xs = ballx * @size
min_z = Math.floor(zs - radius)
min_z = 1 if min_z < 1
max_z = Math.floor(zs + radius)
max_z = @size - 1 if max_z > @size - 1
min_y = Math.floor(ys - radius)
min_y = 1 if min_y < 1
max_y = Math.floor(ys + radius)
max_y = @size - 1 if max_y > @size - 1
min_x = Math.floor(xs - radius)
min_x = 1 if min_x < 1
max_x = Math.floor(xs + radius)
max_x = @size - 1 if max_x > @size - 1
# Don't polygonize in the outer layer because normals aren't
# well-defined there.
x = undefined
y = undefined
z = undefined
y_offset = undefined
z_offset = undefined
fx = undefined
fy = undefined
fz = undefined
fz2 = undefined
fy2 = undefined
val = undefined
z = min_z
while z < max_z
z_offset = @size2 * z
fz = z / @size - ballz
fz2 = fz * fz
y = min_y
while y < max_y
y_offset = z_offset + @size * y
fy = y / @size - bally
fy2 = fy * fy
x = min_x
while x < max_x
fx = x / @size - ballx
val = strength / (0.000001 + fx * fx + fy2 + fz2) - subtract
@field[y_offset + x] += val if val > 0.0
x++
y++
z++
return
@addPlaneX = (strength, subtract) ->
x = undefined
y = undefined
z = undefined
xx = undefined
val = undefined
xdiv = undefined
cxy = undefined
# cache attribute lookups
size = @size
yd = @yd
zd = @zd
field = @field
dist = size * Math.sqrt(strength / subtract)
dist = size if dist > size
x = 0
while x < dist
xdiv = x / size
xx = xdiv * xdiv
val = strength / (0.0001 + xx) - subtract
if val > 0.0
y = 0
while y < size
cxy = x + y * yd
z = 0
while z < size
field[zd * z + cxy] += val
z++
y++
x++
return
@addPlaneY = (strength, subtract) ->
x = undefined
y = undefined
z = undefined
yy = undefined
val = undefined
ydiv = undefined
cy = undefined
cxy = undefined
# cache attribute lookups
size = @size
yd = @yd
zd = @zd
field = @field
dist = size * Math.sqrt(strength / subtract)
dist = size if dist > size
y = 0
while y < dist
ydiv = y / size
yy = ydiv * ydiv
val = strength / (0.0001 + yy) - subtract
if val > 0.0
cy = y * yd
x = 0
while x < size
cxy = cy + x
z = 0
while z < size
field[zd * z + cxy] += val
z++
x++
y++
return
@addPlaneZ = (strength, subtract) ->
x = undefined
y = undefined
z = undefined
zz = undefined
val = undefined
zdiv = undefined
cz = undefined
cyz = undefined
# cache attribute lookups
size = @size
yd = @yd
zd = @zd
field = @field
dist = size * Math.sqrt(strength / subtract)
dist = size if dist > size
z = 0
while z < dist
zdiv = z / size
zz = zdiv * zdiv
val = strength / (0.0001 + zz) - subtract
if val > 0.0
cz = zd * z
y = 0
while y < size
cyz = cz + y * yd
x = 0
while x < size
field[cyz + x] += val
x++
y++
z++
return
#///////////////////////////////////
# Updates
#///////////////////////////////////
@reset = ->
i = undefined
# wipe the normal cache
i = 0
while i < @size3
@normal_cache[i * 3] = 0.0
@field[i] = 0.0
i++
return
@render = (renderCallback) ->
@begin()
# Triangulate. Yeah, this is slow.
q = undefined
x = undefined
y = undefined
z = undefined
fx = undefined
fy = undefined
fz = undefined
y_offset = undefined
z_offset = undefined
smin2 = @size - 2
z = 1
while z < smin2
z_offset = @size2 * z
fz = (z - @halfsize) / @halfsize #+ 1
y = 1
while y < smin2
y_offset = z_offset + @size * y
fy = (y - @halfsize) / @halfsize #+ 1
x = 1
while x < smin2
fx = (x - @halfsize) / @halfsize #+ 1
q = y_offset + x
@polygonize fx, fy, fz, q, @isolation, renderCallback
x++
y++
z++
@end renderCallback
return
@generateGeometry = ->
start = 0
geo = new THREE.Geometry()
normals = []
geo_callback = (object) ->
i = undefined
x = undefined
y = undefined
z = undefined
vertex = undefined
normal = undefined
face = undefined
a = undefined
b = undefined
c = undefined
na = undefined
nb = undefined
nc = undefined
nfaces = undefined
i = 0
while i < object.count
a = i * 3
b = a + 1
c = a + 2
x = object.positionArray[a]
y = object.positionArray[b]
z = object.positionArray[c]
vertex = new THREE.Vector3(x, y, z)
x = object.normalArray[a]
y = object.normalArray[b]
z = object.normalArray[c]
normal = new THREE.Vector3(x, y, z)
normal.normalize()
geo.vertices.push vertex
normals.push normal
i++
nfaces = object.count / 3
i = 0
while i < nfaces
a = (start + i) * 3
b = a + 1
c = a + 2
na = normals[a]
nb = normals[b]
nc = normals[c]
face = new THREE.Face3(a, b, c, [
na
nb
nc
])
geo.faces.push face
i++
start += nfaces
object.count = 0
return
@render geo_callback
# console.log( "generated " + geo.faces.length + " triangles" );
geo
@init resolution
return
THREE.MarchingCubes:: = Object.create(THREE.ImmediateRenderObject::)
#///////////////////////////////////
# Marching cubes lookup tables
#///////////////////////////////////
# These tables are straight from Paul Bourke's page:
# http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/
# who in turn got them from Cory Gene Bloyd.
THREE.edgeTable = new Int32Array([
0x0
0x109
0x203
0x30a
0x406
0x50f
0x605
0x70c
0x80c
0x905
0xa0f
0xb06
0xc0a
0xd03
0xe09
0xf00
0x190
0x99
0x393
0x29a
0x596
0x49f
0x795
0x69c
0x99c
0x895
0xb9f
0xa96
0xd9a
0xc93
0xf99
0xe90
0x230
0x339
0x33
0x13a
0x636
0x73f
0x435
0x53c
0xa3c
0xb35
0x83f
0x936
0xe3a
0xf33
0xc39
0xd30
0x3a0
0x2a9
0x1a3
0xaa
0x7a6
0x6af
0x5a5
0x4ac
0xbac
0xaa5
0x9af
0x8a6
0xfaa
0xea3
0xda9
0xca0
0x460
0x569
0x663
0x76a
0x66
0x16f
0x265
0x36c
0xc6c
0xd65
0xe6f
0xf66
0x86a
0x963
0xa69
0xb60
0x5f0
0x4f9
0x7f3
0x6fa
0x1f6
0xff
0x3f5
0x2fc
0xdfc
0xcf5
0xfff
0xef6
0x9fa
0x8f3
0xbf9
0xaf0
0x650
0x759
0x453
0x55a
0x256
0x35f
0x55
0x15c
0xe5c
0xf55
0xc5f
0xd56
0xa5a
0xb53
0x859
0x950
0x7c0
0x6c9
0x5c3
0x4ca
0x3c6
0x2cf
0x1c5
0xcc
0xfcc
0xec5
0xdcf
0xcc6
0xbca
0xac3
0x9c9
0x8c0
0x8c0
0x9c9
0xac3
0xbca
0xcc6
0xdcf
0xec5
0xfcc
0xcc
0x1c5
0x2cf
0x3c6
0x4ca
0x5c3
0x6c9
0x7c0
0x950
0x859
0xb53
0xa5a
0xd56
0xc5f
0xf55
0xe5c
0x15c
0x55
0x35f
0x256
0x55a
0x453
0x759
0x650
0xaf0
0xbf9
0x8f3
0x9fa
0xef6
0xfff
0xcf5
0xdfc
0x2fc
0x3f5
0xff
0x1f6
0x6fa
0x7f3
0x4f9
0x5f0
0xb60
0xa69
0x963
0x86a
0xf66
0xe6f
0xd65
0xc6c
0x36c
0x265
0x16f
0x66
0x76a
0x663
0x569
0x460
0xca0
0xda9
0xea3
0xfaa
0x8a6
0x9af
0xaa5
0xbac
0x4ac
0x5a5
0x6af
0x7a6
0xaa
0x1a3
0x2a9
0x3a0
0xd30
0xc39
0xf33
0xe3a
0x936
0x83f
0xb35
0xa3c
0x53c
0x435
0x73f
0x636
0x13a
0x33
0x339
0x230
0xe90
0xf99
0xc93
0xd9a
0xa96
0xb9f
0x895
0x99c
0x69c
0x795
0x49f
0x596
0x29a
0x393
0x99
0x190
0xf00
0xe09
0xd03
0xc0a
0xb06
0xa0f
0x905
0x80c
0x70c
0x605
0x50f
0x406
0x30a
0x203
0x109
0x0
])
THREE.triTable = new Int32Array([
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
1
9
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
8
3
9
8
1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
2
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
1
2
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
2
10
0
2
9
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
8
3
2
10
8
10
9
8
-1
-1
-1
-1
-1
-1
-1
3
11
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
11
2
8
11
0
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
9
0
2
3
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
11
2
1
9
11
9
8
11
-1
-1
-1
-1
-1
-1
-1
3
10
1
11
10
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
10
1
0
8
10
8
11
10
-1
-1
-1
-1
-1
-1
-1
3
9
0
3
11
9
11
10
9
-1
-1
-1
-1
-1
-1
-1
9
8
10
10
8
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
7
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
3
0
7
3
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
1
9
8
4
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
1
9
4
7
1
7
3
1
-1
-1
-1
-1
-1
-1
-1
1
2
10
8
4
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
4
7
3
0
4
1
2
10
-1
-1
-1
-1
-1
-1
-1
9
2
10
9
0
2
8
4
7
-1
-1
-1
-1
-1
-1
-1
2
10
9
2
9
7
2
7
3
7
9
4
-1
-1
-1
-1
8
4
7
3
11
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
4
7
11
2
4
2
0
4
-1
-1
-1
-1
-1
-1
-1
9
0
1
8
4
7
2
3
11
-1
-1
-1
-1
-1
-1
-1
4
7
11
9
4
11
9
11
2
9
2
1
-1
-1
-1
-1
3
10
1
3
11
10
7
8
4
-1
-1
-1
-1
-1
-1
-1
1
11
10
1
4
11
1
0
4
7
11
4
-1
-1
-1
-1
4
7
8
9
0
11
9
11
10
11
0
3
-1
-1
-1
-1
4
7
11
4
11
9
9
11
10
-1
-1
-1
-1
-1
-1
-1
9
5
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
5
4
0
8
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
5
4
1
5
0
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
5
4
8
3
5
3
1
5
-1
-1
-1
-1
-1
-1
-1
1
2
10
9
5
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
0
8
1
2
10
4
9
5
-1
-1
-1
-1
-1
-1
-1
5
2
10
5
4
2
4
0
2
-1
-1
-1
-1
-1
-1
-1
2
10
5
3
2
5
3
5
4
3
4
8
-1
-1
-1
-1
9
5
4
2
3
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
11
2
0
8
11
4
9
5
-1
-1
-1
-1
-1
-1
-1
0
5
4
0
1
5
2
3
11
-1
-1
-1
-1
-1
-1
-1
2
1
5
2
5
8
2
8
11
4
8
5
-1
-1
-1
-1
10
3
11
10
1
3
9
5
4
-1
-1
-1
-1
-1
-1
-1
4
9
5
0
8
1
8
10
1
8
11
10
-1
-1
-1
-1
5
4
0
5
0
11
5
11
10
11
0
3
-1
-1
-1
-1
5
4
8
5
8
10
10
8
11
-1
-1
-1
-1
-1
-1
-1
9
7
8
5
7
9
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
3
0
9
5
3
5
7
3
-1
-1
-1
-1
-1
-1
-1
0
7
8
0
1
7
1
5
7
-1
-1
-1
-1
-1
-1
-1
1
5
3
3
5
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
7
8
9
5
7
10
1
2
-1
-1
-1
-1
-1
-1
-1
10
1
2
9
5
0
5
3
0
5
7
3
-1
-1
-1
-1
8
0
2
8
2
5
8
5
7
10
5
2
-1
-1
-1
-1
2
10
5
2
5
3
3
5
7
-1
-1
-1
-1
-1
-1
-1
7
9
5
7
8
9
3
11
2
-1
-1
-1
-1
-1
-1
-1
9
5
7
9
7
2
9
2
0
2
7
11
-1
-1
-1
-1
2
3
11
0
1
8
1
7
8
1
5
7
-1
-1
-1
-1
11
2
1
11
1
7
7
1
5
-1
-1
-1
-1
-1
-1
-1
9
5
8
8
5
7
10
1
3
10
3
11
-1
-1
-1
-1
5
7
0
5
0
9
7
11
0
1
0
10
11
10
0
-1
11
10
0
11
0
3
10
5
0
8
0
7
5
7
0
-1
11
10
5
7
11
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
10
6
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
5
10
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
0
1
5
10
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
8
3
1
9
8
5
10
6
-1
-1
-1
-1
-1
-1
-1
1
6
5
2
6
1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
6
5
1
2
6
3
0
8
-1
-1
-1
-1
-1
-1
-1
9
6
5
9
0
6
0
2
6
-1
-1
-1
-1
-1
-1
-1
5
9
8
5
8
2
5
2
6
3
2
8
-1
-1
-1
-1
2
3
11
10
6
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
0
8
11
2
0
10
6
5
-1
-1
-1
-1
-1
-1
-1
0
1
9
2
3
11
5
10
6
-1
-1
-1
-1
-1
-1
-1
5
10
6
1
9
2
9
11
2
9
8
11
-1
-1
-1
-1
6
3
11
6
5
3
5
1
3
-1
-1
-1
-1
-1
-1
-1
0
8
11
0
11
5
0
5
1
5
11
6
-1
-1
-1
-1
3
11
6
0
3
6
0
6
5
0
5
9
-1
-1
-1
-1
6
5
9
6
9
11
11
9
8
-1
-1
-1
-1
-1
-1
-1
5
10
6
4
7
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
3
0
4
7
3
6
5
10
-1
-1
-1
-1
-1
-1
-1
1
9
0
5
10
6
8
4
7
-1
-1
-1
-1
-1
-1
-1
10
6
5
1
9
7
1
7
3
7
9
4
-1
-1
-1
-1
6
1
2
6
5
1
4
7
8
-1
-1
-1
-1
-1
-1
-1
1
2
5
5
2
6
3
0
4
3
4
7
-1
-1
-1
-1
8
4
7
9
0
5
0
6
5
0
2
6
-1
-1
-1
-1
7
3
9
7
9
4
3
2
9
5
9
6
2
6
9
-1
3
11
2
7
8
4
10
6
5
-1
-1
-1
-1
-1
-1
-1
5
10
6
4
7
2
4
2
0
2
7
11
-1
-1
-1
-1
0
1
9
4
7
8
2
3
11
5
10
6
-1
-1
-1
-1
9
2
1
9
11
2
9
4
11
7
11
4
5
10
6
-1
8
4
7
3
11
5
3
5
1
5
11
6
-1
-1
-1
-1
5
1
11
5
11
6
1
0
11
7
11
4
0
4
11
-1
0
5
9
0
6
5
0
3
6
11
6
3
8
4
7
-1
6
5
9
6
9
11
4
7
9
7
11
9
-1
-1
-1
-1
10
4
9
6
4
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
10
6
4
9
10
0
8
3
-1
-1
-1
-1
-1
-1
-1
10
0
1
10
6
0
6
4
0
-1
-1
-1
-1
-1
-1
-1
8
3
1
8
1
6
8
6
4
6
1
10
-1
-1
-1
-1
1
4
9
1
2
4
2
6
4
-1
-1
-1
-1
-1
-1
-1
3
0
8
1
2
9
2
4
9
2
6
4
-1
-1
-1
-1
0
2
4
4
2
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
3
2
8
2
4
4
2
6
-1
-1
-1
-1
-1
-1
-1
10
4
9
10
6
4
11
2
3
-1
-1
-1
-1
-1
-1
-1
0
8
2
2
8
11
4
9
10
4
10
6
-1
-1
-1
-1
3
11
2
0
1
6
0
6
4
6
1
10
-1
-1
-1
-1
6
4
1
6
1
10
4
8
1
2
1
11
8
11
1
-1
9
6
4
9
3
6
9
1
3
11
6
3
-1
-1
-1
-1
8
11
1
8
1
0
11
6
1
9
1
4
6
4
1
-1
3
11
6
3
6
0
0
6
4
-1
-1
-1
-1
-1
-1
-1
6
4
8
11
6
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
10
6
7
8
10
8
9
10
-1
-1
-1
-1
-1
-1
-1
0
7
3
0
10
7
0
9
10
6
7
10
-1
-1
-1
-1
10
6
7
1
10
7
1
7
8
1
8
0
-1
-1
-1
-1
10
6
7
10
7
1
1
7
3
-1
-1
-1
-1
-1
-1
-1
1
2
6
1
6
8
1
8
9
8
6
7
-1
-1
-1
-1
2
6
9
2
9
1
6
7
9
0
9
3
7
3
9
-1
7
8
0
7
0
6
6
0
2
-1
-1
-1
-1
-1
-1
-1
7
3
2
6
7
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
3
11
10
6
8
10
8
9
8
6
7
-1
-1
-1
-1
2
0
7
2
7
11
0
9
7
6
7
10
9
10
7
-1
1
8
0
1
7
8
1
10
7
6
7
10
2
3
11
-1
11
2
1
11
1
7
10
6
1
6
7
1
-1
-1
-1
-1
8
9
6
8
6
7
9
1
6
11
6
3
1
3
6
-1
0
9
1
11
6
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
8
0
7
0
6
3
11
0
11
6
0
-1
-1
-1
-1
7
11
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
6
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
0
8
11
7
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
1
9
11
7
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
1
9
8
3
1
11
7
6
-1
-1
-1
-1
-1
-1
-1
10
1
2
6
11
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
2
10
3
0
8
6
11
7
-1
-1
-1
-1
-1
-1
-1
2
9
0
2
10
9
6
11
7
-1
-1
-1
-1
-1
-1
-1
6
11
7
2
10
3
10
8
3
10
9
8
-1
-1
-1
-1
7
2
3
6
2
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
0
8
7
6
0
6
2
0
-1
-1
-1
-1
-1
-1
-1
2
7
6
2
3
7
0
1
9
-1
-1
-1
-1
-1
-1
-1
1
6
2
1
8
6
1
9
8
8
7
6
-1
-1
-1
-1
10
7
6
10
1
7
1
3
7
-1
-1
-1
-1
-1
-1
-1
10
7
6
1
7
10
1
8
7
1
0
8
-1
-1
-1
-1
0
3
7
0
7
10
0
10
9
6
10
7
-1
-1
-1
-1
7
6
10
7
10
8
8
10
9
-1
-1
-1
-1
-1
-1
-1
6
8
4
11
8
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
6
11
3
0
6
0
4
6
-1
-1
-1
-1
-1
-1
-1
8
6
11
8
4
6
9
0
1
-1
-1
-1
-1
-1
-1
-1
9
4
6
9
6
3
9
3
1
11
3
6
-1
-1
-1
-1
6
8
4
6
11
8
2
10
1
-1
-1
-1
-1
-1
-1
-1
1
2
10
3
0
11
0
6
11
0
4
6
-1
-1
-1
-1
4
11
8
4
6
11
0
2
9
2
10
9
-1
-1
-1
-1
10
9
3
10
3
2
9
4
3
11
3
6
4
6
3
-1
8
2
3
8
4
2
4
6
2
-1
-1
-1
-1
-1
-1
-1
0
4
2
4
6
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
9
0
2
3
4
2
4
6
4
3
8
-1
-1
-1
-1
1
9
4
1
4
2
2
4
6
-1
-1
-1
-1
-1
-1
-1
8
1
3
8
6
1
8
4
6
6
10
1
-1
-1
-1
-1
10
1
0
10
0
6
6
0
4
-1
-1
-1
-1
-1
-1
-1
4
6
3
4
3
8
6
10
3
0
3
9
10
9
3
-1
10
9
4
6
10
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
9
5
7
6
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
4
9
5
11
7
6
-1
-1
-1
-1
-1
-1
-1
5
0
1
5
4
0
7
6
11
-1
-1
-1
-1
-1
-1
-1
11
7
6
8
3
4
3
5
4
3
1
5
-1
-1
-1
-1
9
5
4
10
1
2
7
6
11
-1
-1
-1
-1
-1
-1
-1
6
11
7
1
2
10
0
8
3
4
9
5
-1
-1
-1
-1
7
6
11
5
4
10
4
2
10
4
0
2
-1
-1
-1
-1
3
4
8
3
5
4
3
2
5
10
5
2
11
7
6
-1
7
2
3
7
6
2
5
4
9
-1
-1
-1
-1
-1
-1
-1
9
5
4
0
8
6
0
6
2
6
8
7
-1
-1
-1
-1
3
6
2
3
7
6
1
5
0
5
4
0
-1
-1
-1
-1
6
2
8
6
8
7
2
1
8
4
8
5
1
5
8
-1
9
5
4
10
1
6
1
7
6
1
3
7
-1
-1
-1
-1
1
6
10
1
7
6
1
0
7
8
7
0
9
5
4
-1
4
0
10
4
10
5
0
3
10
6
10
7
3
7
10
-1
7
6
10
7
10
8
5
4
10
4
8
10
-1
-1
-1
-1
6
9
5
6
11
9
11
8
9
-1
-1
-1
-1
-1
-1
-1
3
6
11
0
6
3
0
5
6
0
9
5
-1
-1
-1
-1
0
11
8
0
5
11
0
1
5
5
6
11
-1
-1
-1
-1
6
11
3
6
3
5
5
3
1
-1
-1
-1
-1
-1
-1
-1
1
2
10
9
5
11
9
11
8
11
5
6
-1
-1
-1
-1
0
11
3
0
6
11
0
9
6
5
6
9
1
2
10
-1
11
8
5
11
5
6
8
0
5
10
5
2
0
2
5
-1
6
11
3
6
3
5
2
10
3
10
5
3
-1
-1
-1
-1
5
8
9
5
2
8
5
6
2
3
8
2
-1
-1
-1
-1
9
5
6
9
6
0
0
6
2
-1
-1
-1
-1
-1
-1
-1
1
5
8
1
8
0
5
6
8
3
8
2
6
2
8
-1
1
5
6
2
1
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
3
6
1
6
10
3
8
6
5
6
9
8
9
6
-1
10
1
0
10
0
6
9
5
0
5
6
0
-1
-1
-1
-1
0
3
8
5
6
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
10
5
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
5
10
7
5
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
5
10
11
7
5
8
3
0
-1
-1
-1
-1
-1
-1
-1
5
11
7
5
10
11
1
9
0
-1
-1
-1
-1
-1
-1
-1
10
7
5
10
11
7
9
8
1
8
3
1
-1
-1
-1
-1
11
1
2
11
7
1
7
5
1
-1
-1
-1
-1
-1
-1
-1
0
8
3
1
2
7
1
7
5
7
2
11
-1
-1
-1
-1
9
7
5
9
2
7
9
0
2
2
11
7
-1
-1
-1
-1
7
5
2
7
2
11
5
9
2
3
2
8
9
8
2
-1
2
5
10
2
3
5
3
7
5
-1
-1
-1
-1
-1
-1
-1
8
2
0
8
5
2
8
7
5
10
2
5
-1
-1
-1
-1
9
0
1
5
10
3
5
3
7
3
10
2
-1
-1
-1
-1
9
8
2
9
2
1
8
7
2
10
2
5
7
5
2
-1
1
3
5
3
7
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
7
0
7
1
1
7
5
-1
-1
-1
-1
-1
-1
-1
9
0
3
9
3
5
5
3
7
-1
-1
-1
-1
-1
-1
-1
9
8
7
5
9
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
5
8
4
5
10
8
10
11
8
-1
-1
-1
-1
-1
-1
-1
5
0
4
5
11
0
5
10
11
11
3
0
-1
-1
-1
-1
0
1
9
8
4
10
8
10
11
10
4
5
-1
-1
-1
-1
10
11
4
10
4
5
11
3
4
9
4
1
3
1
4
-1
2
5
1
2
8
5
2
11
8
4
5
8
-1
-1
-1
-1
0
4
11
0
11
3
4
5
11
2
11
1
5
1
11
-1
0
2
5
0
5
9
2
11
5
4
5
8
11
8
5
-1
9
4
5
2
11
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
5
10
3
5
2
3
4
5
3
8
4
-1
-1
-1
-1
5
10
2
5
2
4
4
2
0
-1
-1
-1
-1
-1
-1
-1
3
10
2
3
5
10
3
8
5
4
5
8
0
1
9
-1
5
10
2
5
2
4
1
9
2
9
4
2
-1
-1
-1
-1
8
4
5
8
5
3
3
5
1
-1
-1
-1
-1
-1
-1
-1
0
4
5
1
0
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
4
5
8
5
3
9
0
5
0
3
5
-1
-1
-1
-1
9
4
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
11
7
4
9
11
9
10
11
-1
-1
-1
-1
-1
-1
-1
0
8
3
4
9
7
9
11
7
9
10
11
-1
-1
-1
-1
1
10
11
1
11
4
1
4
0
7
4
11
-1
-1
-1
-1
3
1
4
3
4
8
1
10
4
7
4
11
10
11
4
-1
4
11
7
9
11
4
9
2
11
9
1
2
-1
-1
-1
-1
9
7
4
9
11
7
9
1
11
2
11
1
0
8
3
-1
11
7
4
11
4
2
2
4
0
-1
-1
-1
-1
-1
-1
-1
11
7
4
11
4
2
8
3
4
3
2
4
-1
-1
-1
-1
2
9
10
2
7
9
2
3
7
7
4
9
-1
-1
-1
-1
9
10
7
9
7
4
10
2
7
8
7
0
2
0
7
-1
3
7
10
3
10
2
7
4
10
1
10
0
4
0
10
-1
1
10
2
8
7
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
9
1
4
1
7
7
1
3
-1
-1
-1
-1
-1
-1
-1
4
9
1
4
1
7
0
8
1
8
7
1
-1
-1
-1
-1
4
0
3
7
4
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
8
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
10
8
10
11
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
0
9
3
9
11
11
9
10
-1
-1
-1
-1
-1
-1
-1
0
1
10
0
10
8
8
10
11
-1
-1
-1
-1
-1
-1
-1
3
1
10
11
3
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
2
11
1
11
9
9
11
8
-1
-1
-1
-1
-1
-1
-1
3
0
9
3
9
11
1
2
9
2
11
9
-1
-1
-1
-1
0
2
11
8
0
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
2
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
3
8
2
8
10
10
8
9
-1
-1
-1
-1
-1
-1
-1
9
10
2
0
9
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
3
8
2
8
10
0
1
8
1
10
8
-1
-1
-1
-1
1
10
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
3
8
9
1
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
9
1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
3
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
])
| 164273 | ###
@author <NAME> / http://alteredqualia.com/
Port of greggman's ThreeD version of marching cubes to Three.js
http://webglsamples.googlecode.com/hg/blob/blob.html
###
THREE.MarchingCubes = (resolution, material, enableUvs, enableColors) ->
THREE.ImmediateRenderObject.call this
@material = material
@enableUvs = (if enableUvs isnt `undefined` then enableUvs else false)
@enableColors = (if enableColors isnt `undefined` then enableColors else false)
# functions have to be object properties
# prototype functions kill performance
# (tested and it was 4x slower !!!)
@init = (resolution) ->
@resolution = resolution
# parameters
@isolation = 80.0
# size of field, 32 is pushing it in Javascript :)
@size = resolution
@size2 = @size * @size
@size3 = @size2 * @size
@halfsize = @size / 2.0
# deltas
@delta = 2.0 / @size
@yd = @size
@zd = @size2
@field = new Float32Array(@size3)
@normal_cache = new Float32Array(@size3 * 3)
# temp buffers used in polygonize
@vlist = new Float32Array(12 * 3)
@nlist = new Float32Array(12 * 3)
@firstDraw = true
# immediate render mode simulator
@maxCount = 4096 # TODO: find the fastest size for this buffer
@count = 0
@hasPositions = false
@hasNormals = false
@hasColors = false
@hasUvs = false
@positionArray = new Float32Array(@maxCount * 3)
@normalArray = new Float32Array(@maxCount * 3)
@uvArray = new Float32Array(@maxCount * 2) if @enableUvs
@colorArray = new Float32Array(@maxCount * 3) if @enableColors
return
#/////////////////////
# Polygonization
#/////////////////////
@lerp = (a, b, t) ->
a + (b - a) * t
@VIntX = (q, pout, nout, offset, isol, x, y, z, valp1, valp2) ->
mu = (isol - valp1) / (valp2 - valp1)
nc = @normal_cache
pout[offset] = x + mu * @delta
pout[offset + 1] = y
pout[offset + 2] = z
nout[offset] = @lerp(nc[q], nc[q + 3], mu)
nout[offset + 1] = @lerp(nc[q + 1], nc[q + 4], mu)
nout[offset + 2] = @lerp(nc[q + 2], nc[q + 5], mu)
return
@VIntY = (q, pout, nout, offset, isol, x, y, z, valp1, valp2) ->
mu = (isol - valp1) / (valp2 - valp1)
nc = @normal_cache
pout[offset] = x
pout[offset + 1] = y + mu * @delta
pout[offset + 2] = z
q2 = q + @yd * 3
nout[offset] = @lerp(nc[q], nc[q2], mu)
nout[offset + 1] = @lerp(nc[q + 1], nc[q2 + 1], mu)
nout[offset + 2] = @lerp(nc[q + 2], nc[q2 + 2], mu)
return
@VIntZ = (q, pout, nout, offset, isol, x, y, z, valp1, valp2) ->
mu = (isol - valp1) / (valp2 - valp1)
nc = @normal_cache
pout[offset] = x
pout[offset + 1] = y
pout[offset + 2] = z + mu * @delta
q2 = q + @zd * 3
nout[offset] = @lerp(nc[q], nc[q2], mu)
nout[offset + 1] = @lerp(nc[q + 1], nc[q2 + 1], mu)
nout[offset + 2] = @lerp(nc[q + 2], nc[q2 + 2], mu)
return
@compNorm = (q) ->
q3 = q * 3
if @normal_cache[q3] is 0.0
@normal_cache[q3] = @field[q - 1] - @field[q + 1]
@normal_cache[q3 + 1] = @field[q - @yd] - @field[q + @yd]
@normal_cache[q3 + 2] = @field[q - @zd] - @field[q + @zd]
return
# Returns total number of triangles. Fills triangles.
# (this is where most of time is spent - it's inner work of O(n3) loop )
@polygonize = (fx, fy, fz, q, isol, renderCallback) ->
# cache indices
q1 = q + 1
qy = q + @yd
qz = q + @zd
q1y = q1 + @yd
q1z = q1 + @zd
qyz = q + @yd + @zd
q1yz = q1 + @yd + @zd
cubeindex = 0
field0 = @field[q]
field1 = @field[q1]
field2 = @field[qy]
field3 = @field[q1y]
field4 = @field[qz]
field5 = @field[q1z]
field6 = @field[qyz]
field7 = @field[q1yz]
cubeindex |= 1 if field0 < isol
cubeindex |= 2 if field1 < isol
cubeindex |= 8 if field2 < isol
cubeindex |= 4 if field3 < isol
cubeindex |= 16 if field4 < isol
cubeindex |= 32 if field5 < isol
cubeindex |= 128 if field6 < isol
cubeindex |= 64 if field7 < isol
# if cube is entirely in/out of the surface - bail, nothing to draw
bits = THREE.edgeTable[cubeindex]
return 0 if bits is 0
d = @delta
fx2 = fx + d
fy2 = fy + d
fz2 = fz + d
# top of the cube
if bits & 1
@compNorm q
@compNorm q1
@VIntX q * 3, @vlist, @nlist, 0, isol, fx, fy, fz, field0, field1
if bits & 2
@compNorm q1
@compNorm q1y
@VIntY q1 * 3, @vlist, @nlist, 3, isol, fx2, fy, fz, field1, field3
if bits & 4
@compNorm qy
@compNorm q1y
@VIntX qy * 3, @vlist, @nlist, 6, isol, fx, fy2, fz, field2, field3
if bits & 8
@compNorm q
@compNorm qy
@VIntY q * 3, @vlist, @nlist, 9, isol, fx, fy, fz, field0, field2
# bottom of the cube
if bits & 16
@compNorm qz
@compNorm q1z
@VIntX qz * 3, @vlist, @nlist, 12, isol, fx, fy, fz2, field4, field5
if bits & 32
@compNorm q1z
@compNorm q1yz
@VIntY q1z * 3, @vlist, @nlist, 15, isol, fx2, fy, fz2, field5, field7
if bits & 64
@compNorm qyz
@compNorm q1yz
@VIntX qyz * 3, @vlist, @nlist, 18, isol, fx, fy2, fz2, field6, field7
if bits & 128
@compNorm qz
@compNorm qyz
@VIntY qz * 3, @vlist, @nlist, 21, isol, fx, fy, fz2, field4, field6
# vertical lines of the cube
if bits & 256
@compNorm q
@compNorm qz
@VIntZ q * 3, @vlist, @nlist, 24, isol, fx, fy, fz, field0, field4
if bits & 512
@compNorm q1
@compNorm q1z
@VIntZ q1 * 3, @vlist, @nlist, 27, isol, fx2, fy, fz, field1, field5
if bits & 1024
@compNorm q1y
@compNorm q1yz
@VIntZ q1y * 3, @vlist, @nlist, 30, isol, fx2, fy2, fz, field3, field7
if bits & 2048
@compNorm qy
@compNorm qyz
@VIntZ qy * 3, @vlist, @nlist, 33, isol, fx, fy2, fz, field2, field6
cubeindex <<= 4 # re-purpose cubeindex into an offset into triTable
o1 = undefined
o2 = undefined
o3 = undefined
numtris = 0
i = 0
# here is where triangles are created
until THREE.triTable[cubeindex + i] is -1
o1 = cubeindex + i
o2 = o1 + 1
o3 = o1 + 2
@posnormtriv @vlist, @nlist, 3 * THREE.triTable[o1], 3 * THREE.triTable[o2], 3 * THREE.triTable[o3], renderCallback
i += 3
numtris++
numtris
#///////////////////////////////////
# Immediate render mode simulator
#///////////////////////////////////
@posnormtriv = (pos, norm, o1, o2, o3, renderCallback) ->
c = @count * 3
# positions
@positionArray[c] = pos[o1]
@positionArray[c + 1] = pos[o1 + 1]
@positionArray[c + 2] = pos[o1 + 2]
@positionArray[c + 3] = pos[o2]
@positionArray[c + 4] = pos[o2 + 1]
@positionArray[c + 5] = pos[o2 + 2]
@positionArray[c + 6] = pos[o3]
@positionArray[c + 7] = pos[o3 + 1]
@positionArray[c + 8] = pos[o3 + 2]
# normals
@normalArray[c] = norm[o1]
@normalArray[c + 1] = norm[o1 + 1]
@normalArray[c + 2] = norm[o1 + 2]
@normalArray[c + 3] = norm[o2]
@normalArray[c + 4] = norm[o2 + 1]
@normalArray[c + 5] = norm[o2 + 2]
@normalArray[c + 6] = norm[o3]
@normalArray[c + 7] = norm[o3 + 1]
@normalArray[c + 8] = norm[o3 + 2]
# uvs
if @enableUvs
d = @count * 2
@uvArray[d] = pos[o1]
@uvArray[d + 1] = pos[o1 + 2]
@uvArray[d + 2] = pos[o2]
@uvArray[d + 3] = pos[o2 + 2]
@uvArray[d + 4] = pos[o3]
@uvArray[d + 5] = pos[o3 + 2]
# colors
if @enableColors
@colorArray[c] = pos[o1]
@colorArray[c + 1] = pos[o1 + 1]
@colorArray[c + 2] = pos[o1 + 2]
@colorArray[c + 3] = pos[o2]
@colorArray[c + 4] = pos[o2 + 1]
@colorArray[c + 5] = pos[o2 + 2]
@colorArray[c + 6] = pos[o3]
@colorArray[c + 7] = pos[o3 + 1]
@colorArray[c + 8] = pos[o3 + 2]
@count += 3
if @count >= @maxCount - 3
@hasPositions = true
@hasNormals = true
@hasUvs = true if @enableUvs
@hasColors = true if @enableColors
renderCallback this
return
@begin = ->
@count = 0
@hasPositions = false
@hasNormals = false
@hasUvs = false
@hasColors = false
return
@end = (renderCallback) ->
return if @count is 0
i = @count * 3
while i < @positionArray.length
@positionArray[i] = 0.0
i++
@hasPositions = true
@hasNormals = true
@hasUvs = true if @enableUvs
@hasColors = true if @enableColors
renderCallback this
return
#///////////////////////////////////
# Metaballs
#///////////////////////////////////
# Adds a reciprocal ball (nice and blobby) that, to be fast, fades to zero after
# a fixed distance, determined by strength and subtract.
@addBall = (ballx, bally, ballz, strength, subtract) ->
# Let's solve the equation to find the radius:
# 1.0 / (0.000001 + radius^2) * strength - subtract = 0
# strength / (radius^2) = subtract
# strength = subtract * radius^2
# radius^2 = strength / subtract
# radius = sqrt(strength / subtract)
radius = @size * Math.sqrt(strength / subtract)
zs = ballz * @size
ys = bally * @size
xs = ballx * @size
min_z = Math.floor(zs - radius)
min_z = 1 if min_z < 1
max_z = Math.floor(zs + radius)
max_z = @size - 1 if max_z > @size - 1
min_y = Math.floor(ys - radius)
min_y = 1 if min_y < 1
max_y = Math.floor(ys + radius)
max_y = @size - 1 if max_y > @size - 1
min_x = Math.floor(xs - radius)
min_x = 1 if min_x < 1
max_x = Math.floor(xs + radius)
max_x = @size - 1 if max_x > @size - 1
# Don't polygonize in the outer layer because normals aren't
# well-defined there.
x = undefined
y = undefined
z = undefined
y_offset = undefined
z_offset = undefined
fx = undefined
fy = undefined
fz = undefined
fz2 = undefined
fy2 = undefined
val = undefined
z = min_z
while z < max_z
z_offset = @size2 * z
fz = z / @size - ballz
fz2 = fz * fz
y = min_y
while y < max_y
y_offset = z_offset + @size * y
fy = y / @size - bally
fy2 = fy * fy
x = min_x
while x < max_x
fx = x / @size - ballx
val = strength / (0.000001 + fx * fx + fy2 + fz2) - subtract
@field[y_offset + x] += val if val > 0.0
x++
y++
z++
return
@addPlaneX = (strength, subtract) ->
x = undefined
y = undefined
z = undefined
xx = undefined
val = undefined
xdiv = undefined
cxy = undefined
# cache attribute lookups
size = @size
yd = @yd
zd = @zd
field = @field
dist = size * Math.sqrt(strength / subtract)
dist = size if dist > size
x = 0
while x < dist
xdiv = x / size
xx = xdiv * xdiv
val = strength / (0.0001 + xx) - subtract
if val > 0.0
y = 0
while y < size
cxy = x + y * yd
z = 0
while z < size
field[zd * z + cxy] += val
z++
y++
x++
return
@addPlaneY = (strength, subtract) ->
x = undefined
y = undefined
z = undefined
yy = undefined
val = undefined
ydiv = undefined
cy = undefined
cxy = undefined
# cache attribute lookups
size = @size
yd = @yd
zd = @zd
field = @field
dist = size * Math.sqrt(strength / subtract)
dist = size if dist > size
y = 0
while y < dist
ydiv = y / size
yy = ydiv * ydiv
val = strength / (0.0001 + yy) - subtract
if val > 0.0
cy = y * yd
x = 0
while x < size
cxy = cy + x
z = 0
while z < size
field[zd * z + cxy] += val
z++
x++
y++
return
@addPlaneZ = (strength, subtract) ->
x = undefined
y = undefined
z = undefined
zz = undefined
val = undefined
zdiv = undefined
cz = undefined
cyz = undefined
# cache attribute lookups
size = @size
yd = @yd
zd = @zd
field = @field
dist = size * Math.sqrt(strength / subtract)
dist = size if dist > size
z = 0
while z < dist
zdiv = z / size
zz = zdiv * zdiv
val = strength / (0.0001 + zz) - subtract
if val > 0.0
cz = zd * z
y = 0
while y < size
cyz = cz + y * yd
x = 0
while x < size
field[cyz + x] += val
x++
y++
z++
return
#///////////////////////////////////
# Updates
#///////////////////////////////////
@reset = ->
i = undefined
# wipe the normal cache
i = 0
while i < @size3
@normal_cache[i * 3] = 0.0
@field[i] = 0.0
i++
return
@render = (renderCallback) ->
@begin()
# Triangulate. Yeah, this is slow.
q = undefined
x = undefined
y = undefined
z = undefined
fx = undefined
fy = undefined
fz = undefined
y_offset = undefined
z_offset = undefined
smin2 = @size - 2
z = 1
while z < smin2
z_offset = @size2 * z
fz = (z - @halfsize) / @halfsize #+ 1
y = 1
while y < smin2
y_offset = z_offset + @size * y
fy = (y - @halfsize) / @halfsize #+ 1
x = 1
while x < smin2
fx = (x - @halfsize) / @halfsize #+ 1
q = y_offset + x
@polygonize fx, fy, fz, q, @isolation, renderCallback
x++
y++
z++
@end renderCallback
return
@generateGeometry = ->
start = 0
geo = new THREE.Geometry()
normals = []
geo_callback = (object) ->
i = undefined
x = undefined
y = undefined
z = undefined
vertex = undefined
normal = undefined
face = undefined
a = undefined
b = undefined
c = undefined
na = undefined
nb = undefined
nc = undefined
nfaces = undefined
i = 0
while i < object.count
a = i * 3
b = a + 1
c = a + 2
x = object.positionArray[a]
y = object.positionArray[b]
z = object.positionArray[c]
vertex = new THREE.Vector3(x, y, z)
x = object.normalArray[a]
y = object.normalArray[b]
z = object.normalArray[c]
normal = new THREE.Vector3(x, y, z)
normal.normalize()
geo.vertices.push vertex
normals.push normal
i++
nfaces = object.count / 3
i = 0
while i < nfaces
a = (start + i) * 3
b = a + 1
c = a + 2
na = normals[a]
nb = normals[b]
nc = normals[c]
face = new THREE.Face3(a, b, c, [
na
nb
nc
])
geo.faces.push face
i++
start += nfaces
object.count = 0
return
@render geo_callback
# console.log( "generated " + geo.faces.length + " triangles" );
geo
@init resolution
return
THREE.MarchingCubes:: = Object.create(THREE.ImmediateRenderObject::)
#///////////////////////////////////
# Marching cubes lookup tables
#///////////////////////////////////
# These tables are straight from <NAME>ourke's page:
# http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/
# who in turn got them from <NAME>.
THREE.edgeTable = new Int32Array([
0x0
0x109
0x203
0x30a
0x406
0x50f
0x605
0x70c
0x80c
0x905
0xa0f
0xb06
0xc0a
0xd03
0xe09
0xf00
0x190
0x99
0x393
0x29a
0x596
0x49f
0x795
0x69c
0x99c
0x895
0xb9f
0xa96
0xd9a
0xc93
0xf99
0xe90
0x230
0x339
0x33
0x13a
0x636
0x73f
0x435
0x53c
0xa3c
0xb35
0x83f
0x936
0xe3a
0xf33
0xc39
0xd30
0x3a0
0x2a9
0x1a3
0xaa
0x7a6
0x6af
0x5a5
0x4ac
0xbac
0xaa5
0x9af
0x8a6
0xfaa
0xea3
0xda9
0xca0
0x460
0x569
0x663
0x76a
0x66
0x16f
0x265
0x36c
0xc6c
0xd65
0xe6f
0xf66
0x86a
0x963
0xa69
0xb60
0x5f0
0x4f9
0x7f3
0x6fa
0x1f6
0xff
0x3f5
0x2fc
0xdfc
0xcf5
0xfff
0xef6
0x9fa
0x8f3
0xbf9
0xaf0
0x650
0x759
0x453
0x55a
0x256
0x35f
0x55
0x15c
0xe5c
0xf55
0xc5f
0xd56
0xa5a
0xb53
0x859
0x950
0x7c0
0x6c9
0x5c3
0x4ca
0x3c6
0x2cf
0x1c5
0xcc
0xfcc
0xec5
0xdcf
0xcc6
0xbca
0xac3
0x9c9
0x8c0
0x8c0
0x9c9
0xac3
0xbca
0xcc6
0xdcf
0xec5
0xfcc
0xcc
0x1c5
0x2cf
0x3c6
0x4ca
0x5c3
0x6c9
0x7c0
0x950
0x859
0xb53
0xa5a
0xd56
0xc5f
0xf55
0xe5c
0x15c
0x55
0x35f
0x256
0x55a
0x453
0x759
0x650
0xaf0
0xbf9
0x8f3
0x9fa
0xef6
0xfff
0xcf5
0xdfc
0x2fc
0x3f5
0xff
0x1f6
0x6fa
0x7f3
0x4f9
0x5f0
0xb60
0xa69
0x963
0x86a
0xf66
0xe6f
0xd65
0xc6c
0x36c
0x265
0x16f
0x66
0x76a
0x663
0x569
0x460
0xca0
0xda9
0xea3
0xfaa
0x8a6
0x9af
0xaa5
0xbac
0x4ac
0x5a5
0x6af
0x7a6
0xaa
0x1a3
0x2a9
0x3a0
0xd30
0xc39
0xf33
0xe3a
0x936
0x83f
0xb35
0xa3c
0x53c
0x435
0x73f
0x636
0x13a
0x33
0x339
0x230
0xe90
0xf99
0xc93
0xd9a
0xa96
0xb9f
0x895
0x99c
0x69c
0x795
0x49f
0x596
0x29a
0x393
0x99
0x190
0xf00
0xe09
0xd03
0xc0a
0xb06
0xa0f
0x905
0x80c
0x70c
0x605
0x50f
0x406
0x30a
0x203
0x109
0x0
])
THREE.triTable = new Int32Array([
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
1
9
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
8
3
9
8
1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
2
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
1
2
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
2
10
0
2
9
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
8
3
2
10
8
10
9
8
-1
-1
-1
-1
-1
-1
-1
3
11
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
11
2
8
11
0
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
9
0
2
3
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
11
2
1
9
11
9
8
11
-1
-1
-1
-1
-1
-1
-1
3
10
1
11
10
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
10
1
0
8
10
8
11
10
-1
-1
-1
-1
-1
-1
-1
3
9
0
3
11
9
11
10
9
-1
-1
-1
-1
-1
-1
-1
9
8
10
10
8
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
7
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
3
0
7
3
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
1
9
8
4
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
1
9
4
7
1
7
3
1
-1
-1
-1
-1
-1
-1
-1
1
2
10
8
4
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
4
7
3
0
4
1
2
10
-1
-1
-1
-1
-1
-1
-1
9
2
10
9
0
2
8
4
7
-1
-1
-1
-1
-1
-1
-1
2
10
9
2
9
7
2
7
3
7
9
4
-1
-1
-1
-1
8
4
7
3
11
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
4
7
11
2
4
2
0
4
-1
-1
-1
-1
-1
-1
-1
9
0
1
8
4
7
2
3
11
-1
-1
-1
-1
-1
-1
-1
4
7
11
9
4
11
9
11
2
9
2
1
-1
-1
-1
-1
3
10
1
3
11
10
7
8
4
-1
-1
-1
-1
-1
-1
-1
1
11
10
1
4
11
1
0
4
7
11
4
-1
-1
-1
-1
4
7
8
9
0
11
9
11
10
11
0
3
-1
-1
-1
-1
4
7
11
4
11
9
9
11
10
-1
-1
-1
-1
-1
-1
-1
9
5
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
5
4
0
8
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
5
4
1
5
0
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
5
4
8
3
5
3
1
5
-1
-1
-1
-1
-1
-1
-1
1
2
10
9
5
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
0
8
1
2
10
4
9
5
-1
-1
-1
-1
-1
-1
-1
5
2
10
5
4
2
4
0
2
-1
-1
-1
-1
-1
-1
-1
2
10
5
3
2
5
3
5
4
3
4
8
-1
-1
-1
-1
9
5
4
2
3
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
11
2
0
8
11
4
9
5
-1
-1
-1
-1
-1
-1
-1
0
5
4
0
1
5
2
3
11
-1
-1
-1
-1
-1
-1
-1
2
1
5
2
5
8
2
8
11
4
8
5
-1
-1
-1
-1
10
3
11
10
1
3
9
5
4
-1
-1
-1
-1
-1
-1
-1
4
9
5
0
8
1
8
10
1
8
11
10
-1
-1
-1
-1
5
4
0
5
0
11
5
11
10
11
0
3
-1
-1
-1
-1
5
4
8
5
8
10
10
8
11
-1
-1
-1
-1
-1
-1
-1
9
7
8
5
7
9
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
3
0
9
5
3
5
7
3
-1
-1
-1
-1
-1
-1
-1
0
7
8
0
1
7
1
5
7
-1
-1
-1
-1
-1
-1
-1
1
5
3
3
5
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
7
8
9
5
7
10
1
2
-1
-1
-1
-1
-1
-1
-1
10
1
2
9
5
0
5
3
0
5
7
3
-1
-1
-1
-1
8
0
2
8
2
5
8
5
7
10
5
2
-1
-1
-1
-1
2
10
5
2
5
3
3
5
7
-1
-1
-1
-1
-1
-1
-1
7
9
5
7
8
9
3
11
2
-1
-1
-1
-1
-1
-1
-1
9
5
7
9
7
2
9
2
0
2
7
11
-1
-1
-1
-1
2
3
11
0
1
8
1
7
8
1
5
7
-1
-1
-1
-1
11
2
1
11
1
7
7
1
5
-1
-1
-1
-1
-1
-1
-1
9
5
8
8
5
7
10
1
3
10
3
11
-1
-1
-1
-1
5
7
0
5
0
9
7
11
0
1
0
10
11
10
0
-1
11
10
0
11
0
3
10
5
0
8
0
7
5
7
0
-1
11
10
5
7
11
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
10
6
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
5
10
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
0
1
5
10
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
8
3
1
9
8
5
10
6
-1
-1
-1
-1
-1
-1
-1
1
6
5
2
6
1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
6
5
1
2
6
3
0
8
-1
-1
-1
-1
-1
-1
-1
9
6
5
9
0
6
0
2
6
-1
-1
-1
-1
-1
-1
-1
5
9
8
5
8
2
5
2
6
3
2
8
-1
-1
-1
-1
2
3
11
10
6
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
0
8
11
2
0
10
6
5
-1
-1
-1
-1
-1
-1
-1
0
1
9
2
3
11
5
10
6
-1
-1
-1
-1
-1
-1
-1
5
10
6
1
9
2
9
11
2
9
8
11
-1
-1
-1
-1
6
3
11
6
5
3
5
1
3
-1
-1
-1
-1
-1
-1
-1
0
8
11
0
11
5
0
5
1
5
11
6
-1
-1
-1
-1
3
11
6
0
3
6
0
6
5
0
5
9
-1
-1
-1
-1
6
5
9
6
9
11
11
9
8
-1
-1
-1
-1
-1
-1
-1
5
10
6
4
7
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
3
0
4
7
3
6
5
10
-1
-1
-1
-1
-1
-1
-1
1
9
0
5
10
6
8
4
7
-1
-1
-1
-1
-1
-1
-1
10
6
5
1
9
7
1
7
3
7
9
4
-1
-1
-1
-1
6
1
2
6
5
1
4
7
8
-1
-1
-1
-1
-1
-1
-1
1
2
5
5
2
6
3
0
4
3
4
7
-1
-1
-1
-1
8
4
7
9
0
5
0
6
5
0
2
6
-1
-1
-1
-1
7
3
9
7
9
4
3
2
9
5
9
6
2
6
9
-1
3
11
2
7
8
4
10
6
5
-1
-1
-1
-1
-1
-1
-1
5
10
6
4
7
2
4
2
0
2
7
11
-1
-1
-1
-1
0
1
9
4
7
8
2
3
11
5
10
6
-1
-1
-1
-1
9
2
1
9
11
2
9
4
11
7
11
4
5
10
6
-1
8
4
7
3
11
5
3
5
1
5
11
6
-1
-1
-1
-1
5
1
11
5
11
6
1
0
11
7
11
4
0
4
11
-1
0
5
9
0
6
5
0
3
6
11
6
3
8
4
7
-1
6
5
9
6
9
11
4
7
9
7
11
9
-1
-1
-1
-1
10
4
9
6
4
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
10
6
4
9
10
0
8
3
-1
-1
-1
-1
-1
-1
-1
10
0
1
10
6
0
6
4
0
-1
-1
-1
-1
-1
-1
-1
8
3
1
8
1
6
8
6
4
6
1
10
-1
-1
-1
-1
1
4
9
1
2
4
2
6
4
-1
-1
-1
-1
-1
-1
-1
3
0
8
1
2
9
2
4
9
2
6
4
-1
-1
-1
-1
0
2
4
4
2
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
3
2
8
2
4
4
2
6
-1
-1
-1
-1
-1
-1
-1
10
4
9
10
6
4
11
2
3
-1
-1
-1
-1
-1
-1
-1
0
8
2
2
8
11
4
9
10
4
10
6
-1
-1
-1
-1
3
11
2
0
1
6
0
6
4
6
1
10
-1
-1
-1
-1
6
4
1
6
1
10
4
8
1
2
1
11
8
11
1
-1
9
6
4
9
3
6
9
1
3
11
6
3
-1
-1
-1
-1
8
11
1
8
1
0
11
6
1
9
1
4
6
4
1
-1
3
11
6
3
6
0
0
6
4
-1
-1
-1
-1
-1
-1
-1
6
4
8
11
6
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
10
6
7
8
10
8
9
10
-1
-1
-1
-1
-1
-1
-1
0
7
3
0
10
7
0
9
10
6
7
10
-1
-1
-1
-1
10
6
7
1
10
7
1
7
8
1
8
0
-1
-1
-1
-1
10
6
7
10
7
1
1
7
3
-1
-1
-1
-1
-1
-1
-1
1
2
6
1
6
8
1
8
9
8
6
7
-1
-1
-1
-1
2
6
9
2
9
1
6
7
9
0
9
3
7
3
9
-1
7
8
0
7
0
6
6
0
2
-1
-1
-1
-1
-1
-1
-1
7
3
2
6
7
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
3
11
10
6
8
10
8
9
8
6
7
-1
-1
-1
-1
2
0
7
2
7
11
0
9
7
6
7
10
9
10
7
-1
1
8
0
1
7
8
1
10
7
6
7
10
2
3
11
-1
11
2
1
11
1
7
10
6
1
6
7
1
-1
-1
-1
-1
8
9
6
8
6
7
9
1
6
11
6
3
1
3
6
-1
0
9
1
11
6
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
8
0
7
0
6
3
11
0
11
6
0
-1
-1
-1
-1
7
11
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
6
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
0
8
11
7
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
1
9
11
7
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
1
9
8
3
1
11
7
6
-1
-1
-1
-1
-1
-1
-1
10
1
2
6
11
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
2
10
3
0
8
6
11
7
-1
-1
-1
-1
-1
-1
-1
2
9
0
2
10
9
6
11
7
-1
-1
-1
-1
-1
-1
-1
6
11
7
2
10
3
10
8
3
10
9
8
-1
-1
-1
-1
7
2
3
6
2
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
0
8
7
6
0
6
2
0
-1
-1
-1
-1
-1
-1
-1
2
7
6
2
3
7
0
1
9
-1
-1
-1
-1
-1
-1
-1
1
6
2
1
8
6
1
9
8
8
7
6
-1
-1
-1
-1
10
7
6
10
1
7
1
3
7
-1
-1
-1
-1
-1
-1
-1
10
7
6
1
7
10
1
8
7
1
0
8
-1
-1
-1
-1
0
3
7
0
7
10
0
10
9
6
10
7
-1
-1
-1
-1
7
6
10
7
10
8
8
10
9
-1
-1
-1
-1
-1
-1
-1
6
8
4
11
8
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
6
11
3
0
6
0
4
6
-1
-1
-1
-1
-1
-1
-1
8
6
11
8
4
6
9
0
1
-1
-1
-1
-1
-1
-1
-1
9
4
6
9
6
3
9
3
1
11
3
6
-1
-1
-1
-1
6
8
4
6
11
8
2
10
1
-1
-1
-1
-1
-1
-1
-1
1
2
10
3
0
11
0
6
11
0
4
6
-1
-1
-1
-1
4
11
8
4
6
11
0
2
9
2
10
9
-1
-1
-1
-1
10
9
3
10
3
2
9
4
3
11
3
6
4
6
3
-1
8
2
3
8
4
2
4
6
2
-1
-1
-1
-1
-1
-1
-1
0
4
2
4
6
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
9
0
2
3
4
2
4
6
4
3
8
-1
-1
-1
-1
1
9
4
1
4
2
2
4
6
-1
-1
-1
-1
-1
-1
-1
8
1
3
8
6
1
8
4
6
6
10
1
-1
-1
-1
-1
10
1
0
10
0
6
6
0
4
-1
-1
-1
-1
-1
-1
-1
4
6
3
4
3
8
6
10
3
0
3
9
10
9
3
-1
10
9
4
6
10
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
9
5
7
6
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
4
9
5
11
7
6
-1
-1
-1
-1
-1
-1
-1
5
0
1
5
4
0
7
6
11
-1
-1
-1
-1
-1
-1
-1
11
7
6
8
3
4
3
5
4
3
1
5
-1
-1
-1
-1
9
5
4
10
1
2
7
6
11
-1
-1
-1
-1
-1
-1
-1
6
11
7
1
2
10
0
8
3
4
9
5
-1
-1
-1
-1
7
6
11
5
4
10
4
2
10
4
0
2
-1
-1
-1
-1
3
4
8
3
5
4
3
2
5
10
5
2
11
7
6
-1
7
2
3
7
6
2
5
4
9
-1
-1
-1
-1
-1
-1
-1
9
5
4
0
8
6
0
6
2
6
8
7
-1
-1
-1
-1
3
6
2
3
7
6
1
5
0
5
4
0
-1
-1
-1
-1
6
2
8
6
8
7
2
1
8
4
8
5
1
5
8
-1
9
5
4
10
1
6
1
7
6
1
3
7
-1
-1
-1
-1
1
6
10
1
7
6
1
0
7
8
7
0
9
5
4
-1
4
0
10
4
10
5
0
3
10
6
10
7
3
7
10
-1
7
6
10
7
10
8
5
4
10
4
8
10
-1
-1
-1
-1
6
9
5
6
11
9
11
8
9
-1
-1
-1
-1
-1
-1
-1
3
6
11
0
6
3
0
5
6
0
9
5
-1
-1
-1
-1
0
11
8
0
5
11
0
1
5
5
6
11
-1
-1
-1
-1
6
11
3
6
3
5
5
3
1
-1
-1
-1
-1
-1
-1
-1
1
2
10
9
5
11
9
11
8
11
5
6
-1
-1
-1
-1
0
11
3
0
6
11
0
9
6
5
6
9
1
2
10
-1
11
8
5
11
5
6
8
0
5
10
5
2
0
2
5
-1
6
11
3
6
3
5
2
10
3
10
5
3
-1
-1
-1
-1
5
8
9
5
2
8
5
6
2
3
8
2
-1
-1
-1
-1
9
5
6
9
6
0
0
6
2
-1
-1
-1
-1
-1
-1
-1
1
5
8
1
8
0
5
6
8
3
8
2
6
2
8
-1
1
5
6
2
1
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
3
6
1
6
10
3
8
6
5
6
9
8
9
6
-1
10
1
0
10
0
6
9
5
0
5
6
0
-1
-1
-1
-1
0
3
8
5
6
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
10
5
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
5
10
7
5
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
5
10
11
7
5
8
3
0
-1
-1
-1
-1
-1
-1
-1
5
11
7
5
10
11
1
9
0
-1
-1
-1
-1
-1
-1
-1
10
7
5
10
11
7
9
8
1
8
3
1
-1
-1
-1
-1
11
1
2
11
7
1
7
5
1
-1
-1
-1
-1
-1
-1
-1
0
8
3
1
2
7
1
7
5
7
2
11
-1
-1
-1
-1
9
7
5
9
2
7
9
0
2
2
11
7
-1
-1
-1
-1
7
5
2
7
2
11
5
9
2
3
2
8
9
8
2
-1
2
5
10
2
3
5
3
7
5
-1
-1
-1
-1
-1
-1
-1
8
2
0
8
5
2
8
7
5
10
2
5
-1
-1
-1
-1
9
0
1
5
10
3
5
3
7
3
10
2
-1
-1
-1
-1
9
8
2
9
2
1
8
7
2
10
2
5
7
5
2
-1
1
3
5
3
7
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
7
0
7
1
1
7
5
-1
-1
-1
-1
-1
-1
-1
9
0
3
9
3
5
5
3
7
-1
-1
-1
-1
-1
-1
-1
9
8
7
5
9
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
5
8
4
5
10
8
10
11
8
-1
-1
-1
-1
-1
-1
-1
5
0
4
5
11
0
5
10
11
11
3
0
-1
-1
-1
-1
0
1
9
8
4
10
8
10
11
10
4
5
-1
-1
-1
-1
10
11
4
10
4
5
11
3
4
9
4
1
3
1
4
-1
2
5
1
2
8
5
2
11
8
4
5
8
-1
-1
-1
-1
0
4
11
0
11
3
4
5
11
2
11
1
5
1
11
-1
0
2
5
0
5
9
2
11
5
4
5
8
11
8
5
-1
9
4
5
2
11
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
5
10
3
5
2
3
4
5
3
8
4
-1
-1
-1
-1
5
10
2
5
2
4
4
2
0
-1
-1
-1
-1
-1
-1
-1
3
10
2
3
5
10
3
8
5
4
5
8
0
1
9
-1
5
10
2
5
2
4
1
9
2
9
4
2
-1
-1
-1
-1
8
4
5
8
5
3
3
5
1
-1
-1
-1
-1
-1
-1
-1
0
4
5
1
0
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
4
5
8
5
3
9
0
5
0
3
5
-1
-1
-1
-1
9
4
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
11
7
4
9
11
9
10
11
-1
-1
-1
-1
-1
-1
-1
0
8
3
4
9
7
9
11
7
9
10
11
-1
-1
-1
-1
1
10
11
1
11
4
1
4
0
7
4
11
-1
-1
-1
-1
3
1
4
3
4
8
1
10
4
7
4
11
10
11
4
-1
4
11
7
9
11
4
9
2
11
9
1
2
-1
-1
-1
-1
9
7
4
9
11
7
9
1
11
2
11
1
0
8
3
-1
11
7
4
11
4
2
2
4
0
-1
-1
-1
-1
-1
-1
-1
11
7
4
11
4
2
8
3
4
3
2
4
-1
-1
-1
-1
2
9
10
2
7
9
2
3
7
7
4
9
-1
-1
-1
-1
9
10
7
9
7
4
10
2
7
8
7
0
2
0
7
-1
3
7
10
3
10
2
7
4
10
1
10
0
4
0
10
-1
1
10
2
8
7
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
9
1
4
1
7
7
1
3
-1
-1
-1
-1
-1
-1
-1
4
9
1
4
1
7
0
8
1
8
7
1
-1
-1
-1
-1
4
0
3
7
4
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
8
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
10
8
10
11
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
0
9
3
9
11
11
9
10
-1
-1
-1
-1
-1
-1
-1
0
1
10
0
10
8
8
10
11
-1
-1
-1
-1
-1
-1
-1
3
1
10
11
3
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
2
11
1
11
9
9
11
8
-1
-1
-1
-1
-1
-1
-1
3
0
9
3
9
11
1
2
9
2
11
9
-1
-1
-1
-1
0
2
11
8
0
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
2
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
3
8
2
8
10
10
8
9
-1
-1
-1
-1
-1
-1
-1
9
10
2
0
9
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
3
8
2
8
10
0
1
8
1
10
8
-1
-1
-1
-1
1
10
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
3
8
9
1
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
9
1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
3
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
])
| true | ###
@author PI:NAME:<NAME>END_PI / http://alteredqualia.com/
Port of greggman's ThreeD version of marching cubes to Three.js
http://webglsamples.googlecode.com/hg/blob/blob.html
###
THREE.MarchingCubes = (resolution, material, enableUvs, enableColors) ->
THREE.ImmediateRenderObject.call this
@material = material
@enableUvs = (if enableUvs isnt `undefined` then enableUvs else false)
@enableColors = (if enableColors isnt `undefined` then enableColors else false)
# functions have to be object properties
# prototype functions kill performance
# (tested and it was 4x slower !!!)
@init = (resolution) ->
@resolution = resolution
# parameters
@isolation = 80.0
# size of field, 32 is pushing it in Javascript :)
@size = resolution
@size2 = @size * @size
@size3 = @size2 * @size
@halfsize = @size / 2.0
# deltas
@delta = 2.0 / @size
@yd = @size
@zd = @size2
@field = new Float32Array(@size3)
@normal_cache = new Float32Array(@size3 * 3)
# temp buffers used in polygonize
@vlist = new Float32Array(12 * 3)
@nlist = new Float32Array(12 * 3)
@firstDraw = true
# immediate render mode simulator
@maxCount = 4096 # TODO: find the fastest size for this buffer
@count = 0
@hasPositions = false
@hasNormals = false
@hasColors = false
@hasUvs = false
@positionArray = new Float32Array(@maxCount * 3)
@normalArray = new Float32Array(@maxCount * 3)
@uvArray = new Float32Array(@maxCount * 2) if @enableUvs
@colorArray = new Float32Array(@maxCount * 3) if @enableColors
return
#/////////////////////
# Polygonization
#/////////////////////
@lerp = (a, b, t) ->
a + (b - a) * t
@VIntX = (q, pout, nout, offset, isol, x, y, z, valp1, valp2) ->
mu = (isol - valp1) / (valp2 - valp1)
nc = @normal_cache
pout[offset] = x + mu * @delta
pout[offset + 1] = y
pout[offset + 2] = z
nout[offset] = @lerp(nc[q], nc[q + 3], mu)
nout[offset + 1] = @lerp(nc[q + 1], nc[q + 4], mu)
nout[offset + 2] = @lerp(nc[q + 2], nc[q + 5], mu)
return
@VIntY = (q, pout, nout, offset, isol, x, y, z, valp1, valp2) ->
mu = (isol - valp1) / (valp2 - valp1)
nc = @normal_cache
pout[offset] = x
pout[offset + 1] = y + mu * @delta
pout[offset + 2] = z
q2 = q + @yd * 3
nout[offset] = @lerp(nc[q], nc[q2], mu)
nout[offset + 1] = @lerp(nc[q + 1], nc[q2 + 1], mu)
nout[offset + 2] = @lerp(nc[q + 2], nc[q2 + 2], mu)
return
@VIntZ = (q, pout, nout, offset, isol, x, y, z, valp1, valp2) ->
mu = (isol - valp1) / (valp2 - valp1)
nc = @normal_cache
pout[offset] = x
pout[offset + 1] = y
pout[offset + 2] = z + mu * @delta
q2 = q + @zd * 3
nout[offset] = @lerp(nc[q], nc[q2], mu)
nout[offset + 1] = @lerp(nc[q + 1], nc[q2 + 1], mu)
nout[offset + 2] = @lerp(nc[q + 2], nc[q2 + 2], mu)
return
@compNorm = (q) ->
q3 = q * 3
if @normal_cache[q3] is 0.0
@normal_cache[q3] = @field[q - 1] - @field[q + 1]
@normal_cache[q3 + 1] = @field[q - @yd] - @field[q + @yd]
@normal_cache[q3 + 2] = @field[q - @zd] - @field[q + @zd]
return
# Returns total number of triangles. Fills triangles.
# (this is where most of time is spent - it's inner work of O(n3) loop )
@polygonize = (fx, fy, fz, q, isol, renderCallback) ->
# cache indices
q1 = q + 1
qy = q + @yd
qz = q + @zd
q1y = q1 + @yd
q1z = q1 + @zd
qyz = q + @yd + @zd
q1yz = q1 + @yd + @zd
cubeindex = 0
field0 = @field[q]
field1 = @field[q1]
field2 = @field[qy]
field3 = @field[q1y]
field4 = @field[qz]
field5 = @field[q1z]
field6 = @field[qyz]
field7 = @field[q1yz]
cubeindex |= 1 if field0 < isol
cubeindex |= 2 if field1 < isol
cubeindex |= 8 if field2 < isol
cubeindex |= 4 if field3 < isol
cubeindex |= 16 if field4 < isol
cubeindex |= 32 if field5 < isol
cubeindex |= 128 if field6 < isol
cubeindex |= 64 if field7 < isol
# if cube is entirely in/out of the surface - bail, nothing to draw
bits = THREE.edgeTable[cubeindex]
return 0 if bits is 0
d = @delta
fx2 = fx + d
fy2 = fy + d
fz2 = fz + d
# top of the cube
if bits & 1
@compNorm q
@compNorm q1
@VIntX q * 3, @vlist, @nlist, 0, isol, fx, fy, fz, field0, field1
if bits & 2
@compNorm q1
@compNorm q1y
@VIntY q1 * 3, @vlist, @nlist, 3, isol, fx2, fy, fz, field1, field3
if bits & 4
@compNorm qy
@compNorm q1y
@VIntX qy * 3, @vlist, @nlist, 6, isol, fx, fy2, fz, field2, field3
if bits & 8
@compNorm q
@compNorm qy
@VIntY q * 3, @vlist, @nlist, 9, isol, fx, fy, fz, field0, field2
# bottom of the cube
if bits & 16
@compNorm qz
@compNorm q1z
@VIntX qz * 3, @vlist, @nlist, 12, isol, fx, fy, fz2, field4, field5
if bits & 32
@compNorm q1z
@compNorm q1yz
@VIntY q1z * 3, @vlist, @nlist, 15, isol, fx2, fy, fz2, field5, field7
if bits & 64
@compNorm qyz
@compNorm q1yz
@VIntX qyz * 3, @vlist, @nlist, 18, isol, fx, fy2, fz2, field6, field7
if bits & 128
@compNorm qz
@compNorm qyz
@VIntY qz * 3, @vlist, @nlist, 21, isol, fx, fy, fz2, field4, field6
# vertical lines of the cube
if bits & 256
@compNorm q
@compNorm qz
@VIntZ q * 3, @vlist, @nlist, 24, isol, fx, fy, fz, field0, field4
if bits & 512
@compNorm q1
@compNorm q1z
@VIntZ q1 * 3, @vlist, @nlist, 27, isol, fx2, fy, fz, field1, field5
if bits & 1024
@compNorm q1y
@compNorm q1yz
@VIntZ q1y * 3, @vlist, @nlist, 30, isol, fx2, fy2, fz, field3, field7
if bits & 2048
@compNorm qy
@compNorm qyz
@VIntZ qy * 3, @vlist, @nlist, 33, isol, fx, fy2, fz, field2, field6
cubeindex <<= 4 # re-purpose cubeindex into an offset into triTable
o1 = undefined
o2 = undefined
o3 = undefined
numtris = 0
i = 0
# here is where triangles are created
until THREE.triTable[cubeindex + i] is -1
o1 = cubeindex + i
o2 = o1 + 1
o3 = o1 + 2
@posnormtriv @vlist, @nlist, 3 * THREE.triTable[o1], 3 * THREE.triTable[o2], 3 * THREE.triTable[o3], renderCallback
i += 3
numtris++
numtris
#///////////////////////////////////
# Immediate render mode simulator
#///////////////////////////////////
@posnormtriv = (pos, norm, o1, o2, o3, renderCallback) ->
c = @count * 3
# positions
@positionArray[c] = pos[o1]
@positionArray[c + 1] = pos[o1 + 1]
@positionArray[c + 2] = pos[o1 + 2]
@positionArray[c + 3] = pos[o2]
@positionArray[c + 4] = pos[o2 + 1]
@positionArray[c + 5] = pos[o2 + 2]
@positionArray[c + 6] = pos[o3]
@positionArray[c + 7] = pos[o3 + 1]
@positionArray[c + 8] = pos[o3 + 2]
# normals
@normalArray[c] = norm[o1]
@normalArray[c + 1] = norm[o1 + 1]
@normalArray[c + 2] = norm[o1 + 2]
@normalArray[c + 3] = norm[o2]
@normalArray[c + 4] = norm[o2 + 1]
@normalArray[c + 5] = norm[o2 + 2]
@normalArray[c + 6] = norm[o3]
@normalArray[c + 7] = norm[o3 + 1]
@normalArray[c + 8] = norm[o3 + 2]
# uvs
if @enableUvs
d = @count * 2
@uvArray[d] = pos[o1]
@uvArray[d + 1] = pos[o1 + 2]
@uvArray[d + 2] = pos[o2]
@uvArray[d + 3] = pos[o2 + 2]
@uvArray[d + 4] = pos[o3]
@uvArray[d + 5] = pos[o3 + 2]
# colors
if @enableColors
@colorArray[c] = pos[o1]
@colorArray[c + 1] = pos[o1 + 1]
@colorArray[c + 2] = pos[o1 + 2]
@colorArray[c + 3] = pos[o2]
@colorArray[c + 4] = pos[o2 + 1]
@colorArray[c + 5] = pos[o2 + 2]
@colorArray[c + 6] = pos[o3]
@colorArray[c + 7] = pos[o3 + 1]
@colorArray[c + 8] = pos[o3 + 2]
@count += 3
if @count >= @maxCount - 3
@hasPositions = true
@hasNormals = true
@hasUvs = true if @enableUvs
@hasColors = true if @enableColors
renderCallback this
return
@begin = ->
@count = 0
@hasPositions = false
@hasNormals = false
@hasUvs = false
@hasColors = false
return
@end = (renderCallback) ->
return if @count is 0
i = @count * 3
while i < @positionArray.length
@positionArray[i] = 0.0
i++
@hasPositions = true
@hasNormals = true
@hasUvs = true if @enableUvs
@hasColors = true if @enableColors
renderCallback this
return
#///////////////////////////////////
# Metaballs
#///////////////////////////////////
# Adds a reciprocal ball (nice and blobby) that, to be fast, fades to zero after
# a fixed distance, determined by strength and subtract.
@addBall = (ballx, bally, ballz, strength, subtract) ->
# Let's solve the equation to find the radius:
# 1.0 / (0.000001 + radius^2) * strength - subtract = 0
# strength / (radius^2) = subtract
# strength = subtract * radius^2
# radius^2 = strength / subtract
# radius = sqrt(strength / subtract)
radius = @size * Math.sqrt(strength / subtract)
zs = ballz * @size
ys = bally * @size
xs = ballx * @size
min_z = Math.floor(zs - radius)
min_z = 1 if min_z < 1
max_z = Math.floor(zs + radius)
max_z = @size - 1 if max_z > @size - 1
min_y = Math.floor(ys - radius)
min_y = 1 if min_y < 1
max_y = Math.floor(ys + radius)
max_y = @size - 1 if max_y > @size - 1
min_x = Math.floor(xs - radius)
min_x = 1 if min_x < 1
max_x = Math.floor(xs + radius)
max_x = @size - 1 if max_x > @size - 1
# Don't polygonize in the outer layer because normals aren't
# well-defined there.
x = undefined
y = undefined
z = undefined
y_offset = undefined
z_offset = undefined
fx = undefined
fy = undefined
fz = undefined
fz2 = undefined
fy2 = undefined
val = undefined
z = min_z
while z < max_z
z_offset = @size2 * z
fz = z / @size - ballz
fz2 = fz * fz
y = min_y
while y < max_y
y_offset = z_offset + @size * y
fy = y / @size - bally
fy2 = fy * fy
x = min_x
while x < max_x
fx = x / @size - ballx
val = strength / (0.000001 + fx * fx + fy2 + fz2) - subtract
@field[y_offset + x] += val if val > 0.0
x++
y++
z++
return
@addPlaneX = (strength, subtract) ->
x = undefined
y = undefined
z = undefined
xx = undefined
val = undefined
xdiv = undefined
cxy = undefined
# cache attribute lookups
size = @size
yd = @yd
zd = @zd
field = @field
dist = size * Math.sqrt(strength / subtract)
dist = size if dist > size
x = 0
while x < dist
xdiv = x / size
xx = xdiv * xdiv
val = strength / (0.0001 + xx) - subtract
if val > 0.0
y = 0
while y < size
cxy = x + y * yd
z = 0
while z < size
field[zd * z + cxy] += val
z++
y++
x++
return
@addPlaneY = (strength, subtract) ->
x = undefined
y = undefined
z = undefined
yy = undefined
val = undefined
ydiv = undefined
cy = undefined
cxy = undefined
# cache attribute lookups
size = @size
yd = @yd
zd = @zd
field = @field
dist = size * Math.sqrt(strength / subtract)
dist = size if dist > size
y = 0
while y < dist
ydiv = y / size
yy = ydiv * ydiv
val = strength / (0.0001 + yy) - subtract
if val > 0.0
cy = y * yd
x = 0
while x < size
cxy = cy + x
z = 0
while z < size
field[zd * z + cxy] += val
z++
x++
y++
return
@addPlaneZ = (strength, subtract) ->
x = undefined
y = undefined
z = undefined
zz = undefined
val = undefined
zdiv = undefined
cz = undefined
cyz = undefined
# cache attribute lookups
size = @size
yd = @yd
zd = @zd
field = @field
dist = size * Math.sqrt(strength / subtract)
dist = size if dist > size
z = 0
while z < dist
zdiv = z / size
zz = zdiv * zdiv
val = strength / (0.0001 + zz) - subtract
if val > 0.0
cz = zd * z
y = 0
while y < size
cyz = cz + y * yd
x = 0
while x < size
field[cyz + x] += val
x++
y++
z++
return
#///////////////////////////////////
# Updates
#///////////////////////////////////
@reset = ->
i = undefined
# wipe the normal cache
i = 0
while i < @size3
@normal_cache[i * 3] = 0.0
@field[i] = 0.0
i++
return
@render = (renderCallback) ->
@begin()
# Triangulate. Yeah, this is slow.
q = undefined
x = undefined
y = undefined
z = undefined
fx = undefined
fy = undefined
fz = undefined
y_offset = undefined
z_offset = undefined
smin2 = @size - 2
z = 1
while z < smin2
z_offset = @size2 * z
fz = (z - @halfsize) / @halfsize #+ 1
y = 1
while y < smin2
y_offset = z_offset + @size * y
fy = (y - @halfsize) / @halfsize #+ 1
x = 1
while x < smin2
fx = (x - @halfsize) / @halfsize #+ 1
q = y_offset + x
@polygonize fx, fy, fz, q, @isolation, renderCallback
x++
y++
z++
@end renderCallback
return
@generateGeometry = ->
start = 0
geo = new THREE.Geometry()
normals = []
geo_callback = (object) ->
i = undefined
x = undefined
y = undefined
z = undefined
vertex = undefined
normal = undefined
face = undefined
a = undefined
b = undefined
c = undefined
na = undefined
nb = undefined
nc = undefined
nfaces = undefined
i = 0
while i < object.count
a = i * 3
b = a + 1
c = a + 2
x = object.positionArray[a]
y = object.positionArray[b]
z = object.positionArray[c]
vertex = new THREE.Vector3(x, y, z)
x = object.normalArray[a]
y = object.normalArray[b]
z = object.normalArray[c]
normal = new THREE.Vector3(x, y, z)
normal.normalize()
geo.vertices.push vertex
normals.push normal
i++
nfaces = object.count / 3
i = 0
while i < nfaces
a = (start + i) * 3
b = a + 1
c = a + 2
na = normals[a]
nb = normals[b]
nc = normals[c]
face = new THREE.Face3(a, b, c, [
na
nb
nc
])
geo.faces.push face
i++
start += nfaces
object.count = 0
return
@render geo_callback
# console.log( "generated " + geo.faces.length + " triangles" );
geo
@init resolution
return
THREE.MarchingCubes:: = Object.create(THREE.ImmediateRenderObject::)
#///////////////////////////////////
# Marching cubes lookup tables
#///////////////////////////////////
# These tables are straight from PI:NAME:<NAME>END_PIourke's page:
# http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/
# who in turn got them from PI:NAME:<NAME>END_PI.
THREE.edgeTable = new Int32Array([
0x0
0x109
0x203
0x30a
0x406
0x50f
0x605
0x70c
0x80c
0x905
0xa0f
0xb06
0xc0a
0xd03
0xe09
0xf00
0x190
0x99
0x393
0x29a
0x596
0x49f
0x795
0x69c
0x99c
0x895
0xb9f
0xa96
0xd9a
0xc93
0xf99
0xe90
0x230
0x339
0x33
0x13a
0x636
0x73f
0x435
0x53c
0xa3c
0xb35
0x83f
0x936
0xe3a
0xf33
0xc39
0xd30
0x3a0
0x2a9
0x1a3
0xaa
0x7a6
0x6af
0x5a5
0x4ac
0xbac
0xaa5
0x9af
0x8a6
0xfaa
0xea3
0xda9
0xca0
0x460
0x569
0x663
0x76a
0x66
0x16f
0x265
0x36c
0xc6c
0xd65
0xe6f
0xf66
0x86a
0x963
0xa69
0xb60
0x5f0
0x4f9
0x7f3
0x6fa
0x1f6
0xff
0x3f5
0x2fc
0xdfc
0xcf5
0xfff
0xef6
0x9fa
0x8f3
0xbf9
0xaf0
0x650
0x759
0x453
0x55a
0x256
0x35f
0x55
0x15c
0xe5c
0xf55
0xc5f
0xd56
0xa5a
0xb53
0x859
0x950
0x7c0
0x6c9
0x5c3
0x4ca
0x3c6
0x2cf
0x1c5
0xcc
0xfcc
0xec5
0xdcf
0xcc6
0xbca
0xac3
0x9c9
0x8c0
0x8c0
0x9c9
0xac3
0xbca
0xcc6
0xdcf
0xec5
0xfcc
0xcc
0x1c5
0x2cf
0x3c6
0x4ca
0x5c3
0x6c9
0x7c0
0x950
0x859
0xb53
0xa5a
0xd56
0xc5f
0xf55
0xe5c
0x15c
0x55
0x35f
0x256
0x55a
0x453
0x759
0x650
0xaf0
0xbf9
0x8f3
0x9fa
0xef6
0xfff
0xcf5
0xdfc
0x2fc
0x3f5
0xff
0x1f6
0x6fa
0x7f3
0x4f9
0x5f0
0xb60
0xa69
0x963
0x86a
0xf66
0xe6f
0xd65
0xc6c
0x36c
0x265
0x16f
0x66
0x76a
0x663
0x569
0x460
0xca0
0xda9
0xea3
0xfaa
0x8a6
0x9af
0xaa5
0xbac
0x4ac
0x5a5
0x6af
0x7a6
0xaa
0x1a3
0x2a9
0x3a0
0xd30
0xc39
0xf33
0xe3a
0x936
0x83f
0xb35
0xa3c
0x53c
0x435
0x73f
0x636
0x13a
0x33
0x339
0x230
0xe90
0xf99
0xc93
0xd9a
0xa96
0xb9f
0x895
0x99c
0x69c
0x795
0x49f
0x596
0x29a
0x393
0x99
0x190
0xf00
0xe09
0xd03
0xc0a
0xb06
0xa0f
0x905
0x80c
0x70c
0x605
0x50f
0x406
0x30a
0x203
0x109
0x0
])
THREE.triTable = new Int32Array([
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
1
9
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
8
3
9
8
1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
2
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
1
2
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
2
10
0
2
9
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
8
3
2
10
8
10
9
8
-1
-1
-1
-1
-1
-1
-1
3
11
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
11
2
8
11
0
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
9
0
2
3
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
11
2
1
9
11
9
8
11
-1
-1
-1
-1
-1
-1
-1
3
10
1
11
10
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
10
1
0
8
10
8
11
10
-1
-1
-1
-1
-1
-1
-1
3
9
0
3
11
9
11
10
9
-1
-1
-1
-1
-1
-1
-1
9
8
10
10
8
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
7
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
3
0
7
3
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
1
9
8
4
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
1
9
4
7
1
7
3
1
-1
-1
-1
-1
-1
-1
-1
1
2
10
8
4
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
4
7
3
0
4
1
2
10
-1
-1
-1
-1
-1
-1
-1
9
2
10
9
0
2
8
4
7
-1
-1
-1
-1
-1
-1
-1
2
10
9
2
9
7
2
7
3
7
9
4
-1
-1
-1
-1
8
4
7
3
11
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
4
7
11
2
4
2
0
4
-1
-1
-1
-1
-1
-1
-1
9
0
1
8
4
7
2
3
11
-1
-1
-1
-1
-1
-1
-1
4
7
11
9
4
11
9
11
2
9
2
1
-1
-1
-1
-1
3
10
1
3
11
10
7
8
4
-1
-1
-1
-1
-1
-1
-1
1
11
10
1
4
11
1
0
4
7
11
4
-1
-1
-1
-1
4
7
8
9
0
11
9
11
10
11
0
3
-1
-1
-1
-1
4
7
11
4
11
9
9
11
10
-1
-1
-1
-1
-1
-1
-1
9
5
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
5
4
0
8
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
5
4
1
5
0
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
5
4
8
3
5
3
1
5
-1
-1
-1
-1
-1
-1
-1
1
2
10
9
5
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
0
8
1
2
10
4
9
5
-1
-1
-1
-1
-1
-1
-1
5
2
10
5
4
2
4
0
2
-1
-1
-1
-1
-1
-1
-1
2
10
5
3
2
5
3
5
4
3
4
8
-1
-1
-1
-1
9
5
4
2
3
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
11
2
0
8
11
4
9
5
-1
-1
-1
-1
-1
-1
-1
0
5
4
0
1
5
2
3
11
-1
-1
-1
-1
-1
-1
-1
2
1
5
2
5
8
2
8
11
4
8
5
-1
-1
-1
-1
10
3
11
10
1
3
9
5
4
-1
-1
-1
-1
-1
-1
-1
4
9
5
0
8
1
8
10
1
8
11
10
-1
-1
-1
-1
5
4
0
5
0
11
5
11
10
11
0
3
-1
-1
-1
-1
5
4
8
5
8
10
10
8
11
-1
-1
-1
-1
-1
-1
-1
9
7
8
5
7
9
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
3
0
9
5
3
5
7
3
-1
-1
-1
-1
-1
-1
-1
0
7
8
0
1
7
1
5
7
-1
-1
-1
-1
-1
-1
-1
1
5
3
3
5
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
7
8
9
5
7
10
1
2
-1
-1
-1
-1
-1
-1
-1
10
1
2
9
5
0
5
3
0
5
7
3
-1
-1
-1
-1
8
0
2
8
2
5
8
5
7
10
5
2
-1
-1
-1
-1
2
10
5
2
5
3
3
5
7
-1
-1
-1
-1
-1
-1
-1
7
9
5
7
8
9
3
11
2
-1
-1
-1
-1
-1
-1
-1
9
5
7
9
7
2
9
2
0
2
7
11
-1
-1
-1
-1
2
3
11
0
1
8
1
7
8
1
5
7
-1
-1
-1
-1
11
2
1
11
1
7
7
1
5
-1
-1
-1
-1
-1
-1
-1
9
5
8
8
5
7
10
1
3
10
3
11
-1
-1
-1
-1
5
7
0
5
0
9
7
11
0
1
0
10
11
10
0
-1
11
10
0
11
0
3
10
5
0
8
0
7
5
7
0
-1
11
10
5
7
11
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
10
6
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
5
10
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
0
1
5
10
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
8
3
1
9
8
5
10
6
-1
-1
-1
-1
-1
-1
-1
1
6
5
2
6
1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
6
5
1
2
6
3
0
8
-1
-1
-1
-1
-1
-1
-1
9
6
5
9
0
6
0
2
6
-1
-1
-1
-1
-1
-1
-1
5
9
8
5
8
2
5
2
6
3
2
8
-1
-1
-1
-1
2
3
11
10
6
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
0
8
11
2
0
10
6
5
-1
-1
-1
-1
-1
-1
-1
0
1
9
2
3
11
5
10
6
-1
-1
-1
-1
-1
-1
-1
5
10
6
1
9
2
9
11
2
9
8
11
-1
-1
-1
-1
6
3
11
6
5
3
5
1
3
-1
-1
-1
-1
-1
-1
-1
0
8
11
0
11
5
0
5
1
5
11
6
-1
-1
-1
-1
3
11
6
0
3
6
0
6
5
0
5
9
-1
-1
-1
-1
6
5
9
6
9
11
11
9
8
-1
-1
-1
-1
-1
-1
-1
5
10
6
4
7
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
3
0
4
7
3
6
5
10
-1
-1
-1
-1
-1
-1
-1
1
9
0
5
10
6
8
4
7
-1
-1
-1
-1
-1
-1
-1
10
6
5
1
9
7
1
7
3
7
9
4
-1
-1
-1
-1
6
1
2
6
5
1
4
7
8
-1
-1
-1
-1
-1
-1
-1
1
2
5
5
2
6
3
0
4
3
4
7
-1
-1
-1
-1
8
4
7
9
0
5
0
6
5
0
2
6
-1
-1
-1
-1
7
3
9
7
9
4
3
2
9
5
9
6
2
6
9
-1
3
11
2
7
8
4
10
6
5
-1
-1
-1
-1
-1
-1
-1
5
10
6
4
7
2
4
2
0
2
7
11
-1
-1
-1
-1
0
1
9
4
7
8
2
3
11
5
10
6
-1
-1
-1
-1
9
2
1
9
11
2
9
4
11
7
11
4
5
10
6
-1
8
4
7
3
11
5
3
5
1
5
11
6
-1
-1
-1
-1
5
1
11
5
11
6
1
0
11
7
11
4
0
4
11
-1
0
5
9
0
6
5
0
3
6
11
6
3
8
4
7
-1
6
5
9
6
9
11
4
7
9
7
11
9
-1
-1
-1
-1
10
4
9
6
4
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
10
6
4
9
10
0
8
3
-1
-1
-1
-1
-1
-1
-1
10
0
1
10
6
0
6
4
0
-1
-1
-1
-1
-1
-1
-1
8
3
1
8
1
6
8
6
4
6
1
10
-1
-1
-1
-1
1
4
9
1
2
4
2
6
4
-1
-1
-1
-1
-1
-1
-1
3
0
8
1
2
9
2
4
9
2
6
4
-1
-1
-1
-1
0
2
4
4
2
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
3
2
8
2
4
4
2
6
-1
-1
-1
-1
-1
-1
-1
10
4
9
10
6
4
11
2
3
-1
-1
-1
-1
-1
-1
-1
0
8
2
2
8
11
4
9
10
4
10
6
-1
-1
-1
-1
3
11
2
0
1
6
0
6
4
6
1
10
-1
-1
-1
-1
6
4
1
6
1
10
4
8
1
2
1
11
8
11
1
-1
9
6
4
9
3
6
9
1
3
11
6
3
-1
-1
-1
-1
8
11
1
8
1
0
11
6
1
9
1
4
6
4
1
-1
3
11
6
3
6
0
0
6
4
-1
-1
-1
-1
-1
-1
-1
6
4
8
11
6
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
10
6
7
8
10
8
9
10
-1
-1
-1
-1
-1
-1
-1
0
7
3
0
10
7
0
9
10
6
7
10
-1
-1
-1
-1
10
6
7
1
10
7
1
7
8
1
8
0
-1
-1
-1
-1
10
6
7
10
7
1
1
7
3
-1
-1
-1
-1
-1
-1
-1
1
2
6
1
6
8
1
8
9
8
6
7
-1
-1
-1
-1
2
6
9
2
9
1
6
7
9
0
9
3
7
3
9
-1
7
8
0
7
0
6
6
0
2
-1
-1
-1
-1
-1
-1
-1
7
3
2
6
7
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
3
11
10
6
8
10
8
9
8
6
7
-1
-1
-1
-1
2
0
7
2
7
11
0
9
7
6
7
10
9
10
7
-1
1
8
0
1
7
8
1
10
7
6
7
10
2
3
11
-1
11
2
1
11
1
7
10
6
1
6
7
1
-1
-1
-1
-1
8
9
6
8
6
7
9
1
6
11
6
3
1
3
6
-1
0
9
1
11
6
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
8
0
7
0
6
3
11
0
11
6
0
-1
-1
-1
-1
7
11
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
6
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
0
8
11
7
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
1
9
11
7
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
1
9
8
3
1
11
7
6
-1
-1
-1
-1
-1
-1
-1
10
1
2
6
11
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
2
10
3
0
8
6
11
7
-1
-1
-1
-1
-1
-1
-1
2
9
0
2
10
9
6
11
7
-1
-1
-1
-1
-1
-1
-1
6
11
7
2
10
3
10
8
3
10
9
8
-1
-1
-1
-1
7
2
3
6
2
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
7
0
8
7
6
0
6
2
0
-1
-1
-1
-1
-1
-1
-1
2
7
6
2
3
7
0
1
9
-1
-1
-1
-1
-1
-1
-1
1
6
2
1
8
6
1
9
8
8
7
6
-1
-1
-1
-1
10
7
6
10
1
7
1
3
7
-1
-1
-1
-1
-1
-1
-1
10
7
6
1
7
10
1
8
7
1
0
8
-1
-1
-1
-1
0
3
7
0
7
10
0
10
9
6
10
7
-1
-1
-1
-1
7
6
10
7
10
8
8
10
9
-1
-1
-1
-1
-1
-1
-1
6
8
4
11
8
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
6
11
3
0
6
0
4
6
-1
-1
-1
-1
-1
-1
-1
8
6
11
8
4
6
9
0
1
-1
-1
-1
-1
-1
-1
-1
9
4
6
9
6
3
9
3
1
11
3
6
-1
-1
-1
-1
6
8
4
6
11
8
2
10
1
-1
-1
-1
-1
-1
-1
-1
1
2
10
3
0
11
0
6
11
0
4
6
-1
-1
-1
-1
4
11
8
4
6
11
0
2
9
2
10
9
-1
-1
-1
-1
10
9
3
10
3
2
9
4
3
11
3
6
4
6
3
-1
8
2
3
8
4
2
4
6
2
-1
-1
-1
-1
-1
-1
-1
0
4
2
4
6
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
9
0
2
3
4
2
4
6
4
3
8
-1
-1
-1
-1
1
9
4
1
4
2
2
4
6
-1
-1
-1
-1
-1
-1
-1
8
1
3
8
6
1
8
4
6
6
10
1
-1
-1
-1
-1
10
1
0
10
0
6
6
0
4
-1
-1
-1
-1
-1
-1
-1
4
6
3
4
3
8
6
10
3
0
3
9
10
9
3
-1
10
9
4
6
10
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
9
5
7
6
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
3
4
9
5
11
7
6
-1
-1
-1
-1
-1
-1
-1
5
0
1
5
4
0
7
6
11
-1
-1
-1
-1
-1
-1
-1
11
7
6
8
3
4
3
5
4
3
1
5
-1
-1
-1
-1
9
5
4
10
1
2
7
6
11
-1
-1
-1
-1
-1
-1
-1
6
11
7
1
2
10
0
8
3
4
9
5
-1
-1
-1
-1
7
6
11
5
4
10
4
2
10
4
0
2
-1
-1
-1
-1
3
4
8
3
5
4
3
2
5
10
5
2
11
7
6
-1
7
2
3
7
6
2
5
4
9
-1
-1
-1
-1
-1
-1
-1
9
5
4
0
8
6
0
6
2
6
8
7
-1
-1
-1
-1
3
6
2
3
7
6
1
5
0
5
4
0
-1
-1
-1
-1
6
2
8
6
8
7
2
1
8
4
8
5
1
5
8
-1
9
5
4
10
1
6
1
7
6
1
3
7
-1
-1
-1
-1
1
6
10
1
7
6
1
0
7
8
7
0
9
5
4
-1
4
0
10
4
10
5
0
3
10
6
10
7
3
7
10
-1
7
6
10
7
10
8
5
4
10
4
8
10
-1
-1
-1
-1
6
9
5
6
11
9
11
8
9
-1
-1
-1
-1
-1
-1
-1
3
6
11
0
6
3
0
5
6
0
9
5
-1
-1
-1
-1
0
11
8
0
5
11
0
1
5
5
6
11
-1
-1
-1
-1
6
11
3
6
3
5
5
3
1
-1
-1
-1
-1
-1
-1
-1
1
2
10
9
5
11
9
11
8
11
5
6
-1
-1
-1
-1
0
11
3
0
6
11
0
9
6
5
6
9
1
2
10
-1
11
8
5
11
5
6
8
0
5
10
5
2
0
2
5
-1
6
11
3
6
3
5
2
10
3
10
5
3
-1
-1
-1
-1
5
8
9
5
2
8
5
6
2
3
8
2
-1
-1
-1
-1
9
5
6
9
6
0
0
6
2
-1
-1
-1
-1
-1
-1
-1
1
5
8
1
8
0
5
6
8
3
8
2
6
2
8
-1
1
5
6
2
1
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
3
6
1
6
10
3
8
6
5
6
9
8
9
6
-1
10
1
0
10
0
6
9
5
0
5
6
0
-1
-1
-1
-1
0
3
8
5
6
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
10
5
6
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
5
10
7
5
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
11
5
10
11
7
5
8
3
0
-1
-1
-1
-1
-1
-1
-1
5
11
7
5
10
11
1
9
0
-1
-1
-1
-1
-1
-1
-1
10
7
5
10
11
7
9
8
1
8
3
1
-1
-1
-1
-1
11
1
2
11
7
1
7
5
1
-1
-1
-1
-1
-1
-1
-1
0
8
3
1
2
7
1
7
5
7
2
11
-1
-1
-1
-1
9
7
5
9
2
7
9
0
2
2
11
7
-1
-1
-1
-1
7
5
2
7
2
11
5
9
2
3
2
8
9
8
2
-1
2
5
10
2
3
5
3
7
5
-1
-1
-1
-1
-1
-1
-1
8
2
0
8
5
2
8
7
5
10
2
5
-1
-1
-1
-1
9
0
1
5
10
3
5
3
7
3
10
2
-1
-1
-1
-1
9
8
2
9
2
1
8
7
2
10
2
5
7
5
2
-1
1
3
5
3
7
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
8
7
0
7
1
1
7
5
-1
-1
-1
-1
-1
-1
-1
9
0
3
9
3
5
5
3
7
-1
-1
-1
-1
-1
-1
-1
9
8
7
5
9
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
5
8
4
5
10
8
10
11
8
-1
-1
-1
-1
-1
-1
-1
5
0
4
5
11
0
5
10
11
11
3
0
-1
-1
-1
-1
0
1
9
8
4
10
8
10
11
10
4
5
-1
-1
-1
-1
10
11
4
10
4
5
11
3
4
9
4
1
3
1
4
-1
2
5
1
2
8
5
2
11
8
4
5
8
-1
-1
-1
-1
0
4
11
0
11
3
4
5
11
2
11
1
5
1
11
-1
0
2
5
0
5
9
2
11
5
4
5
8
11
8
5
-1
9
4
5
2
11
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
5
10
3
5
2
3
4
5
3
8
4
-1
-1
-1
-1
5
10
2
5
2
4
4
2
0
-1
-1
-1
-1
-1
-1
-1
3
10
2
3
5
10
3
8
5
4
5
8
0
1
9
-1
5
10
2
5
2
4
1
9
2
9
4
2
-1
-1
-1
-1
8
4
5
8
5
3
3
5
1
-1
-1
-1
-1
-1
-1
-1
0
4
5
1
0
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
8
4
5
8
5
3
9
0
5
0
3
5
-1
-1
-1
-1
9
4
5
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
11
7
4
9
11
9
10
11
-1
-1
-1
-1
-1
-1
-1
0
8
3
4
9
7
9
11
7
9
10
11
-1
-1
-1
-1
1
10
11
1
11
4
1
4
0
7
4
11
-1
-1
-1
-1
3
1
4
3
4
8
1
10
4
7
4
11
10
11
4
-1
4
11
7
9
11
4
9
2
11
9
1
2
-1
-1
-1
-1
9
7
4
9
11
7
9
1
11
2
11
1
0
8
3
-1
11
7
4
11
4
2
2
4
0
-1
-1
-1
-1
-1
-1
-1
11
7
4
11
4
2
8
3
4
3
2
4
-1
-1
-1
-1
2
9
10
2
7
9
2
3
7
7
4
9
-1
-1
-1
-1
9
10
7
9
7
4
10
2
7
8
7
0
2
0
7
-1
3
7
10
3
10
2
7
4
10
1
10
0
4
0
10
-1
1
10
2
8
7
4
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
9
1
4
1
7
7
1
3
-1
-1
-1
-1
-1
-1
-1
4
9
1
4
1
7
0
8
1
8
7
1
-1
-1
-1
-1
4
0
3
7
4
3
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
4
8
7
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
9
10
8
10
11
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
0
9
3
9
11
11
9
10
-1
-1
-1
-1
-1
-1
-1
0
1
10
0
10
8
8
10
11
-1
-1
-1
-1
-1
-1
-1
3
1
10
11
3
10
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
2
11
1
11
9
9
11
8
-1
-1
-1
-1
-1
-1
-1
3
0
9
3
9
11
1
2
9
2
11
9
-1
-1
-1
-1
0
2
11
8
0
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
3
2
11
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
3
8
2
8
10
10
8
9
-1
-1
-1
-1
-1
-1
-1
9
10
2
0
9
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
2
3
8
2
8
10
0
1
8
1
10
8
-1
-1
-1
-1
1
10
2
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
1
3
8
9
1
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
9
1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
0
3
8
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
])
|
[
{
"context": "###\nCopyright 2012 David Mauro\n\nLicensed under the Apache License, Version 2.0 (",
"end": 30,
"score": 0.9998544454574585,
"start": 19,
"tag": "NAME",
"value": "David Mauro"
}
] | keypress.coffee | cinchcast/Keypress | 0 | ###
Copyright 2012 David Mauro
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.
Keypress is a robust keyboard input capturing Javascript utility
focused on input for games.
version 1.0.1
###
###
Options available and defaults:
keys : [] - An array of the keys pressed together to activate combo
count : 0 - The number of times a counting combo has been pressed. Reset on release.
prevent_default : false - Prevent default behavior for all component key keypresses.
is_ordered : false - Unless this is set to true, the keys can be pressed down in any order
is_counting : false - Makes this a counting combo (see documentation)
is_exclusive : false - This combo will replace other exclusive combos when true
is_sequence : false - Rather than a key combo, this is an ordered key sequence
prevent_repeat : false - Prevent the combo from repeating when keydown is held.
on_keyup : null - A function that is called when the combo is released
on_keydown : null - A function that is called when the combo is pressed.
on_release : null - A function that is called hen all keys are released.
this : undefined - The scope for this of your callback functions
###
# Extending Array's prototype for IE support
unless Array::filter
Array::filter = (callback) ->
element for element in this when callback(element)
_registered_combos = []
_sequence = []
_sequence_timer = null
_keys_down = []
_active_combos = []
_prevent_capture = false
_event_classname = "keypress_events"
_metakey = "ctrl"
_modifier_keys = ["meta", "alt", "option", "ctrl", "shift", "cmd"]
_valid_keys = []
_combo_defaults = {
keys : []
count : 0
}
_log_error = () ->
console.log arguments...
_compare_arrays = (a1, a2) ->
# This will ignore the ordering of the arrays
# and simply check if they have the same contents.
return false unless a1.length is a2.length
for item in a1
continue if item in a2
return false
for item in a2
continue if item in a1
return false
return true
_prevent_default = (e, should_prevent) ->
# If we've pressed a combo, or if we are working towards
# one, we should prevent the default keydown event.
if (should_prevent or keypress.suppress_event_defaults) and not keypress.force_event_defaults
if e.preventDefault then e.preventDefault() else e.returnValue = false
e.stopPropagation() if e.stopPropagation
_allow_key_repeat = (combo) ->
return false if combo.prevent_repeat
# Combos with keydown functions should be able to rapid fire
# when holding down the key for an extended period
return true if typeof combo.on_keydown is "function"
_keys_remain = (combo) ->
for key in combo.keys
if key in _keys_down
keys_remain = true
break
return keys_remain
_fire = (event, combo, key_event) ->
# Only fire this event if the function is defined
if typeof combo["on_" + event] is "function"
if event is "release"
_prevent_default key_event, (combo["on_" + event].call(combo.this, key_event, combo.count) is false)
else
_prevent_default key_event, (combo["on_" + event].call(combo.this, key_event, combo.count) is false)
# We need to mark that keyup has already happened
if event is "release"
combo.count = 0
if event is "keyup"
combo.keyup_fired = true
_match_combo_arrays = (potential_match, source_combo_array, allow_partial_match=false) ->
# This will return all combos that match
matches = []
for source_combo in source_combo_array
continue if source_combo_array.is_sequence
if source_combo.is_ordered
matches.push(source_combo) if potential_match.join("") is source_combo.keys.join("")
matches.push(source_combo) if allow_partial_match and potential_match.join("") is source_combo.keys.slice(0, potential_match.length).join("")
else
matches.push(source_combo) if _compare_arrays potential_match, source_combo.keys
matches.push(source_combo) if allow_partial_match and _compare_arrays potential_match, source_combo.keys.slice(0, potential_match.length)
return matches
_cmd_bug_check = (combo_keys) ->
# We don't want to allow combos to activate if the cmd key
# is pressed, but cmd isn't in them. This is so they don't
# accidentally rapid fire due to our hack-around for the cmd
# key bug and having to fake keyups.
if "cmd" in _keys_down and "cmd" not in combo_keys
return false
return true
_get_active_combos = (key) ->
# Based on the keys_down and the key just pressed or released
# (which should not be in keys_down), we determine if any
# combo in registered_combos matches exactly.
# This will return an array of active combos
potentials = []
# First check that every key in keys_down maps to a combo
keys_down = _keys_down.filter (down_key) ->
down_key isnt key
keys_down.push key
perfect_matches = _match_combo_arrays keys_down, _registered_combos
potentials = perfect_matches if perfect_matches.length and _cmd_bug_check keys_down
is_exclusive = false
for potential in potentials
is_exclusive = true if potential.is_exclusive
# Then work our way back through a combination with each other key down in order
# This will match a combo even if some other key that is not part of the combo
# is being held down.
slice_up_array = (array) ->
for i in [0...array.length]
partial = array.slice()
partial.splice i, 1
continue unless partial.length
fuzzy_matches = _match_combo_arrays partial, _registered_combos
for fuzzy_match in fuzzy_matches
potentials.push(fuzzy_match) unless is_exclusive and fuzzy_match.is_exclusive
slice_up_array partial
return
slice_up_array keys_down
# Trying to return an array of matched combos
return potentials
_get_potential_combos = (key) ->
# Check if we are working towards pressing a combo.
# Used for preventing default on keys that might match
# to a combo in the future.
potentials = []
for combo in _registered_combos
continue if combo.is_sequence
potentials.push(combo) if key in combo.keys and _cmd_bug_check combo.keys
return potentials
_add_to_active_combos = (combo) ->
replaced = false
# An active combo is any combo which the user has already entered.
# We use this to track when a user has released the last key of a
# combo for on_release, and to keep combos from 'overlapping'.
if combo in _active_combos
return false
else if _active_combos.length
# We have to check if we're replacing another active combo
# So compare the combo.keys to all active combos' keys.
for i in [0..._active_combos.length]
active_combo = _active_combos[i]
continue unless active_combo.is_exclusive and combo.is_exclusive
active_keys = active_combo.keys.slice()
for active_key in active_keys
is_match = true
unless active_key in combo.keys
is_match = false
break
if is_match
# In this case we'll just replace it
_active_combos.splice i, 1, combo
replaced = true
break
unless replaced
_active_combos.unshift combo
return true
_remove_from_active_combos = (combo) ->
for i in [0..._active_combos.length]
active_combo = _active_combos[i]
if active_combo is combo
_active_combos.splice i, 1
break
return
_add_key_to_sequence = (key, e) ->
_sequence.push key
# Now check if they're working towards a sequence
sequence_combos = _get_possible_sequences()
if sequence_combos.length
for combo in sequence_combos
_prevent_default e, combo.prevent_default
# If we're working towards one, give them more time to keep going
clearTimeout(_sequence_timer) if _sequence_timer
_sequence_timer = setTimeout ->
_sequence = []
, 800
else
# If we're not working towards something, just clear it out
_sequence = []
return
_get_possible_sequences = ->
# Determine what if any sequences we're working towards.
# We will consider any which any part of the end of the sequence
# matches and return all of them.
matches = []
for combo in _registered_combos
for j in [1.._sequence.length]
sequence = _sequence.slice -j
continue unless combo.is_sequence
unless "shift" in combo.keys
sequence = sequence.filter (key) ->
return key isnt "shift"
continue unless sequence.length
for i in [0...sequence.length]
if combo.keys[i] is sequence[i]
match = true
else
match = false
break
matches.push(combo) if match
return matches
_get_sequence = (key) ->
# Compare _sequence to all combos
for combo in _registered_combos
continue unless combo.is_sequence
for j in [1.._sequence.length]
# As we are traversing backwards through the sequence keys,
# Take out any shift keys, unless shift is in the combo.
sequence = _sequence.filter((seq_key) ->
return true if "shift" in combo.keys
return seq_key isnt "shift"
).slice -j
continue unless combo.keys.length is sequence.length
for i in [0...sequence.length]
seq_key = sequence[i]
# Special case for shift. Ignore shift keys, unless the sequence explicitly uses them
continue if seq_key is "shift" unless "shift" in combo.keys
# Don't select this combo if we're pressing shift and shift isn't in it
continue if key is "shift" and "shift" not in combo.keys
if combo.keys[i] is seq_key
match = true
else
match = false
break
return combo if match
return false
_convert_to_shifted_key = (key, e) ->
return false unless e.shiftKey
k = _keycode_shifted_keys[key]
return k if k?
return false
_handle_combo_down = (combo, key, e) ->
# Make sure we're not trying to fire for a combo that already fired
return false unless key in combo.keys
_prevent_default e, (combo and combo.prevent_default)
# If we've already pressed this key, check that we want to fire
# again, otherwise just add it to the keys_down list.
if key in _keys_down
return false unless _allow_key_repeat combo
# Now we add this combo or replace it in _active_combos
_add_to_active_combos combo, key
# We reset the keyup_fired property because you should be
# able to fire that again, if you've pressed the key down again
combo.keyup_fired = false
# Now we fire the keydown event
if combo.is_counting and typeof combo.on_keydown is "function"
combo.count += 1
_fire "keydown", combo, e
_key_down = (key, e) ->
# Check if we're holding shift
shifted_key = _convert_to_shifted_key key, e
key = shifted_key if shifted_key
# Add the key to sequences
_add_key_to_sequence key, e
sequence_combo = _get_sequence key
_fire("keydown", sequence_combo, e) if sequence_combo
# We might have modifier keys down when coming back to
# this window and they might now be in _keys_down, so
# we're doing a check to make sure we put it back in.
# This only works for explicit modifier keys.
for mod, event_mod of _modifier_event_mapping
continue unless e[event_mod]
mod = _metakey if mod is "meta"
continue if mod is key or mod in _keys_down
_keys_down.push mod
# Alternatively, we might not have modifier keys down
# that we think are, so we should catch those too
for mod, event_mod of _modifier_event_mapping
mod = _metakey if mod is "meta"
continue if mod is key
if mod in _keys_down and not e[event_mod]
for i in [0..._keys_down.length]
_keys_down.splice(i, 1) if _keys_down[i] is mod
# Find which combos we have pressed or might be working towards, and prevent default
combos = _get_active_combos key
for combo in combos
_handle_combo_down combo, key, e
potential_combos = _get_potential_combos key
if potential_combos.length
for potential in potential_combos
_prevent_default e, potential.prevent_default
if key not in _keys_down
_keys_down.push key
return
_handle_combo_up = (combo, e) ->
# Check if any keys from this combo are still being held.
keys_remaining = _keys_remain combo
# Any unactivated combos will fire, unless it is a counting combo with no keys remaining.
# We don't fire those because they will fire on_release on their last key release.
if !combo.keyup_fired and (!combo.is_counting or (combo.is_counting and keys_remaining))
_fire "keyup", combo, e
# Dont' add to the count unless we only have a keyup callback
if combo.is_counting and typeof combo.on_keyup is "function" and typeof combo.on_keydown isnt "function"
combo.count += 1
# If this was the last key released of the combo, clean up.
unless keys_remaining
if combo.is_counting
_fire "release", combo, e
_remove_from_active_combos combo
return
_key_up = (key, e) ->
# Check if we're holding shift
unshifted_key = key
shifted_key = _convert_to_shifted_key key, e
key = shifted_key if shifted_key
shifted_key = _keycode_shifted_keys[unshifted_key]
# We have to make sure the key matches to what we had in _keys_down
if e.shiftKey
key = unshifted_key unless shifted_key and shifted_key in _keys_down
else
key = shifted_key unless unshifted_key and unshifted_key in _keys_down
# Check if we have a keyup firing
sequence_combo = _get_sequence key
_fire("keyup", sequence_combo, e) if sequence_combo
# Remove from the list
return false unless key in _keys_down
for i in [0..._keys_down.length]
if _keys_down[i] in [key, shifted_key, unshifted_key]
_keys_down.splice i, 1
break
# Store this for later cleanup
active_combos_length = _active_combos.length
# When releasing we should only check if we
# match from _active_combos so that we don't
# accidentally fire for a combo that was a
# smaller part of the one we actually wanted.
combos = []
for active_combo in _active_combos
if key in active_combo.keys
combos.push active_combo
for combo in combos
_handle_combo_up combo, e
# We also need to check other combos that might still be in active_combos
# and needs to be removed from it.
if active_combos_length > 1
for active_combo in _active_combos
continue if active_combo is undefined or active_combo in combos
unless _keys_remain active_combo
_remove_from_active_combos active_combo
return
_receive_input = (e, is_keydown) ->
# If we're not capturing input, we should
# clear out _keys_down for good measure
if _prevent_capture
if _keys_down.length
_keys_down = []
return
# Catch tabbing out of a non-capturing state
if !is_keydown and !_keys_down.length
return
key = _convert_key_to_readable e.keyCode
return unless key
if is_keydown
_key_down key, e
else
_key_up key, e
_unregister_combo = (combo) ->
for i in [0..._registered_combos.length]
if combo is _registered_combos[i]
_registered_combos.splice i, 1
break
_validate_combo = (combo) ->
# Warn for lack of keys
unless combo.keys.length
_log_error "You're trying to bind a combo with no keys."
# Convert "meta" to either "ctrl" or "cmd"
# Don't explicity use the command key, it breaks
# because it is the windows key in Windows, and
# cannot be hijacked.
for i in [0...combo.keys.length]
key = combo.keys[i]
# Check the name and replace if needed
alt_name = _keycode_alternate_names[key]
key = combo.keys[i] = alt_name if alt_name
if key is "meta"
combo.keys.splice i, 1, _metakey
if key is "cmd"
_log_error "Warning: use the \"meta\" key rather than \"cmd\" for Windows compatibility"
# Check that all keys in the combo are valid
for key in combo.keys
unless key in _valid_keys
_log_error "Do not recognize the key \"#{key}\""
return false
# We can only allow a single non-modifier key
# in combos that include the command key (this
# includes 'meta') because of the keyup bug.
if "meta" in combo.keys or "cmd" in combo.keys
non_modifier_keys = combo.keys.slice()
for mod_key in _modifier_keys
if (i = non_modifier_keys.indexOf(mod_key)) > -1
non_modifier_keys.splice(i, 1)
if non_modifier_keys.length > 1
_log_error "META and CMD key combos cannot have more than 1 non-modifier keys", combo, non_modifier_keys
return true
return true
_decide_meta_key = ->
# If the useragent reports Mac OS X, assume cmd is metakey
if navigator.userAgent.indexOf("Mac OS X") != -1
_metakey = "cmd"
return
_bug_catcher = (e) ->
# Force a keyup for non-modifier keys when command is held because they don't fire
if "cmd" in _keys_down and _convert_key_to_readable(e.keyCode) not in ["cmd", "shift", "alt", "caps", "tab"]
_receive_input e, false
_change_keycodes_by_browser = ->
if navigator.userAgent.indexOf("Opera") != -1
# Opera does weird stuff with command and control keys, let's fix that.
# Note: Opera cannot override meta + s browser default of save page.
# Note: Opera does some really strange stuff when cmd+alt+shift
# are held and a non-modifier key is pressed.
_keycode_dictionary["17"] = "cmd"
return
_bind_key_events = ->
document.body.onkeydown = (e) ->
e = e or window.event
_receive_input e, true
_bug_catcher e
document.body.onkeyup = (e) ->
e = e or window.event
_receive_input e, false
window.onblur = ->
# Assume all keys are released when we can't catch key events
# This prevents alt+tab conflicts
for key in _keys_down
_key_up key, {}
_keys_down = []
_valid_combos = []
_init = ->
_decide_meta_key()
_change_keycodes_by_browser()
###########################
# Public object and methods
###########################
window.keypress = {}
keypress.force_event_defaults = false
keypress.suppress_event_defaults = false
keypress.reset = () ->
_registered_combos = []
return
keypress.combo = (keys, callback, prevent_default=false) ->
# Shortcut for simple combos.
keypress.register_combo(
keys : keys
on_keydown : callback
prevent_default : prevent_default
)
keypress.counting_combo = (keys, count_callback, prevent_default=false) ->
# Shortcut for counting combos
keypress.register_combo(
keys : keys
is_counting : true
is_ordered : true
on_keydown : count_callback
prevent_default : prevent_default
)
keypress.sequence_combo = (keys, callback, prevent_default=false) ->
keypress.register_combo(
keys : keys
on_keydown : callback
is_sequence : true
prevent_default : prevent_default
)
keypress.register_combo = (combo) ->
if typeof combo.keys is "string"
combo.keys = combo.keys.split " "
for own property, value of _combo_defaults
combo[property] = value unless combo[property]?
if _validate_combo combo
_registered_combos.push combo
return true
keypress.register_many = (combo_array) ->
keypress.register_combo(combo) for combo in combo_array
keypress.unregister_combo = (keys_or_combo) ->
return false unless keys_or_combo
if keys_or_combo.keys
_unregister_combo keys_or_combo
else
for combo in _registered_combos
continue unless combo
if _compare_arrays keys, combo.keys
_unregister_combo combo
keypress.unregister_many = (combo_array) ->
for combo in combo_array
keypress.unregister_combo combo
keypress.listen = ->
_prevent_capture = false
keypress.stop_listening = ->
_prevent_capture = true
_convert_key_to_readable = (k) ->
return _keycode_dictionary[k]
_modifier_event_mapping =
"meta" : "metaKey"
"ctrl" : "ctrlKey"
"shift" : "shiftKey"
"alt" : "altKey"
_keycode_alternate_names =
"control" : "ctrl"
"command" : "cmd"
"break" : "pause"
"windows" : "cmd"
"option" : "alt"
"caps_lock" : "caps"
"apostrophe" : "\'"
"semicolon" : ";"
"tilde" : "~"
"accent" : "`"
"scroll_lock" : "scroll"
"num_lock" : "num"
_keycode_shifted_keys =
"/" : "?"
"." : ">"
"," : "<"
"\'" : "\""
";" : ":"
"[" : "{"
"]" : "}"
"\\" : "|"
"`" : "~"
"=" : "+"
"-" : "_"
"1" : "!"
"2" : "@"
"3" : "#"
"4" : "$"
"5" : "%"
"6" : "^"
"7" : "&"
"8" : "*"
"9" : "("
"0" : ")"
_keycode_dictionary =
0 : "\\" # Firefox reports this keyCode when shift is held
8 : "backspace"
9 : "tab"
12 : "num"
13 : "enter"
16 : "shift"
17 : "ctrl"
18 : "alt"
19 : "pause"
20 : "caps"
27 : "escape"
32 : "space"
33 : "pageup"
34 : "pagedown"
35 : "end"
36 : "home"
37 : "left"
38 : "up"
39 : "right"
40 : "down"
44 : "print"
45 : "insert"
46 : "delete"
48 : "0"
49 : "1"
50 : "2"
51 : "3"
52 : "4"
53 : "5"
54 : "6"
55 : "7"
56 : "8"
57 : "9"
65 : "a"
66 : "b"
67 : "c"
68 : "d"
69 : "e"
70 : "f"
71 : "g"
72 : "h"
73 : "i"
74 : "j"
75 : "k"
76 : "l"
77 : "m"
78 : "n"
79 : "o"
80 : "p"
81 : "q"
82 : "r"
83 : "s"
84 : "t"
85 : "u"
86 : "v"
87 : "w"
88 : "x"
89 : "y"
90 : "z"
91 : "cmd"
92 : "cmd"
93 : "cmd"
96 : "num_0"
97 : "num_1"
98 : "num_2"
99 : "num_3"
100 : "num_4"
101 : "num_5"
102 : "num_6"
103 : "num_7"
104 : "num_8"
105 : "num_9"
106 : "num_multiply"
107 : "num_add"
108 : "num_enter"
109 : "num_subtract"
110 : "num_decimal"
111 : "num_divide"
124 : "print"
144 : "num"
145 : "scroll"
186 : ";"
187 : "="
188 : ","
189 : "-"
190 : "."
191 : "/"
192 : "`"
219 : "["
220 : "\\"
221 : "]"
222 : "\'"
224 : "cmd"
# Opera weirdness
57392 : "ctrl"
63289 : "num"
for _, key of _keycode_dictionary
_valid_keys.push key
for _, key of _keycode_shifted_keys
_valid_keys.push key
############################
# Initialize, bind on ready
############################
_init()
_ready = (callback) ->
if /in/.test document.readyState
setTimeout ->
_ready callback
, 9
else
callback()
_ready _bind_key_events
| 11766 | ###
Copyright 2012 <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.
Keypress is a robust keyboard input capturing Javascript utility
focused on input for games.
version 1.0.1
###
###
Options available and defaults:
keys : [] - An array of the keys pressed together to activate combo
count : 0 - The number of times a counting combo has been pressed. Reset on release.
prevent_default : false - Prevent default behavior for all component key keypresses.
is_ordered : false - Unless this is set to true, the keys can be pressed down in any order
is_counting : false - Makes this a counting combo (see documentation)
is_exclusive : false - This combo will replace other exclusive combos when true
is_sequence : false - Rather than a key combo, this is an ordered key sequence
prevent_repeat : false - Prevent the combo from repeating when keydown is held.
on_keyup : null - A function that is called when the combo is released
on_keydown : null - A function that is called when the combo is pressed.
on_release : null - A function that is called hen all keys are released.
this : undefined - The scope for this of your callback functions
###
# Extending Array's prototype for IE support
unless Array::filter
Array::filter = (callback) ->
element for element in this when callback(element)
_registered_combos = []
_sequence = []
_sequence_timer = null
_keys_down = []
_active_combos = []
_prevent_capture = false
_event_classname = "keypress_events"
_metakey = "ctrl"
_modifier_keys = ["meta", "alt", "option", "ctrl", "shift", "cmd"]
_valid_keys = []
_combo_defaults = {
keys : []
count : 0
}
_log_error = () ->
console.log arguments...
_compare_arrays = (a1, a2) ->
# This will ignore the ordering of the arrays
# and simply check if they have the same contents.
return false unless a1.length is a2.length
for item in a1
continue if item in a2
return false
for item in a2
continue if item in a1
return false
return true
_prevent_default = (e, should_prevent) ->
# If we've pressed a combo, or if we are working towards
# one, we should prevent the default keydown event.
if (should_prevent or keypress.suppress_event_defaults) and not keypress.force_event_defaults
if e.preventDefault then e.preventDefault() else e.returnValue = false
e.stopPropagation() if e.stopPropagation
_allow_key_repeat = (combo) ->
return false if combo.prevent_repeat
# Combos with keydown functions should be able to rapid fire
# when holding down the key for an extended period
return true if typeof combo.on_keydown is "function"
_keys_remain = (combo) ->
for key in combo.keys
if key in _keys_down
keys_remain = true
break
return keys_remain
_fire = (event, combo, key_event) ->
# Only fire this event if the function is defined
if typeof combo["on_" + event] is "function"
if event is "release"
_prevent_default key_event, (combo["on_" + event].call(combo.this, key_event, combo.count) is false)
else
_prevent_default key_event, (combo["on_" + event].call(combo.this, key_event, combo.count) is false)
# We need to mark that keyup has already happened
if event is "release"
combo.count = 0
if event is "keyup"
combo.keyup_fired = true
_match_combo_arrays = (potential_match, source_combo_array, allow_partial_match=false) ->
# This will return all combos that match
matches = []
for source_combo in source_combo_array
continue if source_combo_array.is_sequence
if source_combo.is_ordered
matches.push(source_combo) if potential_match.join("") is source_combo.keys.join("")
matches.push(source_combo) if allow_partial_match and potential_match.join("") is source_combo.keys.slice(0, potential_match.length).join("")
else
matches.push(source_combo) if _compare_arrays potential_match, source_combo.keys
matches.push(source_combo) if allow_partial_match and _compare_arrays potential_match, source_combo.keys.slice(0, potential_match.length)
return matches
_cmd_bug_check = (combo_keys) ->
# We don't want to allow combos to activate if the cmd key
# is pressed, but cmd isn't in them. This is so they don't
# accidentally rapid fire due to our hack-around for the cmd
# key bug and having to fake keyups.
if "cmd" in _keys_down and "cmd" not in combo_keys
return false
return true
_get_active_combos = (key) ->
# Based on the keys_down and the key just pressed or released
# (which should not be in keys_down), we determine if any
# combo in registered_combos matches exactly.
# This will return an array of active combos
potentials = []
# First check that every key in keys_down maps to a combo
keys_down = _keys_down.filter (down_key) ->
down_key isnt key
keys_down.push key
perfect_matches = _match_combo_arrays keys_down, _registered_combos
potentials = perfect_matches if perfect_matches.length and _cmd_bug_check keys_down
is_exclusive = false
for potential in potentials
is_exclusive = true if potential.is_exclusive
# Then work our way back through a combination with each other key down in order
# This will match a combo even if some other key that is not part of the combo
# is being held down.
slice_up_array = (array) ->
for i in [0...array.length]
partial = array.slice()
partial.splice i, 1
continue unless partial.length
fuzzy_matches = _match_combo_arrays partial, _registered_combos
for fuzzy_match in fuzzy_matches
potentials.push(fuzzy_match) unless is_exclusive and fuzzy_match.is_exclusive
slice_up_array partial
return
slice_up_array keys_down
# Trying to return an array of matched combos
return potentials
_get_potential_combos = (key) ->
# Check if we are working towards pressing a combo.
# Used for preventing default on keys that might match
# to a combo in the future.
potentials = []
for combo in _registered_combos
continue if combo.is_sequence
potentials.push(combo) if key in combo.keys and _cmd_bug_check combo.keys
return potentials
_add_to_active_combos = (combo) ->
replaced = false
# An active combo is any combo which the user has already entered.
# We use this to track when a user has released the last key of a
# combo for on_release, and to keep combos from 'overlapping'.
if combo in _active_combos
return false
else if _active_combos.length
# We have to check if we're replacing another active combo
# So compare the combo.keys to all active combos' keys.
for i in [0..._active_combos.length]
active_combo = _active_combos[i]
continue unless active_combo.is_exclusive and combo.is_exclusive
active_keys = active_combo.keys.slice()
for active_key in active_keys
is_match = true
unless active_key in combo.keys
is_match = false
break
if is_match
# In this case we'll just replace it
_active_combos.splice i, 1, combo
replaced = true
break
unless replaced
_active_combos.unshift combo
return true
_remove_from_active_combos = (combo) ->
for i in [0..._active_combos.length]
active_combo = _active_combos[i]
if active_combo is combo
_active_combos.splice i, 1
break
return
_add_key_to_sequence = (key, e) ->
_sequence.push key
# Now check if they're working towards a sequence
sequence_combos = _get_possible_sequences()
if sequence_combos.length
for combo in sequence_combos
_prevent_default e, combo.prevent_default
# If we're working towards one, give them more time to keep going
clearTimeout(_sequence_timer) if _sequence_timer
_sequence_timer = setTimeout ->
_sequence = []
, 800
else
# If we're not working towards something, just clear it out
_sequence = []
return
_get_possible_sequences = ->
# Determine what if any sequences we're working towards.
# We will consider any which any part of the end of the sequence
# matches and return all of them.
matches = []
for combo in _registered_combos
for j in [1.._sequence.length]
sequence = _sequence.slice -j
continue unless combo.is_sequence
unless "shift" in combo.keys
sequence = sequence.filter (key) ->
return key isnt "shift"
continue unless sequence.length
for i in [0...sequence.length]
if combo.keys[i] is sequence[i]
match = true
else
match = false
break
matches.push(combo) if match
return matches
_get_sequence = (key) ->
# Compare _sequence to all combos
for combo in _registered_combos
continue unless combo.is_sequence
for j in [1.._sequence.length]
# As we are traversing backwards through the sequence keys,
# Take out any shift keys, unless shift is in the combo.
sequence = _sequence.filter((seq_key) ->
return true if "shift" in combo.keys
return seq_key isnt "shift"
).slice -j
continue unless combo.keys.length is sequence.length
for i in [0...sequence.length]
seq_key = sequence[i]
# Special case for shift. Ignore shift keys, unless the sequence explicitly uses them
continue if seq_key is "shift" unless "shift" in combo.keys
# Don't select this combo if we're pressing shift and shift isn't in it
continue if key is "shift" and "shift" not in combo.keys
if combo.keys[i] is seq_key
match = true
else
match = false
break
return combo if match
return false
_convert_to_shifted_key = (key, e) ->
return false unless e.shiftKey
k = _keycode_shifted_keys[key]
return k if k?
return false
_handle_combo_down = (combo, key, e) ->
# Make sure we're not trying to fire for a combo that already fired
return false unless key in combo.keys
_prevent_default e, (combo and combo.prevent_default)
# If we've already pressed this key, check that we want to fire
# again, otherwise just add it to the keys_down list.
if key in _keys_down
return false unless _allow_key_repeat combo
# Now we add this combo or replace it in _active_combos
_add_to_active_combos combo, key
# We reset the keyup_fired property because you should be
# able to fire that again, if you've pressed the key down again
combo.keyup_fired = false
# Now we fire the keydown event
if combo.is_counting and typeof combo.on_keydown is "function"
combo.count += 1
_fire "keydown", combo, e
_key_down = (key, e) ->
# Check if we're holding shift
shifted_key = _convert_to_shifted_key key, e
key = shifted_key if shifted_key
# Add the key to sequences
_add_key_to_sequence key, e
sequence_combo = _get_sequence key
_fire("keydown", sequence_combo, e) if sequence_combo
# We might have modifier keys down when coming back to
# this window and they might now be in _keys_down, so
# we're doing a check to make sure we put it back in.
# This only works for explicit modifier keys.
for mod, event_mod of _modifier_event_mapping
continue unless e[event_mod]
mod = _metakey if mod is "meta"
continue if mod is key or mod in _keys_down
_keys_down.push mod
# Alternatively, we might not have modifier keys down
# that we think are, so we should catch those too
for mod, event_mod of _modifier_event_mapping
mod = _metakey if mod is "meta"
continue if mod is key
if mod in _keys_down and not e[event_mod]
for i in [0..._keys_down.length]
_keys_down.splice(i, 1) if _keys_down[i] is mod
# Find which combos we have pressed or might be working towards, and prevent default
combos = _get_active_combos key
for combo in combos
_handle_combo_down combo, key, e
potential_combos = _get_potential_combos key
if potential_combos.length
for potential in potential_combos
_prevent_default e, potential.prevent_default
if key not in _keys_down
_keys_down.push key
return
_handle_combo_up = (combo, e) ->
# Check if any keys from this combo are still being held.
keys_remaining = _keys_remain combo
# Any unactivated combos will fire, unless it is a counting combo with no keys remaining.
# We don't fire those because they will fire on_release on their last key release.
if !combo.keyup_fired and (!combo.is_counting or (combo.is_counting and keys_remaining))
_fire "keyup", combo, e
# Dont' add to the count unless we only have a keyup callback
if combo.is_counting and typeof combo.on_keyup is "function" and typeof combo.on_keydown isnt "function"
combo.count += 1
# If this was the last key released of the combo, clean up.
unless keys_remaining
if combo.is_counting
_fire "release", combo, e
_remove_from_active_combos combo
return
_key_up = (key, e) ->
# Check if we're holding shift
unshifted_key = key
shifted_key = _convert_to_shifted_key key, e
key = shifted_key if shifted_key
shifted_key = _keycode_shifted_keys[unshifted_key]
# We have to make sure the key matches to what we had in _keys_down
if e.shiftKey
key = unshifted_key unless shifted_key and shifted_key in _keys_down
else
key = shifted_key unless unshifted_key and unshifted_key in _keys_down
# Check if we have a keyup firing
sequence_combo = _get_sequence key
_fire("keyup", sequence_combo, e) if sequence_combo
# Remove from the list
return false unless key in _keys_down
for i in [0..._keys_down.length]
if _keys_down[i] in [key, shifted_key, unshifted_key]
_keys_down.splice i, 1
break
# Store this for later cleanup
active_combos_length = _active_combos.length
# When releasing we should only check if we
# match from _active_combos so that we don't
# accidentally fire for a combo that was a
# smaller part of the one we actually wanted.
combos = []
for active_combo in _active_combos
if key in active_combo.keys
combos.push active_combo
for combo in combos
_handle_combo_up combo, e
# We also need to check other combos that might still be in active_combos
# and needs to be removed from it.
if active_combos_length > 1
for active_combo in _active_combos
continue if active_combo is undefined or active_combo in combos
unless _keys_remain active_combo
_remove_from_active_combos active_combo
return
_receive_input = (e, is_keydown) ->
# If we're not capturing input, we should
# clear out _keys_down for good measure
if _prevent_capture
if _keys_down.length
_keys_down = []
return
# Catch tabbing out of a non-capturing state
if !is_keydown and !_keys_down.length
return
key = _convert_key_to_readable e.keyCode
return unless key
if is_keydown
_key_down key, e
else
_key_up key, e
_unregister_combo = (combo) ->
for i in [0..._registered_combos.length]
if combo is _registered_combos[i]
_registered_combos.splice i, 1
break
_validate_combo = (combo) ->
# Warn for lack of keys
unless combo.keys.length
_log_error "You're trying to bind a combo with no keys."
# Convert "meta" to either "ctrl" or "cmd"
# Don't explicity use the command key, it breaks
# because it is the windows key in Windows, and
# cannot be hijacked.
for i in [0...combo.keys.length]
key = combo.keys[i]
# Check the name and replace if needed
alt_name = _keycode_alternate_names[key]
key = combo.keys[i] = alt_name if alt_name
if key is "meta"
combo.keys.splice i, 1, _metakey
if key is "cmd"
_log_error "Warning: use the \"meta\" key rather than \"cmd\" for Windows compatibility"
# Check that all keys in the combo are valid
for key in combo.keys
unless key in _valid_keys
_log_error "Do not recognize the key \"#{key}\""
return false
# We can only allow a single non-modifier key
# in combos that include the command key (this
# includes 'meta') because of the keyup bug.
if "meta" in combo.keys or "cmd" in combo.keys
non_modifier_keys = combo.keys.slice()
for mod_key in _modifier_keys
if (i = non_modifier_keys.indexOf(mod_key)) > -1
non_modifier_keys.splice(i, 1)
if non_modifier_keys.length > 1
_log_error "META and CMD key combos cannot have more than 1 non-modifier keys", combo, non_modifier_keys
return true
return true
_decide_meta_key = ->
# If the useragent reports Mac OS X, assume cmd is metakey
if navigator.userAgent.indexOf("Mac OS X") != -1
_metakey = "cmd"
return
_bug_catcher = (e) ->
# Force a keyup for non-modifier keys when command is held because they don't fire
if "cmd" in _keys_down and _convert_key_to_readable(e.keyCode) not in ["cmd", "shift", "alt", "caps", "tab"]
_receive_input e, false
_change_keycodes_by_browser = ->
if navigator.userAgent.indexOf("Opera") != -1
# Opera does weird stuff with command and control keys, let's fix that.
# Note: Opera cannot override meta + s browser default of save page.
# Note: Opera does some really strange stuff when cmd+alt+shift
# are held and a non-modifier key is pressed.
_keycode_dictionary["17"] = "cmd"
return
_bind_key_events = ->
document.body.onkeydown = (e) ->
e = e or window.event
_receive_input e, true
_bug_catcher e
document.body.onkeyup = (e) ->
e = e or window.event
_receive_input e, false
window.onblur = ->
# Assume all keys are released when we can't catch key events
# This prevents alt+tab conflicts
for key in _keys_down
_key_up key, {}
_keys_down = []
_valid_combos = []
_init = ->
_decide_meta_key()
_change_keycodes_by_browser()
###########################
# Public object and methods
###########################
window.keypress = {}
keypress.force_event_defaults = false
keypress.suppress_event_defaults = false
keypress.reset = () ->
_registered_combos = []
return
keypress.combo = (keys, callback, prevent_default=false) ->
# Shortcut for simple combos.
keypress.register_combo(
keys : keys
on_keydown : callback
prevent_default : prevent_default
)
keypress.counting_combo = (keys, count_callback, prevent_default=false) ->
# Shortcut for counting combos
keypress.register_combo(
keys : keys
is_counting : true
is_ordered : true
on_keydown : count_callback
prevent_default : prevent_default
)
keypress.sequence_combo = (keys, callback, prevent_default=false) ->
keypress.register_combo(
keys : keys
on_keydown : callback
is_sequence : true
prevent_default : prevent_default
)
keypress.register_combo = (combo) ->
if typeof combo.keys is "string"
combo.keys = combo.keys.split " "
for own property, value of _combo_defaults
combo[property] = value unless combo[property]?
if _validate_combo combo
_registered_combos.push combo
return true
keypress.register_many = (combo_array) ->
keypress.register_combo(combo) for combo in combo_array
keypress.unregister_combo = (keys_or_combo) ->
return false unless keys_or_combo
if keys_or_combo.keys
_unregister_combo keys_or_combo
else
for combo in _registered_combos
continue unless combo
if _compare_arrays keys, combo.keys
_unregister_combo combo
keypress.unregister_many = (combo_array) ->
for combo in combo_array
keypress.unregister_combo combo
keypress.listen = ->
_prevent_capture = false
keypress.stop_listening = ->
_prevent_capture = true
_convert_key_to_readable = (k) ->
return _keycode_dictionary[k]
_modifier_event_mapping =
"meta" : "metaKey"
"ctrl" : "ctrlKey"
"shift" : "shiftKey"
"alt" : "altKey"
_keycode_alternate_names =
"control" : "ctrl"
"command" : "cmd"
"break" : "pause"
"windows" : "cmd"
"option" : "alt"
"caps_lock" : "caps"
"apostrophe" : "\'"
"semicolon" : ";"
"tilde" : "~"
"accent" : "`"
"scroll_lock" : "scroll"
"num_lock" : "num"
_keycode_shifted_keys =
"/" : "?"
"." : ">"
"," : "<"
"\'" : "\""
";" : ":"
"[" : "{"
"]" : "}"
"\\" : "|"
"`" : "~"
"=" : "+"
"-" : "_"
"1" : "!"
"2" : "@"
"3" : "#"
"4" : "$"
"5" : "%"
"6" : "^"
"7" : "&"
"8" : "*"
"9" : "("
"0" : ")"
_keycode_dictionary =
0 : "\\" # Firefox reports this keyCode when shift is held
8 : "backspace"
9 : "tab"
12 : "num"
13 : "enter"
16 : "shift"
17 : "ctrl"
18 : "alt"
19 : "pause"
20 : "caps"
27 : "escape"
32 : "space"
33 : "pageup"
34 : "pagedown"
35 : "end"
36 : "home"
37 : "left"
38 : "up"
39 : "right"
40 : "down"
44 : "print"
45 : "insert"
46 : "delete"
48 : "0"
49 : "1"
50 : "2"
51 : "3"
52 : "4"
53 : "5"
54 : "6"
55 : "7"
56 : "8"
57 : "9"
65 : "a"
66 : "b"
67 : "c"
68 : "d"
69 : "e"
70 : "f"
71 : "g"
72 : "h"
73 : "i"
74 : "j"
75 : "k"
76 : "l"
77 : "m"
78 : "n"
79 : "o"
80 : "p"
81 : "q"
82 : "r"
83 : "s"
84 : "t"
85 : "u"
86 : "v"
87 : "w"
88 : "x"
89 : "y"
90 : "z"
91 : "cmd"
92 : "cmd"
93 : "cmd"
96 : "num_0"
97 : "num_1"
98 : "num_2"
99 : "num_3"
100 : "num_4"
101 : "num_5"
102 : "num_6"
103 : "num_7"
104 : "num_8"
105 : "num_9"
106 : "num_multiply"
107 : "num_add"
108 : "num_enter"
109 : "num_subtract"
110 : "num_decimal"
111 : "num_divide"
124 : "print"
144 : "num"
145 : "scroll"
186 : ";"
187 : "="
188 : ","
189 : "-"
190 : "."
191 : "/"
192 : "`"
219 : "["
220 : "\\"
221 : "]"
222 : "\'"
224 : "cmd"
# Opera weirdness
57392 : "ctrl"
63289 : "num"
for _, key of _keycode_dictionary
_valid_keys.push key
for _, key of _keycode_shifted_keys
_valid_keys.push key
############################
# Initialize, bind on ready
############################
_init()
_ready = (callback) ->
if /in/.test document.readyState
setTimeout ->
_ready callback
, 9
else
callback()
_ready _bind_key_events
| true | ###
Copyright 2012 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.
Keypress is a robust keyboard input capturing Javascript utility
focused on input for games.
version 1.0.1
###
###
Options available and defaults:
keys : [] - An array of the keys pressed together to activate combo
count : 0 - The number of times a counting combo has been pressed. Reset on release.
prevent_default : false - Prevent default behavior for all component key keypresses.
is_ordered : false - Unless this is set to true, the keys can be pressed down in any order
is_counting : false - Makes this a counting combo (see documentation)
is_exclusive : false - This combo will replace other exclusive combos when true
is_sequence : false - Rather than a key combo, this is an ordered key sequence
prevent_repeat : false - Prevent the combo from repeating when keydown is held.
on_keyup : null - A function that is called when the combo is released
on_keydown : null - A function that is called when the combo is pressed.
on_release : null - A function that is called hen all keys are released.
this : undefined - The scope for this of your callback functions
###
# Extending Array's prototype for IE support
unless Array::filter
Array::filter = (callback) ->
element for element in this when callback(element)
_registered_combos = []
_sequence = []
_sequence_timer = null
_keys_down = []
_active_combos = []
_prevent_capture = false
_event_classname = "keypress_events"
_metakey = "ctrl"
_modifier_keys = ["meta", "alt", "option", "ctrl", "shift", "cmd"]
_valid_keys = []
_combo_defaults = {
keys : []
count : 0
}
_log_error = () ->
console.log arguments...
_compare_arrays = (a1, a2) ->
# This will ignore the ordering of the arrays
# and simply check if they have the same contents.
return false unless a1.length is a2.length
for item in a1
continue if item in a2
return false
for item in a2
continue if item in a1
return false
return true
_prevent_default = (e, should_prevent) ->
# If we've pressed a combo, or if we are working towards
# one, we should prevent the default keydown event.
if (should_prevent or keypress.suppress_event_defaults) and not keypress.force_event_defaults
if e.preventDefault then e.preventDefault() else e.returnValue = false
e.stopPropagation() if e.stopPropagation
_allow_key_repeat = (combo) ->
return false if combo.prevent_repeat
# Combos with keydown functions should be able to rapid fire
# when holding down the key for an extended period
return true if typeof combo.on_keydown is "function"
_keys_remain = (combo) ->
for key in combo.keys
if key in _keys_down
keys_remain = true
break
return keys_remain
_fire = (event, combo, key_event) ->
# Only fire this event if the function is defined
if typeof combo["on_" + event] is "function"
if event is "release"
_prevent_default key_event, (combo["on_" + event].call(combo.this, key_event, combo.count) is false)
else
_prevent_default key_event, (combo["on_" + event].call(combo.this, key_event, combo.count) is false)
# We need to mark that keyup has already happened
if event is "release"
combo.count = 0
if event is "keyup"
combo.keyup_fired = true
_match_combo_arrays = (potential_match, source_combo_array, allow_partial_match=false) ->
# This will return all combos that match
matches = []
for source_combo in source_combo_array
continue if source_combo_array.is_sequence
if source_combo.is_ordered
matches.push(source_combo) if potential_match.join("") is source_combo.keys.join("")
matches.push(source_combo) if allow_partial_match and potential_match.join("") is source_combo.keys.slice(0, potential_match.length).join("")
else
matches.push(source_combo) if _compare_arrays potential_match, source_combo.keys
matches.push(source_combo) if allow_partial_match and _compare_arrays potential_match, source_combo.keys.slice(0, potential_match.length)
return matches
_cmd_bug_check = (combo_keys) ->
# We don't want to allow combos to activate if the cmd key
# is pressed, but cmd isn't in them. This is so they don't
# accidentally rapid fire due to our hack-around for the cmd
# key bug and having to fake keyups.
if "cmd" in _keys_down and "cmd" not in combo_keys
return false
return true
_get_active_combos = (key) ->
# Based on the keys_down and the key just pressed or released
# (which should not be in keys_down), we determine if any
# combo in registered_combos matches exactly.
# This will return an array of active combos
potentials = []
# First check that every key in keys_down maps to a combo
keys_down = _keys_down.filter (down_key) ->
down_key isnt key
keys_down.push key
perfect_matches = _match_combo_arrays keys_down, _registered_combos
potentials = perfect_matches if perfect_matches.length and _cmd_bug_check keys_down
is_exclusive = false
for potential in potentials
is_exclusive = true if potential.is_exclusive
# Then work our way back through a combination with each other key down in order
# This will match a combo even if some other key that is not part of the combo
# is being held down.
slice_up_array = (array) ->
for i in [0...array.length]
partial = array.slice()
partial.splice i, 1
continue unless partial.length
fuzzy_matches = _match_combo_arrays partial, _registered_combos
for fuzzy_match in fuzzy_matches
potentials.push(fuzzy_match) unless is_exclusive and fuzzy_match.is_exclusive
slice_up_array partial
return
slice_up_array keys_down
# Trying to return an array of matched combos
return potentials
_get_potential_combos = (key) ->
# Check if we are working towards pressing a combo.
# Used for preventing default on keys that might match
# to a combo in the future.
potentials = []
for combo in _registered_combos
continue if combo.is_sequence
potentials.push(combo) if key in combo.keys and _cmd_bug_check combo.keys
return potentials
_add_to_active_combos = (combo) ->
replaced = false
# An active combo is any combo which the user has already entered.
# We use this to track when a user has released the last key of a
# combo for on_release, and to keep combos from 'overlapping'.
if combo in _active_combos
return false
else if _active_combos.length
# We have to check if we're replacing another active combo
# So compare the combo.keys to all active combos' keys.
for i in [0..._active_combos.length]
active_combo = _active_combos[i]
continue unless active_combo.is_exclusive and combo.is_exclusive
active_keys = active_combo.keys.slice()
for active_key in active_keys
is_match = true
unless active_key in combo.keys
is_match = false
break
if is_match
# In this case we'll just replace it
_active_combos.splice i, 1, combo
replaced = true
break
unless replaced
_active_combos.unshift combo
return true
_remove_from_active_combos = (combo) ->
for i in [0..._active_combos.length]
active_combo = _active_combos[i]
if active_combo is combo
_active_combos.splice i, 1
break
return
_add_key_to_sequence = (key, e) ->
_sequence.push key
# Now check if they're working towards a sequence
sequence_combos = _get_possible_sequences()
if sequence_combos.length
for combo in sequence_combos
_prevent_default e, combo.prevent_default
# If we're working towards one, give them more time to keep going
clearTimeout(_sequence_timer) if _sequence_timer
_sequence_timer = setTimeout ->
_sequence = []
, 800
else
# If we're not working towards something, just clear it out
_sequence = []
return
_get_possible_sequences = ->
# Determine what if any sequences we're working towards.
# We will consider any which any part of the end of the sequence
# matches and return all of them.
matches = []
for combo in _registered_combos
for j in [1.._sequence.length]
sequence = _sequence.slice -j
continue unless combo.is_sequence
unless "shift" in combo.keys
sequence = sequence.filter (key) ->
return key isnt "shift"
continue unless sequence.length
for i in [0...sequence.length]
if combo.keys[i] is sequence[i]
match = true
else
match = false
break
matches.push(combo) if match
return matches
_get_sequence = (key) ->
# Compare _sequence to all combos
for combo in _registered_combos
continue unless combo.is_sequence
for j in [1.._sequence.length]
# As we are traversing backwards through the sequence keys,
# Take out any shift keys, unless shift is in the combo.
sequence = _sequence.filter((seq_key) ->
return true if "shift" in combo.keys
return seq_key isnt "shift"
).slice -j
continue unless combo.keys.length is sequence.length
for i in [0...sequence.length]
seq_key = sequence[i]
# Special case for shift. Ignore shift keys, unless the sequence explicitly uses them
continue if seq_key is "shift" unless "shift" in combo.keys
# Don't select this combo if we're pressing shift and shift isn't in it
continue if key is "shift" and "shift" not in combo.keys
if combo.keys[i] is seq_key
match = true
else
match = false
break
return combo if match
return false
_convert_to_shifted_key = (key, e) ->
return false unless e.shiftKey
k = _keycode_shifted_keys[key]
return k if k?
return false
_handle_combo_down = (combo, key, e) ->
# Make sure we're not trying to fire for a combo that already fired
return false unless key in combo.keys
_prevent_default e, (combo and combo.prevent_default)
# If we've already pressed this key, check that we want to fire
# again, otherwise just add it to the keys_down list.
if key in _keys_down
return false unless _allow_key_repeat combo
# Now we add this combo or replace it in _active_combos
_add_to_active_combos combo, key
# We reset the keyup_fired property because you should be
# able to fire that again, if you've pressed the key down again
combo.keyup_fired = false
# Now we fire the keydown event
if combo.is_counting and typeof combo.on_keydown is "function"
combo.count += 1
_fire "keydown", combo, e
_key_down = (key, e) ->
# Check if we're holding shift
shifted_key = _convert_to_shifted_key key, e
key = shifted_key if shifted_key
# Add the key to sequences
_add_key_to_sequence key, e
sequence_combo = _get_sequence key
_fire("keydown", sequence_combo, e) if sequence_combo
# We might have modifier keys down when coming back to
# this window and they might now be in _keys_down, so
# we're doing a check to make sure we put it back in.
# This only works for explicit modifier keys.
for mod, event_mod of _modifier_event_mapping
continue unless e[event_mod]
mod = _metakey if mod is "meta"
continue if mod is key or mod in _keys_down
_keys_down.push mod
# Alternatively, we might not have modifier keys down
# that we think are, so we should catch those too
for mod, event_mod of _modifier_event_mapping
mod = _metakey if mod is "meta"
continue if mod is key
if mod in _keys_down and not e[event_mod]
for i in [0..._keys_down.length]
_keys_down.splice(i, 1) if _keys_down[i] is mod
# Find which combos we have pressed or might be working towards, and prevent default
combos = _get_active_combos key
for combo in combos
_handle_combo_down combo, key, e
potential_combos = _get_potential_combos key
if potential_combos.length
for potential in potential_combos
_prevent_default e, potential.prevent_default
if key not in _keys_down
_keys_down.push key
return
_handle_combo_up = (combo, e) ->
# Check if any keys from this combo are still being held.
keys_remaining = _keys_remain combo
# Any unactivated combos will fire, unless it is a counting combo with no keys remaining.
# We don't fire those because they will fire on_release on their last key release.
if !combo.keyup_fired and (!combo.is_counting or (combo.is_counting and keys_remaining))
_fire "keyup", combo, e
# Dont' add to the count unless we only have a keyup callback
if combo.is_counting and typeof combo.on_keyup is "function" and typeof combo.on_keydown isnt "function"
combo.count += 1
# If this was the last key released of the combo, clean up.
unless keys_remaining
if combo.is_counting
_fire "release", combo, e
_remove_from_active_combos combo
return
_key_up = (key, e) ->
# Check if we're holding shift
unshifted_key = key
shifted_key = _convert_to_shifted_key key, e
key = shifted_key if shifted_key
shifted_key = _keycode_shifted_keys[unshifted_key]
# We have to make sure the key matches to what we had in _keys_down
if e.shiftKey
key = unshifted_key unless shifted_key and shifted_key in _keys_down
else
key = shifted_key unless unshifted_key and unshifted_key in _keys_down
# Check if we have a keyup firing
sequence_combo = _get_sequence key
_fire("keyup", sequence_combo, e) if sequence_combo
# Remove from the list
return false unless key in _keys_down
for i in [0..._keys_down.length]
if _keys_down[i] in [key, shifted_key, unshifted_key]
_keys_down.splice i, 1
break
# Store this for later cleanup
active_combos_length = _active_combos.length
# When releasing we should only check if we
# match from _active_combos so that we don't
# accidentally fire for a combo that was a
# smaller part of the one we actually wanted.
combos = []
for active_combo in _active_combos
if key in active_combo.keys
combos.push active_combo
for combo in combos
_handle_combo_up combo, e
# We also need to check other combos that might still be in active_combos
# and needs to be removed from it.
if active_combos_length > 1
for active_combo in _active_combos
continue if active_combo is undefined or active_combo in combos
unless _keys_remain active_combo
_remove_from_active_combos active_combo
return
_receive_input = (e, is_keydown) ->
# If we're not capturing input, we should
# clear out _keys_down for good measure
if _prevent_capture
if _keys_down.length
_keys_down = []
return
# Catch tabbing out of a non-capturing state
if !is_keydown and !_keys_down.length
return
key = _convert_key_to_readable e.keyCode
return unless key
if is_keydown
_key_down key, e
else
_key_up key, e
_unregister_combo = (combo) ->
for i in [0..._registered_combos.length]
if combo is _registered_combos[i]
_registered_combos.splice i, 1
break
_validate_combo = (combo) ->
# Warn for lack of keys
unless combo.keys.length
_log_error "You're trying to bind a combo with no keys."
# Convert "meta" to either "ctrl" or "cmd"
# Don't explicity use the command key, it breaks
# because it is the windows key in Windows, and
# cannot be hijacked.
for i in [0...combo.keys.length]
key = combo.keys[i]
# Check the name and replace if needed
alt_name = _keycode_alternate_names[key]
key = combo.keys[i] = alt_name if alt_name
if key is "meta"
combo.keys.splice i, 1, _metakey
if key is "cmd"
_log_error "Warning: use the \"meta\" key rather than \"cmd\" for Windows compatibility"
# Check that all keys in the combo are valid
for key in combo.keys
unless key in _valid_keys
_log_error "Do not recognize the key \"#{key}\""
return false
# We can only allow a single non-modifier key
# in combos that include the command key (this
# includes 'meta') because of the keyup bug.
if "meta" in combo.keys or "cmd" in combo.keys
non_modifier_keys = combo.keys.slice()
for mod_key in _modifier_keys
if (i = non_modifier_keys.indexOf(mod_key)) > -1
non_modifier_keys.splice(i, 1)
if non_modifier_keys.length > 1
_log_error "META and CMD key combos cannot have more than 1 non-modifier keys", combo, non_modifier_keys
return true
return true
_decide_meta_key = ->
# If the useragent reports Mac OS X, assume cmd is metakey
if navigator.userAgent.indexOf("Mac OS X") != -1
_metakey = "cmd"
return
_bug_catcher = (e) ->
# Force a keyup for non-modifier keys when command is held because they don't fire
if "cmd" in _keys_down and _convert_key_to_readable(e.keyCode) not in ["cmd", "shift", "alt", "caps", "tab"]
_receive_input e, false
_change_keycodes_by_browser = ->
if navigator.userAgent.indexOf("Opera") != -1
# Opera does weird stuff with command and control keys, let's fix that.
# Note: Opera cannot override meta + s browser default of save page.
# Note: Opera does some really strange stuff when cmd+alt+shift
# are held and a non-modifier key is pressed.
_keycode_dictionary["17"] = "cmd"
return
_bind_key_events = ->
document.body.onkeydown = (e) ->
e = e or window.event
_receive_input e, true
_bug_catcher e
document.body.onkeyup = (e) ->
e = e or window.event
_receive_input e, false
window.onblur = ->
# Assume all keys are released when we can't catch key events
# This prevents alt+tab conflicts
for key in _keys_down
_key_up key, {}
_keys_down = []
_valid_combos = []
_init = ->
_decide_meta_key()
_change_keycodes_by_browser()
###########################
# Public object and methods
###########################
window.keypress = {}
keypress.force_event_defaults = false
keypress.suppress_event_defaults = false
keypress.reset = () ->
_registered_combos = []
return
keypress.combo = (keys, callback, prevent_default=false) ->
# Shortcut for simple combos.
keypress.register_combo(
keys : keys
on_keydown : callback
prevent_default : prevent_default
)
keypress.counting_combo = (keys, count_callback, prevent_default=false) ->
# Shortcut for counting combos
keypress.register_combo(
keys : keys
is_counting : true
is_ordered : true
on_keydown : count_callback
prevent_default : prevent_default
)
keypress.sequence_combo = (keys, callback, prevent_default=false) ->
keypress.register_combo(
keys : keys
on_keydown : callback
is_sequence : true
prevent_default : prevent_default
)
keypress.register_combo = (combo) ->
if typeof combo.keys is "string"
combo.keys = combo.keys.split " "
for own property, value of _combo_defaults
combo[property] = value unless combo[property]?
if _validate_combo combo
_registered_combos.push combo
return true
keypress.register_many = (combo_array) ->
keypress.register_combo(combo) for combo in combo_array
keypress.unregister_combo = (keys_or_combo) ->
return false unless keys_or_combo
if keys_or_combo.keys
_unregister_combo keys_or_combo
else
for combo in _registered_combos
continue unless combo
if _compare_arrays keys, combo.keys
_unregister_combo combo
keypress.unregister_many = (combo_array) ->
for combo in combo_array
keypress.unregister_combo combo
keypress.listen = ->
_prevent_capture = false
keypress.stop_listening = ->
_prevent_capture = true
_convert_key_to_readable = (k) ->
return _keycode_dictionary[k]
_modifier_event_mapping =
"meta" : "metaKey"
"ctrl" : "ctrlKey"
"shift" : "shiftKey"
"alt" : "altKey"
_keycode_alternate_names =
"control" : "ctrl"
"command" : "cmd"
"break" : "pause"
"windows" : "cmd"
"option" : "alt"
"caps_lock" : "caps"
"apostrophe" : "\'"
"semicolon" : ";"
"tilde" : "~"
"accent" : "`"
"scroll_lock" : "scroll"
"num_lock" : "num"
_keycode_shifted_keys =
"/" : "?"
"." : ">"
"," : "<"
"\'" : "\""
";" : ":"
"[" : "{"
"]" : "}"
"\\" : "|"
"`" : "~"
"=" : "+"
"-" : "_"
"1" : "!"
"2" : "@"
"3" : "#"
"4" : "$"
"5" : "%"
"6" : "^"
"7" : "&"
"8" : "*"
"9" : "("
"0" : ")"
_keycode_dictionary =
0 : "\\" # Firefox reports this keyCode when shift is held
8 : "backspace"
9 : "tab"
12 : "num"
13 : "enter"
16 : "shift"
17 : "ctrl"
18 : "alt"
19 : "pause"
20 : "caps"
27 : "escape"
32 : "space"
33 : "pageup"
34 : "pagedown"
35 : "end"
36 : "home"
37 : "left"
38 : "up"
39 : "right"
40 : "down"
44 : "print"
45 : "insert"
46 : "delete"
48 : "0"
49 : "1"
50 : "2"
51 : "3"
52 : "4"
53 : "5"
54 : "6"
55 : "7"
56 : "8"
57 : "9"
65 : "a"
66 : "b"
67 : "c"
68 : "d"
69 : "e"
70 : "f"
71 : "g"
72 : "h"
73 : "i"
74 : "j"
75 : "k"
76 : "l"
77 : "m"
78 : "n"
79 : "o"
80 : "p"
81 : "q"
82 : "r"
83 : "s"
84 : "t"
85 : "u"
86 : "v"
87 : "w"
88 : "x"
89 : "y"
90 : "z"
91 : "cmd"
92 : "cmd"
93 : "cmd"
96 : "num_0"
97 : "num_1"
98 : "num_2"
99 : "num_3"
100 : "num_4"
101 : "num_5"
102 : "num_6"
103 : "num_7"
104 : "num_8"
105 : "num_9"
106 : "num_multiply"
107 : "num_add"
108 : "num_enter"
109 : "num_subtract"
110 : "num_decimal"
111 : "num_divide"
124 : "print"
144 : "num"
145 : "scroll"
186 : ";"
187 : "="
188 : ","
189 : "-"
190 : "."
191 : "/"
192 : "`"
219 : "["
220 : "\\"
221 : "]"
222 : "\'"
224 : "cmd"
# Opera weirdness
57392 : "ctrl"
63289 : "num"
for _, key of _keycode_dictionary
_valid_keys.push key
for _, key of _keycode_shifted_keys
_valid_keys.push key
############################
# Initialize, bind on ready
############################
_init()
_ready = (callback) ->
if /in/.test document.readyState
setTimeout ->
_ready callback
, 9
else
callback()
_ready _bind_key_events
|
[
{
"context": "TRAVIS\n project.configure\n username: 'shiptester'\n password: config.github.password\n ",
"end": 368,
"score": 0.9997095465660095,
"start": 358,
"tag": "USERNAME",
"value": "shiptester"
},
{
"context": "e\n username: 'shiptester'\n ... | test/gh-pages.coffee | carrot/ship | 151 | request = require 'request'
nodefn = require 'when/node'
config = require '../config'
path = require 'path'
describe 'gh-pages', ->
it 'deploys a complex nested site to an empty repo', ->
project = new Ship(root: path.join(_path, 'deployers/gh-pages'), deployer: 'gh-pages')
if process.env.TRAVIS
project.configure
username: 'shiptester'
password: config.github.password
repo: 'shiptester/test'
project.deploy()
.tap ->
nodefn.call(request, "https://raw.githubusercontent.com/shiptester/test/gh-pages/index.html")
.tap (r) -> r[0].body.should.match /Testing Page/
.then (res) -> res.destroy()
.catch (err) -> console.error(err); throw err
.should.be.fulfilled
it 'deploys a site to gh-pages when master is already present', ->
project = new Ship(root: path.join(_path, 'deployers/gh-pages2'), deployer: 'gh-pages')
if process.env.TRAVIS
project.configure
username: 'shiptester'
password: config.github.password
repo: 'shiptester/test2'
project.deploy()
.tap ->
nodefn.call(request, "https://raw.githubusercontent.com/shiptester/test2/gh-pages/index.html")
.tap (r) -> r[0].body.should.match /wow/
.then (res) -> res.destroy()
.catch (err) -> console.error(err); throw err
.should.be.fulfilled
| 35961 | request = require 'request'
nodefn = require 'when/node'
config = require '../config'
path = require 'path'
describe 'gh-pages', ->
it 'deploys a complex nested site to an empty repo', ->
project = new Ship(root: path.join(_path, 'deployers/gh-pages'), deployer: 'gh-pages')
if process.env.TRAVIS
project.configure
username: 'shiptester'
password: <PASSWORD>
repo: 'shiptester/test'
project.deploy()
.tap ->
nodefn.call(request, "https://raw.githubusercontent.com/shiptester/test/gh-pages/index.html")
.tap (r) -> r[0].body.should.match /Testing Page/
.then (res) -> res.destroy()
.catch (err) -> console.error(err); throw err
.should.be.fulfilled
it 'deploys a site to gh-pages when master is already present', ->
project = new Ship(root: path.join(_path, 'deployers/gh-pages2'), deployer: 'gh-pages')
if process.env.TRAVIS
project.configure
username: 'shiptester'
password: <PASSWORD>
repo: 'shiptester/test2'
project.deploy()
.tap ->
nodefn.call(request, "https://raw.githubusercontent.com/shiptester/test2/gh-pages/index.html")
.tap (r) -> r[0].body.should.match /wow/
.then (res) -> res.destroy()
.catch (err) -> console.error(err); throw err
.should.be.fulfilled
| true | request = require 'request'
nodefn = require 'when/node'
config = require '../config'
path = require 'path'
describe 'gh-pages', ->
it 'deploys a complex nested site to an empty repo', ->
project = new Ship(root: path.join(_path, 'deployers/gh-pages'), deployer: 'gh-pages')
if process.env.TRAVIS
project.configure
username: 'shiptester'
password: PI:PASSWORD:<PASSWORD>END_PI
repo: 'shiptester/test'
project.deploy()
.tap ->
nodefn.call(request, "https://raw.githubusercontent.com/shiptester/test/gh-pages/index.html")
.tap (r) -> r[0].body.should.match /Testing Page/
.then (res) -> res.destroy()
.catch (err) -> console.error(err); throw err
.should.be.fulfilled
it 'deploys a site to gh-pages when master is already present', ->
project = new Ship(root: path.join(_path, 'deployers/gh-pages2'), deployer: 'gh-pages')
if process.env.TRAVIS
project.configure
username: 'shiptester'
password: PI:PASSWORD:<PASSWORD>END_PI
repo: 'shiptester/test2'
project.deploy()
.tap ->
nodefn.call(request, "https://raw.githubusercontent.com/shiptester/test2/gh-pages/index.html")
.tap (r) -> r[0].body.should.match /wow/
.then (res) -> res.destroy()
.catch (err) -> console.error(err); throw err
.should.be.fulfilled
|
[
{
"context": "###\n @author Gilles Gerlinger\n Copyright 2016. All rights reserved.\n###\n\nlog =",
"end": 30,
"score": 0.9998587965965271,
"start": 14,
"tag": "NAME",
"value": "Gilles Gerlinger"
}
] | src/easyRpc.coffee | gigerlin/easyRPC | 1 | ###
@author Gilles Gerlinger
Copyright 2016. All rights reserved.
###
log = require './log'
cnf = require './config'
className = 'class name'
#
# Client Side
#
exports.Remote = class Remote
constructor: (options) ->
@[className] = options.class
count = 0; uid = cnf.random()
ctx = use:options.use, request:"#{options.url or location.origin}/#{encodeURIComponent options.class}"
options.methods = options.methods or []
options.methods.push cnf.sse # SSE support
( (method) => @[method] = -> send ctx, method:method, args:[].slice.call(arguments), id:"#{uid}-#{++count}"
) method for method in options.methods
send = (ctx, msg) ->
log "#{msg.id} out", msg
if ctx.use
msg.args = [ctx.use, msg.method].concat msg.args
msg.method = 'invoke'
new Promise (resolve, reject) ->
fetch ctx.request, headers:{'Content-Type':'application/json; charset=utf-8'}, method:'post', body:JSON.stringify msg
.catch (err) ->
log "#{msg.id} in", err
reject err
.then (response) ->
if response.ok then response.json() else
log "#{msg.id} in network error:", response.statusText # 404 for example
reject response.statusText
.then (rep) -> if rep
log "#{msg.id} in", rep
if rep.err then reject rep.err else resolve rep.rep
#
# SSE Support
#
class Source
constructor: (@source, @remoteID) ->
close: -> @source.close()
exports.expose = (local, remote, url = location.origin) ->
local = local or {}
methods = (method for method of local when method.charAt(0) isnt '_')
remote = remote or "#{cnf.sse}": -> log "missing remote object in expose"
new Promise (resolve, reject) ->
source = new EventSource "#{url}/#{cnf.tag}"
source.addEventListener cnf.tag, (init) ->
log 'SSE init', init.data
msg = JSON.parse init.data
if msg.uid # tell the remote object on the server which channel and methods to use
source.uid = msg.uid
source.addEventListener "#{cnf.tag}/#{msg.uid}", (e) ->
log 'SSE in', e.type, e.data
msg = JSON.parse e.data
if msg.method
if local[msg.method]
rep = local[msg.method] msg.args...
if msg.args = rep # only if there is a value to be returned
msg.method = cnf.srv
send request:"#{url}/#{encodeURIComponent remote[className]}", msg
else log 'SSE error: no method', msg.method, 'for local object', local
remote[cnf.sse] msg.uid, methods # this calls _remoteReady
.then (remoteID) -> resolve new Source source, remoteID # return source so that source.stop() can be called and P2P can be used
, false
#
# Required modules
#
if typeof window is 'object' # for Safari & IE
fetch = window.fetch or require './fetch'
Promise = window.Promise or require './promise'
EventSource = window.EventSource
else if typeof global is 'object' # Nodejs
Promise = global.Promise
http = require 'http'
EventSource = require 'eventsource'
fetch = (uri, options) -> new Promise (resolve, reject) ->
uri = uri.replace /https?:\/\//, ''
tmp = uri.split '/'
options.path = "/#{tmp[1]}"
tmp = tmp[0].split ':'
options.hostname = tmp[0]
options.port = tmp[1] if tmp[1]
# console.log "#{options.hostname}:#{options.port}#{options.path}"
req = http.request options, (res) ->
res.setEncoding('utf8')
res.on 'data', (body) -> if body.indexOf('"') is -1 then reject body else resolve new Response body
req.on 'error', (e) -> reject e.message
req.write options.body
req.end()
class Response
constructor: (@data, @ok = true) ->
json: -> JSON.parse @data
| 122447 | ###
@author <NAME>
Copyright 2016. All rights reserved.
###
log = require './log'
cnf = require './config'
className = 'class name'
#
# Client Side
#
exports.Remote = class Remote
constructor: (options) ->
@[className] = options.class
count = 0; uid = cnf.random()
ctx = use:options.use, request:"#{options.url or location.origin}/#{encodeURIComponent options.class}"
options.methods = options.methods or []
options.methods.push cnf.sse # SSE support
( (method) => @[method] = -> send ctx, method:method, args:[].slice.call(arguments), id:"#{uid}-#{++count}"
) method for method in options.methods
send = (ctx, msg) ->
log "#{msg.id} out", msg
if ctx.use
msg.args = [ctx.use, msg.method].concat msg.args
msg.method = 'invoke'
new Promise (resolve, reject) ->
fetch ctx.request, headers:{'Content-Type':'application/json; charset=utf-8'}, method:'post', body:JSON.stringify msg
.catch (err) ->
log "#{msg.id} in", err
reject err
.then (response) ->
if response.ok then response.json() else
log "#{msg.id} in network error:", response.statusText # 404 for example
reject response.statusText
.then (rep) -> if rep
log "#{msg.id} in", rep
if rep.err then reject rep.err else resolve rep.rep
#
# SSE Support
#
class Source
constructor: (@source, @remoteID) ->
close: -> @source.close()
exports.expose = (local, remote, url = location.origin) ->
local = local or {}
methods = (method for method of local when method.charAt(0) isnt '_')
remote = remote or "#{cnf.sse}": -> log "missing remote object in expose"
new Promise (resolve, reject) ->
source = new EventSource "#{url}/#{cnf.tag}"
source.addEventListener cnf.tag, (init) ->
log 'SSE init', init.data
msg = JSON.parse init.data
if msg.uid # tell the remote object on the server which channel and methods to use
source.uid = msg.uid
source.addEventListener "#{cnf.tag}/#{msg.uid}", (e) ->
log 'SSE in', e.type, e.data
msg = JSON.parse e.data
if msg.method
if local[msg.method]
rep = local[msg.method] msg.args...
if msg.args = rep # only if there is a value to be returned
msg.method = cnf.srv
send request:"#{url}/#{encodeURIComponent remote[className]}", msg
else log 'SSE error: no method', msg.method, 'for local object', local
remote[cnf.sse] msg.uid, methods # this calls _remoteReady
.then (remoteID) -> resolve new Source source, remoteID # return source so that source.stop() can be called and P2P can be used
, false
#
# Required modules
#
if typeof window is 'object' # for Safari & IE
fetch = window.fetch or require './fetch'
Promise = window.Promise or require './promise'
EventSource = window.EventSource
else if typeof global is 'object' # Nodejs
Promise = global.Promise
http = require 'http'
EventSource = require 'eventsource'
fetch = (uri, options) -> new Promise (resolve, reject) ->
uri = uri.replace /https?:\/\//, ''
tmp = uri.split '/'
options.path = "/#{tmp[1]}"
tmp = tmp[0].split ':'
options.hostname = tmp[0]
options.port = tmp[1] if tmp[1]
# console.log "#{options.hostname}:#{options.port}#{options.path}"
req = http.request options, (res) ->
res.setEncoding('utf8')
res.on 'data', (body) -> if body.indexOf('"') is -1 then reject body else resolve new Response body
req.on 'error', (e) -> reject e.message
req.write options.body
req.end()
class Response
constructor: (@data, @ok = true) ->
json: -> JSON.parse @data
| true | ###
@author PI:NAME:<NAME>END_PI
Copyright 2016. All rights reserved.
###
log = require './log'
cnf = require './config'
className = 'class name'
#
# Client Side
#
exports.Remote = class Remote
constructor: (options) ->
@[className] = options.class
count = 0; uid = cnf.random()
ctx = use:options.use, request:"#{options.url or location.origin}/#{encodeURIComponent options.class}"
options.methods = options.methods or []
options.methods.push cnf.sse # SSE support
( (method) => @[method] = -> send ctx, method:method, args:[].slice.call(arguments), id:"#{uid}-#{++count}"
) method for method in options.methods
send = (ctx, msg) ->
log "#{msg.id} out", msg
if ctx.use
msg.args = [ctx.use, msg.method].concat msg.args
msg.method = 'invoke'
new Promise (resolve, reject) ->
fetch ctx.request, headers:{'Content-Type':'application/json; charset=utf-8'}, method:'post', body:JSON.stringify msg
.catch (err) ->
log "#{msg.id} in", err
reject err
.then (response) ->
if response.ok then response.json() else
log "#{msg.id} in network error:", response.statusText # 404 for example
reject response.statusText
.then (rep) -> if rep
log "#{msg.id} in", rep
if rep.err then reject rep.err else resolve rep.rep
#
# SSE Support
#
class Source
constructor: (@source, @remoteID) ->
close: -> @source.close()
exports.expose = (local, remote, url = location.origin) ->
local = local or {}
methods = (method for method of local when method.charAt(0) isnt '_')
remote = remote or "#{cnf.sse}": -> log "missing remote object in expose"
new Promise (resolve, reject) ->
source = new EventSource "#{url}/#{cnf.tag}"
source.addEventListener cnf.tag, (init) ->
log 'SSE init', init.data
msg = JSON.parse init.data
if msg.uid # tell the remote object on the server which channel and methods to use
source.uid = msg.uid
source.addEventListener "#{cnf.tag}/#{msg.uid}", (e) ->
log 'SSE in', e.type, e.data
msg = JSON.parse e.data
if msg.method
if local[msg.method]
rep = local[msg.method] msg.args...
if msg.args = rep # only if there is a value to be returned
msg.method = cnf.srv
send request:"#{url}/#{encodeURIComponent remote[className]}", msg
else log 'SSE error: no method', msg.method, 'for local object', local
remote[cnf.sse] msg.uid, methods # this calls _remoteReady
.then (remoteID) -> resolve new Source source, remoteID # return source so that source.stop() can be called and P2P can be used
, false
#
# Required modules
#
if typeof window is 'object' # for Safari & IE
fetch = window.fetch or require './fetch'
Promise = window.Promise or require './promise'
EventSource = window.EventSource
else if typeof global is 'object' # Nodejs
Promise = global.Promise
http = require 'http'
EventSource = require 'eventsource'
fetch = (uri, options) -> new Promise (resolve, reject) ->
uri = uri.replace /https?:\/\//, ''
tmp = uri.split '/'
options.path = "/#{tmp[1]}"
tmp = tmp[0].split ':'
options.hostname = tmp[0]
options.port = tmp[1] if tmp[1]
# console.log "#{options.hostname}:#{options.port}#{options.path}"
req = http.request options, (res) ->
res.setEncoding('utf8')
res.on 'data', (body) -> if body.indexOf('"') is -1 then reject body else resolve new Response body
req.on 'error', (e) -> reject e.message
req.write options.body
req.end()
class Response
constructor: (@data, @ok = true) ->
json: -> JSON.parse @data
|
[
{
"context": "ck) ->\n monthKey = monthToLoad.format 'YYYY-MM'\n unless window.app.mainStore.loadedMonths",
"end": 428,
"score": 0.657389760017395,
"start": 426,
"tag": "KEY",
"value": "MM"
}
] | client/app/collections/events.coffee | kondaldurgam/cozy-calendar | 2 | ScheduleItemsCollection = require './scheduleitems'
Event = require '../models/event'
request = require 'lib/request'
module.exports = class EventCollection extends ScheduleItemsCollection
model: Event
url: 'events'
# Check if given month is already. If not, request the server to retrieve
# events occuring that month.
loadMonth: (monthToLoad, callback) ->
monthKey = monthToLoad.format 'YYYY-MM'
unless window.app.mainStore.loadedMonths[monthKey]
year = monthToLoad.format 'YYYY'
month = monthToLoad.format 'MM'
request.get "events/#{year}/#{month}", (err, events) =>
@add events,
silent: true
sort: false
@trigger 'change'
window.app.mainStore.loadedMonths[monthKey] = true
callback()
else
callback()
| 213110 | ScheduleItemsCollection = require './scheduleitems'
Event = require '../models/event'
request = require 'lib/request'
module.exports = class EventCollection extends ScheduleItemsCollection
model: Event
url: 'events'
# Check if given month is already. If not, request the server to retrieve
# events occuring that month.
loadMonth: (monthToLoad, callback) ->
monthKey = monthToLoad.format 'YYYY-<KEY>'
unless window.app.mainStore.loadedMonths[monthKey]
year = monthToLoad.format 'YYYY'
month = monthToLoad.format 'MM'
request.get "events/#{year}/#{month}", (err, events) =>
@add events,
silent: true
sort: false
@trigger 'change'
window.app.mainStore.loadedMonths[monthKey] = true
callback()
else
callback()
| true | ScheduleItemsCollection = require './scheduleitems'
Event = require '../models/event'
request = require 'lib/request'
module.exports = class EventCollection extends ScheduleItemsCollection
model: Event
url: 'events'
# Check if given month is already. If not, request the server to retrieve
# events occuring that month.
loadMonth: (monthToLoad, callback) ->
monthKey = monthToLoad.format 'YYYY-PI:KEY:<KEY>END_PI'
unless window.app.mainStore.loadedMonths[monthKey]
year = monthToLoad.format 'YYYY'
month = monthToLoad.format 'MM'
request.get "events/#{year}/#{month}", (err, events) =>
@add events,
silent: true
sort: false
@trigger 'change'
window.app.mainStore.loadedMonths[monthKey] = true
callback()
else
callback()
|
[
{
"context": "0'\n educationLevel: ['Middle']\n firstName: 'Mr'\n lastName: 'Bean'\n }\n\n beforeEach ->\n sp",
"end": 1426,
"score": 0.9995998740196228,
"start": 1424,
"tag": "NAME",
"value": "Mr"
},
{
"context": "el: ['Middle']\n firstName: 'Mr'\n lastName: 'Bea... | test/app/views/teachers/ConvertToTeacherAccountView.spec.coffee | gugumiao/codecombat | 2 | ConvertToTeacherAccountView = require 'views/teachers/ConvertToTeacherAccountView'
storage = require 'core/storage'
forms = require 'core/forms'
describe '/teachers/update-account', ->
describe 'when logged out', ->
it 'redirects to /teachers/signup', ->
spyOn(me, 'isAnonymous').and.returnValue(true)
spyOn(application.router, 'navigate')
Backbone.history.loadUrl('/teachers/update-account')
expect(application.router.navigate.calls.count()).toBe(1)
args = application.router.navigate.calls.argsFor(0)
expect(args[0]).toBe('/teachers/signup')
describe 'when logged in', ->
it 'displays ConvertToTeacherAccountView', ->
spyOn(me, 'isAnonymous').and.returnValue(false)
spyOn(me, 'isTeacher').and.returnValue(false)
spyOn(application.router, 'routeDirectly')
Backbone.history.loadUrl('/teachers/update-account')
expect(application.router.routeDirectly.calls.count()).toBe(1)
args = application.router.routeDirectly.calls.argsFor(0)
expect(args[0]).toBe('teachers/ConvertToTeacherAccountView')
describe 'ConvertToTeacherAccountView (/teachers/update-account)', ->
view = null
successForm = {
phoneNumber: '555-555-5555'
role: 'Teacher'
organization: 'School'
district: 'District'
city: 'Springfield'
state: 'AA'
country: 'asdf'
numStudents: '1-10'
educationLevel: ['Middle']
firstName: 'Mr'
lastName: 'Bean'
}
beforeEach ->
spyOn(application.router, 'navigate')
me.clear()
me.set({
_id: '1234'
anonymous: false
email: 'some@email.com'
name: 'Existing User'
})
me._revertAttributes = {}
view = new ConvertToTeacherAccountView()
view.render()
jasmine.demoEl(view.$el)
spyOn(storage, 'load').and.returnValue({ lastName: 'Saved Changes' })
afterEach (done) ->
_.defer(done) # let everything finish loading, keep navigate spied on
describe 'when the form is unchanged', ->
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
describe 'when the form has changed but is not submitted', ->
beforeEach ->
view.$el.find('form').trigger('change')
it 'prevents navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeTruthy()
describe 'when the user already has a TrialRequest and is a teacher', ->
beforeEach (done) ->
spyOn(me, 'isTeacher').and.returnValue(true)
_.last(view.trialRequests.fakeRequests).respondWith({
status: 200
responseText: JSON.stringify([{
_id: '1'
properties: {
firstName: 'First'
lastName: 'Last'
}
}])
})
_.defer done # Let SuperModel finish
# TODO: re-enable when student and teacher areas are enforced
xit 'redirects to /teachers/courses', ->
expect(application.router.navigate).toHaveBeenCalled()
args = application.router.navigate.calls.argsFor(0)
expect(args[0]).toBe('/teachers/courses')
describe 'when the user has role "student"', ->
beforeEach ->
me.set('role', 'student')
_.last(view.trialRequests.fakeRequests).respondWith({ status: 200, responseText: JSON.stringify('[]') })
view.render()
it 'shows a warning that they will convert to a teacher account', ->
expect(view.$('#conversion-warning').length).toBe(1)
# TODO: Figure out how to test this
# describe 'the warning', ->
# it 'includes a learn more link which opens a modal with more info'
describe 'submitting the form', ->
beforeEach ->
form = view.$('form')
forms.objectToForm(form, successForm, {overwriteExisting: true})
spyOn(view, 'openModalView')
form.submit()
it 'requires confirmation', ->
expect(view.trialRequest.fakeRequests.length).toBe(0)
confirmModal = view.openModalView.calls.argsFor(0)[0]
confirmModal.trigger 'confirm'
request = _.last(view.trialRequest.fakeRequests)
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
describe '"Log out" link', ->
beforeEach ->
_.last(view.trialRequests.fakeRequests).respondWith({ status: 200, responseText: JSON.stringify('[]') })
it 'logs out the user and redirects them to /teachers/signup', ->
spyOn(me, 'logout')
view.$('#logout-link').click()
expect(me.logout).toHaveBeenCalled()
describe 'submitting the form', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
_.last(view.trialRequests.fakeRequests).respondWith({ status: 200, responseText: JSON.stringify('[]') })
form = view.$('form')
forms.objectToForm(form, successForm, {overwriteExisting: true})
form.submit()
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
it 'creates a new TrialRequest with the information', ->
request = _.last(view.trialRequest.fakeRequests)
expect(request).toBeTruthy()
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.firstName).toBe('Mr')
expect(attrs.properties?.siteOrigin).toBe('convert teacher')
expect(attrs.properties?.email).toBe('some@email.com')
it 'redirects to /teachers/classes', ->
request = _.last(view.trialRequest.fakeRequests)
request.respondWith({
status: 201
responseText: JSON.stringify(_.extend({_id:'fraghlarghl'}, JSON.parse(request.params)))
})
expect(application.router.navigate).toHaveBeenCalled()
args = application.router.navigate.calls.argsFor(0)
expect(args[0]).toBe('/teachers/classes')
it 'sets a teacher role', ->
request = _.last(view.trialRequest.fakeRequests)
request.respondWith({
status: 201
responseText: JSON.stringify(_.extend({_id:'fraghlarghl'}, JSON.parse(request.params)))
})
expect(me.get('role')).toBe(successForm.role.toLowerCase())
describe 'submitting the form without school', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('form')
formData = _.omit(successForm, ['organization'])
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include school setting', ->
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.organization).toBeUndefined()
expect(attrs.properties?.district).toEqual('District')
describe 'submitting the form without district', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('form')
formData = _.omit(successForm, ['district'])
forms.objectToForm(form, formData)
form.submit()
it 'displays a validation error on district and not school', ->
expect(view.$('#organization-control').parent().hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').parent().hasClass('has-error')).toEqual(true)
describe 'submitting the form district set to n/a', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('form')
formData = _.omit(successForm, ['organization'])
formData.district = 'N/A'
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include district setting', ->
expect(view.$('#organization-control').parent().hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').parent().hasClass('has-error')).toEqual(false)
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.district).toBeUndefined()
| 30797 | ConvertToTeacherAccountView = require 'views/teachers/ConvertToTeacherAccountView'
storage = require 'core/storage'
forms = require 'core/forms'
describe '/teachers/update-account', ->
describe 'when logged out', ->
it 'redirects to /teachers/signup', ->
spyOn(me, 'isAnonymous').and.returnValue(true)
spyOn(application.router, 'navigate')
Backbone.history.loadUrl('/teachers/update-account')
expect(application.router.navigate.calls.count()).toBe(1)
args = application.router.navigate.calls.argsFor(0)
expect(args[0]).toBe('/teachers/signup')
describe 'when logged in', ->
it 'displays ConvertToTeacherAccountView', ->
spyOn(me, 'isAnonymous').and.returnValue(false)
spyOn(me, 'isTeacher').and.returnValue(false)
spyOn(application.router, 'routeDirectly')
Backbone.history.loadUrl('/teachers/update-account')
expect(application.router.routeDirectly.calls.count()).toBe(1)
args = application.router.routeDirectly.calls.argsFor(0)
expect(args[0]).toBe('teachers/ConvertToTeacherAccountView')
describe 'ConvertToTeacherAccountView (/teachers/update-account)', ->
view = null
successForm = {
phoneNumber: '555-555-5555'
role: 'Teacher'
organization: 'School'
district: 'District'
city: 'Springfield'
state: 'AA'
country: 'asdf'
numStudents: '1-10'
educationLevel: ['Middle']
firstName: '<NAME>'
lastName: '<NAME>'
}
beforeEach ->
spyOn(application.router, 'navigate')
me.clear()
me.set({
_id: '1234'
anonymous: false
email: '<EMAIL>'
name: 'Existing User'
})
me._revertAttributes = {}
view = new ConvertToTeacherAccountView()
view.render()
jasmine.demoEl(view.$el)
spyOn(storage, 'load').and.returnValue({ lastName: 'Saved Changes' })
afterEach (done) ->
_.defer(done) # let everything finish loading, keep navigate spied on
describe 'when the form is unchanged', ->
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
describe 'when the form has changed but is not submitted', ->
beforeEach ->
view.$el.find('form').trigger('change')
it 'prevents navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeTruthy()
describe 'when the user already has a TrialRequest and is a teacher', ->
beforeEach (done) ->
spyOn(me, 'isTeacher').and.returnValue(true)
_.last(view.trialRequests.fakeRequests).respondWith({
status: 200
responseText: JSON.stringify([{
_id: '1'
properties: {
firstName: '<NAME>'
lastName: '<NAME>'
}
}])
})
_.defer done # Let SuperModel finish
# TODO: re-enable when student and teacher areas are enforced
xit 'redirects to /teachers/courses', ->
expect(application.router.navigate).toHaveBeenCalled()
args = application.router.navigate.calls.argsFor(0)
expect(args[0]).toBe('/teachers/courses')
describe 'when the user has role "student"', ->
beforeEach ->
me.set('role', 'student')
_.last(view.trialRequests.fakeRequests).respondWith({ status: 200, responseText: JSON.stringify('[]') })
view.render()
it 'shows a warning that they will convert to a teacher account', ->
expect(view.$('#conversion-warning').length).toBe(1)
# TODO: Figure out how to test this
# describe 'the warning', ->
# it 'includes a learn more link which opens a modal with more info'
describe 'submitting the form', ->
beforeEach ->
form = view.$('form')
forms.objectToForm(form, successForm, {overwriteExisting: true})
spyOn(view, 'openModalView')
form.submit()
it 'requires confirmation', ->
expect(view.trialRequest.fakeRequests.length).toBe(0)
confirmModal = view.openModalView.calls.argsFor(0)[0]
confirmModal.trigger 'confirm'
request = _.last(view.trialRequest.fakeRequests)
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
describe '"Log out" link', ->
beforeEach ->
_.last(view.trialRequests.fakeRequests).respondWith({ status: 200, responseText: JSON.stringify('[]') })
it 'logs out the user and redirects them to /teachers/signup', ->
spyOn(me, 'logout')
view.$('#logout-link').click()
expect(me.logout).toHaveBeenCalled()
describe 'submitting the form', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
_.last(view.trialRequests.fakeRequests).respondWith({ status: 200, responseText: JSON.stringify('[]') })
form = view.$('form')
forms.objectToForm(form, successForm, {overwriteExisting: true})
form.submit()
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
it 'creates a new TrialRequest with the information', ->
request = _.last(view.trialRequest.fakeRequests)
expect(request).toBeTruthy()
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.firstName).toBe('Mr')
expect(attrs.properties?.siteOrigin).toBe('convert teacher')
expect(attrs.properties?.email).toBe('<EMAIL>')
it 'redirects to /teachers/classes', ->
request = _.last(view.trialRequest.fakeRequests)
request.respondWith({
status: 201
responseText: JSON.stringify(_.extend({_id:'fraghlarghl'}, JSON.parse(request.params)))
})
expect(application.router.navigate).toHaveBeenCalled()
args = application.router.navigate.calls.argsFor(0)
expect(args[0]).toBe('/teachers/classes')
it 'sets a teacher role', ->
request = _.last(view.trialRequest.fakeRequests)
request.respondWith({
status: 201
responseText: JSON.stringify(_.extend({_id:'fraghlarghl'}, JSON.parse(request.params)))
})
expect(me.get('role')).toBe(successForm.role.toLowerCase())
describe 'submitting the form without school', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('form')
formData = _.omit(successForm, ['organization'])
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include school setting', ->
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.organization).toBeUndefined()
expect(attrs.properties?.district).toEqual('District')
describe 'submitting the form without district', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('form')
formData = _.omit(successForm, ['district'])
forms.objectToForm(form, formData)
form.submit()
it 'displays a validation error on district and not school', ->
expect(view.$('#organization-control').parent().hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').parent().hasClass('has-error')).toEqual(true)
describe 'submitting the form district set to n/a', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('form')
formData = _.omit(successForm, ['organization'])
formData.district = 'N/A'
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include district setting', ->
expect(view.$('#organization-control').parent().hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').parent().hasClass('has-error')).toEqual(false)
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.district).toBeUndefined()
| true | ConvertToTeacherAccountView = require 'views/teachers/ConvertToTeacherAccountView'
storage = require 'core/storage'
forms = require 'core/forms'
describe '/teachers/update-account', ->
describe 'when logged out', ->
it 'redirects to /teachers/signup', ->
spyOn(me, 'isAnonymous').and.returnValue(true)
spyOn(application.router, 'navigate')
Backbone.history.loadUrl('/teachers/update-account')
expect(application.router.navigate.calls.count()).toBe(1)
args = application.router.navigate.calls.argsFor(0)
expect(args[0]).toBe('/teachers/signup')
describe 'when logged in', ->
it 'displays ConvertToTeacherAccountView', ->
spyOn(me, 'isAnonymous').and.returnValue(false)
spyOn(me, 'isTeacher').and.returnValue(false)
spyOn(application.router, 'routeDirectly')
Backbone.history.loadUrl('/teachers/update-account')
expect(application.router.routeDirectly.calls.count()).toBe(1)
args = application.router.routeDirectly.calls.argsFor(0)
expect(args[0]).toBe('teachers/ConvertToTeacherAccountView')
describe 'ConvertToTeacherAccountView (/teachers/update-account)', ->
view = null
successForm = {
phoneNumber: '555-555-5555'
role: 'Teacher'
organization: 'School'
district: 'District'
city: 'Springfield'
state: 'AA'
country: 'asdf'
numStudents: '1-10'
educationLevel: ['Middle']
firstName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
}
beforeEach ->
spyOn(application.router, 'navigate')
me.clear()
me.set({
_id: '1234'
anonymous: false
email: 'PI:EMAIL:<EMAIL>END_PI'
name: 'Existing User'
})
me._revertAttributes = {}
view = new ConvertToTeacherAccountView()
view.render()
jasmine.demoEl(view.$el)
spyOn(storage, 'load').and.returnValue({ lastName: 'Saved Changes' })
afterEach (done) ->
_.defer(done) # let everything finish loading, keep navigate spied on
describe 'when the form is unchanged', ->
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
describe 'when the form has changed but is not submitted', ->
beforeEach ->
view.$el.find('form').trigger('change')
it 'prevents navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeTruthy()
describe 'when the user already has a TrialRequest and is a teacher', ->
beforeEach (done) ->
spyOn(me, 'isTeacher').and.returnValue(true)
_.last(view.trialRequests.fakeRequests).respondWith({
status: 200
responseText: JSON.stringify([{
_id: '1'
properties: {
firstName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
}
}])
})
_.defer done # Let SuperModel finish
# TODO: re-enable when student and teacher areas are enforced
xit 'redirects to /teachers/courses', ->
expect(application.router.navigate).toHaveBeenCalled()
args = application.router.navigate.calls.argsFor(0)
expect(args[0]).toBe('/teachers/courses')
describe 'when the user has role "student"', ->
beforeEach ->
me.set('role', 'student')
_.last(view.trialRequests.fakeRequests).respondWith({ status: 200, responseText: JSON.stringify('[]') })
view.render()
it 'shows a warning that they will convert to a teacher account', ->
expect(view.$('#conversion-warning').length).toBe(1)
# TODO: Figure out how to test this
# describe 'the warning', ->
# it 'includes a learn more link which opens a modal with more info'
describe 'submitting the form', ->
beforeEach ->
form = view.$('form')
forms.objectToForm(form, successForm, {overwriteExisting: true})
spyOn(view, 'openModalView')
form.submit()
it 'requires confirmation', ->
expect(view.trialRequest.fakeRequests.length).toBe(0)
confirmModal = view.openModalView.calls.argsFor(0)[0]
confirmModal.trigger 'confirm'
request = _.last(view.trialRequest.fakeRequests)
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
describe '"Log out" link', ->
beforeEach ->
_.last(view.trialRequests.fakeRequests).respondWith({ status: 200, responseText: JSON.stringify('[]') })
it 'logs out the user and redirects them to /teachers/signup', ->
spyOn(me, 'logout')
view.$('#logout-link').click()
expect(me.logout).toHaveBeenCalled()
describe 'submitting the form', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
_.last(view.trialRequests.fakeRequests).respondWith({ status: 200, responseText: JSON.stringify('[]') })
form = view.$('form')
forms.objectToForm(form, successForm, {overwriteExisting: true})
form.submit()
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
it 'creates a new TrialRequest with the information', ->
request = _.last(view.trialRequest.fakeRequests)
expect(request).toBeTruthy()
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.firstName).toBe('Mr')
expect(attrs.properties?.siteOrigin).toBe('convert teacher')
expect(attrs.properties?.email).toBe('PI:EMAIL:<EMAIL>END_PI')
it 'redirects to /teachers/classes', ->
request = _.last(view.trialRequest.fakeRequests)
request.respondWith({
status: 201
responseText: JSON.stringify(_.extend({_id:'fraghlarghl'}, JSON.parse(request.params)))
})
expect(application.router.navigate).toHaveBeenCalled()
args = application.router.navigate.calls.argsFor(0)
expect(args[0]).toBe('/teachers/classes')
it 'sets a teacher role', ->
request = _.last(view.trialRequest.fakeRequests)
request.respondWith({
status: 201
responseText: JSON.stringify(_.extend({_id:'fraghlarghl'}, JSON.parse(request.params)))
})
expect(me.get('role')).toBe(successForm.role.toLowerCase())
describe 'submitting the form without school', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('form')
formData = _.omit(successForm, ['organization'])
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include school setting', ->
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.organization).toBeUndefined()
expect(attrs.properties?.district).toEqual('District')
describe 'submitting the form without district', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('form')
formData = _.omit(successForm, ['district'])
forms.objectToForm(form, formData)
form.submit()
it 'displays a validation error on district and not school', ->
expect(view.$('#organization-control').parent().hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').parent().hasClass('has-error')).toEqual(true)
describe 'submitting the form district set to n/a', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('form')
formData = _.omit(successForm, ['organization'])
formData.district = 'N/A'
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include district setting', ->
expect(view.$('#organization-control').parent().hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').parent().hasClass('has-error')).toEqual(false)
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.district).toBeUndefined()
|
[
{
"context": "http://maps.googleapis.com/maps/api/staticmap?key=AIzaSyCmfR2XMO4sljkBUtkxrE3aizEn9AL39zw&size=640x480&path=weight:4%7Ccolor:red%7Cenc:#{en",
"end": 346,
"score": 0.99974524974823,
"start": 307,
"tag": "KEY",
"value": "AIzaSyCmfR2XMO4sljkBUtkxrE3aizEn9AL39zw"
},
{
"cont... | assets/js/models/Activity.coffee | jsilland/delta | 0 | Soliton.module 'Soliton.Cotton.Models'
class Soliton.Cotton.Models.Activity extends Backbone.Model
url: ->
"/strava/activities/#{@id}"
fullAthleteName: ->
"#{@get('athlete').firstname} #{@get('athlete').lastname}"
largeMapUrl: ->
"http://maps.googleapis.com/maps/api/staticmap?key=AIzaSyCmfR2XMO4sljkBUtkxrE3aizEn9AL39zw&size=640x480&path=weight:4%7Ccolor:red%7Cenc:#{encodeURIComponent(@get('map').summary_polyline)}"
mapUrl: ->
"http://maps.googleapis.com/maps/api/staticmap?key=AIzaSyCmfR2XMO4sljkBUtkxrE3aizEn9AL39zw&size=640x284&path=weight:4%7Ccolor:red%7Cenc:#{encodeURIComponent(@get('map').summary_polyline)}"
littleMapUrl: ->
"http://maps.googleapis.com/maps/api/staticmap?key=AIzaSyCmfR2XMO4sljkBUtkxrE3aizEn9AL39zw&size=320x284&path=weight:4%7Ccolor:red%7Cenc:#{encodeURIComponent(@get('map').summary_polyline)}"
isInteresting: ->
lame = @get('commute') || @get('trainer') || @get('manual')
long = (@get('type') == 'Run' && @get('distance') > 5000) || (@get('type') == 'Ride' && @get('distance') > 15000)
!lame && long | 110314 | Soliton.module 'Soliton.Cotton.Models'
class Soliton.Cotton.Models.Activity extends Backbone.Model
url: ->
"/strava/activities/#{@id}"
fullAthleteName: ->
"#{@get('athlete').firstname} #{@get('athlete').lastname}"
largeMapUrl: ->
"http://maps.googleapis.com/maps/api/staticmap?key=<KEY>&size=640x480&path=weight:4%7Ccolor:red%7Cenc:#{encodeURIComponent(@get('map').summary_polyline)}"
mapUrl: ->
"http://maps.googleapis.com/maps/api/staticmap?key=<KEY>&size=640x284&path=weight:4%7Ccolor:red%7Cenc:#{encodeURIComponent(@get('map').summary_polyline)}"
littleMapUrl: ->
"http://maps.googleapis.com/maps/api/staticmap?key=<KEY>&size=320x284&path=weight:4%7Ccolor:red%7Cenc:#{encodeURIComponent(@get('map').summary_polyline)}"
isInteresting: ->
lame = @get('commute') || @get('trainer') || @get('manual')
long = (@get('type') == 'Run' && @get('distance') > 5000) || (@get('type') == 'Ride' && @get('distance') > 15000)
!lame && long | true | Soliton.module 'Soliton.Cotton.Models'
class Soliton.Cotton.Models.Activity extends Backbone.Model
url: ->
"/strava/activities/#{@id}"
fullAthleteName: ->
"#{@get('athlete').firstname} #{@get('athlete').lastname}"
largeMapUrl: ->
"http://maps.googleapis.com/maps/api/staticmap?key=PI:KEY:<KEY>END_PI&size=640x480&path=weight:4%7Ccolor:red%7Cenc:#{encodeURIComponent(@get('map').summary_polyline)}"
mapUrl: ->
"http://maps.googleapis.com/maps/api/staticmap?key=PI:KEY:<KEY>END_PI&size=640x284&path=weight:4%7Ccolor:red%7Cenc:#{encodeURIComponent(@get('map').summary_polyline)}"
littleMapUrl: ->
"http://maps.googleapis.com/maps/api/staticmap?key=PI:KEY:<KEY>END_PI&size=320x284&path=weight:4%7Ccolor:red%7Cenc:#{encodeURIComponent(@get('map').summary_polyline)}"
isInteresting: ->
lame = @get('commute') || @get('trainer') || @get('manual')
long = (@get('type') == 'Run' && @get('distance') > 5000) || (@get('type') == 'Ride' && @get('distance') > 15000)
!lame && long |
[
{
"context": "tory: configuration.buildDir)\n keypath = keygen('signature/')\n fs.readFile keypath, (err, data) ->\n crx.",
"end": 700,
"score": 0.6712501645088196,
"start": 691,
"tag": "KEY",
"value": "signature"
}
] | compilation/script-package.coffee | romanornr/ledger-wallet-crw | 0 |
archiver = require 'archiver'
zip = archiver 'zip'
fs = require 'fs'
{ensureDistDir, ensureSignatureDir} = require './utils'
ChromeExtension = require 'crx'
rsa = require 'node-rsa'
path = require 'path'
join = path.join
resolve = path.resolve
Q = require 'q'
keygen = (dir) ->
dir = resolve dir
keyPath = join dir, "key.pem"
unless fs.existsSync keyPath
key = new rsa b: 1024
fs.writeFileSync keyPath, key.exportKey('pkcs1-private-pem')
keyPath
module.exports = (configuration) ->
defer = Q.defer()
ensureDistDir()
ensureSignatureDir()
crx = new ChromeExtension(rootDirectory: configuration.buildDir)
keypath = keygen('signature/')
fs.readFile keypath, (err, data) ->
crx.privateKey = data
crx.load()
.then ->
crx.loadContents()
.then (archiveBuffer) ->
crx.pack archiveBuffer
.then (crxBuffer) ->
manifest = require "../#{configuration.buildDir}/manifest.json"
fs.writeFileSync("dist/ledger-wallet-#{manifest.version}.crx", crxBuffer)
defer.resolve()
crx.destroy()
return
defer.promise
| 225455 |
archiver = require 'archiver'
zip = archiver 'zip'
fs = require 'fs'
{ensureDistDir, ensureSignatureDir} = require './utils'
ChromeExtension = require 'crx'
rsa = require 'node-rsa'
path = require 'path'
join = path.join
resolve = path.resolve
Q = require 'q'
keygen = (dir) ->
dir = resolve dir
keyPath = join dir, "key.pem"
unless fs.existsSync keyPath
key = new rsa b: 1024
fs.writeFileSync keyPath, key.exportKey('pkcs1-private-pem')
keyPath
module.exports = (configuration) ->
defer = Q.defer()
ensureDistDir()
ensureSignatureDir()
crx = new ChromeExtension(rootDirectory: configuration.buildDir)
keypath = keygen('<KEY>/')
fs.readFile keypath, (err, data) ->
crx.privateKey = data
crx.load()
.then ->
crx.loadContents()
.then (archiveBuffer) ->
crx.pack archiveBuffer
.then (crxBuffer) ->
manifest = require "../#{configuration.buildDir}/manifest.json"
fs.writeFileSync("dist/ledger-wallet-#{manifest.version}.crx", crxBuffer)
defer.resolve()
crx.destroy()
return
defer.promise
| true |
archiver = require 'archiver'
zip = archiver 'zip'
fs = require 'fs'
{ensureDistDir, ensureSignatureDir} = require './utils'
ChromeExtension = require 'crx'
rsa = require 'node-rsa'
path = require 'path'
join = path.join
resolve = path.resolve
Q = require 'q'
keygen = (dir) ->
dir = resolve dir
keyPath = join dir, "key.pem"
unless fs.existsSync keyPath
key = new rsa b: 1024
fs.writeFileSync keyPath, key.exportKey('pkcs1-private-pem')
keyPath
module.exports = (configuration) ->
defer = Q.defer()
ensureDistDir()
ensureSignatureDir()
crx = new ChromeExtension(rootDirectory: configuration.buildDir)
keypath = keygen('PI:KEY:<KEY>END_PI/')
fs.readFile keypath, (err, data) ->
crx.privateKey = data
crx.load()
.then ->
crx.loadContents()
.then (archiveBuffer) ->
crx.pack archiveBuffer
.then (crxBuffer) ->
manifest = require "../#{configuration.buildDir}/manifest.json"
fs.writeFileSync("dist/ledger-wallet-#{manifest.version}.crx", crxBuffer)
defer.resolve()
crx.destroy()
return
defer.promise
|
[
{
"context": "om = (->\n seed = 49734321\n ->\n \n # Robert Jenkins' 32 bit integer hash function.\n seed = ((see",
"end": 3149,
"score": 0.999686598777771,
"start": 3135,
"tag": "NAME",
"value": "Robert Jenkins"
}
] | deps/v8/test/js-perf-test/base.coffee | lxe/io.coffee | 0 | # Copyright 2014 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Performance.now is used in latency benchmarks, the fallback is Date.now.
# Simple framework for running the benchmark suites and
# computing a score based on the timing measurements.
# A benchmark has a name (string) and a function that will be run to
# do the performance measurement. The optional setup and tearDown
# arguments are functions that will be invoked before and after
# running the benchmark, but the running time of these functions will
# not be accounted for in the benchmark score.
Benchmark = (name, doWarmup, doDeterministic, deterministicIterations, run, setup, tearDown, rmsResult, minIterations) ->
@name = name
@doWarmup = doWarmup
@doDeterministic = doDeterministic
@deterministicIterations = deterministicIterations
@run = run
@Setup = (if setup then setup else ->
)
@TearDown = (if tearDown then tearDown else ->
)
@rmsResult = (if rmsResult then rmsResult else null)
@minIterations = (if minIterations then minIterations else 32)
return
# Benchmark results hold the benchmark and the measured time used to
# run the benchmark. The benchmark score is computed later once a
# full benchmark suite has run to completion. If latency is set to 0
# then there is no latency score for this benchmark.
BenchmarkResult = (benchmark, time, latency) ->
@benchmark = benchmark
@time = time
@latency = latency
return
# Automatically convert results to numbers. Used by the geometric
# mean computation.
# Suites of benchmarks consist of a name and the set of benchmarks in
# addition to the reference timing that the final score will be based
# on. This way, all scores are relative to a reference run and higher
# scores implies better performance.
BenchmarkSuite = (name, reference, benchmarks) ->
@name = name
@reference = reference
@benchmarks = benchmarks
BenchmarkSuite.suites.push this
return
performance = performance or {}
performance.now = (->
performance.now or performance.mozNow or performance.msNow or performance.oNow or performance.webkitNow or Date.now
)()
BenchmarkResult::valueOf = ->
@time
# Keep track of all declared benchmark suites.
BenchmarkSuite.suites = []
# Scores are not comparable across versions. Bump the version if
# you're making changes that will affect that scores, e.g. if you add
# a new benchmark or change an existing one.
BenchmarkSuite.version = "1"
# Defines global benchsuite running mode that overrides benchmark suite
# behavior. Intended to be set by the benchmark driver. Undefined
# values here allow a benchmark to define behaviour itself.
BenchmarkSuite.config =
doWarmup: `undefined`
doDeterministic: `undefined`
# Override the alert function to throw an exception instead.
alert = (s) ->
throw "Alert called with argument: " + sreturn
# To make the benchmark results predictable, we replace Math.random
# with a 100% deterministic alternative.
BenchmarkSuite.ResetRNG = ->
Math.random = (->
seed = 49734321
->
# Robert Jenkins' 32 bit integer hash function.
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff
(seed & 0xfffffff) / 0x10000000
)()
return
# Runs all registered benchmark suites and optionally yields between
# each individual benchmark to avoid running for too long in the
# context of browsers. Once done, the final score is reported to the
# runner.
BenchmarkSuite.RunSuites = (runner, skipBenchmarks) ->
RunStep = ->
while continuation or index < length
if continuation
continuation = continuation()
else
suite = suites[index++]
runner.NotifyStart suite.name if runner.NotifyStart
if skipBenchmarks.indexOf(suite.name) > -1
suite.NotifySkipped runner
else
continuation = suite.RunStep(runner)
if continuation and typeof window isnt "undefined" and window.setTimeout
window.setTimeout RunStep, 25
return
# show final result
if runner.NotifyScore
score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores)
formatted = BenchmarkSuite.FormatScore(100 * score)
runner.NotifyScore formatted
return
skipBenchmarks = (if typeof skipBenchmarks is "undefined" then [] else skipBenchmarks)
continuation = null
suites = BenchmarkSuite.suites
length = suites.length
BenchmarkSuite.scores = []
index = 0
RunStep()
return
# Counts the total number of registered benchmarks. Useful for
# showing progress as a percentage.
BenchmarkSuite.CountBenchmarks = ->
result = 0
suites = BenchmarkSuite.suites
i = 0
while i < suites.length
result += suites[i].benchmarks.length
i++
result
# Computes the geometric mean of a set of numbers.
BenchmarkSuite.GeometricMean = (numbers) ->
log = 0
i = 0
while i < numbers.length
log += Math.log(numbers[i])
i++
Math.pow Math.E, log / numbers.length
# Computes the geometric mean of a set of throughput time measurements.
BenchmarkSuite.GeometricMeanTime = (measurements) ->
log = 0
i = 0
while i < measurements.length
log += Math.log(measurements[i].time)
i++
Math.pow Math.E, log / measurements.length
# Computes the geometric mean of a set of rms measurements.
BenchmarkSuite.GeometricMeanLatency = (measurements) ->
log = 0
hasLatencyResult = false
i = 0
while i < measurements.length
unless measurements[i].latency is 0
log += Math.log(measurements[i].latency)
hasLatencyResult = true
i++
if hasLatencyResult
Math.pow Math.E, log / measurements.length
else
0
# Converts a score value to a string with at least three significant
# digits.
BenchmarkSuite.FormatScore = (value) ->
if value > 100
value.toFixed 0
else
value.toPrecision 3
# Notifies the runner that we're done running a single benchmark in
# the benchmark suite. This can be useful to report progress.
BenchmarkSuite::NotifyStep = (result) ->
@results.push result
@runner.NotifyStep result.benchmark.name if @runner.NotifyStep
return
# Notifies the runner that we're done with running a suite and that
# we have a result which can be reported to the user if needed.
BenchmarkSuite::NotifyResult = ->
mean = BenchmarkSuite.GeometricMeanTime(@results)
score = @reference[0] / mean
BenchmarkSuite.scores.push score
if @runner.NotifyResult
formatted = BenchmarkSuite.FormatScore(100 * score)
@runner.NotifyResult @name, formatted
if @reference.length is 2
meanLatency = BenchmarkSuite.GeometricMeanLatency(@results)
unless meanLatency is 0
scoreLatency = @reference[1] / meanLatency
BenchmarkSuite.scores.push scoreLatency
if @runner.NotifyResult
formattedLatency = BenchmarkSuite.FormatScore(100 * scoreLatency)
@runner.NotifyResult @name + "Latency", formattedLatency
return
BenchmarkSuite::NotifySkipped = (runner) ->
BenchmarkSuite.scores.push 1 # push default reference score.
runner.NotifyResult @name, "Skipped" if runner.NotifyResult
return
# Notifies the runner that running a benchmark resulted in an error.
BenchmarkSuite::NotifyError = (error) ->
@runner.NotifyError @name, error if @runner.NotifyError
@runner.NotifyStep @name if @runner.NotifyStep
return
# Runs a single benchmark for at least a second and computes the
# average time it takes to run a single iteration.
BenchmarkSuite::RunSingleBenchmark = (benchmark, data) ->
Measure = (data) ->
elapsed = 0
start = new Date()
# Run either for 1 second or for the number of iterations specified
# by minIterations, depending on the config flag doDeterministic.
i = 0
while ((if doDeterministic then i < benchmark.deterministicIterations else elapsed < 1000))
benchmark.run()
elapsed = new Date() - start
i++
if data?
data.runs += i
data.elapsed += elapsed
return
config = BenchmarkSuite.config
doWarmup = (if config.doWarmup isnt `undefined` then config.doWarmup else benchmark.doWarmup)
doDeterministic = (if config.doDeterministic isnt `undefined` then config.doDeterministic else benchmark.doDeterministic)
# Sets up data in order to skip or not the warmup phase.
if not doWarmup and not data?
data =
runs: 0
elapsed: 0
unless data?
Measure null
runs: 0
elapsed: 0
else
Measure data
# If we've run too few iterations, we continue for another second.
return data if data.runs < benchmark.minIterations
usec = (data.elapsed * 1000) / data.runs
rms = (if (benchmark.rmsResult?) then benchmark.rmsResult() else 0)
@NotifyStep new BenchmarkResult(benchmark, usec, rms)
null
# This function starts running a suite, but stops between each
# individual benchmark in the suite and returns a continuation
# function which can be invoked to run the next benchmark. Once the
# last benchmark has been executed, null is returned.
BenchmarkSuite::RunStep = (runner) ->
# Run the setup, the actual benchmark, and the tear down in three
# separate steps to allow the framework to yield between any of the
# steps.
RunNextSetup = ->
if index < length
try
suite.benchmarks[index].Setup()
catch e
suite.NotifyError e
return null
return RunNextBenchmark
suite.NotifyResult()
null
RunNextBenchmark = ->
try
data = suite.RunSingleBenchmark(suite.benchmarks[index], data)
catch e
suite.NotifyError e
return null
# If data is null, we're done with this benchmark.
(if (not (data?)) then RunNextTearDown else RunNextBenchmark())
RunNextTearDown = ->
try
suite.benchmarks[index++].TearDown()
catch e
suite.NotifyError e
return null
RunNextSetup
BenchmarkSuite.ResetRNG()
@results = []
@runner = runner
length = @benchmarks.length
index = 0
suite = this
data = undefined
# Start out running the setup.
RunNextSetup()
| 152181 | # Copyright 2014 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Performance.now is used in latency benchmarks, the fallback is Date.now.
# Simple framework for running the benchmark suites and
# computing a score based on the timing measurements.
# A benchmark has a name (string) and a function that will be run to
# do the performance measurement. The optional setup and tearDown
# arguments are functions that will be invoked before and after
# running the benchmark, but the running time of these functions will
# not be accounted for in the benchmark score.
Benchmark = (name, doWarmup, doDeterministic, deterministicIterations, run, setup, tearDown, rmsResult, minIterations) ->
@name = name
@doWarmup = doWarmup
@doDeterministic = doDeterministic
@deterministicIterations = deterministicIterations
@run = run
@Setup = (if setup then setup else ->
)
@TearDown = (if tearDown then tearDown else ->
)
@rmsResult = (if rmsResult then rmsResult else null)
@minIterations = (if minIterations then minIterations else 32)
return
# Benchmark results hold the benchmark and the measured time used to
# run the benchmark. The benchmark score is computed later once a
# full benchmark suite has run to completion. If latency is set to 0
# then there is no latency score for this benchmark.
BenchmarkResult = (benchmark, time, latency) ->
@benchmark = benchmark
@time = time
@latency = latency
return
# Automatically convert results to numbers. Used by the geometric
# mean computation.
# Suites of benchmarks consist of a name and the set of benchmarks in
# addition to the reference timing that the final score will be based
# on. This way, all scores are relative to a reference run and higher
# scores implies better performance.
BenchmarkSuite = (name, reference, benchmarks) ->
@name = name
@reference = reference
@benchmarks = benchmarks
BenchmarkSuite.suites.push this
return
performance = performance or {}
performance.now = (->
performance.now or performance.mozNow or performance.msNow or performance.oNow or performance.webkitNow or Date.now
)()
BenchmarkResult::valueOf = ->
@time
# Keep track of all declared benchmark suites.
BenchmarkSuite.suites = []
# Scores are not comparable across versions. Bump the version if
# you're making changes that will affect that scores, e.g. if you add
# a new benchmark or change an existing one.
BenchmarkSuite.version = "1"
# Defines global benchsuite running mode that overrides benchmark suite
# behavior. Intended to be set by the benchmark driver. Undefined
# values here allow a benchmark to define behaviour itself.
BenchmarkSuite.config =
doWarmup: `undefined`
doDeterministic: `undefined`
# Override the alert function to throw an exception instead.
alert = (s) ->
throw "Alert called with argument: " + sreturn
# To make the benchmark results predictable, we replace Math.random
# with a 100% deterministic alternative.
BenchmarkSuite.ResetRNG = ->
Math.random = (->
seed = 49734321
->
# <NAME>' 32 bit integer hash function.
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff
(seed & 0xfffffff) / 0x10000000
)()
return
# Runs all registered benchmark suites and optionally yields between
# each individual benchmark to avoid running for too long in the
# context of browsers. Once done, the final score is reported to the
# runner.
BenchmarkSuite.RunSuites = (runner, skipBenchmarks) ->
RunStep = ->
while continuation or index < length
if continuation
continuation = continuation()
else
suite = suites[index++]
runner.NotifyStart suite.name if runner.NotifyStart
if skipBenchmarks.indexOf(suite.name) > -1
suite.NotifySkipped runner
else
continuation = suite.RunStep(runner)
if continuation and typeof window isnt "undefined" and window.setTimeout
window.setTimeout RunStep, 25
return
# show final result
if runner.NotifyScore
score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores)
formatted = BenchmarkSuite.FormatScore(100 * score)
runner.NotifyScore formatted
return
skipBenchmarks = (if typeof skipBenchmarks is "undefined" then [] else skipBenchmarks)
continuation = null
suites = BenchmarkSuite.suites
length = suites.length
BenchmarkSuite.scores = []
index = 0
RunStep()
return
# Counts the total number of registered benchmarks. Useful for
# showing progress as a percentage.
BenchmarkSuite.CountBenchmarks = ->
result = 0
suites = BenchmarkSuite.suites
i = 0
while i < suites.length
result += suites[i].benchmarks.length
i++
result
# Computes the geometric mean of a set of numbers.
BenchmarkSuite.GeometricMean = (numbers) ->
log = 0
i = 0
while i < numbers.length
log += Math.log(numbers[i])
i++
Math.pow Math.E, log / numbers.length
# Computes the geometric mean of a set of throughput time measurements.
BenchmarkSuite.GeometricMeanTime = (measurements) ->
log = 0
i = 0
while i < measurements.length
log += Math.log(measurements[i].time)
i++
Math.pow Math.E, log / measurements.length
# Computes the geometric mean of a set of rms measurements.
BenchmarkSuite.GeometricMeanLatency = (measurements) ->
log = 0
hasLatencyResult = false
i = 0
while i < measurements.length
unless measurements[i].latency is 0
log += Math.log(measurements[i].latency)
hasLatencyResult = true
i++
if hasLatencyResult
Math.pow Math.E, log / measurements.length
else
0
# Converts a score value to a string with at least three significant
# digits.
BenchmarkSuite.FormatScore = (value) ->
if value > 100
value.toFixed 0
else
value.toPrecision 3
# Notifies the runner that we're done running a single benchmark in
# the benchmark suite. This can be useful to report progress.
BenchmarkSuite::NotifyStep = (result) ->
@results.push result
@runner.NotifyStep result.benchmark.name if @runner.NotifyStep
return
# Notifies the runner that we're done with running a suite and that
# we have a result which can be reported to the user if needed.
BenchmarkSuite::NotifyResult = ->
mean = BenchmarkSuite.GeometricMeanTime(@results)
score = @reference[0] / mean
BenchmarkSuite.scores.push score
if @runner.NotifyResult
formatted = BenchmarkSuite.FormatScore(100 * score)
@runner.NotifyResult @name, formatted
if @reference.length is 2
meanLatency = BenchmarkSuite.GeometricMeanLatency(@results)
unless meanLatency is 0
scoreLatency = @reference[1] / meanLatency
BenchmarkSuite.scores.push scoreLatency
if @runner.NotifyResult
formattedLatency = BenchmarkSuite.FormatScore(100 * scoreLatency)
@runner.NotifyResult @name + "Latency", formattedLatency
return
BenchmarkSuite::NotifySkipped = (runner) ->
BenchmarkSuite.scores.push 1 # push default reference score.
runner.NotifyResult @name, "Skipped" if runner.NotifyResult
return
# Notifies the runner that running a benchmark resulted in an error.
BenchmarkSuite::NotifyError = (error) ->
@runner.NotifyError @name, error if @runner.NotifyError
@runner.NotifyStep @name if @runner.NotifyStep
return
# Runs a single benchmark for at least a second and computes the
# average time it takes to run a single iteration.
BenchmarkSuite::RunSingleBenchmark = (benchmark, data) ->
Measure = (data) ->
elapsed = 0
start = new Date()
# Run either for 1 second or for the number of iterations specified
# by minIterations, depending on the config flag doDeterministic.
i = 0
while ((if doDeterministic then i < benchmark.deterministicIterations else elapsed < 1000))
benchmark.run()
elapsed = new Date() - start
i++
if data?
data.runs += i
data.elapsed += elapsed
return
config = BenchmarkSuite.config
doWarmup = (if config.doWarmup isnt `undefined` then config.doWarmup else benchmark.doWarmup)
doDeterministic = (if config.doDeterministic isnt `undefined` then config.doDeterministic else benchmark.doDeterministic)
# Sets up data in order to skip or not the warmup phase.
if not doWarmup and not data?
data =
runs: 0
elapsed: 0
unless data?
Measure null
runs: 0
elapsed: 0
else
Measure data
# If we've run too few iterations, we continue for another second.
return data if data.runs < benchmark.minIterations
usec = (data.elapsed * 1000) / data.runs
rms = (if (benchmark.rmsResult?) then benchmark.rmsResult() else 0)
@NotifyStep new BenchmarkResult(benchmark, usec, rms)
null
# This function starts running a suite, but stops between each
# individual benchmark in the suite and returns a continuation
# function which can be invoked to run the next benchmark. Once the
# last benchmark has been executed, null is returned.
BenchmarkSuite::RunStep = (runner) ->
# Run the setup, the actual benchmark, and the tear down in three
# separate steps to allow the framework to yield between any of the
# steps.
RunNextSetup = ->
if index < length
try
suite.benchmarks[index].Setup()
catch e
suite.NotifyError e
return null
return RunNextBenchmark
suite.NotifyResult()
null
RunNextBenchmark = ->
try
data = suite.RunSingleBenchmark(suite.benchmarks[index], data)
catch e
suite.NotifyError e
return null
# If data is null, we're done with this benchmark.
(if (not (data?)) then RunNextTearDown else RunNextBenchmark())
RunNextTearDown = ->
try
suite.benchmarks[index++].TearDown()
catch e
suite.NotifyError e
return null
RunNextSetup
BenchmarkSuite.ResetRNG()
@results = []
@runner = runner
length = @benchmarks.length
index = 0
suite = this
data = undefined
# Start out running the setup.
RunNextSetup()
| true | # Copyright 2014 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Performance.now is used in latency benchmarks, the fallback is Date.now.
# Simple framework for running the benchmark suites and
# computing a score based on the timing measurements.
# A benchmark has a name (string) and a function that will be run to
# do the performance measurement. The optional setup and tearDown
# arguments are functions that will be invoked before and after
# running the benchmark, but the running time of these functions will
# not be accounted for in the benchmark score.
Benchmark = (name, doWarmup, doDeterministic, deterministicIterations, run, setup, tearDown, rmsResult, minIterations) ->
@name = name
@doWarmup = doWarmup
@doDeterministic = doDeterministic
@deterministicIterations = deterministicIterations
@run = run
@Setup = (if setup then setup else ->
)
@TearDown = (if tearDown then tearDown else ->
)
@rmsResult = (if rmsResult then rmsResult else null)
@minIterations = (if minIterations then minIterations else 32)
return
# Benchmark results hold the benchmark and the measured time used to
# run the benchmark. The benchmark score is computed later once a
# full benchmark suite has run to completion. If latency is set to 0
# then there is no latency score for this benchmark.
BenchmarkResult = (benchmark, time, latency) ->
@benchmark = benchmark
@time = time
@latency = latency
return
# Automatically convert results to numbers. Used by the geometric
# mean computation.
# Suites of benchmarks consist of a name and the set of benchmarks in
# addition to the reference timing that the final score will be based
# on. This way, all scores are relative to a reference run and higher
# scores implies better performance.
BenchmarkSuite = (name, reference, benchmarks) ->
@name = name
@reference = reference
@benchmarks = benchmarks
BenchmarkSuite.suites.push this
return
performance = performance or {}
performance.now = (->
performance.now or performance.mozNow or performance.msNow or performance.oNow or performance.webkitNow or Date.now
)()
BenchmarkResult::valueOf = ->
@time
# Keep track of all declared benchmark suites.
BenchmarkSuite.suites = []
# Scores are not comparable across versions. Bump the version if
# you're making changes that will affect that scores, e.g. if you add
# a new benchmark or change an existing one.
BenchmarkSuite.version = "1"
# Defines global benchsuite running mode that overrides benchmark suite
# behavior. Intended to be set by the benchmark driver. Undefined
# values here allow a benchmark to define behaviour itself.
BenchmarkSuite.config =
doWarmup: `undefined`
doDeterministic: `undefined`
# Override the alert function to throw an exception instead.
alert = (s) ->
throw "Alert called with argument: " + sreturn
# To make the benchmark results predictable, we replace Math.random
# with a 100% deterministic alternative.
BenchmarkSuite.ResetRNG = ->
Math.random = (->
seed = 49734321
->
# PI:NAME:<NAME>END_PI' 32 bit integer hash function.
seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff
seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff
seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff
seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff
seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff
seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff
(seed & 0xfffffff) / 0x10000000
)()
return
# Runs all registered benchmark suites and optionally yields between
# each individual benchmark to avoid running for too long in the
# context of browsers. Once done, the final score is reported to the
# runner.
BenchmarkSuite.RunSuites = (runner, skipBenchmarks) ->
RunStep = ->
while continuation or index < length
if continuation
continuation = continuation()
else
suite = suites[index++]
runner.NotifyStart suite.name if runner.NotifyStart
if skipBenchmarks.indexOf(suite.name) > -1
suite.NotifySkipped runner
else
continuation = suite.RunStep(runner)
if continuation and typeof window isnt "undefined" and window.setTimeout
window.setTimeout RunStep, 25
return
# show final result
if runner.NotifyScore
score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores)
formatted = BenchmarkSuite.FormatScore(100 * score)
runner.NotifyScore formatted
return
skipBenchmarks = (if typeof skipBenchmarks is "undefined" then [] else skipBenchmarks)
continuation = null
suites = BenchmarkSuite.suites
length = suites.length
BenchmarkSuite.scores = []
index = 0
RunStep()
return
# Counts the total number of registered benchmarks. Useful for
# showing progress as a percentage.
BenchmarkSuite.CountBenchmarks = ->
result = 0
suites = BenchmarkSuite.suites
i = 0
while i < suites.length
result += suites[i].benchmarks.length
i++
result
# Computes the geometric mean of a set of numbers.
BenchmarkSuite.GeometricMean = (numbers) ->
log = 0
i = 0
while i < numbers.length
log += Math.log(numbers[i])
i++
Math.pow Math.E, log / numbers.length
# Computes the geometric mean of a set of throughput time measurements.
BenchmarkSuite.GeometricMeanTime = (measurements) ->
log = 0
i = 0
while i < measurements.length
log += Math.log(measurements[i].time)
i++
Math.pow Math.E, log / measurements.length
# Computes the geometric mean of a set of rms measurements.
BenchmarkSuite.GeometricMeanLatency = (measurements) ->
log = 0
hasLatencyResult = false
i = 0
while i < measurements.length
unless measurements[i].latency is 0
log += Math.log(measurements[i].latency)
hasLatencyResult = true
i++
if hasLatencyResult
Math.pow Math.E, log / measurements.length
else
0
# Converts a score value to a string with at least three significant
# digits.
BenchmarkSuite.FormatScore = (value) ->
if value > 100
value.toFixed 0
else
value.toPrecision 3
# Notifies the runner that we're done running a single benchmark in
# the benchmark suite. This can be useful to report progress.
BenchmarkSuite::NotifyStep = (result) ->
@results.push result
@runner.NotifyStep result.benchmark.name if @runner.NotifyStep
return
# Notifies the runner that we're done with running a suite and that
# we have a result which can be reported to the user if needed.
BenchmarkSuite::NotifyResult = ->
mean = BenchmarkSuite.GeometricMeanTime(@results)
score = @reference[0] / mean
BenchmarkSuite.scores.push score
if @runner.NotifyResult
formatted = BenchmarkSuite.FormatScore(100 * score)
@runner.NotifyResult @name, formatted
if @reference.length is 2
meanLatency = BenchmarkSuite.GeometricMeanLatency(@results)
unless meanLatency is 0
scoreLatency = @reference[1] / meanLatency
BenchmarkSuite.scores.push scoreLatency
if @runner.NotifyResult
formattedLatency = BenchmarkSuite.FormatScore(100 * scoreLatency)
@runner.NotifyResult @name + "Latency", formattedLatency
return
BenchmarkSuite::NotifySkipped = (runner) ->
BenchmarkSuite.scores.push 1 # push default reference score.
runner.NotifyResult @name, "Skipped" if runner.NotifyResult
return
# Notifies the runner that running a benchmark resulted in an error.
BenchmarkSuite::NotifyError = (error) ->
@runner.NotifyError @name, error if @runner.NotifyError
@runner.NotifyStep @name if @runner.NotifyStep
return
# Runs a single benchmark for at least a second and computes the
# average time it takes to run a single iteration.
BenchmarkSuite::RunSingleBenchmark = (benchmark, data) ->
Measure = (data) ->
elapsed = 0
start = new Date()
# Run either for 1 second or for the number of iterations specified
# by minIterations, depending on the config flag doDeterministic.
i = 0
while ((if doDeterministic then i < benchmark.deterministicIterations else elapsed < 1000))
benchmark.run()
elapsed = new Date() - start
i++
if data?
data.runs += i
data.elapsed += elapsed
return
config = BenchmarkSuite.config
doWarmup = (if config.doWarmup isnt `undefined` then config.doWarmup else benchmark.doWarmup)
doDeterministic = (if config.doDeterministic isnt `undefined` then config.doDeterministic else benchmark.doDeterministic)
# Sets up data in order to skip or not the warmup phase.
if not doWarmup and not data?
data =
runs: 0
elapsed: 0
unless data?
Measure null
runs: 0
elapsed: 0
else
Measure data
# If we've run too few iterations, we continue for another second.
return data if data.runs < benchmark.minIterations
usec = (data.elapsed * 1000) / data.runs
rms = (if (benchmark.rmsResult?) then benchmark.rmsResult() else 0)
@NotifyStep new BenchmarkResult(benchmark, usec, rms)
null
# This function starts running a suite, but stops between each
# individual benchmark in the suite and returns a continuation
# function which can be invoked to run the next benchmark. Once the
# last benchmark has been executed, null is returned.
BenchmarkSuite::RunStep = (runner) ->
# Run the setup, the actual benchmark, and the tear down in three
# separate steps to allow the framework to yield between any of the
# steps.
RunNextSetup = ->
if index < length
try
suite.benchmarks[index].Setup()
catch e
suite.NotifyError e
return null
return RunNextBenchmark
suite.NotifyResult()
null
RunNextBenchmark = ->
try
data = suite.RunSingleBenchmark(suite.benchmarks[index], data)
catch e
suite.NotifyError e
return null
# If data is null, we're done with this benchmark.
(if (not (data?)) then RunNextTearDown else RunNextBenchmark())
RunNextTearDown = ->
try
suite.benchmarks[index++].TearDown()
catch e
suite.NotifyError e
return null
RunNextSetup
BenchmarkSuite.ResetRNG()
@results = []
@runner = runner
length = @benchmarks.length
index = 0
suite = this
data = undefined
# Start out running the setup.
RunNextSetup()
|
[
{
"context": "\napp.use authenticate.middleware(\n encrypt_key: 'Pa2#a'\n validate_key: 'Fir@n2e'\n)\n\n# Authenticate.\n# N",
"end": 2519,
"score": 0.9993739128112793,
"start": 2514,
"tag": "KEY",
"value": "Pa2#a"
},
{
"context": "ddleware(\n encrypt_key: 'Pa2#a'\n validate_key:... | server/server.coffee | ohsu-qin/qiprofile | 0 | #
# The Quantitative Imaging Profile Express server application.
#
express = require 'express'
http = require 'http'
path = require 'path'
mkdirp = require 'mkdirp'
net = require 'net'
fs = require 'fs'
logger = require 'express-bunyan-logger'
authenticate = require 'authenticate'
spawn = require './spawn'
favicon = require 'serve-favicon'
bodyParser = require 'body-parser'
serveStatic = require 'serve-static'
methodOverride = require 'method-override'
errorHandler = require 'express-error-handler'
watcher = require 'chokidar-socket-emitter'
# The port assignments.
PORT = 3000
PORT_TEST = PORT + 1
MONGODB_PORT = 27017
QIREST_PORT = 5000
# The grunt build tasks place all compiled and copied files
# within the public directory. However, the Angular, jspm and
# test frameworks all conspire to force the demo-mode assumption
# that the root is the top-level project directory. Therefore,
# we make the parent directory the root and qualify the HTML
# with the public subdirectory where necessary. This scheme is
# not ideal, since the web client potentially has access to
# source. However, since the source is public anyway, we'll
# let that slide.
root = path.join(__dirname, '..')
# The REST request handler.
rest = require './rest'
# The Express server app.
app = express()
# Set the port.
app.set 'port', process.env.PORT or PORT
# The run environment.
env = app.get('env') or 'production'
# @return /var/log/qiprofile.log, if it is writable,
# ./log/qiprofile.log otherwise
defaultLogFile = ->
try
fd = fs.openSync('/var/log/qiprofile.log', 'w')
fs.closeSync(fd)
'/var/log/qiprofile.log'
catch err
'./log/qiprofile.log'
# The log file is either set in the environment or defaults to
# log/qiprofile.log in the current directory.
relLogFile = app.get('log') or defaultLogFile()
logFile = path.resolve(relLogFile)
logDir = path.dirname(logFile)
mkdirp(logDir)
# If the server has the debug flag set, then the log level is debug.
# Otherwise, the log level is inferred from the environment.
if app.get('debug') or env is not 'production'
logLevel = 'debug'
else
logLevel = 'info'
# The logger configuration.
logConfig =
name: 'qiprofile'
streams: [
level: logLevel, path: logFile
]
# Enable the middleware.
app.use favicon("#{ root }/public/media/favicon.ico")
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
app.use methodOverride()
app.use logger(logConfig)
app.use serveStatic(root)
app.use authenticate.middleware(
encrypt_key: 'Pa2#a'
validate_key: 'Fir@n2e'
)
# Authenticate.
# Note: authentication is not enabled by default.
app.get '/login', (req, res) ->
res.writeHead 200, ContentType: 'application/json'
res.write JSON.stringify(
'access_token': authenticate.serializeToken(req.data.client_id,
req.data.user_id)
)
res.end
# The REST API route.
restUrl = process.env.QIREST_HOST or 'localhost'
app.use '/qirest', rest(restUrl)
# /qiprofile always serves the SAP index page.
# The app then routes to the correct partial.
app.get '/qiprofile*', (req, res) ->
res.sendFile "#{ root }/index.html"
# All other files are served up relative to the public directory.
#
# TODO - this is not the final route, e.g. /stylesheets/app.css
# resolves correctly to /public/stylesheets/app.css, but
# /stylesheets/app.styl should result in a 404, but instead
# resolves to /stylesheets/app.styl.
app.get '/*', (req, res) ->
file = "#{ root }/public#{ req.path }"
options =
headers:
'x-timestamp': Date.now()
'x-sent': true
res.sendFile file, options, (err) ->
if err
console.log(err)
res.status(err.status).end()
# Log the error.
app.use (err, req, res, next) ->
# Print the error.
console.log("Server error: #{ err }")
console.log("See the log at #{ logFile }")
# Log the error.
req.log.error(req.body)
# Pass on to the error handler enabled in the Eve callback
# below.
next(err)
# Nothing else responded; this must be a 404.
errorHandlerConfig =
static:
'404': "#{ root }/public/html/error/404.html"
app.use errorHandler(errorHandlerConfig)
# TODO - enable error handling below.
# # Log the error.
# app.use (err, req, res, next) ->
# # Print the error.
# console.log("Server error: #{ req.body.message }")
# console.log("See the log at #{ logFile }")
# # Log the error.
# req.log.info(req.body)
# # Pass on to the error handler enabled in the Eve callback
# # below.
# next(err)
#
# # Nothing else responded; this must be an error.
# app.use errorHandler.httpError(404)
#
# # Enable the error handler.
# errorHandlerConfig =
# static:
# '404': "#{ root }/public/html/error/404.html"
# app.use errorHandler(errorHandlerConfig)
#
# # Development error handling.
# if env is 'development'
# app.use errorHandler()
# app.set 'pretty', true
# The test port.
if env is 'test'
app.set 'port', PORT_TEST
# Callback invoked after MongoDB is started.
start_app = ->
# The REST server start mode, production or development.
restMode = if env is 'test' then 'development' else env
# The REST server command.
qirest = if restMode? then "qirest --#{ restMode }" else 'qirest'
# The callback after the REST server is started.
start_eve = ->
# The server port.
port = app.get 'port'
# Make the server.
server = http.createServer(app)
# The watcher hot reloads modules.
watcher({app: server})
# Start the server.
server.listen port, ->
env = app.settings.env
console.log "The qiprofile server is listening on port #{ port }" +
" in #{ env } mode."
# Start the REST app without logging to the console.
spawn(qirest, QIREST_PORT, start_eve, {silent: true})
# Start MongoDB, if necessary, and forward to the callback.
spawn('mongod', MONGODB_PORT, start_app, {silent: true})
module.exports = app
| 103395 | #
# The Quantitative Imaging Profile Express server application.
#
express = require 'express'
http = require 'http'
path = require 'path'
mkdirp = require 'mkdirp'
net = require 'net'
fs = require 'fs'
logger = require 'express-bunyan-logger'
authenticate = require 'authenticate'
spawn = require './spawn'
favicon = require 'serve-favicon'
bodyParser = require 'body-parser'
serveStatic = require 'serve-static'
methodOverride = require 'method-override'
errorHandler = require 'express-error-handler'
watcher = require 'chokidar-socket-emitter'
# The port assignments.
PORT = 3000
PORT_TEST = PORT + 1
MONGODB_PORT = 27017
QIREST_PORT = 5000
# The grunt build tasks place all compiled and copied files
# within the public directory. However, the Angular, jspm and
# test frameworks all conspire to force the demo-mode assumption
# that the root is the top-level project directory. Therefore,
# we make the parent directory the root and qualify the HTML
# with the public subdirectory where necessary. This scheme is
# not ideal, since the web client potentially has access to
# source. However, since the source is public anyway, we'll
# let that slide.
root = path.join(__dirname, '..')
# The REST request handler.
rest = require './rest'
# The Express server app.
app = express()
# Set the port.
app.set 'port', process.env.PORT or PORT
# The run environment.
env = app.get('env') or 'production'
# @return /var/log/qiprofile.log, if it is writable,
# ./log/qiprofile.log otherwise
defaultLogFile = ->
try
fd = fs.openSync('/var/log/qiprofile.log', 'w')
fs.closeSync(fd)
'/var/log/qiprofile.log'
catch err
'./log/qiprofile.log'
# The log file is either set in the environment or defaults to
# log/qiprofile.log in the current directory.
relLogFile = app.get('log') or defaultLogFile()
logFile = path.resolve(relLogFile)
logDir = path.dirname(logFile)
mkdirp(logDir)
# If the server has the debug flag set, then the log level is debug.
# Otherwise, the log level is inferred from the environment.
if app.get('debug') or env is not 'production'
logLevel = 'debug'
else
logLevel = 'info'
# The logger configuration.
logConfig =
name: 'qiprofile'
streams: [
level: logLevel, path: logFile
]
# Enable the middleware.
app.use favicon("#{ root }/public/media/favicon.ico")
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
app.use methodOverride()
app.use logger(logConfig)
app.use serveStatic(root)
app.use authenticate.middleware(
encrypt_key: '<KEY>'
validate_key: '<KEY>'
)
# Authenticate.
# Note: authentication is not enabled by default.
app.get '/login', (req, res) ->
res.writeHead 200, ContentType: 'application/json'
res.write JSON.stringify(
'access_token': authenticate.serializeToken(req.data.client_id,
req.data.user_id)
)
res.end
# The REST API route.
restUrl = process.env.QIREST_HOST or 'localhost'
app.use '/qirest', rest(restUrl)
# /qiprofile always serves the SAP index page.
# The app then routes to the correct partial.
app.get '/qiprofile*', (req, res) ->
res.sendFile "#{ root }/index.html"
# All other files are served up relative to the public directory.
#
# TODO - this is not the final route, e.g. /stylesheets/app.css
# resolves correctly to /public/stylesheets/app.css, but
# /stylesheets/app.styl should result in a 404, but instead
# resolves to /stylesheets/app.styl.
app.get '/*', (req, res) ->
file = "#{ root }/public#{ req.path }"
options =
headers:
'x-timestamp': Date.now()
'x-sent': true
res.sendFile file, options, (err) ->
if err
console.log(err)
res.status(err.status).end()
# Log the error.
app.use (err, req, res, next) ->
# Print the error.
console.log("Server error: #{ err }")
console.log("See the log at #{ logFile }")
# Log the error.
req.log.error(req.body)
# Pass on to the error handler enabled in the Eve callback
# below.
next(err)
# Nothing else responded; this must be a 404.
errorHandlerConfig =
static:
'404': "#{ root }/public/html/error/404.html"
app.use errorHandler(errorHandlerConfig)
# TODO - enable error handling below.
# # Log the error.
# app.use (err, req, res, next) ->
# # Print the error.
# console.log("Server error: #{ req.body.message }")
# console.log("See the log at #{ logFile }")
# # Log the error.
# req.log.info(req.body)
# # Pass on to the error handler enabled in the Eve callback
# # below.
# next(err)
#
# # Nothing else responded; this must be an error.
# app.use errorHandler.httpError(404)
#
# # Enable the error handler.
# errorHandlerConfig =
# static:
# '404': "#{ root }/public/html/error/404.html"
# app.use errorHandler(errorHandlerConfig)
#
# # Development error handling.
# if env is 'development'
# app.use errorHandler()
# app.set 'pretty', true
# The test port.
if env is 'test'
app.set 'port', PORT_TEST
# Callback invoked after MongoDB is started.
start_app = ->
# The REST server start mode, production or development.
restMode = if env is 'test' then 'development' else env
# The REST server command.
qirest = if restMode? then "qirest --#{ restMode }" else 'qirest'
# The callback after the REST server is started.
start_eve = ->
# The server port.
port = app.get 'port'
# Make the server.
server = http.createServer(app)
# The watcher hot reloads modules.
watcher({app: server})
# Start the server.
server.listen port, ->
env = app.settings.env
console.log "The qiprofile server is listening on port #{ port }" +
" in #{ env } mode."
# Start the REST app without logging to the console.
spawn(qirest, QIREST_PORT, start_eve, {silent: true})
# Start MongoDB, if necessary, and forward to the callback.
spawn('mongod', MONGODB_PORT, start_app, {silent: true})
module.exports = app
| true | #
# The Quantitative Imaging Profile Express server application.
#
express = require 'express'
http = require 'http'
path = require 'path'
mkdirp = require 'mkdirp'
net = require 'net'
fs = require 'fs'
logger = require 'express-bunyan-logger'
authenticate = require 'authenticate'
spawn = require './spawn'
favicon = require 'serve-favicon'
bodyParser = require 'body-parser'
serveStatic = require 'serve-static'
methodOverride = require 'method-override'
errorHandler = require 'express-error-handler'
watcher = require 'chokidar-socket-emitter'
# The port assignments.
PORT = 3000
PORT_TEST = PORT + 1
MONGODB_PORT = 27017
QIREST_PORT = 5000
# The grunt build tasks place all compiled and copied files
# within the public directory. However, the Angular, jspm and
# test frameworks all conspire to force the demo-mode assumption
# that the root is the top-level project directory. Therefore,
# we make the parent directory the root and qualify the HTML
# with the public subdirectory where necessary. This scheme is
# not ideal, since the web client potentially has access to
# source. However, since the source is public anyway, we'll
# let that slide.
root = path.join(__dirname, '..')
# The REST request handler.
rest = require './rest'
# The Express server app.
app = express()
# Set the port.
app.set 'port', process.env.PORT or PORT
# The run environment.
env = app.get('env') or 'production'
# @return /var/log/qiprofile.log, if it is writable,
# ./log/qiprofile.log otherwise
defaultLogFile = ->
try
fd = fs.openSync('/var/log/qiprofile.log', 'w')
fs.closeSync(fd)
'/var/log/qiprofile.log'
catch err
'./log/qiprofile.log'
# The log file is either set in the environment or defaults to
# log/qiprofile.log in the current directory.
relLogFile = app.get('log') or defaultLogFile()
logFile = path.resolve(relLogFile)
logDir = path.dirname(logFile)
mkdirp(logDir)
# If the server has the debug flag set, then the log level is debug.
# Otherwise, the log level is inferred from the environment.
if app.get('debug') or env is not 'production'
logLevel = 'debug'
else
logLevel = 'info'
# The logger configuration.
logConfig =
name: 'qiprofile'
streams: [
level: logLevel, path: logFile
]
# Enable the middleware.
app.use favicon("#{ root }/public/media/favicon.ico")
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
app.use methodOverride()
app.use logger(logConfig)
app.use serveStatic(root)
app.use authenticate.middleware(
encrypt_key: 'PI:KEY:<KEY>END_PI'
validate_key: 'PI:KEY:<KEY>END_PI'
)
# Authenticate.
# Note: authentication is not enabled by default.
app.get '/login', (req, res) ->
res.writeHead 200, ContentType: 'application/json'
res.write JSON.stringify(
'access_token': authenticate.serializeToken(req.data.client_id,
req.data.user_id)
)
res.end
# The REST API route.
restUrl = process.env.QIREST_HOST or 'localhost'
app.use '/qirest', rest(restUrl)
# /qiprofile always serves the SAP index page.
# The app then routes to the correct partial.
app.get '/qiprofile*', (req, res) ->
res.sendFile "#{ root }/index.html"
# All other files are served up relative to the public directory.
#
# TODO - this is not the final route, e.g. /stylesheets/app.css
# resolves correctly to /public/stylesheets/app.css, but
# /stylesheets/app.styl should result in a 404, but instead
# resolves to /stylesheets/app.styl.
app.get '/*', (req, res) ->
file = "#{ root }/public#{ req.path }"
options =
headers:
'x-timestamp': Date.now()
'x-sent': true
res.sendFile file, options, (err) ->
if err
console.log(err)
res.status(err.status).end()
# Log the error.
app.use (err, req, res, next) ->
# Print the error.
console.log("Server error: #{ err }")
console.log("See the log at #{ logFile }")
# Log the error.
req.log.error(req.body)
# Pass on to the error handler enabled in the Eve callback
# below.
next(err)
# Nothing else responded; this must be a 404.
errorHandlerConfig =
static:
'404': "#{ root }/public/html/error/404.html"
app.use errorHandler(errorHandlerConfig)
# TODO - enable error handling below.
# # Log the error.
# app.use (err, req, res, next) ->
# # Print the error.
# console.log("Server error: #{ req.body.message }")
# console.log("See the log at #{ logFile }")
# # Log the error.
# req.log.info(req.body)
# # Pass on to the error handler enabled in the Eve callback
# # below.
# next(err)
#
# # Nothing else responded; this must be an error.
# app.use errorHandler.httpError(404)
#
# # Enable the error handler.
# errorHandlerConfig =
# static:
# '404': "#{ root }/public/html/error/404.html"
# app.use errorHandler(errorHandlerConfig)
#
# # Development error handling.
# if env is 'development'
# app.use errorHandler()
# app.set 'pretty', true
# The test port.
if env is 'test'
app.set 'port', PORT_TEST
# Callback invoked after MongoDB is started.
start_app = ->
# The REST server start mode, production or development.
restMode = if env is 'test' then 'development' else env
# The REST server command.
qirest = if restMode? then "qirest --#{ restMode }" else 'qirest'
# The callback after the REST server is started.
start_eve = ->
# The server port.
port = app.get 'port'
# Make the server.
server = http.createServer(app)
# The watcher hot reloads modules.
watcher({app: server})
# Start the server.
server.listen port, ->
env = app.settings.env
console.log "The qiprofile server is listening on port #{ port }" +
" in #{ env } mode."
# Start the REST app without logging to the console.
spawn(qirest, QIREST_PORT, start_eve, {silent: true})
# Start MongoDB, if necessary, and forward to the callback.
spawn('mongod', MONGODB_PORT, start_app, {silent: true})
module.exports = app
|
[
{
"context": "atabase}\"\n\nsecure = !!/https/.exec host\nauth = {username, password}\nconn = new Cradle.Connection {host, ",
"end": 678,
"score": 0.9969593286514282,
"start": 670,
"tag": "USERNAME",
"value": "username"
},
{
"context": "le.Connection {host, port, secure, auth: us... | boot.coffee | nextorigin/flat-white | 0 | #!./node_modules/.bin/iced
url = require "url"
Cradle = require "cradle"
errify = require "errify"
CloudantUser = require "cloudant-user"
CouchApp = require "couchapp"
_security = require "./_security-docs/_security"
## Couch server admin credentials
username = ""
password = ""
## URL, Database for blog
host = ""
port = 443
database = "blog"
## New admin user for blog
bloguser = ""
email = ""
blogpass = ""
## design doc for blog app
ddoc_path = "./_design-docs/app.coffee"
## Boot
{log, error} = console
log "setting up couch connection to #{host}"
log "using database #{database}"
secure = !!/https/.exec host
auth = {username, password}
conn = new Cradle.Connection {host, port, secure, auth}
db = conn.database database
ideally = errify (err) ->
error err
process.exit 1
await db.exists ideally defer exists
unless exists
log "creating database #{database}"
await db.create ideally defer res
log "adding _security document to database with admins", _security.admins
await db.save "_security", _security, ideally defer res
log "creating blog admin user #{bloguser}"
cloudantUser = new CloudantUser {host, port, secure, auth: {username, password}}
await cloudantUser.createWithMeta bloguser, blogpass, "blog", "admin", "_reader", "_writer", {email}, ideally defer res
log "testing blog database with user #{bloguser}"
testconn = new Cradle.Connection {host, port, secure, auth: username: bloguser, password: blogpass}
testdb = testconn.database database
testname = (new Buffer "#{Math.random()}").toString "base64"
log "creating test document #{testname}"
await testdb.save testname, {testing: true}, ideally defer res
log "removing test document #{testname}"
await testdb.remove testname, ideally defer res
fullurl = "#{host}:#{port}/#{database}"
log "pushing #{ddoc_path} to #{fullurl}"
fullauthurl = url.parse fullurl
fullauthurl.auth = "#{username}:#{password}"
fullauthurl = url.format fullauthurl
ddoc = require ddoc_path
await CouchApp.createApp ddoc, fullauthurl, defer couchapp
await couchapp.push ideally defer res
log "database ready" | 185206 | #!./node_modules/.bin/iced
url = require "url"
Cradle = require "cradle"
errify = require "errify"
CloudantUser = require "cloudant-user"
CouchApp = require "couchapp"
_security = require "./_security-docs/_security"
## Couch server admin credentials
username = ""
password = ""
## URL, Database for blog
host = ""
port = 443
database = "blog"
## New admin user for blog
bloguser = ""
email = ""
blogpass = ""
## design doc for blog app
ddoc_path = "./_design-docs/app.coffee"
## Boot
{log, error} = console
log "setting up couch connection to #{host}"
log "using database #{database}"
secure = !!/https/.exec host
auth = {username, password}
conn = new Cradle.Connection {host, port, secure, auth}
db = conn.database database
ideally = errify (err) ->
error err
process.exit 1
await db.exists ideally defer exists
unless exists
log "creating database #{database}"
await db.create ideally defer res
log "adding _security document to database with admins", _security.admins
await db.save "_security", _security, ideally defer res
log "creating blog admin user #{bloguser}"
cloudantUser = new CloudantUser {host, port, secure, auth: {username, password}}
await cloudantUser.createWithMeta bloguser, blogpass, "blog", "admin", "_reader", "_writer", {email}, ideally defer res
log "testing blog database with user #{bloguser}"
testconn = new Cradle.Connection {host, port, secure, auth: username: bloguser, password: <PASSWORD>}
testdb = testconn.database database
testname = (new Buffer "#{Math.random()}").toString "base64"
log "creating test document #{testname}"
await testdb.save testname, {testing: true}, ideally defer res
log "removing test document #{testname}"
await testdb.remove testname, ideally defer res
fullurl = "#{host}:#{port}/#{database}"
log "pushing #{ddoc_path} to #{fullurl}"
fullauthurl = url.parse fullurl
fullauthurl.auth = "#{username}:#{password}"
fullauthurl = url.format fullauthurl
ddoc = require ddoc_path
await CouchApp.createApp ddoc, fullauthurl, defer couchapp
await couchapp.push ideally defer res
log "database ready" | true | #!./node_modules/.bin/iced
url = require "url"
Cradle = require "cradle"
errify = require "errify"
CloudantUser = require "cloudant-user"
CouchApp = require "couchapp"
_security = require "./_security-docs/_security"
## Couch server admin credentials
username = ""
password = ""
## URL, Database for blog
host = ""
port = 443
database = "blog"
## New admin user for blog
bloguser = ""
email = ""
blogpass = ""
## design doc for blog app
ddoc_path = "./_design-docs/app.coffee"
## Boot
{log, error} = console
log "setting up couch connection to #{host}"
log "using database #{database}"
secure = !!/https/.exec host
auth = {username, password}
conn = new Cradle.Connection {host, port, secure, auth}
db = conn.database database
ideally = errify (err) ->
error err
process.exit 1
await db.exists ideally defer exists
unless exists
log "creating database #{database}"
await db.create ideally defer res
log "adding _security document to database with admins", _security.admins
await db.save "_security", _security, ideally defer res
log "creating blog admin user #{bloguser}"
cloudantUser = new CloudantUser {host, port, secure, auth: {username, password}}
await cloudantUser.createWithMeta bloguser, blogpass, "blog", "admin", "_reader", "_writer", {email}, ideally defer res
log "testing blog database with user #{bloguser}"
testconn = new Cradle.Connection {host, port, secure, auth: username: bloguser, password: PI:PASSWORD:<PASSWORD>END_PI}
testdb = testconn.database database
testname = (new Buffer "#{Math.random()}").toString "base64"
log "creating test document #{testname}"
await testdb.save testname, {testing: true}, ideally defer res
log "removing test document #{testname}"
await testdb.remove testname, ideally defer res
fullurl = "#{host}:#{port}/#{database}"
log "pushing #{ddoc_path} to #{fullurl}"
fullauthurl = url.parse fullurl
fullauthurl.auth = "#{username}:#{password}"
fullauthurl = url.format fullauthurl
ddoc = require ddoc_path
await CouchApp.createApp ddoc, fullauthurl, defer couchapp
await couchapp.push ideally defer res
log "database ready" |
[
{
"context": "ittle Mocha Reference ========\nhttps://github.com/visionmedia/should.js\nhttps://github.com/visionmedia/mocha\n\nM",
"end": 150,
"score": 0.9995959997177124,
"start": 139,
"tag": "USERNAME",
"value": "visionmedia"
},
{
"context": "thub.com/visionmedia/should.js\nhttps:... | src/test/node-sportsdata_test.coffee | pureawesome/node-sportsdata | 1 | 'use strict'
node_sportsdata = require('../lib/node-sportsdata')
###
======== A Handy Little Mocha Reference ========
https://github.com/visionmedia/should.js
https://github.com/visionmedia/mocha
Mocha hooks:
before ()-> # before describe
after ()-> # after describe
beforeEach ()-> # before each it
afterEach ()-> # after each it
Should assertions:
should.exist('hello')
should.fail('expected an error!')
true.should.be.ok
true.should.be.true
false.should.be.false
(()-> arguments)(1,2,3).should.be.arguments
[1,2,3].should.eql([1,2,3])
should.strictEqual(undefined, value)
user.age.should.be.within(5, 50)
username.should.match(/^\w+$/)
user.should.be.a('object')
[].should.be.an.instanceOf(Array)
user.should.have.property('age', 15)
user.age.should.be.above(5)
user.age.should.be.below(100)
user.pets.should.have.length(5)
res.should.have.status(200) #res.statusCode should be 200
res.should.be.json
res.should.be.html
res.should.have.header('Content-Length', '123')
[].should.be.empty
[1,2,3].should.include(3)
'foo bar baz'.should.include('foo')
{ name: 'TJ', pet: tobi }.user.should.include({ pet: tobi, name: 'TJ' })
{ foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar')
(()-> throw new Error('failed to baz')).should.throwError(/^fail.+/)
user.should.have.property('pets').with.lengthOf(4)
user.should.be.a('object').and.have.property('name', 'tj')
###
describe 'Awesome', ()->
describe '#of()', ()->
it 'awesome', ()->
node_sportsdata.awesome().should.eql('awesome')
describe 'Node SportsData API', ->
describe 'v3', ->
it 'should be an object', ->
node_sportsdata.v3.should.be.a('object')
it 'should have a MLB function', ->
node_sportsdata.v3.mlb.should.be.a('function')
it 'should have a NCAAMB function', ->
node_sportsdata.v3.ncaamb.should.be.a('function')
describe '#mlb()', ->
it 'should return an MLB object', ->
node_sportsdata.v3.mlb('api-key', 't').should.be.a('object')
it 'should throw an error without api key', ->
(->
node_sportsdata.v3.mlb()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v3.mlb('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v3.mlb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /mlb-t3/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v3.mlb('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /mlb-test-t3/
describe '#ncaamb()', ->
it 'should return an NCAAMB object', ->
node_sportsdata.v3.ncaamb('api-key', 't').should.be.a('object')
it 'should throw an error without api key', ->
(->
node_sportsdata.v3.ncaamb()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v3.ncaamb('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v3.ncaamb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /ncaamb-t3/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v3.ncaamb('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /ncaamb-test-t3/
describe '#ncaawb()', ->
it 'should return an NCAAWB object', ->
node_sportsdata.v3.ncaawb('api-key', 't').should.be.a('object')
it 'should have a path of /ncaawb', ->
httpOptions = node_sportsdata.v3.ncaawb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /ncaawb-t3/
describe 'v2', ->
it 'should be an object', ->
node_sportsdata.v2.should.be.a('object')
describe 'v1', ->
it 'should be an object', ->
node_sportsdata.v1.should.be.a('object')
it 'should have an NCAAF function', ->
node_sportsdata.v1.ncaafb.should.be.a('function')
describe '#ncaafb()', ->
it 'should return an NCAAFB object', ->
node_sportsdata.v1.ncaafb('api-key', 't').should.be.a('object')
it 'should throw an error without api key', ->
(->
node_sportsdata.v1.ncaafb()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v1.ncaafb('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v1.ncaafb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /ncaafb-t1/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v1.ncaafb('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /ncaafb-test-t1/
it 'should have an NFL function', ->
node_sportsdata.v1.nfl.should.be.a('function')
describe '#nfl', ->
it 'should return an NFL object', ->
node_sportsdata.v1.nfl('api-key', 't').should.be.a('object')
it 'should return an error without api key', ->
(->
node_sportsdata.v1.nfl()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v1.nfl('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v1.nfl('api-key', 't').getHttpOptions()
httpOptions.path.should.match /nfl-t1/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v1.nfl('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /nfl-test-t1/
| 150983 | 'use strict'
node_sportsdata = require('../lib/node-sportsdata')
###
======== A Handy Little Mocha Reference ========
https://github.com/visionmedia/should.js
https://github.com/visionmedia/mocha
Mocha hooks:
before ()-> # before describe
after ()-> # after describe
beforeEach ()-> # before each it
afterEach ()-> # after each it
Should assertions:
should.exist('hello')
should.fail('expected an error!')
true.should.be.ok
true.should.be.true
false.should.be.false
(()-> arguments)(1,2,3).should.be.arguments
[1,2,3].should.eql([1,2,3])
should.strictEqual(undefined, value)
user.age.should.be.within(5, 50)
username.should.match(/^\w+$/)
user.should.be.a('object')
[].should.be.an.instanceOf(Array)
user.should.have.property('age', 15)
user.age.should.be.above(5)
user.age.should.be.below(100)
user.pets.should.have.length(5)
res.should.have.status(200) #res.statusCode should be 200
res.should.be.json
res.should.be.html
res.should.have.header('Content-Length', '123')
[].should.be.empty
[1,2,3].should.include(3)
'foo bar baz'.should.include('foo')
{ name: '<NAME>', pet: tobi }.user.should.include({ pet: tobi, name: '<NAME>' })
{ foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar')
(()-> throw new Error('failed to baz')).should.throwError(/^fail.+/)
user.should.have.property('pets').with.lengthOf(4)
user.should.be.a('object').and.have.property('name', '<NAME>')
###
describe 'Awesome', ()->
describe '#of()', ()->
it 'awesome', ()->
node_sportsdata.awesome().should.eql('awesome')
describe 'Node SportsData API', ->
describe 'v3', ->
it 'should be an object', ->
node_sportsdata.v3.should.be.a('object')
it 'should have a MLB function', ->
node_sportsdata.v3.mlb.should.be.a('function')
it 'should have a NCAAMB function', ->
node_sportsdata.v3.ncaamb.should.be.a('function')
describe '#mlb()', ->
it 'should return an MLB object', ->
node_sportsdata.v3.mlb('api-key', 't').should.be.a('object')
it 'should throw an error without api key', ->
(->
node_sportsdata.v3.mlb()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v3.mlb('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v3.mlb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /mlb-t3/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v3.mlb('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /mlb-test-t3/
describe '#ncaamb()', ->
it 'should return an NCAAMB object', ->
node_sportsdata.v3.ncaamb('api-key', 't').should.be.a('object')
it 'should throw an error without api key', ->
(->
node_sportsdata.v3.ncaamb()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v3.ncaamb('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v3.ncaamb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /ncaamb-t3/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v3.ncaamb('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /ncaamb-test-t3/
describe '#ncaawb()', ->
it 'should return an NCAAWB object', ->
node_sportsdata.v3.ncaawb('api-key', 't').should.be.a('object')
it 'should have a path of /ncaawb', ->
httpOptions = node_sportsdata.v3.ncaawb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /ncaawb-t3/
describe 'v2', ->
it 'should be an object', ->
node_sportsdata.v2.should.be.a('object')
describe 'v1', ->
it 'should be an object', ->
node_sportsdata.v1.should.be.a('object')
it 'should have an NCAAF function', ->
node_sportsdata.v1.ncaafb.should.be.a('function')
describe '#ncaafb()', ->
it 'should return an NCAAFB object', ->
node_sportsdata.v1.ncaafb('api-key', 't').should.be.a('object')
it 'should throw an error without api key', ->
(->
node_sportsdata.v1.ncaafb()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v1.ncaafb('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v1.ncaafb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /ncaafb-t1/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v1.ncaafb('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /ncaafb-test-t1/
it 'should have an NFL function', ->
node_sportsdata.v1.nfl.should.be.a('function')
describe '#nfl', ->
it 'should return an NFL object', ->
node_sportsdata.v1.nfl('api-key', 't').should.be.a('object')
it 'should return an error without api key', ->
(->
node_sportsdata.v1.nfl()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v1.nfl('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v1.nfl('api-key', 't').getHttpOptions()
httpOptions.path.should.match /nfl-t1/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v1.nfl('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /nfl-test-t1/
| true | 'use strict'
node_sportsdata = require('../lib/node-sportsdata')
###
======== A Handy Little Mocha Reference ========
https://github.com/visionmedia/should.js
https://github.com/visionmedia/mocha
Mocha hooks:
before ()-> # before describe
after ()-> # after describe
beforeEach ()-> # before each it
afterEach ()-> # after each it
Should assertions:
should.exist('hello')
should.fail('expected an error!')
true.should.be.ok
true.should.be.true
false.should.be.false
(()-> arguments)(1,2,3).should.be.arguments
[1,2,3].should.eql([1,2,3])
should.strictEqual(undefined, value)
user.age.should.be.within(5, 50)
username.should.match(/^\w+$/)
user.should.be.a('object')
[].should.be.an.instanceOf(Array)
user.should.have.property('age', 15)
user.age.should.be.above(5)
user.age.should.be.below(100)
user.pets.should.have.length(5)
res.should.have.status(200) #res.statusCode should be 200
res.should.be.json
res.should.be.html
res.should.have.header('Content-Length', '123')
[].should.be.empty
[1,2,3].should.include(3)
'foo bar baz'.should.include('foo')
{ name: 'PI:NAME:<NAME>END_PI', pet: tobi }.user.should.include({ pet: tobi, name: 'PI:NAME:<NAME>END_PI' })
{ foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar')
(()-> throw new Error('failed to baz')).should.throwError(/^fail.+/)
user.should.have.property('pets').with.lengthOf(4)
user.should.be.a('object').and.have.property('name', 'PI:NAME:<NAME>END_PI')
###
describe 'Awesome', ()->
describe '#of()', ()->
it 'awesome', ()->
node_sportsdata.awesome().should.eql('awesome')
describe 'Node SportsData API', ->
describe 'v3', ->
it 'should be an object', ->
node_sportsdata.v3.should.be.a('object')
it 'should have a MLB function', ->
node_sportsdata.v3.mlb.should.be.a('function')
it 'should have a NCAAMB function', ->
node_sportsdata.v3.ncaamb.should.be.a('function')
describe '#mlb()', ->
it 'should return an MLB object', ->
node_sportsdata.v3.mlb('api-key', 't').should.be.a('object')
it 'should throw an error without api key', ->
(->
node_sportsdata.v3.mlb()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v3.mlb('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v3.mlb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /mlb-t3/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v3.mlb('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /mlb-test-t3/
describe '#ncaamb()', ->
it 'should return an NCAAMB object', ->
node_sportsdata.v3.ncaamb('api-key', 't').should.be.a('object')
it 'should throw an error without api key', ->
(->
node_sportsdata.v3.ncaamb()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v3.ncaamb('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v3.ncaamb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /ncaamb-t3/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v3.ncaamb('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /ncaamb-test-t3/
describe '#ncaawb()', ->
it 'should return an NCAAWB object', ->
node_sportsdata.v3.ncaawb('api-key', 't').should.be.a('object')
it 'should have a path of /ncaawb', ->
httpOptions = node_sportsdata.v3.ncaawb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /ncaawb-t3/
describe 'v2', ->
it 'should be an object', ->
node_sportsdata.v2.should.be.a('object')
describe 'v1', ->
it 'should be an object', ->
node_sportsdata.v1.should.be.a('object')
it 'should have an NCAAF function', ->
node_sportsdata.v1.ncaafb.should.be.a('function')
describe '#ncaafb()', ->
it 'should return an NCAAFB object', ->
node_sportsdata.v1.ncaafb('api-key', 't').should.be.a('object')
it 'should throw an error without api key', ->
(->
node_sportsdata.v1.ncaafb()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v1.ncaafb('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v1.ncaafb('api-key', 't').getHttpOptions()
httpOptions.path.should.match /ncaafb-t1/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v1.ncaafb('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /ncaafb-test-t1/
it 'should have an NFL function', ->
node_sportsdata.v1.nfl.should.be.a('function')
describe '#nfl', ->
it 'should return an NFL object', ->
node_sportsdata.v1.nfl('api-key', 't').should.be.a('object')
it 'should return an error without api key', ->
(->
node_sportsdata.v1.nfl()
).should.throwError(/You must provide an API Key/)
it 'should throw an error without access level', ->
(->
node_sportsdata.v1.nfl('api-key')
).should.throwError(/You must provide an Access Level/)
it 'should default to not test league mode', ->
httpOptions = node_sportsdata.v1.nfl('api-key', 't').getHttpOptions()
httpOptions.path.should.match /nfl-t1/
it 'should support test league mode', ->
httpOptions = node_sportsdata.v1.nfl('api-key', 't', true).getHttpOptions()
httpOptions.path.should.match /nfl-test-t1/
|
[
{
"context": "view.followed = new Backbone.Collection [{ name: 'Foo Bar', id: 'foo-bar' }, { name: 'Baz Qux', id: 'baz-qu",
"end": 5233,
"score": 0.7485669255256653,
"start": 5226,
"tag": "NAME",
"value": "Foo Bar"
},
{
"context": "ion [{ name: 'Foo Bar', id: 'foo-bar' }, { name: 'Ba... | src/mobile/apps/personalize/test/client/client.coffee | streamich/force | 1 | _ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
PersonalizeState = require '../../client/personalize_state.coffee'
CurrentUser = require '../../../../models/current_user.coffee'
benv = require 'benv'
{ resolve } = require 'path'
describe 'Personalization view code', ->
beforeEach (done) ->
benv.setup =>
benv.expose $: benv.require 'jquery'
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @CollectView } = benv.requireWithJadeify resolve(__dirname, '../../client/collect_view'),
['template']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @CollectView(state: @state, user: @user)
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#setCollectorLevel', ->
beforeEach ->
@view.render()
it 'sets the collector_level attribute on the user', ->
@view.$('a').eq(0).click()
@view.user.get('collector_level').should.equal 3
it 'sets the level of PersonalizeState', ->
@view.$('a').eq(1).click()
@view.state.get('current_level').should.equal 2
it 'triggers the event \'transition:next\' on PersonalizeState', ->
spy = sinon.spy @view, 'advance'
@view.$('a').eq(1).click()
spy.called.should.be.ok()
describe '#render', ->
it 'renders the template', ->
@view.render()
@view.$el.html().should.containEql 'Do you buy art?'
describe 'LocationView', ->
beforeEach (done) ->
benv.setup =>
benv.expose { $: benv.require 'jquery' }
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @LocationView } = mod = benv.requireWithJadeify resolve(__dirname, '../../client/location_view'),
['template']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @LocationView(state: @state, user: @user)
@view.postRender = -> # Ignore
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#update', ->
before ->
# Mock response of New York
@location = require './location.coffee'
it 'sets the location on the user', ->
@view.update @location
@view.user.get('location').city.should.equal 'New York'
@view.user.get('location').state.should.equal 'New York'
@view.user.get('location').state_code.should.equal 'NY'
it 'triggers the event \'transition:next\' on PersonalizeState', ->
spy = sinon.spy()
@view.state.on 'transition:next', spy
@view.update @location
spy.called.should.be.ok()
describe '#render', ->
it 'renders the template', ->
@view.render()
@view.$el.html().should.containEql 'Where do you call home?'
it 'calls #postRender', ->
spy = sinon.spy @view, 'postRender'
@view.render()
spy.called.should.be.ok()
describe 'ArtistsView', ->
beforeEach (done) ->
benv.setup =>
benv.expose { $: benv.require 'jquery' }
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @ArtistsView } = mod = benv.requireWithJadeify resolve(__dirname, '../../client/artists_view'),
['template', 'resultsTemplate', 'followedTemplate']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @ArtistsView(state: @state, user: @user)
@view.postRender = -> # Ignore
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#skip', ->
it 'triggers the event \'transition:next\' on PersonalizeState', ->
spy = sinon.spy()
@view.render()
@view.state.on 'transition:next', spy
@view.$('#skip').click()
spy.called.should.be.ok()
describe '#_search', ->
beforeEach ->
@view.render()
it 'gets the input value and initiates search', ->
term = 'Foo Bar'
@view.$('input').val term
@view._search()
@view.term.should.equal term
it 'should indicate loading', ->
spy = sinon.spy @view, 'renderLoadingSpinner'
@view.term = null
@view.$('input').val 'Foo Bar'
@view._search()
spy.called.should.be.ok()
it 'should not perform a search if the term is the same as last time', ->
spy = sinon.spy @view.service, 'fetch'
@view.term = 'Foo Bar'
@view.$('input').val 'Foo Bar'
@view._search()
spy.called.should.not.be.ok()
@view.$('input').val 'Bar Baz'
@view._search()
spy.called.should.be.ok()
describe '#renderLoadingSpinner', ->
it 'renders the loading-spinner', ->
@view.render()
@view.$el.html().should.not.containEql 'loading-spinner'
@view.renderLoadingSpinner()
@view.$el.html().should.containEql 'loading-spinner'
describe '#renderFollowed', ->
it 'renders a string that is a comma separated list that ends with a period', ->
@view.render()
@view.followed = new Backbone.Collection [{ name: 'Foo Bar', id: 'foo-bar' }, { name: 'Baz Qux', id: 'baz-qux' }]
@view.renderFollowed()
@view.$el.html().should.containEql 'Foo Bar, Baz Qux.'
describe '#follow', ->
beforeEach ->
@view.results = new Backbone.Collection [{ name: 'Foo Bar', id: 'foo-bar' }]
@view.render()
@view.renderResults()
afterEach ->
@view.remove()
it 'should set the followed attribute on the appropriate model to true', ->
$follow = @view.$('.follow').eq(0)
model = @view.results.get($follow.data('id'))
model.attributes.should.not.have.property 'followed'
$follow.click()
model.get('followed').should.be.ok()
it 'should call #followArtist on the user', ->
spy = sinon.spy @view.user, 'followArtist'
@view.$('.follow').eq(0).click()
spy.called.should.be.ok()
it 'should prepend the followed artist to the followed collection', ->
@view.$('.follow').eq(0).click()
@view.results.reset { name: 'Baz Qux', id: 'baz-qux' }
@view.renderResults()
@view.$('.follow').eq(0).click()
@view.followed.at(0).id.should.equal 'baz-qux'
describe '#render', ->
it 'renders the template', ->
@view.render().$el.html().should.containEql 'Follow artists to get personalized recommendations'
describe 'PriceRangeView', ->
beforeEach (done) ->
benv.setup =>
benv.expose { $: benv.require 'jquery' }
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @PriceRangeView } = mod = benv.requireWithJadeify resolve(__dirname, '../../client/price_range_view'),
['template']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @PriceRangeView(state: @state, user: @user)
@view.postRender = -> # Ignore
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#setRange', ->
it 'sets the price_range attribute on the user', ->
@view.render()
@view.$('a').eq(0).click()
@view.user.get('price_range_min').should.equal '-1'
@view.user.get('price_range_max').should.equal '500'
it 'should call done', ->
@view.render()
spy = sinon.spy @view, 'done'
@view.$('a').eq(0).click()
spy.called.should.be.ok()
describe '#done', ->
it 'triggers the done event on PersonalizeState', ->
spy = sinon.spy()
@view.state.on 'done', spy
@view.done()
spy.called.should.be.ok()
describe '#render', ->
it 'renders the view', ->
@view.render()
@view.$el.html().should.containEql 'Price range?'
| 48907 | _ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
PersonalizeState = require '../../client/personalize_state.coffee'
CurrentUser = require '../../../../models/current_user.coffee'
benv = require 'benv'
{ resolve } = require 'path'
describe 'Personalization view code', ->
beforeEach (done) ->
benv.setup =>
benv.expose $: benv.require 'jquery'
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @CollectView } = benv.requireWithJadeify resolve(__dirname, '../../client/collect_view'),
['template']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @CollectView(state: @state, user: @user)
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#setCollectorLevel', ->
beforeEach ->
@view.render()
it 'sets the collector_level attribute on the user', ->
@view.$('a').eq(0).click()
@view.user.get('collector_level').should.equal 3
it 'sets the level of PersonalizeState', ->
@view.$('a').eq(1).click()
@view.state.get('current_level').should.equal 2
it 'triggers the event \'transition:next\' on PersonalizeState', ->
spy = sinon.spy @view, 'advance'
@view.$('a').eq(1).click()
spy.called.should.be.ok()
describe '#render', ->
it 'renders the template', ->
@view.render()
@view.$el.html().should.containEql 'Do you buy art?'
describe 'LocationView', ->
beforeEach (done) ->
benv.setup =>
benv.expose { $: benv.require 'jquery' }
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @LocationView } = mod = benv.requireWithJadeify resolve(__dirname, '../../client/location_view'),
['template']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @LocationView(state: @state, user: @user)
@view.postRender = -> # Ignore
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#update', ->
before ->
# Mock response of New York
@location = require './location.coffee'
it 'sets the location on the user', ->
@view.update @location
@view.user.get('location').city.should.equal 'New York'
@view.user.get('location').state.should.equal 'New York'
@view.user.get('location').state_code.should.equal 'NY'
it 'triggers the event \'transition:next\' on PersonalizeState', ->
spy = sinon.spy()
@view.state.on 'transition:next', spy
@view.update @location
spy.called.should.be.ok()
describe '#render', ->
it 'renders the template', ->
@view.render()
@view.$el.html().should.containEql 'Where do you call home?'
it 'calls #postRender', ->
spy = sinon.spy @view, 'postRender'
@view.render()
spy.called.should.be.ok()
describe 'ArtistsView', ->
beforeEach (done) ->
benv.setup =>
benv.expose { $: benv.require 'jquery' }
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @ArtistsView } = mod = benv.requireWithJadeify resolve(__dirname, '../../client/artists_view'),
['template', 'resultsTemplate', 'followedTemplate']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @ArtistsView(state: @state, user: @user)
@view.postRender = -> # Ignore
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#skip', ->
it 'triggers the event \'transition:next\' on PersonalizeState', ->
spy = sinon.spy()
@view.render()
@view.state.on 'transition:next', spy
@view.$('#skip').click()
spy.called.should.be.ok()
describe '#_search', ->
beforeEach ->
@view.render()
it 'gets the input value and initiates search', ->
term = 'Foo Bar'
@view.$('input').val term
@view._search()
@view.term.should.equal term
it 'should indicate loading', ->
spy = sinon.spy @view, 'renderLoadingSpinner'
@view.term = null
@view.$('input').val 'Foo Bar'
@view._search()
spy.called.should.be.ok()
it 'should not perform a search if the term is the same as last time', ->
spy = sinon.spy @view.service, 'fetch'
@view.term = 'Foo Bar'
@view.$('input').val 'Foo Bar'
@view._search()
spy.called.should.not.be.ok()
@view.$('input').val 'Bar Baz'
@view._search()
spy.called.should.be.ok()
describe '#renderLoadingSpinner', ->
it 'renders the loading-spinner', ->
@view.render()
@view.$el.html().should.not.containEql 'loading-spinner'
@view.renderLoadingSpinner()
@view.$el.html().should.containEql 'loading-spinner'
describe '#renderFollowed', ->
it 'renders a string that is a comma separated list that ends with a period', ->
@view.render()
@view.followed = new Backbone.Collection [{ name: '<NAME>', id: 'foo-bar' }, { name: '<NAME>', id: 'baz-qux' }]
@view.renderFollowed()
@view.$el.html().should.containEql 'Foo Bar, Baz Qux.'
describe '#follow', ->
beforeEach ->
@view.results = new Backbone.Collection [{ name: '<NAME>', id: 'foo-bar' }]
@view.render()
@view.renderResults()
afterEach ->
@view.remove()
it 'should set the followed attribute on the appropriate model to true', ->
$follow = @view.$('.follow').eq(0)
model = @view.results.get($follow.data('id'))
model.attributes.should.not.have.property 'followed'
$follow.click()
model.get('followed').should.be.ok()
it 'should call #followArtist on the user', ->
spy = sinon.spy @view.user, 'followArtist'
@view.$('.follow').eq(0).click()
spy.called.should.be.ok()
it 'should prepend the followed artist to the followed collection', ->
@view.$('.follow').eq(0).click()
@view.results.reset { name: '<NAME>', id: 'baz-qux' }
@view.renderResults()
@view.$('.follow').eq(0).click()
@view.followed.at(0).id.should.equal 'baz-qux'
describe '#render', ->
it 'renders the template', ->
@view.render().$el.html().should.containEql 'Follow artists to get personalized recommendations'
describe 'PriceRangeView', ->
beforeEach (done) ->
benv.setup =>
benv.expose { $: benv.require 'jquery' }
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @PriceRangeView } = mod = benv.requireWithJadeify resolve(__dirname, '../../client/price_range_view'),
['template']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @PriceRangeView(state: @state, user: @user)
@view.postRender = -> # Ignore
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#setRange', ->
it 'sets the price_range attribute on the user', ->
@view.render()
@view.$('a').eq(0).click()
@view.user.get('price_range_min').should.equal '-1'
@view.user.get('price_range_max').should.equal '500'
it 'should call done', ->
@view.render()
spy = sinon.spy @view, 'done'
@view.$('a').eq(0).click()
spy.called.should.be.ok()
describe '#done', ->
it 'triggers the done event on PersonalizeState', ->
spy = sinon.spy()
@view.state.on 'done', spy
@view.done()
spy.called.should.be.ok()
describe '#render', ->
it 'renders the view', ->
@view.render()
@view.$el.html().should.containEql 'Price range?'
| true | _ = require 'underscore'
Backbone = require 'backbone'
sinon = require 'sinon'
PersonalizeState = require '../../client/personalize_state.coffee'
CurrentUser = require '../../../../models/current_user.coffee'
benv = require 'benv'
{ resolve } = require 'path'
describe 'Personalization view code', ->
beforeEach (done) ->
benv.setup =>
benv.expose $: benv.require 'jquery'
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @CollectView } = benv.requireWithJadeify resolve(__dirname, '../../client/collect_view'),
['template']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @CollectView(state: @state, user: @user)
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#setCollectorLevel', ->
beforeEach ->
@view.render()
it 'sets the collector_level attribute on the user', ->
@view.$('a').eq(0).click()
@view.user.get('collector_level').should.equal 3
it 'sets the level of PersonalizeState', ->
@view.$('a').eq(1).click()
@view.state.get('current_level').should.equal 2
it 'triggers the event \'transition:next\' on PersonalizeState', ->
spy = sinon.spy @view, 'advance'
@view.$('a').eq(1).click()
spy.called.should.be.ok()
describe '#render', ->
it 'renders the template', ->
@view.render()
@view.$el.html().should.containEql 'Do you buy art?'
describe 'LocationView', ->
beforeEach (done) ->
benv.setup =>
benv.expose { $: benv.require 'jquery' }
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @LocationView } = mod = benv.requireWithJadeify resolve(__dirname, '../../client/location_view'),
['template']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @LocationView(state: @state, user: @user)
@view.postRender = -> # Ignore
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#update', ->
before ->
# Mock response of New York
@location = require './location.coffee'
it 'sets the location on the user', ->
@view.update @location
@view.user.get('location').city.should.equal 'New York'
@view.user.get('location').state.should.equal 'New York'
@view.user.get('location').state_code.should.equal 'NY'
it 'triggers the event \'transition:next\' on PersonalizeState', ->
spy = sinon.spy()
@view.state.on 'transition:next', spy
@view.update @location
spy.called.should.be.ok()
describe '#render', ->
it 'renders the template', ->
@view.render()
@view.$el.html().should.containEql 'Where do you call home?'
it 'calls #postRender', ->
spy = sinon.spy @view, 'postRender'
@view.render()
spy.called.should.be.ok()
describe 'ArtistsView', ->
beforeEach (done) ->
benv.setup =>
benv.expose { $: benv.require 'jquery' }
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @ArtistsView } = mod = benv.requireWithJadeify resolve(__dirname, '../../client/artists_view'),
['template', 'resultsTemplate', 'followedTemplate']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @ArtistsView(state: @state, user: @user)
@view.postRender = -> # Ignore
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#skip', ->
it 'triggers the event \'transition:next\' on PersonalizeState', ->
spy = sinon.spy()
@view.render()
@view.state.on 'transition:next', spy
@view.$('#skip').click()
spy.called.should.be.ok()
describe '#_search', ->
beforeEach ->
@view.render()
it 'gets the input value and initiates search', ->
term = 'Foo Bar'
@view.$('input').val term
@view._search()
@view.term.should.equal term
it 'should indicate loading', ->
spy = sinon.spy @view, 'renderLoadingSpinner'
@view.term = null
@view.$('input').val 'Foo Bar'
@view._search()
spy.called.should.be.ok()
it 'should not perform a search if the term is the same as last time', ->
spy = sinon.spy @view.service, 'fetch'
@view.term = 'Foo Bar'
@view.$('input').val 'Foo Bar'
@view._search()
spy.called.should.not.be.ok()
@view.$('input').val 'Bar Baz'
@view._search()
spy.called.should.be.ok()
describe '#renderLoadingSpinner', ->
it 'renders the loading-spinner', ->
@view.render()
@view.$el.html().should.not.containEql 'loading-spinner'
@view.renderLoadingSpinner()
@view.$el.html().should.containEql 'loading-spinner'
describe '#renderFollowed', ->
it 'renders a string that is a comma separated list that ends with a period', ->
@view.render()
@view.followed = new Backbone.Collection [{ name: 'PI:NAME:<NAME>END_PI', id: 'foo-bar' }, { name: 'PI:NAME:<NAME>END_PI', id: 'baz-qux' }]
@view.renderFollowed()
@view.$el.html().should.containEql 'Foo Bar, Baz Qux.'
describe '#follow', ->
beforeEach ->
@view.results = new Backbone.Collection [{ name: 'PI:NAME:<NAME>END_PI', id: 'foo-bar' }]
@view.render()
@view.renderResults()
afterEach ->
@view.remove()
it 'should set the followed attribute on the appropriate model to true', ->
$follow = @view.$('.follow').eq(0)
model = @view.results.get($follow.data('id'))
model.attributes.should.not.have.property 'followed'
$follow.click()
model.get('followed').should.be.ok()
it 'should call #followArtist on the user', ->
spy = sinon.spy @view.user, 'followArtist'
@view.$('.follow').eq(0).click()
spy.called.should.be.ok()
it 'should prepend the followed artist to the followed collection', ->
@view.$('.follow').eq(0).click()
@view.results.reset { name: 'PI:NAME:<NAME>END_PI', id: 'baz-qux' }
@view.renderResults()
@view.$('.follow').eq(0).click()
@view.followed.at(0).id.should.equal 'baz-qux'
describe '#render', ->
it 'renders the template', ->
@view.render().$el.html().should.containEql 'Follow artists to get personalized recommendations'
describe 'PriceRangeView', ->
beforeEach (done) ->
benv.setup =>
benv.expose { $: benv.require 'jquery' }
Backbone.$ = $
sinon.stub Backbone, 'sync'
benv.render resolve(__dirname, '../../templates/index.jade'), {
sd: {}
}, =>
{ @PriceRangeView } = mod = benv.requireWithJadeify resolve(__dirname, '../../client/price_range_view'),
['template']
@state = new PersonalizeState
@user = new CurrentUser
@view = new @PriceRangeView(state: @state, user: @user)
@view.postRender = -> # Ignore
done()
afterEach ->
benv.teardown()
Backbone.sync.restore()
describe '#setRange', ->
it 'sets the price_range attribute on the user', ->
@view.render()
@view.$('a').eq(0).click()
@view.user.get('price_range_min').should.equal '-1'
@view.user.get('price_range_max').should.equal '500'
it 'should call done', ->
@view.render()
spy = sinon.spy @view, 'done'
@view.$('a').eq(0).click()
spy.called.should.be.ok()
describe '#done', ->
it 'triggers the done event on PersonalizeState', ->
spy = sinon.spy()
@view.state.on 'done', spy
@view.done()
spy.called.should.be.ok()
describe '#render', ->
it 'renders the view', ->
@view.render()
@view.$el.html().should.containEql 'Price range?'
|
[
{
"context": "a font name for use later\n doc.registerFont('Charter', 'assets/charter.ttf')\n\n # Set the font, draw s",
"end": 134,
"score": 0.6111172437667847,
"start": 131,
"tag": "NAME",
"value": "ter"
},
{
"context": "\n # Set the font, draw some text\n doc.font('Charter')\n... | pitfall/ptest/test12.coffee | mbutterick/typesetting | 22 | PDFDocument = require 'pdfkit'
fs = require 'fs'
make = (doc) ->
# Register a font name for use later
doc.registerFont('Charter', 'assets/charter.ttf')
# Set the font, draw some text
doc.font('Charter')
.fontSize(25)
.text('Some text with an embedded font', 100, 100, {width: false})
doc.end()
doc = new PDFDocument({compress: no})
doc.pipe(fs.createWriteStream('test12.pdf'))
make doc
doc = new PDFDocument({compress: yes})
doc.pipe(fs.createWriteStream('test12c.pdf'))
make doc
| 111803 | PDFDocument = require 'pdfkit'
fs = require 'fs'
make = (doc) ->
# Register a font name for use later
doc.registerFont('Char<NAME>', 'assets/charter.ttf')
# Set the font, draw some text
doc.font('Char<NAME>')
.fontSize(25)
.text('Some text with an embedded font', 100, 100, {width: false})
doc.end()
doc = new PDFDocument({compress: no})
doc.pipe(fs.createWriteStream('test12.pdf'))
make doc
doc = new PDFDocument({compress: yes})
doc.pipe(fs.createWriteStream('test12c.pdf'))
make doc
| true | PDFDocument = require 'pdfkit'
fs = require 'fs'
make = (doc) ->
# Register a font name for use later
doc.registerFont('CharPI:NAME:<NAME>END_PI', 'assets/charter.ttf')
# Set the font, draw some text
doc.font('CharPI:NAME:<NAME>END_PI')
.fontSize(25)
.text('Some text with an embedded font', 100, 100, {width: false})
doc.end()
doc = new PDFDocument({compress: no})
doc.pipe(fs.createWriteStream('test12.pdf'))
make doc
doc = new PDFDocument({compress: yes})
doc.pipe(fs.createWriteStream('test12c.pdf'))
make doc
|
[
{
"context": " a = document.createElement 'a'\n link = 'john.doe@johnny.com'\n a.href = 'mailto:' + link\n a.innerTex",
"end": 2836,
"score": 0.9998638033866882,
"start": 2817,
"tag": "EMAIL",
"value": "john.doe@johnny.com"
}
] | spec/chattifier.spec.coffee | kubkon/email-chattifier | 0 | jsdom = require("jsdom").jsdom
Chattifier = require "../src/chattifier.coffee"
describe "A suite of Chattifier tests:", ->
chattifier = {}
document = {}
node = {}
beforeEach ->
# create mock documentument
document = jsdom '<html></html>'
# create mock node
node = document.createElement 'div'
document.body.appendChild node
# create the Chattifier and add the node
chattifier = new Chattifier document
chattifier.ancestorNode = node
describe "tests whether the immediate parent node of", ->
beforeEach ->
# create mock documentument
document = jsdom '<html></html>'
# create mock node
node = document.createElement 'div'
node.className = 'the-parent'
document.body.appendChild node
# create the Chattifier and add the node
chattifier = new Chattifier document
it "topmost blockquote element is selected, or", ->
html = "<blockquote id='top'><blockquote id='inner'></blockquote></blockquote>"
node.innerHTML = html
# run chattifier
chattifier.inferAncestorNode()
# test
expect(chattifier.ancestorNode.tagName.toLowerCase()).
toEqual "div"
expect(chattifier.ancestorNode.className.toLowerCase()).
toEqual "the-parent"
it "the parent of the element containing the text blockquotes of type >...>, or", ->
html = "<p>>> something\n>> something\n>> something</p>"
node.innerHTML = html
# run chattifier
chattifier.inferAncestorNode()
# test
expect(chattifier.ancestorNode.tagName.toLowerCase()).
toEqual "div"
expect(chattifier.ancestorNode.className.toLowerCase()).
toEqual "the-parent"
it "exits gracefully otherwise", ->
# run chattifier
chattifier.inferAncestorNode()
# test
expect(chattifier.ancestorNode).
toEqual null
describe "tests that any existing hyperlink within the ancestor node", ->
it "should be escaped before parsing content", ->
links = [
'www.google.com',
'http://www.google.com',
'https://www.google.com',
'http://google.com',
'https://google.com',
'https://google.com/0/12398sf',
'https://chrome.google.com/webstore/detail/e-c/abcdefghijkslme?utm_source=gmail'
]
# generate links of different structure
for link in links
a = document.createElement 'a'
a.href = link
a.innerText = link
node.appendChild a
# run chattifier
chattifier.escapeHyperlinks()
# test output
for a, i in node.getElementsByTagName "a"
expect(a.innerText).
toEqual "[" + links[i] + "](" + links[i] + ")"
it "unless it is an email address", ->
a = document.createElement 'a'
link = 'john.doe@johnny.com'
a.href = 'mailto:' + link
a.innerText = link
node.appendChild a
# run chattifier
chattifier.escapeHyperlinks()
# test output
expect(a.innerText).
toEqual link
it "tests removing blockquote elements and preserving its HTML content", ->
# create mock document containing blockquote elements
html = "<blockquote><p>Outer blockquote</p>" +
"<blockquote><p>Inner blockquote</p>" +
"</blockquote></blockquote>"
node.innerHTML = html
# run chattifier
chattifier.removeBlockquotes()
# test output
expect(node.getElementsByTagName("blockquote").length).
toEqual 0
html = "<p><p>Outer blockquote</p><p><p>Inner blockquote</p></p></p>"
expect(node.innerHTML).
toEqual html
describe "tests the HTML output should be grouped into divs regardless if", ->
it "has a header element as the topmost element, or if", ->
# create mock document of the following structure
h = "h" + Chattifier.headerStartLevel
html = "<" + h + "><p>First</p></" + h + ">" +
"<" + h + "><p>Second</p></" + h + ">"
node.innerHTML = html
# run chattifier
chattifier.groupIntoDivs()
# test output
html = '<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '"></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[1] + '">' +
'<' + h + '><p>First</p></' + h + '></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '">' +
'<' + h + '><p>Second</p></' + h + '></div>'
expect(node.innerHTML).
toEqual html
it "has a paragraph element as the topmost element", ->
# create mock document of the following structure
h = "h" + Chattifier.headerStartLevel
html = "<p>Zero</p>" +
"<" + h + "><p>First</p></" + h + ">" +
"<" + h + "><p>Second</p></" + h + ">"
node.innerHTML = html
# run chattifier
chattifier.groupIntoDivs()
# test output
html = '<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '">' +
'<p>Zero</p></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[1] + '">' +
'<' + h + '><p>First</p></' + h + '></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '">' +
'<' + h + '><p>Second</p></' + h + '></div>'
expect(node.innerHTML).
toEqual html
| 211428 | jsdom = require("jsdom").jsdom
Chattifier = require "../src/chattifier.coffee"
describe "A suite of Chattifier tests:", ->
chattifier = {}
document = {}
node = {}
beforeEach ->
# create mock documentument
document = jsdom '<html></html>'
# create mock node
node = document.createElement 'div'
document.body.appendChild node
# create the Chattifier and add the node
chattifier = new Chattifier document
chattifier.ancestorNode = node
describe "tests whether the immediate parent node of", ->
beforeEach ->
# create mock documentument
document = jsdom '<html></html>'
# create mock node
node = document.createElement 'div'
node.className = 'the-parent'
document.body.appendChild node
# create the Chattifier and add the node
chattifier = new Chattifier document
it "topmost blockquote element is selected, or", ->
html = "<blockquote id='top'><blockquote id='inner'></blockquote></blockquote>"
node.innerHTML = html
# run chattifier
chattifier.inferAncestorNode()
# test
expect(chattifier.ancestorNode.tagName.toLowerCase()).
toEqual "div"
expect(chattifier.ancestorNode.className.toLowerCase()).
toEqual "the-parent"
it "the parent of the element containing the text blockquotes of type >...>, or", ->
html = "<p>>> something\n>> something\n>> something</p>"
node.innerHTML = html
# run chattifier
chattifier.inferAncestorNode()
# test
expect(chattifier.ancestorNode.tagName.toLowerCase()).
toEqual "div"
expect(chattifier.ancestorNode.className.toLowerCase()).
toEqual "the-parent"
it "exits gracefully otherwise", ->
# run chattifier
chattifier.inferAncestorNode()
# test
expect(chattifier.ancestorNode).
toEqual null
describe "tests that any existing hyperlink within the ancestor node", ->
it "should be escaped before parsing content", ->
links = [
'www.google.com',
'http://www.google.com',
'https://www.google.com',
'http://google.com',
'https://google.com',
'https://google.com/0/12398sf',
'https://chrome.google.com/webstore/detail/e-c/abcdefghijkslme?utm_source=gmail'
]
# generate links of different structure
for link in links
a = document.createElement 'a'
a.href = link
a.innerText = link
node.appendChild a
# run chattifier
chattifier.escapeHyperlinks()
# test output
for a, i in node.getElementsByTagName "a"
expect(a.innerText).
toEqual "[" + links[i] + "](" + links[i] + ")"
it "unless it is an email address", ->
a = document.createElement 'a'
link = '<EMAIL>'
a.href = 'mailto:' + link
a.innerText = link
node.appendChild a
# run chattifier
chattifier.escapeHyperlinks()
# test output
expect(a.innerText).
toEqual link
it "tests removing blockquote elements and preserving its HTML content", ->
# create mock document containing blockquote elements
html = "<blockquote><p>Outer blockquote</p>" +
"<blockquote><p>Inner blockquote</p>" +
"</blockquote></blockquote>"
node.innerHTML = html
# run chattifier
chattifier.removeBlockquotes()
# test output
expect(node.getElementsByTagName("blockquote").length).
toEqual 0
html = "<p><p>Outer blockquote</p><p><p>Inner blockquote</p></p></p>"
expect(node.innerHTML).
toEqual html
describe "tests the HTML output should be grouped into divs regardless if", ->
it "has a header element as the topmost element, or if", ->
# create mock document of the following structure
h = "h" + Chattifier.headerStartLevel
html = "<" + h + "><p>First</p></" + h + ">" +
"<" + h + "><p>Second</p></" + h + ">"
node.innerHTML = html
# run chattifier
chattifier.groupIntoDivs()
# test output
html = '<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '"></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[1] + '">' +
'<' + h + '><p>First</p></' + h + '></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '">' +
'<' + h + '><p>Second</p></' + h + '></div>'
expect(node.innerHTML).
toEqual html
it "has a paragraph element as the topmost element", ->
# create mock document of the following structure
h = "h" + Chattifier.headerStartLevel
html = "<p>Zero</p>" +
"<" + h + "><p>First</p></" + h + ">" +
"<" + h + "><p>Second</p></" + h + ">"
node.innerHTML = html
# run chattifier
chattifier.groupIntoDivs()
# test output
html = '<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '">' +
'<p>Zero</p></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[1] + '">' +
'<' + h + '><p>First</p></' + h + '></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '">' +
'<' + h + '><p>Second</p></' + h + '></div>'
expect(node.innerHTML).
toEqual html
| true | jsdom = require("jsdom").jsdom
Chattifier = require "../src/chattifier.coffee"
describe "A suite of Chattifier tests:", ->
chattifier = {}
document = {}
node = {}
beforeEach ->
# create mock documentument
document = jsdom '<html></html>'
# create mock node
node = document.createElement 'div'
document.body.appendChild node
# create the Chattifier and add the node
chattifier = new Chattifier document
chattifier.ancestorNode = node
describe "tests whether the immediate parent node of", ->
beforeEach ->
# create mock documentument
document = jsdom '<html></html>'
# create mock node
node = document.createElement 'div'
node.className = 'the-parent'
document.body.appendChild node
# create the Chattifier and add the node
chattifier = new Chattifier document
it "topmost blockquote element is selected, or", ->
html = "<blockquote id='top'><blockquote id='inner'></blockquote></blockquote>"
node.innerHTML = html
# run chattifier
chattifier.inferAncestorNode()
# test
expect(chattifier.ancestorNode.tagName.toLowerCase()).
toEqual "div"
expect(chattifier.ancestorNode.className.toLowerCase()).
toEqual "the-parent"
it "the parent of the element containing the text blockquotes of type >...>, or", ->
html = "<p>>> something\n>> something\n>> something</p>"
node.innerHTML = html
# run chattifier
chattifier.inferAncestorNode()
# test
expect(chattifier.ancestorNode.tagName.toLowerCase()).
toEqual "div"
expect(chattifier.ancestorNode.className.toLowerCase()).
toEqual "the-parent"
it "exits gracefully otherwise", ->
# run chattifier
chattifier.inferAncestorNode()
# test
expect(chattifier.ancestorNode).
toEqual null
describe "tests that any existing hyperlink within the ancestor node", ->
it "should be escaped before parsing content", ->
links = [
'www.google.com',
'http://www.google.com',
'https://www.google.com',
'http://google.com',
'https://google.com',
'https://google.com/0/12398sf',
'https://chrome.google.com/webstore/detail/e-c/abcdefghijkslme?utm_source=gmail'
]
# generate links of different structure
for link in links
a = document.createElement 'a'
a.href = link
a.innerText = link
node.appendChild a
# run chattifier
chattifier.escapeHyperlinks()
# test output
for a, i in node.getElementsByTagName "a"
expect(a.innerText).
toEqual "[" + links[i] + "](" + links[i] + ")"
it "unless it is an email address", ->
a = document.createElement 'a'
link = 'PI:EMAIL:<EMAIL>END_PI'
a.href = 'mailto:' + link
a.innerText = link
node.appendChild a
# run chattifier
chattifier.escapeHyperlinks()
# test output
expect(a.innerText).
toEqual link
it "tests removing blockquote elements and preserving its HTML content", ->
# create mock document containing blockquote elements
html = "<blockquote><p>Outer blockquote</p>" +
"<blockquote><p>Inner blockquote</p>" +
"</blockquote></blockquote>"
node.innerHTML = html
# run chattifier
chattifier.removeBlockquotes()
# test output
expect(node.getElementsByTagName("blockquote").length).
toEqual 0
html = "<p><p>Outer blockquote</p><p><p>Inner blockquote</p></p></p>"
expect(node.innerHTML).
toEqual html
describe "tests the HTML output should be grouped into divs regardless if", ->
it "has a header element as the topmost element, or if", ->
# create mock document of the following structure
h = "h" + Chattifier.headerStartLevel
html = "<" + h + "><p>First</p></" + h + ">" +
"<" + h + "><p>Second</p></" + h + ">"
node.innerHTML = html
# run chattifier
chattifier.groupIntoDivs()
# test output
html = '<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '"></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[1] + '">' +
'<' + h + '><p>First</p></' + h + '></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '">' +
'<' + h + '><p>Second</p></' + h + '></div>'
expect(node.innerHTML).
toEqual html
it "has a paragraph element as the topmost element", ->
# create mock document of the following structure
h = "h" + Chattifier.headerStartLevel
html = "<p>Zero</p>" +
"<" + h + "><p>First</p></" + h + ">" +
"<" + h + "><p>Second</p></" + h + ">"
node.innerHTML = html
# run chattifier
chattifier.groupIntoDivs()
# test output
html = '<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '">' +
'<p>Zero</p></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[1] + '">' +
'<' + h + '><p>First</p></' + h + '></div>' +
'<div class="' + Chattifier.cssAttrs.mainClass + ' ' +
Chattifier.cssAttrs.alternatingClasses[0] + '">' +
'<' + h + '><p>Second</p></' + h + '></div>'
expect(node.innerHTML).
toEqual html
|
[
{
"context": "fault']\n\n p1 = P.create()\n p1.name('foo')\n p1.age(1)\n\n p1Obj =\n ",
"end": 380,
"score": 0.8667365908622742,
"start": 377,
"tag": "NAME",
"value": "foo"
},
{
"context": " p1.age(1)\n\n p1Obj =\n name: 'fo... | samplenode/samplenode/node_modules/nodejs-model/test/test-attributes-tags.coffee | thakurarun/Basic-nodejs-express-app | 19 | u = require 'util'
model = require '../lib/index'
_ = require 'underscore'
describe 'Attributes Tags', ->
it "Ensure default tag is 'default'", (done) ->
P = model("Person").attr('name').attr('age')
P.attrsDefs().name.tags.should.deep.equal ['default']
P.attrsDefs().age.tags.should.deep.equal ['default']
p1 = P.create()
p1.name('foo')
p1.age(1)
p1Obj =
name: 'foo'
age: 1
p1.toJSON().should.deep.equal p1Obj
p1.toJSON('default').should.deep.equal p1Obj
p1.toJSON('priv').should.deep.equal {}
done()
#TODO: More tests goes here | 165179 | u = require 'util'
model = require '../lib/index'
_ = require 'underscore'
describe 'Attributes Tags', ->
it "Ensure default tag is 'default'", (done) ->
P = model("Person").attr('name').attr('age')
P.attrsDefs().name.tags.should.deep.equal ['default']
P.attrsDefs().age.tags.should.deep.equal ['default']
p1 = P.create()
p1.name('<NAME>')
p1.age(1)
p1Obj =
name: '<NAME>'
age: 1
p1.toJSON().should.deep.equal p1Obj
p1.toJSON('default').should.deep.equal p1Obj
p1.toJSON('priv').should.deep.equal {}
done()
#TODO: More tests goes here | true | u = require 'util'
model = require '../lib/index'
_ = require 'underscore'
describe 'Attributes Tags', ->
it "Ensure default tag is 'default'", (done) ->
P = model("Person").attr('name').attr('age')
P.attrsDefs().name.tags.should.deep.equal ['default']
P.attrsDefs().age.tags.should.deep.equal ['default']
p1 = P.create()
p1.name('PI:NAME:<NAME>END_PI')
p1.age(1)
p1Obj =
name: 'PI:NAME:<NAME>END_PI'
age: 1
p1.toJSON().should.deep.equal p1Obj
p1.toJSON('default').should.deep.equal p1Obj
p1.toJSON('priv').should.deep.equal {}
done()
#TODO: More tests goes here |
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9985394477844238,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-http-client-race-2.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
url = require("url")
#
# Slight variation on test-http-client-race to test for another race
# condition involving the parsers FreeList used internally by http.Client.
#
body1_s = "1111111111111111"
body2_s = "22222"
body3_s = "3333333333333333333"
server = http.createServer((req, res) ->
pathname = url.parse(req.url).pathname
body = undefined
switch pathname
when "/1"
body = body1_s
when "/2"
body = body2_s
else
body = body3_s
res.writeHead 200,
"Content-Type": "text/plain"
"Content-Length": body.length
res.end body
return
)
server.listen common.PORT
body1 = ""
body2 = ""
body3 = ""
server.on "listening", ->
client = http.createClient(common.PORT)
#
# Client #1 is assigned Parser #1
#
req1 = client.request("/1")
req1.end()
req1.on "response", (res1) ->
res1.setEncoding "utf8"
res1.on "data", (chunk) ->
body1 += chunk
return
res1.on "end", ->
#
# Delay execution a little to allow the 'close' event to be processed
# (required to trigger this bug!)
#
setTimeout (->
#
# The bug would introduce itself here: Client #2 would be allocated the
# parser that previously belonged to Client #1. But we're not finished
# with Client #1 yet!
#
client2 = http.createClient(common.PORT)
#
# At this point, the bug would manifest itself and crash because the
# internal state of the parser was no longer valid for use by Client #1
#
req2 = client.request("/2")
req2.end()
req2.on "response", (res2) ->
res2.setEncoding "utf8"
res2.on "data", (chunk) ->
body2 += chunk
return
res2.on "end", ->
#
# Just to be really sure we've covered all our bases, execute a
# request using client2.
#
req3 = client2.request("/3")
req3.end()
req3.on "response", (res3) ->
res3.setEncoding "utf8"
res3.on "data", (chunk) ->
body3 += chunk
return
res3.on "end", ->
server.close()
return
return
return
return
return
), 500
return
return
return
process.on "exit", ->
assert.equal body1_s, body1
assert.equal body2_s, body2
assert.equal body3_s, body3
return
| 163850 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
url = require("url")
#
# Slight variation on test-http-client-race to test for another race
# condition involving the parsers FreeList used internally by http.Client.
#
body1_s = "1111111111111111"
body2_s = "22222"
body3_s = "3333333333333333333"
server = http.createServer((req, res) ->
pathname = url.parse(req.url).pathname
body = undefined
switch pathname
when "/1"
body = body1_s
when "/2"
body = body2_s
else
body = body3_s
res.writeHead 200,
"Content-Type": "text/plain"
"Content-Length": body.length
res.end body
return
)
server.listen common.PORT
body1 = ""
body2 = ""
body3 = ""
server.on "listening", ->
client = http.createClient(common.PORT)
#
# Client #1 is assigned Parser #1
#
req1 = client.request("/1")
req1.end()
req1.on "response", (res1) ->
res1.setEncoding "utf8"
res1.on "data", (chunk) ->
body1 += chunk
return
res1.on "end", ->
#
# Delay execution a little to allow the 'close' event to be processed
# (required to trigger this bug!)
#
setTimeout (->
#
# The bug would introduce itself here: Client #2 would be allocated the
# parser that previously belonged to Client #1. But we're not finished
# with Client #1 yet!
#
client2 = http.createClient(common.PORT)
#
# At this point, the bug would manifest itself and crash because the
# internal state of the parser was no longer valid for use by Client #1
#
req2 = client.request("/2")
req2.end()
req2.on "response", (res2) ->
res2.setEncoding "utf8"
res2.on "data", (chunk) ->
body2 += chunk
return
res2.on "end", ->
#
# Just to be really sure we've covered all our bases, execute a
# request using client2.
#
req3 = client2.request("/3")
req3.end()
req3.on "response", (res3) ->
res3.setEncoding "utf8"
res3.on "data", (chunk) ->
body3 += chunk
return
res3.on "end", ->
server.close()
return
return
return
return
return
), 500
return
return
return
process.on "exit", ->
assert.equal body1_s, body1
assert.equal body2_s, body2
assert.equal body3_s, body3
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
http = require("http")
url = require("url")
#
# Slight variation on test-http-client-race to test for another race
# condition involving the parsers FreeList used internally by http.Client.
#
body1_s = "1111111111111111"
body2_s = "22222"
body3_s = "3333333333333333333"
server = http.createServer((req, res) ->
pathname = url.parse(req.url).pathname
body = undefined
switch pathname
when "/1"
body = body1_s
when "/2"
body = body2_s
else
body = body3_s
res.writeHead 200,
"Content-Type": "text/plain"
"Content-Length": body.length
res.end body
return
)
server.listen common.PORT
body1 = ""
body2 = ""
body3 = ""
server.on "listening", ->
client = http.createClient(common.PORT)
#
# Client #1 is assigned Parser #1
#
req1 = client.request("/1")
req1.end()
req1.on "response", (res1) ->
res1.setEncoding "utf8"
res1.on "data", (chunk) ->
body1 += chunk
return
res1.on "end", ->
#
# Delay execution a little to allow the 'close' event to be processed
# (required to trigger this bug!)
#
setTimeout (->
#
# The bug would introduce itself here: Client #2 would be allocated the
# parser that previously belonged to Client #1. But we're not finished
# with Client #1 yet!
#
client2 = http.createClient(common.PORT)
#
# At this point, the bug would manifest itself and crash because the
# internal state of the parser was no longer valid for use by Client #1
#
req2 = client.request("/2")
req2.end()
req2.on "response", (res2) ->
res2.setEncoding "utf8"
res2.on "data", (chunk) ->
body2 += chunk
return
res2.on "end", ->
#
# Just to be really sure we've covered all our bases, execute a
# request using client2.
#
req3 = client2.request("/3")
req3.end()
req3.on "response", (res3) ->
res3.setEncoding "utf8"
res3.on "data", (chunk) ->
body3 += chunk
return
res3.on "end", ->
server.close()
return
return
return
return
return
), 500
return
return
return
process.on "exit", ->
assert.equal body1_s, body1
assert.equal body2_s, body2
assert.equal body3_s, body3
return
|
[
{
"context": " }\n ],\n \"message\": null,\n \"token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1MTk4OTI3MTMsImV4cCI6MTU1MTQyODcxMywiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSJ9._PWCLR7lgLmX3qA3gVnAhyGj-wt3WjDeNaml_tOunJM\"\n}\n... | server/src/upgrade.coffee | muonium/docs | 0 | ###
@api {get} /upgrade/history Get upgrade history
@apiName GetHistory
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object[]} data Array of objects containing:
@apiSuccess (Success 200) {String} data.txn_id Transaction id.
@apiSuccess (Success 200) {Int} data.size Amount of storage obtained with this offer in B.
@apiSuccess (Success 200) {Float} data.price Price.
@apiSuccess (Success 200) {String} data.currency Currency (ISO 4217).
@apiSuccess (Success 200) {String} data.currency_symbol Currency (symbol).
@apiSuccess (Success 200) {Int} data.start Timestamp which corresponds to subscription date.
@apiSuccess (Success 200) {Int} data.end Timestamp which corresponds to upgrade expiration.
@apiSuccess (Success 200) {Int} data.removed 0: no, 1: yes.
@apiSuccessExample {json} Success-Response:
{
"code": 200,
"status": "success",
"data": [
{
"txn_id": "XDGHGTFHHBTH",
"size": "10000000000",
"price": 4,
"currency": "EUR",
"start": 0,
"end": 1525104943,
"removed": 0,
"currency_symbol": "€"
},
{
"txn_id": "XDGHGTFHHBTT",
"size": "10000000000",
"price": 4,
"currency": "EUR",
"start": 0,
"end": 1525104943,
"removed": 0,
"currency_symbol": "€"
}
],
"message": null,
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1MTk4OTI3MTMsImV4cCI6MTU1MTQyODcxMywiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSJ9._PWCLR7lgLmX3qA3gVnAhyGj-wt3WjDeNaml_tOunJM"
}
###
###
@api {get} /upgrade/plans Get available plans/offers
@apiName GetPlans
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {String} data.endpoint Endpoint. You have to create a form for each offer which targets this endpoint.
@apiSuccess (Success 200) {Object[]} data.plans Array of objects containing:
@apiSuccess (Success 200) {Int} data.plans.size Amount of storage for this offer in B.
@apiSuccess (Success 200) {Float} data.plans.price Price.
@apiSuccess (Success 200) {String} data.plans.currency Currency (ISO 4217).
@apiSuccess (Success 200) {String} data.plans.currency_symbol Currency (symbol).
@apiSuccess (Success 200) {Int} data.plans.duration Duration in months.
@apiSuccess (Success 200) {String} data.plans.product_id Product ID.
@apiSuccess (Success 200) {Object} data.plans.fields An object containing data which have to be sent within the form (as hidden input with key as name and value as value). You will have to add manually an hidden input for success (success_url) and cancel URL (cancel_url) (as it may change according to client used)
@apiSuccessExample {json} Success-Response:
{
"code": 200,
"status": "success",
"data": {
"endpoint": "https://www.coinpayments.net/index.php",
"plans": [
{
"size": "10000000000",
"price": 4,
"currency": "eur",
"duration": 6,
"product_id": "PGVG4FRY3EDKG",
"fields": {
"cmd": "_pay_simple",
"merchant": "2df67e134da679931d3cd7baa62496d0",
"item_name": "10 GB - 4 EUR - 6 months",
"item_number": "PGVG4FRY3EDKG",
"currency": "eur",
"amountf": 4,
"ipn_url": "https://localhost/server/ipn",
"custom": null,
"want_shipping": "0"
}
}
]
},
"message": null,
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE1MTk4OTI3MTMsImV4cCI6MTU1MTQyODcxMywiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSJ9._PWCLR7lgLmX3qA3gVnAhyGj-wt3WjDeNaml_tOunJM"
}
###
###
@api {get} /upgrade/canSubscribe Can the user subscribe to a new offer?
@apiName GetCanSubscribe
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.can_subscribe true or false.
###
###
@api {get} /upgrade/hasSubscriptionActive Does the user have an active offer?
@apiName GetHasSubscriptionActive
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.subscribed true or false.
@apiSuccess (Success 200) {Int} [data.id_upgrade] Upgrade ID.
###
###
@api {get} /upgrade/cancel Cancel the current offer
@apiName GetCancel
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.canceled true or false.
###
###
@api {get} /upgrade/hasSubscriptionEnded Has the current offer ended?
@apiName GetHasSubscriptionEnded
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.expired true or false.
@apiSuccess (Success 200) {Int} [data.days_left] Days left.
@apiSuccess (Success 200) {Boolean} [data.expires_soon] Expiration in less than 1 week?
###
| 82100 | ###
@api {get} /upgrade/history Get upgrade history
@apiName GetHistory
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object[]} data Array of objects containing:
@apiSuccess (Success 200) {String} data.txn_id Transaction id.
@apiSuccess (Success 200) {Int} data.size Amount of storage obtained with this offer in B.
@apiSuccess (Success 200) {Float} data.price Price.
@apiSuccess (Success 200) {String} data.currency Currency (ISO 4217).
@apiSuccess (Success 200) {String} data.currency_symbol Currency (symbol).
@apiSuccess (Success 200) {Int} data.start Timestamp which corresponds to subscription date.
@apiSuccess (Success 200) {Int} data.end Timestamp which corresponds to upgrade expiration.
@apiSuccess (Success 200) {Int} data.removed 0: no, 1: yes.
@apiSuccessExample {json} Success-Response:
{
"code": 200,
"status": "success",
"data": [
{
"txn_id": "XDGHGTFHHBTH",
"size": "10000000000",
"price": 4,
"currency": "EUR",
"start": 0,
"end": 1525104943,
"removed": 0,
"currency_symbol": "€"
},
{
"txn_id": "XDGHGTFHHBTT",
"size": "10000000000",
"price": 4,
"currency": "EUR",
"start": 0,
"end": 1525104943,
"removed": 0,
"currency_symbol": "€"
}
],
"message": null,
"token": "<KEY>"
}
###
###
@api {get} /upgrade/plans Get available plans/offers
@apiName GetPlans
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {String} data.endpoint Endpoint. You have to create a form for each offer which targets this endpoint.
@apiSuccess (Success 200) {Object[]} data.plans Array of objects containing:
@apiSuccess (Success 200) {Int} data.plans.size Amount of storage for this offer in B.
@apiSuccess (Success 200) {Float} data.plans.price Price.
@apiSuccess (Success 200) {String} data.plans.currency Currency (ISO 4217).
@apiSuccess (Success 200) {String} data.plans.currency_symbol Currency (symbol).
@apiSuccess (Success 200) {Int} data.plans.duration Duration in months.
@apiSuccess (Success 200) {String} data.plans.product_id Product ID.
@apiSuccess (Success 200) {Object} data.plans.fields An object containing data which have to be sent within the form (as hidden input with key as name and value as value). You will have to add manually an hidden input for success (success_url) and cancel URL (cancel_url) (as it may change according to client used)
@apiSuccessExample {json} Success-Response:
{
"code": 200,
"status": "success",
"data": {
"endpoint": "https://www.coinpayments.net/index.php",
"plans": [
{
"size": "10000000000",
"price": 4,
"currency": "eur",
"duration": 6,
"product_id": "PGVG4FRY3EDKG",
"fields": {
"cmd": "_pay_simple",
"merchant": "2df67e134da679931d3cd7baa62496d0",
"item_name": "10 GB - 4 EUR - 6 months",
"item_number": "PGVG4FRY3EDKG",
"currency": "eur",
"amountf": 4,
"ipn_url": "https://localhost/server/ipn",
"custom": null,
"want_shipping": "0"
}
}
]
},
"message": null,
"token": "<KEY>"
}
###
###
@api {get} /upgrade/canSubscribe Can the user subscribe to a new offer?
@apiName GetCanSubscribe
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.can_subscribe true or false.
###
###
@api {get} /upgrade/hasSubscriptionActive Does the user have an active offer?
@apiName GetHasSubscriptionActive
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.subscribed true or false.
@apiSuccess (Success 200) {Int} [data.id_upgrade] Upgrade ID.
###
###
@api {get} /upgrade/cancel Cancel the current offer
@apiName GetCancel
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.canceled true or false.
###
###
@api {get} /upgrade/hasSubscriptionEnded Has the current offer ended?
@apiName GetHasSubscriptionEnded
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.expired true or false.
@apiSuccess (Success 200) {Int} [data.days_left] Days left.
@apiSuccess (Success 200) {Boolean} [data.expires_soon] Expiration in less than 1 week?
###
| true | ###
@api {get} /upgrade/history Get upgrade history
@apiName GetHistory
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object[]} data Array of objects containing:
@apiSuccess (Success 200) {String} data.txn_id Transaction id.
@apiSuccess (Success 200) {Int} data.size Amount of storage obtained with this offer in B.
@apiSuccess (Success 200) {Float} data.price Price.
@apiSuccess (Success 200) {String} data.currency Currency (ISO 4217).
@apiSuccess (Success 200) {String} data.currency_symbol Currency (symbol).
@apiSuccess (Success 200) {Int} data.start Timestamp which corresponds to subscription date.
@apiSuccess (Success 200) {Int} data.end Timestamp which corresponds to upgrade expiration.
@apiSuccess (Success 200) {Int} data.removed 0: no, 1: yes.
@apiSuccessExample {json} Success-Response:
{
"code": 200,
"status": "success",
"data": [
{
"txn_id": "XDGHGTFHHBTH",
"size": "10000000000",
"price": 4,
"currency": "EUR",
"start": 0,
"end": 1525104943,
"removed": 0,
"currency_symbol": "€"
},
{
"txn_id": "XDGHGTFHHBTT",
"size": "10000000000",
"price": 4,
"currency": "EUR",
"start": 0,
"end": 1525104943,
"removed": 0,
"currency_symbol": "€"
}
],
"message": null,
"token": "PI:KEY:<KEY>END_PI"
}
###
###
@api {get} /upgrade/plans Get available plans/offers
@apiName GetPlans
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {String} data.endpoint Endpoint. You have to create a form for each offer which targets this endpoint.
@apiSuccess (Success 200) {Object[]} data.plans Array of objects containing:
@apiSuccess (Success 200) {Int} data.plans.size Amount of storage for this offer in B.
@apiSuccess (Success 200) {Float} data.plans.price Price.
@apiSuccess (Success 200) {String} data.plans.currency Currency (ISO 4217).
@apiSuccess (Success 200) {String} data.plans.currency_symbol Currency (symbol).
@apiSuccess (Success 200) {Int} data.plans.duration Duration in months.
@apiSuccess (Success 200) {String} data.plans.product_id Product ID.
@apiSuccess (Success 200) {Object} data.plans.fields An object containing data which have to be sent within the form (as hidden input with key as name and value as value). You will have to add manually an hidden input for success (success_url) and cancel URL (cancel_url) (as it may change according to client used)
@apiSuccessExample {json} Success-Response:
{
"code": 200,
"status": "success",
"data": {
"endpoint": "https://www.coinpayments.net/index.php",
"plans": [
{
"size": "10000000000",
"price": 4,
"currency": "eur",
"duration": 6,
"product_id": "PGVG4FRY3EDKG",
"fields": {
"cmd": "_pay_simple",
"merchant": "2df67e134da679931d3cd7baa62496d0",
"item_name": "10 GB - 4 EUR - 6 months",
"item_number": "PGVG4FRY3EDKG",
"currency": "eur",
"amountf": 4,
"ipn_url": "https://localhost/server/ipn",
"custom": null,
"want_shipping": "0"
}
}
]
},
"message": null,
"token": "PI:KEY:<KEY>END_PI"
}
###
###
@api {get} /upgrade/canSubscribe Can the user subscribe to a new offer?
@apiName GetCanSubscribe
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.can_subscribe true or false.
###
###
@api {get} /upgrade/hasSubscriptionActive Does the user have an active offer?
@apiName GetHasSubscriptionActive
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.subscribed true or false.
@apiSuccess (Success 200) {Int} [data.id_upgrade] Upgrade ID.
###
###
@api {get} /upgrade/cancel Cancel the current offer
@apiName GetCancel
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.canceled true or false.
###
###
@api {get} /upgrade/hasSubscriptionEnded Has the current offer ended?
@apiName GetHasSubscriptionEnded
@apiGroup Upgrade
@apiHeader {String} token Token (Authorization: Bearer).
@apiSuccess (Success 200) {String} token Current token.
@apiSuccess (Success 200) {Object} data
@apiSuccess (Success 200) {Boolean} data.expired true or false.
@apiSuccess (Success 200) {Int} [data.days_left] Days left.
@apiSuccess (Success 200) {Boolean} [data.expires_soon] Expiration in less than 1 week?
###
|
[
{
"context": " = options.sync\n BASE_COUNT = 5\n\n PICK_KEYS = ['id', 'name']\n\n describe \"hasOne #{options.$paramete",
"end": 631,
"score": 0.7990486025810242,
"start": 629,
"tag": "KEY",
"value": "id"
},
{
"context": "urn done() if options.embed\n\n related_key = 'reverse... | test/spec/sync/relational/has_one.tests.coffee | dk-dev/backbone-orm | 54 | assert = assert or require?('chai').assert
BackboneORM = window?.BackboneORM; try BackboneORM or= require?('backbone-orm') catch; try BackboneORM or= require?('../../../../backbone-orm')
{_, Backbone, Queue, Utils, JSONUtils, Fabricator} = BackboneORM
_.each BackboneORM.TestUtils.optionSets(), exports = (options) ->
options = _.extend({}, options, __test__parameters) if __test__parameters?
return if options.embed and not options.sync.capabilities(options.database_url or '').embed
DATABASE_URL = options.database_url or ''
BASE_SCHEMA = options.schema or {}
SYNC = options.sync
BASE_COUNT = 5
PICK_KEYS = ['id', 'name']
describe "hasOne #{options.$parameter_tags or ''}#{options.$tags} @has_one", ->
Flat = Reverse = ForeignReverse = Owner = null
before ->
BackboneORM.configure {model_cache: {enabled: !!options.cache, max: 100}}
class Flat extends Backbone.Model
model_name: 'Flat'
urlRoot: "#{DATABASE_URL}/one_flats"
schema: _.defaults({
owner: -> ['hasOne', Owner]
}, BASE_SCHEMA)
sync: SYNC(Flat)
class Reverse extends Backbone.Model
model_name: 'Reverse'
urlRoot: "#{DATABASE_URL}/one_reverses"
schema: _.defaults({
owner: -> ['belongsTo', Owner]
owner_as: -> ['belongsTo', Owner, as: 'reverse_as']
}, BASE_SCHEMA)
sync: SYNC(Reverse)
class ForeignReverse extends Backbone.Model
model_name: 'ForeignReverse'
urlRoot: "#{DATABASE_URL}/one_foreign_reverses"
schema: _.defaults({
owner: -> ['belongsTo', Owner, foreign_key: 'ownerish_id']
}, BASE_SCHEMA)
sync: SYNC(ForeignReverse)
class Owner extends Backbone.Model
model_name: 'Owner'
urlRoot: "#{DATABASE_URL}/one_owners"
schema: _.defaults({
flat: -> ['belongsTo', Flat, embed: options.embed]
reverse: -> ['hasOne', Reverse]
reverse_as: -> ['hasOne', Reverse, as: 'owner_as']
foreign_reverse: -> ['hasOne', ForeignReverse]
}, BASE_SCHEMA)
sync: SYNC(Owner)
after (callback) -> Utils.resetSchemas [Flat, Reverse, ForeignReverse, Owner], callback
beforeEach (callback) ->
relation = Owner.relation('flat')
delete relation.virtual
MODELS = {}
queue = new Queue(1)
queue.defer (callback) -> Utils.resetSchemas [Flat, Reverse, ForeignReverse, Owner], callback
queue.defer (callback) ->
create_queue = new Queue()
create_queue.defer (callback) -> Fabricator.create Flat, BASE_COUNT, {
name: Fabricator.uniqueId('flat_')
created_at: Fabricator.date
}, (err, models) -> MODELS.flat = models; callback(err)
create_queue.defer (callback) -> Fabricator.create Reverse, BASE_COUNT, {
name: Fabricator.uniqueId('reverse_')
created_at: Fabricator.date
}, (err, models) -> MODELS.reverse = models; callback(err)
create_queue.defer (callback) -> Fabricator.create ForeignReverse, BASE_COUNT, {
name: Fabricator.uniqueId('foreign_reverse_')
created_at: Fabricator.date
}, (err, models) -> MODELS.foreign_reverse = models; callback(err)
create_queue.defer (callback) -> Fabricator.create Owner, BASE_COUNT, {
name: Fabricator.uniqueId('owner_')
created_at: Fabricator.date
}, (err, models) -> MODELS.owner = models; callback(err)
create_queue.await callback
# link and save all
queue.defer (callback) ->
save_queue = new Queue(1) # NOTE: save serially because we are including reverse_as in reverse over (overlap between saves)
reversed_reverse = _.clone(MODELS.reverse).reverse()
for owner in MODELS.owner
do (owner) -> save_queue.defer (callback) ->
owner.set({
flat: MODELS.flat.pop()
reverse: MODELS.reverse.pop()
reverse_as: reversed_reverse.pop()
foreign_reverse: MODELS.foreign_reverse.pop()
})
owner.save callback
save_queue.await callback
queue.await callback
it 'Can fetch and serialize a custom foreign key', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'foreign_reverse', (err, related_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(related_model, 'found related model')
related_json = related_model.toJSON()
assert.equal(test_model.id, related_json.ownerish_id, "Serialized the foreign id. Expected: #{test_model.id}. Actual: #{related_json.ownerish_id}")
done()
it 'Can create a model and load a related model by id (belongsTo)', (done) ->
Flat.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
flat_id = test_model.id
new_model = new Owner({flat_id: flat_id})
new_model.save (err) ->
assert.ok(!err, "No errors: #{err}")
new_model.get 'flat', (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found related model')
assert.equal(flat_id, flat.id, 'Loaded model is correct')
done()
patchAddTests = (unload) ->
it "Can manually add a relationship by related_id (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
Reverse.cursor({id: {$ne: reverse.id}, $one: true}).toJSON (err, another_reverse_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_reverse_json, "loaded another model.")
assert.ok(reverse.id isnt another_reverse_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchAdd 'reverse', another_reverse_json.id, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_reverse = owner.get('reverse')
assert.ok(updated_reverse.id is another_reverse_json.id, "Set the id. Expected: #{another_reverse_json.id}. Actual: #{updated_reverse.id}")
owner.get 'reverse', (err, updated_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_reverse, "loaded another model.")
assert.equal(updated_reverse.get('owner_id'), owner.id, "owner_id is correct.")
assert.ok(_.isEqual(_.pick(updated_reverse.toJSON(), PICK_KEYS), _.pick(another_reverse_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_reverse_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_reverse.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related json (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
Reverse.cursor({id: {$ne: reverse.id}, $one: true}).toJSON (err, another_reverse_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_reverse_json, "loaded another model.")
assert.ok(reverse.id isnt another_reverse_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchAdd 'reverse', another_reverse_json, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_reverse = owner.get('reverse')
assert.ok(updated_reverse.id is another_reverse_json.id, "Set the id. Expected: #{another_reverse_json.id}. Actual: #{updated_reverse.id}")
owner.get 'reverse', (err, updated_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_reverse, "loaded another model.")
assert.equal(updated_reverse.get('owner_id'), owner.id, "owner_id is correct.")
assert.ok(_.isEqual(_.pick(updated_reverse.toJSON(), PICK_KEYS), _.pick(another_reverse_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_reverse_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_reverse.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related model (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
Reverse.cursor({id: {$ne: reverse.id}}).toModel (err, another_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_reverse, "loaded another model.")
assert.ok(reverse.id isnt another_reverse.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchAdd 'reverse', another_reverse, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_reverse = owner.get('reverse')
assert.ok(updated_reverse.id is another_reverse.id, "Set the id. Expected: #{another_reverse.id}. Actual: #{updated_reverse.id}")
owner.get 'reverse', (err, updated_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_reverse, "loaded another model.")
assert.equal(updated_reverse.get('owner_id'), owner.id, "owner_id is correct.")
assert.ok(_.isEqual(_.pick(updated_reverse.toJSON(), PICK_KEYS), _.pick(another_reverse.toJSON(), PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_reverse.toJSON(), PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_reverse.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related_id (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model.")
Owner.cursor({id: {$ne: owner.id}, $one: true}).toJSON (err, another_owner_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_owner_json, "loaded another model.")
assert.ok(owner.id isnt another_owner_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchAdd 'owner', another_owner_json.id, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_owner = reverse.get('owner')
assert.ok(updated_owner.id is another_owner_json.id, "Set the id. Expected: #{another_owner_json.id}. Actual: #{updated_owner.id}")
reverse.get 'owner', (err, updated_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_owner, "loaded another model.")
assert.equal(updated_owner.get('reverse_id'), reverse.id, "reverse_id is correct.")
assert.ok(_.isEqual(_.pick(updated_owner.toJSON(), PICK_KEYS), _.pick(another_owner_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_owner_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_owner.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related json (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model.")
Owner.cursor({id: {$ne: owner.id}, $one: true}).toJSON (err, another_owner_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_owner_json, "loaded another model.")
assert.ok(owner.id isnt another_owner_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchAdd 'owner', another_owner_json, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_owner = reverse.get('owner')
assert.ok(updated_owner.id is another_owner_json.id, "Set the id. Expected: #{another_owner_json.id}. Actual: #{updated_owner.id}")
reverse.get 'owner', (err, updated_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_owner, "loaded another model.")
assert.equal(updated_owner.get('reverse_id'), reverse.id, "reverse_id is correct.")
assert.ok(_.isEqual(_.pick(updated_owner.toJSON(), PICK_KEYS), _.pick(another_owner_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_owner_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_owner.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related model (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model.")
Owner.cursor({id: {$ne: owner.id}}).toModel (err, another_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_owner, "loaded another model.")
assert.ok(owner.id isnt another_owner.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchAdd 'owner', another_owner, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_owner = reverse.get('owner')
assert.ok(updated_owner.id is another_owner.id, "Set the id. Expected: #{another_owner.id}. Actual: #{updated_owner.id}")
reverse.get 'owner', (err, updated_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_owner, "loaded another model.")
assert.equal(updated_owner.get('reverse_id'), reverse.id, "reverse_id is correct.")
assert.ok(_.isEqual(_.pick(updated_owner.toJSON(), PICK_KEYS), _.pick(another_owner.toJSON(), PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_owner.toJSON(), PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_owner.toJSON(), PICK_KEYS))}")
done()
patchAddTests(false)
patchAddTests(true)
patchRemoveTests = (unload) ->
it "Can manually delete a relationship by related_id (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', destroyed_model.id, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by related_json (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', destroyed_model.toJSON(), (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by related model (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', destroyed_model, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by array related of model (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', [destroyed_model], (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by related_id (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', destroyed_model.id, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
it "Can manually delete a relationship by related_json (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', destroyed_model.toJSON(), (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
it "Can manually delete a relationship by related_model (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', destroyed_model, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
it "Can manually delete a relationship by array of related_model (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', [destroyed_model], (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
patchRemoveTests(false)
patchRemoveTests(true)
it 'Can create a model and update the relationship (belongsTo)', (done) ->
related_key = 'flat'
related_id_accessor = 'flat_id'
Owner.cursor().include(related_key).toModel (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
owner_id = owner.id
related = owner.get(related_key)
related_id = related.id
assert.ok(related, 'included related')
(attributes = {})[related_key] = related
new_owner = new Owner(attributes)
owner1 = null; new_owner1 = null; new_owner_id = null
assert.equal(related, owner.get(related_key), "Didn't modify previous related. Expected: #{related}. Actual: #{owner.get(related_key)}")
assert.equal(related_id, owner.get(related_id_accessor), "Got related_id from previous related. Expected: #{related_id}. Actual: #{owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
queue = new Queue(1)
queue.defer (callback) -> new_owner.save callback
queue.defer (callback) -> owner.save callback
# make sure nothing changed after save
queue.defer (callback) ->
new_owner_id = new_owner.id
assert.ok(new_owner_id, 'had an id after after')
assert.equal(related, owner.get(related_key), "Didn't modify previous related. Expected: #{related}. Actual: #{owner.get(related_key)}")
assert.equal(related_id, owner.get(related_id_accessor), "Got related_id from previous related. Expected: #{related_id}. Actual: #{owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
callback()
# load
queue.defer (callback) -> Owner.find owner_id, (err, _owner) -> callback(err, owner1 = _owner)
queue.defer (callback) -> Owner.find new_owner_id, (err, _owner) -> callback(err, new_owner1 = _owner)
# check
queue.defer (callback) ->
assert.equal(related_id, owner1.get(related_id_accessor), "Got related_id from reloaded previous related. Expected: #{related_id}. Actual: #{owner1.get(related_id_accessor)}")
assert.equal(related_id, new_owner1.get(related_id_accessor), "Got related_id from reloaded copied related. Expected: #{related_id}. Actual: #{new_owner1.get(related_id_accessor)}")
owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(related_id, related.id, "Loaded related from previous related. Expected: #{related_id}. Actual: #{related.id}")
new_owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(related_id, related.id, "Loaded related from previous related. Expected: #{related_id}. Actual: #{related.id}")
callback()
queue.await done
it 'Can create a model and update the relationship (hasOne)', (done) ->
# TODO: implement embedded set - should clone in set or the caller needed to clone? (problem is sharing an in memory instance)
return done() if options.embed
related_key = 'reverse'
related_id_accessor = 'reverse_id'
Owner.cursor().include(related_key).toModel (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
related = owner.get(related_key)
owner_id = owner.id
related_id = related.id
assert.ok(related, 'included related')
(attributes = {})[related_key] = related
new_owner = new Owner(attributes)
owner1 = null; new_owner1 = null; new_owner_id = null
assert.equal(null, owner.get(related_key), "Modified previous related. Expected: #{null}. Actual: #{owner.get(related_key)}")
assert.equal(null, owner.get(related_id_accessor), "Failed to get related_id from previous related. Expected: #{null}. Actual: #{new_owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
queue = new Queue(1)
queue.defer (callback) -> new_owner.save callback
queue.defer (callback) -> owner.save callback
# make sure nothing changed after save
queue.defer (callback) ->
new_owner_id = new_owner.id
assert.ok(new_owner_id, 'had an id after after')
assert.equal(null, owner.get(related_key), "Modified previous related. Expected: #{null}. Actual: #{owner.get(related_key)}")
assert.equal(null, owner.get(related_id_accessor), "Got related_id from previous related. Expected: #{null}. Actual: #{new_owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
callback()
# load
queue.defer (callback) -> Owner.find owner_id, (err, _owner) -> callback(err, owner1 = _owner)
queue.defer (callback) -> Owner.find new_owner_id, (err, _owner) -> callback(err, new_owner1 = _owner)
# check
queue.defer (callback) ->
owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(null, related, "Failed to loaded related from previous related. Expected: #{null}. Actual: #{related}")
assert.equal(null, owner1.get(related_id_accessor), "Failed to get related_id from reloaded previous related. Expected: #{null}. Actual: #{owner1.get(related_id_accessor)}")
new_owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(related_id, related.id, "Loaded related from previous related. Expected: #{related_id}. Actual: #{related.id}")
assert.equal(related_id, new_owner1.get(related_id_accessor), "Got related_id from reloaded copied related. Expected: #{related_id}. Actual: #{new_owner1.get(related_id_accessor)}")
callback()
queue.await done
# TODO: should the related model be loaded to save?
it.skip 'Can create a related model by id (hasOne)', (done) ->
Reverse.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
reverse_id = test_model.id
new_model = new Owner()
new_model.save (err) ->
assert.ok(!err, "No errors: #{err}")
new_model.set({reverse_id: reverse_id})
new_model.save (err) ->
assert.ok(!err, "No errors: #{err}")
new_model.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(reverse_id, reverse.id, 'Loaded model is correct')
done()
it 'Handles a get query for a belongsTo relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'flat', (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found related model')
if test_model.relationIsEmbedded('flat')
assert.deepEqual(test_model.toJSON().flat, flat.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().flat)}. Actual: #{JSONUtils.stringify(flat.toJSON())}")
else
assert.deepEqual(test_model.toJSON().flat_id, flat.id, "Serialized id only. Expected: #{test_model.toJSON().flat_id}. Actual: #{flat.id}")
assert.equal(test_model.get('flat_id'), flat.id, "\nExpected: #{test_model.get('flat_id')}\nActual: #{flat.id}")
done()
it 'Handles a get query for a hasOne relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(test_model.id, reverse.get('owner_id'), "\nExpected: #{test_model.id}\nActual: #{reverse.get('owner_id')}")
assert.equal(test_model.id, reverse.toJSON().owner_id, "\nReverse toJSON has an owner_id. Expected: #{test_model.id}\nActual: #{reverse.toJSON().owner_id}")
if test_model.relationIsEmbedded('reverse')
assert.deepEqual(test_model.toJSON().reverse, reverse.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().reverse)}. Actual: #{JSONUtils.stringify(reverse.toJSON())}")
assert.ok(!test_model.toJSON().reverse_id, 'No reverese_id in owner json')
done()
it 'Can retrieve an id for a hasOne relation via async virtual method', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse_id', (err, id) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(id, 'found id')
done()
it 'Can retrieve a belongsTo id synchronously and then a model asynchronously from get methods', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
assert.ok(test_model.get('flat_id'), 'Has the belongsTo id')
test_model.get 'flat', (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'loaded model')
assert.equal(test_model.get('flat_id'), flat.id, "\nExpected: #{test_model.get('flat_id')}\nActual: #{flat.id}")
done()
it 'Handles a get query for a hasOne and belongsTo two sided relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(test_model.id, reverse.get('owner_id'), "\nExpected: #{test_model.id}\nActual: #{reverse.get('owner_id')}")
assert.equal(test_model.id, reverse.toJSON().owner_id, "\nReverse toJSON has an owner_id. Expected: #{test_model.id}\nActual: #{reverse.toJSON().owner_id}")
if test_model.relationIsEmbedded('reverse')
assert.deepEqual(test_model.toJSON().reverse, reverse.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().reverse)}. Actual: #{JSONUtils.stringify(reverse.toJSON())}")
assert.ok(!test_model.toJSON().reverse_id, 'No reverse_id in owner json')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found original model')
assert.deepEqual(reverse.toJSON().owner_id, owner.id, "Serialized id only. Expected: #{reverse.toJSON().owner_id}. Actual: #{owner.id}")
if Owner.cache
assert.deepEqual(test_model.toJSON(), owner.toJSON(), "\nExpected: #{JSONUtils.stringify(test_model.toJSON())}\nActual: #{JSONUtils.stringify(owner.toJSON())}")
else
assert.equal(test_model.id, owner.id, "\nExpected: #{test_model.id}\nActual: #{owner.id}")
done()
it 'Appends json for a related model', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
JSONUtils.renderRelated test_model, 'reverse', ['id', 'created_at'], (err, related_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(related_json.id, "reverse has an id")
assert.ok(related_json.created_at, "reverse has a created_at")
assert.ok(!related_json.updated_at, "reverse doesn't have updated_at")
JSONUtils.renderRelated test_model, 'flat', ['id', 'created_at'], (err, related_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(related_json.id, "flat has an id")
# assert.ok(related_json.created_at, "flat has a created_at")
assert.ok(!related_json.updated_at, "flat doesn't have updated_at")
done()
# TODO: delay the returning of memory models related models to test lazy loading properly
it 'Fetches a relation from the store if not present', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
fetched_owner = new Owner({id: test_model.id})
fetched_owner.fetch (err) ->
assert.ok(!err, "No errors: #{err}")
delete fetched_owner.attributes.reverse
fetched_owner.get 'reverse', (err, reverse) ->
if fetched_owner.relationIsEmbedded('reverse')
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, 'Cannot yet load the model') # TODO: implement a fetch from the related model
done()
else
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'loaded the model lazily')
assert.equal(reverse.get('owner_id'), test_model.id)
done()
# assert.equal(reverse, null, 'has not loaded the model initially')
it 'Has an id loaded for a belongsTo and not for a hasOne relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
assert.ok(test_model.get('flat_id'), 'belongsTo id is loaded')
# assert.ok(!test_model.get('reverse_id'), 'hasOne id is not loaded')
done()
it 'Handles a get query for a hasOne and belongsTo two sided relation as "as" fields', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse_as', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(test_model.id, reverse.get('owner_as_id'), "\nExpected: #{test_model.id}\nActual: #{reverse.get('owner_as_id')}")
assert.equal(test_model.id, reverse.toJSON().owner_as_id, "\nReverse toJSON has an owner_id. Expected: #{test_model.id}\nActual: #{reverse.toJSON().owner_as_id}")
if test_model.relationIsEmbedded('reverse_as')
assert.deepEqual(test_model.toJSON().reverse_as, reverse.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().reverse)}. Actual: #{JSONUtils.stringify(reverse.toJSON())}")
assert.ok(!test_model.toJSON().reverse_as_id, 'No reverse_as_id in owner json')
reverse.get 'owner_as', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found original model')
assert.deepEqual(reverse.toJSON().owner_as_id, owner.id, "Serialized id only. Expected: #{reverse.toJSON().owner_as_id}. Actual: #{owner.id}")
if Owner.cache
assert.deepEqual(test_model.toJSON(), owner.toJSON(), "\nExpected: #{JSONUtils.stringify(test_model.toJSON())}\nActual: #{JSONUtils.stringify(owner.toJSON())}")
else
assert.equal(test_model.id, owner.id, "\nExpected: #{test_model.id}\nActual: #{owner.id}")
done()
it 'Can include a related (belongsTo) model', (done) ->
Owner.cursor({$one: true}).include('flat').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, 'found model')
assert.ok(json.flat, "Has a related flat")
assert.ok(json.flat.id, "Related model has an id")
unless Owner.relationIsEmbedded('flat') # TODO: confirm this is correct
assert.equal(json.flat_id, json.flat.id, "\nRelated model has the correct id: Expected: #{json.flat_id}\nActual: #{json.flat.id}")
done()
it 'Can include a related (hasOne) model', (done) ->
Owner.cursor({$one: true}).include('reverse').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, 'found model')
assert.ok(json.reverse, "Has a related reverse")
assert.ok(json.reverse.id, "Related model has an id")
assert.equal(json.id, json.reverse.owner_id, "\nRelated model has the correct id: Expected: #{json.id}\nActual: #{json.reverse.owner_id}")
done()
it 'Can include multiple related models', (done) ->
Owner.cursor({$one: true}).include('reverse', 'flat').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, 'found model')
assert.ok(json.reverse, "Has a related reverse")
assert.ok(json.reverse.id, "Related model has an id")
assert.ok(json.flat, "Has a related flat")
assert.ok(json.flat.id, "Included model has an id")
unless Owner.relationIsEmbedded('flat') # TODO: confirm this is correct
assert.equal(json.flat_id, json.flat.id, "\nIncluded model has the correct id: Expected: #{json.flat_id}\nActual: #{json.flat.id}")
assert.equal(json.id, json.reverse.owner_id, "\nIncluded model has the correct id: Expected: #{json.id}\nActual: #{json.reverse.owner_id}")
done()
it 'Can query on a related (belongsTo) model property', (done) ->
Flat.findOne (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found model')
Owner.cursor({$one: true, 'flat.id': flat.id}).toJSON (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
unless Owner.relationIsEmbedded('flat') # TODO: confirm this is correct
assert.equal(flat.id, owner.flat_id, "\nRelated model has the correct id: Expected: #{flat.id}\nActual: #{owner.flat_id}")
done()
it 'Can query on a related (belongsTo) model property when the relation is included', (done) ->
Flat.findOne (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found model')
Owner.cursor({$one: true, 'flat.name': flat.get('name')}).include('flat').toJSON (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
assert.ok(owner.flat, "Has a related flat")
assert.ok(owner.flat.id, "Included model has an id")
assert.equal(flat.id, owner.flat.id, "\nIncluded model has the correct id: Expected: #{flat.id}\nActual: #{owner.flat.id}")
assert.equal(flat.get('name'), owner.flat.name, "\nIncluded model has the correct name: Expected: #{flat.get('name')}\nActual: #{owner.flat.name}")
done()
it 'Can query on a related (hasOne) model', (done) ->
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'Reverse found model')
Owner.cursor({$one: true, 'reverse.name': reverse.get('name')}).toJSON (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'Owner found model')
unless Owner.relationIsEmbedded('reverse') # TODO: confirm this is correct
assert.equal(reverse.get('owner_id'), owner.id, "\nRelated model has the correct id: Expected: #{reverse.get('owner_id')}\nActual: #{owner.id}")
done()
it 'Can query on a related (hasOne) model property when the relation is included', (done) ->
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found model')
Owner.cursor({'reverse.name': reverse.get('name')}).include('reverse').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, "found json")
assert.equal(json.length, 1, "json has the correct number or results. Expecting: 1. Actual #{json.length}")
owner = json[0]
assert.ok(owner.reverse, "Has a related reverse")
assert.ok(owner.reverse.id, "Related model has an id")
unless Owner.relationIsEmbedded('reverse') # TODO: confirm this is correct
assert.equal(reverse.get('owner_id'), owner.id, "\nRelated model has the correct id: Expected: #{reverse.get('owner_id')}\nActual: #{owner.id}")
assert.equal(reverse.get('name'), owner.reverse.name, "\nIncluded model has the correct name: Expected: #{reverse.get('name')}\nActual: #{owner.reverse.name}")
done()
it 'Should be able to count relationships', (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
Reverse.count {owner_id: owner.id}, (err, count) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(1, count, "Counted reverses. Expected: 1. Actual: #{count}")
done()
it 'Should be able to count relationships with paging', (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
Reverse.cursor({owner_id: owner.id, $page: true}).toJSON (err, paging_info) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(0, paging_info.offset, "Has offset. Expected: 0. Actual: #{paging_info.offset}")
assert.equal(1, paging_info.total_rows, "Counted reverses. Expected: 1. Actual: #{paging_info.total_rows}")
done()
backlinkTests = (virtual) ->
it "Should update backlinks using set (#{if virtual then 'virtual' else 'no modifiers'})", (done) ->
# TODO: implement embedded
return done() if options.embed
checkReverseFn = (reverse, expected_owner) -> return (callback) ->
assert.ok(reverse, 'Reverse exists')
assert.equal(expected_owner, reverse.get('owner'), "Reverse owner is correct. Expected: #{expected_owner}. Actual: #{reverse.get('owner')}")
callback()
Owner.cursor().limit(2).include('reverse').toModels (err, owners) ->
if virtual # set as virtual relationship after including reverse
relation = Owner.relation('reverse')
relation.virtual = true
assert.ok(!err, "No errors: #{err}")
assert.equal(2, owners.length, "Found owners. Expected: 2. Actual: #{owners.length}")
owner0 = owners[0]; owner0_id = owner0.id; reverse0 = owner0.get('reverse')
owner1 = owners[1]; owner1_id = owner1.id; reverse1 = owner1.get('reverse')
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(owner1.get('reverse'), "Owner1 has 1 reverse.")
queue = new Queue(1)
queue.defer checkReverseFn(reverse0, owner0)
queue.defer checkReverseFn(reverse1, owner1)
queue.defer (callback) ->
owner0.set({reverse: reverse1})
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(!owner1.get('reverse'), "Owner1 has no reverse.")
queue.defer checkReverseFn(reverse1, owner0) # confirm it also is related
queue.defer checkReverseFn(reverse0, owner0) # confirm it stayed
assert.equal(null, owner1.get('reverse'), "Owner's reverse is cleared.\nExpected: #{null}.\nActual: #{JSONUtils.stringify(owner1.get('reverse'))}")
callback()
# save and recheck
queue.defer (callback) -> owner0.save callback
queue.defer (callback) -> owner1.save callback
queue.defer (callback) ->
BackboneORM.model_cache.reset() # reset cache
Owner.cursor({$ids: [owner0.id, owner1.id]}).limit(2).include('reverse').toModels (err, owners) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(2, owners.length, "Found owners post-save. Expected: 2. Actual: #{owners.length}")
# lookup owners
owner0 = owner1 = null
for owner in owners
if owner.id is owner0_id
owner0 = owner
else if owner.id is owner1_id
owner1 = owner
assert(owner0, 'refound owner0')
assert(owner1, 'refound owner1')
reverse0b = owner0.get('reverse')
reverse1b = owner1.get('reverse')
if virtual
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(owner1.get('reverse'), "Owner1 has 1 reverse.")
else
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(!owner1.get('reverse'), "Owner1 has no reverse.")
queue.defer checkReverseFn(reverse0b, owner0) # confirm it moved
# TODO: determine reason on SQL for updated_at missing
# assert.deepEqual(reverse1.toJSON(), reverse0b.toJSON(), "Reverse is cleared.\nExpected: #{JSONUtils.stringify(reverse1.toJSON())}.\nActual: #{JSONUtils.stringify(reverse0b.toJSON())}")
assert.deepEqual(_.pick(reverse1.toJSON(), 'created_at'), _.pick(reverse0b.toJSON(), 'created_at'), "Reverse is cleared.\nExpected: #{JSONUtils.stringify(_.pick(reverse1.toJSON(), 'updated_at', 'created_at'))}.\nActual: #{JSONUtils.stringify(_.pick(reverse0b.toJSON(), 'updated_at', 'created_at'))}")
assert.equal(null, owner1.get('reverse'), "Owner's reverse is cleared.\nExpected: #{null}.\nActual: #{JSONUtils.stringify(owner1.get('reverse'))}")
callback()
queue.await (err) ->
assert.ok(!err, "No errors: #{err}")
done()
backlinkTests(false)
backlinkTests(true)
it 'does not serialize virtual attributes', (done) ->
json_key = if options.embed then 'flat' else 'flat_id'
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'Owners found')
flat_id = owner.get('flat').id
json = owner.toJSON()
assert.ok(json.hasOwnProperty(json_key), 'Serialized flat')
relation = owner.relation('flat')
relation.virtual = true
virtual_json = owner.toJSON()
assert.ok(!virtual_json.hasOwnProperty(json_key), 'Did not serialize flat')
owner_with_flat = new Owner(json)
assert.equal(owner_with_flat.get('flat').id, flat_id, 'Virtual with flat was deserialized')
owner_with_virtual_flat = new Owner(virtual_json)
assert.equal(owner_with_virtual_flat.get('flat'), null, 'Virtual without flat was deserialized')
done()
# owner.save {flat: null}, (err) ->
# assert.ok(!err, "No errors: #{err}")
# BackboneORM.model_cache.reset() # reset cache
# Owner.find owner.id, (err, loaded_owner) ->
# assert.ok(!err, "No errors: #{err}")
# assert.equal(loaded_owner.get('flat').id, flat_id, 'Virtual flat is not saved')
# done()
| 37688 | assert = assert or require?('chai').assert
BackboneORM = window?.BackboneORM; try BackboneORM or= require?('backbone-orm') catch; try BackboneORM or= require?('../../../../backbone-orm')
{_, Backbone, Queue, Utils, JSONUtils, Fabricator} = BackboneORM
_.each BackboneORM.TestUtils.optionSets(), exports = (options) ->
options = _.extend({}, options, __test__parameters) if __test__parameters?
return if options.embed and not options.sync.capabilities(options.database_url or '').embed
DATABASE_URL = options.database_url or ''
BASE_SCHEMA = options.schema or {}
SYNC = options.sync
BASE_COUNT = 5
PICK_KEYS = ['<KEY>', 'name']
describe "hasOne #{options.$parameter_tags or ''}#{options.$tags} @has_one", ->
Flat = Reverse = ForeignReverse = Owner = null
before ->
BackboneORM.configure {model_cache: {enabled: !!options.cache, max: 100}}
class Flat extends Backbone.Model
model_name: 'Flat'
urlRoot: "#{DATABASE_URL}/one_flats"
schema: _.defaults({
owner: -> ['hasOne', Owner]
}, BASE_SCHEMA)
sync: SYNC(Flat)
class Reverse extends Backbone.Model
model_name: 'Reverse'
urlRoot: "#{DATABASE_URL}/one_reverses"
schema: _.defaults({
owner: -> ['belongsTo', Owner]
owner_as: -> ['belongsTo', Owner, as: 'reverse_as']
}, BASE_SCHEMA)
sync: SYNC(Reverse)
class ForeignReverse extends Backbone.Model
model_name: 'ForeignReverse'
urlRoot: "#{DATABASE_URL}/one_foreign_reverses"
schema: _.defaults({
owner: -> ['belongsTo', Owner, foreign_key: 'ownerish_id']
}, BASE_SCHEMA)
sync: SYNC(ForeignReverse)
class Owner extends Backbone.Model
model_name: 'Owner'
urlRoot: "#{DATABASE_URL}/one_owners"
schema: _.defaults({
flat: -> ['belongsTo', Flat, embed: options.embed]
reverse: -> ['hasOne', Reverse]
reverse_as: -> ['hasOne', Reverse, as: 'owner_as']
foreign_reverse: -> ['hasOne', ForeignReverse]
}, BASE_SCHEMA)
sync: SYNC(Owner)
after (callback) -> Utils.resetSchemas [Flat, Reverse, ForeignReverse, Owner], callback
beforeEach (callback) ->
relation = Owner.relation('flat')
delete relation.virtual
MODELS = {}
queue = new Queue(1)
queue.defer (callback) -> Utils.resetSchemas [Flat, Reverse, ForeignReverse, Owner], callback
queue.defer (callback) ->
create_queue = new Queue()
create_queue.defer (callback) -> Fabricator.create Flat, BASE_COUNT, {
name: Fabricator.uniqueId('flat_')
created_at: Fabricator.date
}, (err, models) -> MODELS.flat = models; callback(err)
create_queue.defer (callback) -> Fabricator.create Reverse, BASE_COUNT, {
name: Fabricator.uniqueId('reverse_')
created_at: Fabricator.date
}, (err, models) -> MODELS.reverse = models; callback(err)
create_queue.defer (callback) -> Fabricator.create ForeignReverse, BASE_COUNT, {
name: Fabricator.uniqueId('foreign_reverse_')
created_at: Fabricator.date
}, (err, models) -> MODELS.foreign_reverse = models; callback(err)
create_queue.defer (callback) -> Fabricator.create Owner, BASE_COUNT, {
name: Fabricator.uniqueId('owner_')
created_at: Fabricator.date
}, (err, models) -> MODELS.owner = models; callback(err)
create_queue.await callback
# link and save all
queue.defer (callback) ->
save_queue = new Queue(1) # NOTE: save serially because we are including reverse_as in reverse over (overlap between saves)
reversed_reverse = _.clone(MODELS.reverse).reverse()
for owner in MODELS.owner
do (owner) -> save_queue.defer (callback) ->
owner.set({
flat: MODELS.flat.pop()
reverse: MODELS.reverse.pop()
reverse_as: reversed_reverse.pop()
foreign_reverse: MODELS.foreign_reverse.pop()
})
owner.save callback
save_queue.await callback
queue.await callback
it 'Can fetch and serialize a custom foreign key', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'foreign_reverse', (err, related_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(related_model, 'found related model')
related_json = related_model.toJSON()
assert.equal(test_model.id, related_json.ownerish_id, "Serialized the foreign id. Expected: #{test_model.id}. Actual: #{related_json.ownerish_id}")
done()
it 'Can create a model and load a related model by id (belongsTo)', (done) ->
Flat.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
flat_id = test_model.id
new_model = new Owner({flat_id: flat_id})
new_model.save (err) ->
assert.ok(!err, "No errors: #{err}")
new_model.get 'flat', (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found related model')
assert.equal(flat_id, flat.id, 'Loaded model is correct')
done()
patchAddTests = (unload) ->
it "Can manually add a relationship by related_id (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
Reverse.cursor({id: {$ne: reverse.id}, $one: true}).toJSON (err, another_reverse_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_reverse_json, "loaded another model.")
assert.ok(reverse.id isnt another_reverse_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchAdd 'reverse', another_reverse_json.id, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_reverse = owner.get('reverse')
assert.ok(updated_reverse.id is another_reverse_json.id, "Set the id. Expected: #{another_reverse_json.id}. Actual: #{updated_reverse.id}")
owner.get 'reverse', (err, updated_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_reverse, "loaded another model.")
assert.equal(updated_reverse.get('owner_id'), owner.id, "owner_id is correct.")
assert.ok(_.isEqual(_.pick(updated_reverse.toJSON(), PICK_KEYS), _.pick(another_reverse_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_reverse_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_reverse.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related json (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
Reverse.cursor({id: {$ne: reverse.id}, $one: true}).toJSON (err, another_reverse_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_reverse_json, "loaded another model.")
assert.ok(reverse.id isnt another_reverse_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchAdd 'reverse', another_reverse_json, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_reverse = owner.get('reverse')
assert.ok(updated_reverse.id is another_reverse_json.id, "Set the id. Expected: #{another_reverse_json.id}. Actual: #{updated_reverse.id}")
owner.get 'reverse', (err, updated_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_reverse, "loaded another model.")
assert.equal(updated_reverse.get('owner_id'), owner.id, "owner_id is correct.")
assert.ok(_.isEqual(_.pick(updated_reverse.toJSON(), PICK_KEYS), _.pick(another_reverse_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_reverse_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_reverse.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related model (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
Reverse.cursor({id: {$ne: reverse.id}}).toModel (err, another_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_reverse, "loaded another model.")
assert.ok(reverse.id isnt another_reverse.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchAdd 'reverse', another_reverse, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_reverse = owner.get('reverse')
assert.ok(updated_reverse.id is another_reverse.id, "Set the id. Expected: #{another_reverse.id}. Actual: #{updated_reverse.id}")
owner.get 'reverse', (err, updated_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_reverse, "loaded another model.")
assert.equal(updated_reverse.get('owner_id'), owner.id, "owner_id is correct.")
assert.ok(_.isEqual(_.pick(updated_reverse.toJSON(), PICK_KEYS), _.pick(another_reverse.toJSON(), PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_reverse.toJSON(), PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_reverse.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related_id (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model.")
Owner.cursor({id: {$ne: owner.id}, $one: true}).toJSON (err, another_owner_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_owner_json, "loaded another model.")
assert.ok(owner.id isnt another_owner_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchAdd 'owner', another_owner_json.id, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_owner = reverse.get('owner')
assert.ok(updated_owner.id is another_owner_json.id, "Set the id. Expected: #{another_owner_json.id}. Actual: #{updated_owner.id}")
reverse.get 'owner', (err, updated_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_owner, "loaded another model.")
assert.equal(updated_owner.get('reverse_id'), reverse.id, "reverse_id is correct.")
assert.ok(_.isEqual(_.pick(updated_owner.toJSON(), PICK_KEYS), _.pick(another_owner_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_owner_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_owner.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related json (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model.")
Owner.cursor({id: {$ne: owner.id}, $one: true}).toJSON (err, another_owner_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_owner_json, "loaded another model.")
assert.ok(owner.id isnt another_owner_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchAdd 'owner', another_owner_json, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_owner = reverse.get('owner')
assert.ok(updated_owner.id is another_owner_json.id, "Set the id. Expected: #{another_owner_json.id}. Actual: #{updated_owner.id}")
reverse.get 'owner', (err, updated_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_owner, "loaded another model.")
assert.equal(updated_owner.get('reverse_id'), reverse.id, "reverse_id is correct.")
assert.ok(_.isEqual(_.pick(updated_owner.toJSON(), PICK_KEYS), _.pick(another_owner_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_owner_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_owner.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related model (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model.")
Owner.cursor({id: {$ne: owner.id}}).toModel (err, another_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_owner, "loaded another model.")
assert.ok(owner.id isnt another_owner.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchAdd 'owner', another_owner, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_owner = reverse.get('owner')
assert.ok(updated_owner.id is another_owner.id, "Set the id. Expected: #{another_owner.id}. Actual: #{updated_owner.id}")
reverse.get 'owner', (err, updated_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_owner, "loaded another model.")
assert.equal(updated_owner.get('reverse_id'), reverse.id, "reverse_id is correct.")
assert.ok(_.isEqual(_.pick(updated_owner.toJSON(), PICK_KEYS), _.pick(another_owner.toJSON(), PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_owner.toJSON(), PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_owner.toJSON(), PICK_KEYS))}")
done()
patchAddTests(false)
patchAddTests(true)
patchRemoveTests = (unload) ->
it "Can manually delete a relationship by related_id (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', destroyed_model.id, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by related_json (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', destroyed_model.toJSON(), (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by related model (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', destroyed_model, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by array related of model (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', [destroyed_model], (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by related_id (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', destroyed_model.id, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
it "Can manually delete a relationship by related_json (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', destroyed_model.toJSON(), (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
it "Can manually delete a relationship by related_model (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', destroyed_model, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
it "Can manually delete a relationship by array of related_model (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', [destroyed_model], (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
patchRemoveTests(false)
patchRemoveTests(true)
it 'Can create a model and update the relationship (belongsTo)', (done) ->
related_key = 'flat'
related_id_accessor = 'flat_id'
Owner.cursor().include(related_key).toModel (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
owner_id = owner.id
related = owner.get(related_key)
related_id = related.id
assert.ok(related, 'included related')
(attributes = {})[related_key] = related
new_owner = new Owner(attributes)
owner1 = null; new_owner1 = null; new_owner_id = null
assert.equal(related, owner.get(related_key), "Didn't modify previous related. Expected: #{related}. Actual: #{owner.get(related_key)}")
assert.equal(related_id, owner.get(related_id_accessor), "Got related_id from previous related. Expected: #{related_id}. Actual: #{owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
queue = new Queue(1)
queue.defer (callback) -> new_owner.save callback
queue.defer (callback) -> owner.save callback
# make sure nothing changed after save
queue.defer (callback) ->
new_owner_id = new_owner.id
assert.ok(new_owner_id, 'had an id after after')
assert.equal(related, owner.get(related_key), "Didn't modify previous related. Expected: #{related}. Actual: #{owner.get(related_key)}")
assert.equal(related_id, owner.get(related_id_accessor), "Got related_id from previous related. Expected: #{related_id}. Actual: #{owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
callback()
# load
queue.defer (callback) -> Owner.find owner_id, (err, _owner) -> callback(err, owner1 = _owner)
queue.defer (callback) -> Owner.find new_owner_id, (err, _owner) -> callback(err, new_owner1 = _owner)
# check
queue.defer (callback) ->
assert.equal(related_id, owner1.get(related_id_accessor), "Got related_id from reloaded previous related. Expected: #{related_id}. Actual: #{owner1.get(related_id_accessor)}")
assert.equal(related_id, new_owner1.get(related_id_accessor), "Got related_id from reloaded copied related. Expected: #{related_id}. Actual: #{new_owner1.get(related_id_accessor)}")
owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(related_id, related.id, "Loaded related from previous related. Expected: #{related_id}. Actual: #{related.id}")
new_owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(related_id, related.id, "Loaded related from previous related. Expected: #{related_id}. Actual: #{related.id}")
callback()
queue.await done
it 'Can create a model and update the relationship (hasOne)', (done) ->
# TODO: implement embedded set - should clone in set or the caller needed to clone? (problem is sharing an in memory instance)
return done() if options.embed
related_key = '<KEY>'
related_id_accessor = 'reverse_id'
Owner.cursor().include(related_key).toModel (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
related = owner.get(related_key)
owner_id = owner.id
related_id = related.id
assert.ok(related, 'included related')
(attributes = {})[related_key] = related
new_owner = new Owner(attributes)
owner1 = null; new_owner1 = null; new_owner_id = null
assert.equal(null, owner.get(related_key), "Modified previous related. Expected: #{null}. Actual: #{owner.get(related_key)}")
assert.equal(null, owner.get(related_id_accessor), "Failed to get related_id from previous related. Expected: #{null}. Actual: #{new_owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
queue = new Queue(1)
queue.defer (callback) -> new_owner.save callback
queue.defer (callback) -> owner.save callback
# make sure nothing changed after save
queue.defer (callback) ->
new_owner_id = new_owner.id
assert.ok(new_owner_id, 'had an id after after')
assert.equal(null, owner.get(related_key), "Modified previous related. Expected: #{null}. Actual: #{owner.get(related_key)}")
assert.equal(null, owner.get(related_id_accessor), "Got related_id from previous related. Expected: #{null}. Actual: #{new_owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
callback()
# load
queue.defer (callback) -> Owner.find owner_id, (err, _owner) -> callback(err, owner1 = _owner)
queue.defer (callback) -> Owner.find new_owner_id, (err, _owner) -> callback(err, new_owner1 = _owner)
# check
queue.defer (callback) ->
owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(null, related, "Failed to loaded related from previous related. Expected: #{null}. Actual: #{related}")
assert.equal(null, owner1.get(related_id_accessor), "Failed to get related_id from reloaded previous related. Expected: #{null}. Actual: #{owner1.get(related_id_accessor)}")
new_owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(related_id, related.id, "Loaded related from previous related. Expected: #{related_id}. Actual: #{related.id}")
assert.equal(related_id, new_owner1.get(related_id_accessor), "Got related_id from reloaded copied related. Expected: #{related_id}. Actual: #{new_owner1.get(related_id_accessor)}")
callback()
queue.await done
# TODO: should the related model be loaded to save?
it.skip 'Can create a related model by id (hasOne)', (done) ->
Reverse.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
reverse_id = test_model.id
new_model = new Owner()
new_model.save (err) ->
assert.ok(!err, "No errors: #{err}")
new_model.set({reverse_id: reverse_id})
new_model.save (err) ->
assert.ok(!err, "No errors: #{err}")
new_model.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(reverse_id, reverse.id, 'Loaded model is correct')
done()
it 'Handles a get query for a belongsTo relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'flat', (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found related model')
if test_model.relationIsEmbedded('flat')
assert.deepEqual(test_model.toJSON().flat, flat.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().flat)}. Actual: #{JSONUtils.stringify(flat.toJSON())}")
else
assert.deepEqual(test_model.toJSON().flat_id, flat.id, "Serialized id only. Expected: #{test_model.toJSON().flat_id}. Actual: #{flat.id}")
assert.equal(test_model.get('flat_id'), flat.id, "\nExpected: #{test_model.get('flat_id')}\nActual: #{flat.id}")
done()
it 'Handles a get query for a hasOne relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(test_model.id, reverse.get('owner_id'), "\nExpected: #{test_model.id}\nActual: #{reverse.get('owner_id')}")
assert.equal(test_model.id, reverse.toJSON().owner_id, "\nReverse toJSON has an owner_id. Expected: #{test_model.id}\nActual: #{reverse.toJSON().owner_id}")
if test_model.relationIsEmbedded('reverse')
assert.deepEqual(test_model.toJSON().reverse, reverse.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().reverse)}. Actual: #{JSONUtils.stringify(reverse.toJSON())}")
assert.ok(!test_model.toJSON().reverse_id, 'No reverese_id in owner json')
done()
it 'Can retrieve an id for a hasOne relation via async virtual method', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse_id', (err, id) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(id, 'found id')
done()
it 'Can retrieve a belongsTo id synchronously and then a model asynchronously from get methods', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
assert.ok(test_model.get('flat_id'), 'Has the belongsTo id')
test_model.get 'flat', (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'loaded model')
assert.equal(test_model.get('flat_id'), flat.id, "\nExpected: #{test_model.get('flat_id')}\nActual: #{flat.id}")
done()
it 'Handles a get query for a hasOne and belongsTo two sided relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(test_model.id, reverse.get('owner_id'), "\nExpected: #{test_model.id}\nActual: #{reverse.get('owner_id')}")
assert.equal(test_model.id, reverse.toJSON().owner_id, "\nReverse toJSON has an owner_id. Expected: #{test_model.id}\nActual: #{reverse.toJSON().owner_id}")
if test_model.relationIsEmbedded('reverse')
assert.deepEqual(test_model.toJSON().reverse, reverse.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().reverse)}. Actual: #{JSONUtils.stringify(reverse.toJSON())}")
assert.ok(!test_model.toJSON().reverse_id, 'No reverse_id in owner json')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found original model')
assert.deepEqual(reverse.toJSON().owner_id, owner.id, "Serialized id only. Expected: #{reverse.toJSON().owner_id}. Actual: #{owner.id}")
if Owner.cache
assert.deepEqual(test_model.toJSON(), owner.toJSON(), "\nExpected: #{JSONUtils.stringify(test_model.toJSON())}\nActual: #{JSONUtils.stringify(owner.toJSON())}")
else
assert.equal(test_model.id, owner.id, "\nExpected: #{test_model.id}\nActual: #{owner.id}")
done()
it 'Appends json for a related model', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
JSONUtils.renderRelated test_model, 'reverse', ['id', 'created_at'], (err, related_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(related_json.id, "reverse has an id")
assert.ok(related_json.created_at, "reverse has a created_at")
assert.ok(!related_json.updated_at, "reverse doesn't have updated_at")
JSONUtils.renderRelated test_model, 'flat', ['id', 'created_at'], (err, related_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(related_json.id, "flat has an id")
# assert.ok(related_json.created_at, "flat has a created_at")
assert.ok(!related_json.updated_at, "flat doesn't have updated_at")
done()
# TODO: delay the returning of memory models related models to test lazy loading properly
it 'Fetches a relation from the store if not present', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
fetched_owner = new Owner({id: test_model.id})
fetched_owner.fetch (err) ->
assert.ok(!err, "No errors: #{err}")
delete fetched_owner.attributes.reverse
fetched_owner.get 'reverse', (err, reverse) ->
if fetched_owner.relationIsEmbedded('reverse')
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, 'Cannot yet load the model') # TODO: implement a fetch from the related model
done()
else
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'loaded the model lazily')
assert.equal(reverse.get('owner_id'), test_model.id)
done()
# assert.equal(reverse, null, 'has not loaded the model initially')
it 'Has an id loaded for a belongsTo and not for a hasOne relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
assert.ok(test_model.get('flat_id'), 'belongsTo id is loaded')
# assert.ok(!test_model.get('reverse_id'), 'hasOne id is not loaded')
done()
it 'Handles a get query for a hasOne and belongsTo two sided relation as "as" fields', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse_as', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(test_model.id, reverse.get('owner_as_id'), "\nExpected: #{test_model.id}\nActual: #{reverse.get('owner_as_id')}")
assert.equal(test_model.id, reverse.toJSON().owner_as_id, "\nReverse toJSON has an owner_id. Expected: #{test_model.id}\nActual: #{reverse.toJSON().owner_as_id}")
if test_model.relationIsEmbedded('reverse_as')
assert.deepEqual(test_model.toJSON().reverse_as, reverse.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().reverse)}. Actual: #{JSONUtils.stringify(reverse.toJSON())}")
assert.ok(!test_model.toJSON().reverse_as_id, 'No reverse_as_id in owner json')
reverse.get 'owner_as', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found original model')
assert.deepEqual(reverse.toJSON().owner_as_id, owner.id, "Serialized id only. Expected: #{reverse.toJSON().owner_as_id}. Actual: #{owner.id}")
if Owner.cache
assert.deepEqual(test_model.toJSON(), owner.toJSON(), "\nExpected: #{JSONUtils.stringify(test_model.toJSON())}\nActual: #{JSONUtils.stringify(owner.toJSON())}")
else
assert.equal(test_model.id, owner.id, "\nExpected: #{test_model.id}\nActual: #{owner.id}")
done()
it 'Can include a related (belongsTo) model', (done) ->
Owner.cursor({$one: true}).include('flat').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, 'found model')
assert.ok(json.flat, "Has a related flat")
assert.ok(json.flat.id, "Related model has an id")
unless Owner.relationIsEmbedded('flat') # TODO: confirm this is correct
assert.equal(json.flat_id, json.flat.id, "\nRelated model has the correct id: Expected: #{json.flat_id}\nActual: #{json.flat.id}")
done()
it 'Can include a related (hasOne) model', (done) ->
Owner.cursor({$one: true}).include('reverse').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, 'found model')
assert.ok(json.reverse, "Has a related reverse")
assert.ok(json.reverse.id, "Related model has an id")
assert.equal(json.id, json.reverse.owner_id, "\nRelated model has the correct id: Expected: #{json.id}\nActual: #{json.reverse.owner_id}")
done()
it 'Can include multiple related models', (done) ->
Owner.cursor({$one: true}).include('reverse', 'flat').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, 'found model')
assert.ok(json.reverse, "Has a related reverse")
assert.ok(json.reverse.id, "Related model has an id")
assert.ok(json.flat, "Has a related flat")
assert.ok(json.flat.id, "Included model has an id")
unless Owner.relationIsEmbedded('flat') # TODO: confirm this is correct
assert.equal(json.flat_id, json.flat.id, "\nIncluded model has the correct id: Expected: #{json.flat_id}\nActual: #{json.flat.id}")
assert.equal(json.id, json.reverse.owner_id, "\nIncluded model has the correct id: Expected: #{json.id}\nActual: #{json.reverse.owner_id}")
done()
it 'Can query on a related (belongsTo) model property', (done) ->
Flat.findOne (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found model')
Owner.cursor({$one: true, 'flat.id': flat.id}).toJSON (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
unless Owner.relationIsEmbedded('flat') # TODO: confirm this is correct
assert.equal(flat.id, owner.flat_id, "\nRelated model has the correct id: Expected: #{flat.id}\nActual: #{owner.flat_id}")
done()
it 'Can query on a related (belongsTo) model property when the relation is included', (done) ->
Flat.findOne (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found model')
Owner.cursor({$one: true, 'flat.name': flat.get('name')}).include('flat').toJSON (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
assert.ok(owner.flat, "Has a related flat")
assert.ok(owner.flat.id, "Included model has an id")
assert.equal(flat.id, owner.flat.id, "\nIncluded model has the correct id: Expected: #{flat.id}\nActual: #{owner.flat.id}")
assert.equal(flat.get('name'), owner.flat.name, "\nIncluded model has the correct name: Expected: #{flat.get('name')}\nActual: #{owner.flat.name}")
done()
it 'Can query on a related (hasOne) model', (done) ->
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'Reverse found model')
Owner.cursor({$one: true, 'reverse.name': reverse.get('name')}).toJSON (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'Owner found model')
unless Owner.relationIsEmbedded('reverse') # TODO: confirm this is correct
assert.equal(reverse.get('owner_id'), owner.id, "\nRelated model has the correct id: Expected: #{reverse.get('owner_id')}\nActual: #{owner.id}")
done()
it 'Can query on a related (hasOne) model property when the relation is included', (done) ->
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found model')
Owner.cursor({'reverse.name': reverse.get('name')}).include('reverse').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, "found json")
assert.equal(json.length, 1, "json has the correct number or results. Expecting: 1. Actual #{json.length}")
owner = json[0]
assert.ok(owner.reverse, "Has a related reverse")
assert.ok(owner.reverse.id, "Related model has an id")
unless Owner.relationIsEmbedded('reverse') # TODO: confirm this is correct
assert.equal(reverse.get('owner_id'), owner.id, "\nRelated model has the correct id: Expected: #{reverse.get('owner_id')}\nActual: #{owner.id}")
assert.equal(reverse.get('name'), owner.reverse.name, "\nIncluded model has the correct name: Expected: #{reverse.get('name')}\nActual: #{owner.reverse.name}")
done()
it 'Should be able to count relationships', (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
Reverse.count {owner_id: owner.id}, (err, count) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(1, count, "Counted reverses. Expected: 1. Actual: #{count}")
done()
it 'Should be able to count relationships with paging', (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
Reverse.cursor({owner_id: owner.id, $page: true}).toJSON (err, paging_info) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(0, paging_info.offset, "Has offset. Expected: 0. Actual: #{paging_info.offset}")
assert.equal(1, paging_info.total_rows, "Counted reverses. Expected: 1. Actual: #{paging_info.total_rows}")
done()
backlinkTests = (virtual) ->
it "Should update backlinks using set (#{if virtual then 'virtual' else 'no modifiers'})", (done) ->
# TODO: implement embedded
return done() if options.embed
checkReverseFn = (reverse, expected_owner) -> return (callback) ->
assert.ok(reverse, 'Reverse exists')
assert.equal(expected_owner, reverse.get('owner'), "Reverse owner is correct. Expected: #{expected_owner}. Actual: #{reverse.get('owner')}")
callback()
Owner.cursor().limit(2).include('reverse').toModels (err, owners) ->
if virtual # set as virtual relationship after including reverse
relation = Owner.relation('reverse')
relation.virtual = true
assert.ok(!err, "No errors: #{err}")
assert.equal(2, owners.length, "Found owners. Expected: 2. Actual: #{owners.length}")
owner0 = owners[0]; owner0_id = owner0.id; reverse0 = owner0.get('reverse')
owner1 = owners[1]; owner1_id = owner1.id; reverse1 = owner1.get('reverse')
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(owner1.get('reverse'), "Owner1 has 1 reverse.")
queue = new Queue(1)
queue.defer checkReverseFn(reverse0, owner0)
queue.defer checkReverseFn(reverse1, owner1)
queue.defer (callback) ->
owner0.set({reverse: reverse1})
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(!owner1.get('reverse'), "Owner1 has no reverse.")
queue.defer checkReverseFn(reverse1, owner0) # confirm it also is related
queue.defer checkReverseFn(reverse0, owner0) # confirm it stayed
assert.equal(null, owner1.get('reverse'), "Owner's reverse is cleared.\nExpected: #{null}.\nActual: #{JSONUtils.stringify(owner1.get('reverse'))}")
callback()
# save and recheck
queue.defer (callback) -> owner0.save callback
queue.defer (callback) -> owner1.save callback
queue.defer (callback) ->
BackboneORM.model_cache.reset() # reset cache
Owner.cursor({$ids: [owner0.id, owner1.id]}).limit(2).include('reverse').toModels (err, owners) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(2, owners.length, "Found owners post-save. Expected: 2. Actual: #{owners.length}")
# lookup owners
owner0 = owner1 = null
for owner in owners
if owner.id is owner0_id
owner0 = owner
else if owner.id is owner1_id
owner1 = owner
assert(owner0, 'refound owner0')
assert(owner1, 'refound owner1')
reverse0b = owner0.get('reverse')
reverse1b = owner1.get('reverse')
if virtual
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(owner1.get('reverse'), "Owner1 has 1 reverse.")
else
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(!owner1.get('reverse'), "Owner1 has no reverse.")
queue.defer checkReverseFn(reverse0b, owner0) # confirm it moved
# TODO: determine reason on SQL for updated_at missing
# assert.deepEqual(reverse1.toJSON(), reverse0b.toJSON(), "Reverse is cleared.\nExpected: #{JSONUtils.stringify(reverse1.toJSON())}.\nActual: #{JSONUtils.stringify(reverse0b.toJSON())}")
assert.deepEqual(_.pick(reverse1.toJSON(), 'created_at'), _.pick(reverse0b.toJSON(), 'created_at'), "Reverse is cleared.\nExpected: #{JSONUtils.stringify(_.pick(reverse1.toJSON(), 'updated_at', 'created_at'))}.\nActual: #{JSONUtils.stringify(_.pick(reverse0b.toJSON(), 'updated_at', 'created_at'))}")
assert.equal(null, owner1.get('reverse'), "Owner's reverse is cleared.\nExpected: #{null}.\nActual: #{JSONUtils.stringify(owner1.get('reverse'))}")
callback()
queue.await (err) ->
assert.ok(!err, "No errors: #{err}")
done()
backlinkTests(false)
backlinkTests(true)
it 'does not serialize virtual attributes', (done) ->
json_key = if options.embed then '<KEY>' else '<KEY>'
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'Owners found')
flat_id = owner.get('flat').id
json = owner.toJSON()
assert.ok(json.hasOwnProperty(json_key), 'Serialized flat')
relation = owner.relation('flat')
relation.virtual = true
virtual_json = owner.toJSON()
assert.ok(!virtual_json.hasOwnProperty(json_key), 'Did not serialize flat')
owner_with_flat = new Owner(json)
assert.equal(owner_with_flat.get('flat').id, flat_id, 'Virtual with flat was deserialized')
owner_with_virtual_flat = new Owner(virtual_json)
assert.equal(owner_with_virtual_flat.get('flat'), null, 'Virtual without flat was deserialized')
done()
# owner.save {flat: null}, (err) ->
# assert.ok(!err, "No errors: #{err}")
# BackboneORM.model_cache.reset() # reset cache
# Owner.find owner.id, (err, loaded_owner) ->
# assert.ok(!err, "No errors: #{err}")
# assert.equal(loaded_owner.get('flat').id, flat_id, 'Virtual flat is not saved')
# done()
| true | assert = assert or require?('chai').assert
BackboneORM = window?.BackboneORM; try BackboneORM or= require?('backbone-orm') catch; try BackboneORM or= require?('../../../../backbone-orm')
{_, Backbone, Queue, Utils, JSONUtils, Fabricator} = BackboneORM
_.each BackboneORM.TestUtils.optionSets(), exports = (options) ->
options = _.extend({}, options, __test__parameters) if __test__parameters?
return if options.embed and not options.sync.capabilities(options.database_url or '').embed
DATABASE_URL = options.database_url or ''
BASE_SCHEMA = options.schema or {}
SYNC = options.sync
BASE_COUNT = 5
PICK_KEYS = ['PI:KEY:<KEY>END_PI', 'name']
describe "hasOne #{options.$parameter_tags or ''}#{options.$tags} @has_one", ->
Flat = Reverse = ForeignReverse = Owner = null
before ->
BackboneORM.configure {model_cache: {enabled: !!options.cache, max: 100}}
class Flat extends Backbone.Model
model_name: 'Flat'
urlRoot: "#{DATABASE_URL}/one_flats"
schema: _.defaults({
owner: -> ['hasOne', Owner]
}, BASE_SCHEMA)
sync: SYNC(Flat)
class Reverse extends Backbone.Model
model_name: 'Reverse'
urlRoot: "#{DATABASE_URL}/one_reverses"
schema: _.defaults({
owner: -> ['belongsTo', Owner]
owner_as: -> ['belongsTo', Owner, as: 'reverse_as']
}, BASE_SCHEMA)
sync: SYNC(Reverse)
class ForeignReverse extends Backbone.Model
model_name: 'ForeignReverse'
urlRoot: "#{DATABASE_URL}/one_foreign_reverses"
schema: _.defaults({
owner: -> ['belongsTo', Owner, foreign_key: 'ownerish_id']
}, BASE_SCHEMA)
sync: SYNC(ForeignReverse)
class Owner extends Backbone.Model
model_name: 'Owner'
urlRoot: "#{DATABASE_URL}/one_owners"
schema: _.defaults({
flat: -> ['belongsTo', Flat, embed: options.embed]
reverse: -> ['hasOne', Reverse]
reverse_as: -> ['hasOne', Reverse, as: 'owner_as']
foreign_reverse: -> ['hasOne', ForeignReverse]
}, BASE_SCHEMA)
sync: SYNC(Owner)
after (callback) -> Utils.resetSchemas [Flat, Reverse, ForeignReverse, Owner], callback
beforeEach (callback) ->
relation = Owner.relation('flat')
delete relation.virtual
MODELS = {}
queue = new Queue(1)
queue.defer (callback) -> Utils.resetSchemas [Flat, Reverse, ForeignReverse, Owner], callback
queue.defer (callback) ->
create_queue = new Queue()
create_queue.defer (callback) -> Fabricator.create Flat, BASE_COUNT, {
name: Fabricator.uniqueId('flat_')
created_at: Fabricator.date
}, (err, models) -> MODELS.flat = models; callback(err)
create_queue.defer (callback) -> Fabricator.create Reverse, BASE_COUNT, {
name: Fabricator.uniqueId('reverse_')
created_at: Fabricator.date
}, (err, models) -> MODELS.reverse = models; callback(err)
create_queue.defer (callback) -> Fabricator.create ForeignReverse, BASE_COUNT, {
name: Fabricator.uniqueId('foreign_reverse_')
created_at: Fabricator.date
}, (err, models) -> MODELS.foreign_reverse = models; callback(err)
create_queue.defer (callback) -> Fabricator.create Owner, BASE_COUNT, {
name: Fabricator.uniqueId('owner_')
created_at: Fabricator.date
}, (err, models) -> MODELS.owner = models; callback(err)
create_queue.await callback
# link and save all
queue.defer (callback) ->
save_queue = new Queue(1) # NOTE: save serially because we are including reverse_as in reverse over (overlap between saves)
reversed_reverse = _.clone(MODELS.reverse).reverse()
for owner in MODELS.owner
do (owner) -> save_queue.defer (callback) ->
owner.set({
flat: MODELS.flat.pop()
reverse: MODELS.reverse.pop()
reverse_as: reversed_reverse.pop()
foreign_reverse: MODELS.foreign_reverse.pop()
})
owner.save callback
save_queue.await callback
queue.await callback
it 'Can fetch and serialize a custom foreign key', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'foreign_reverse', (err, related_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(related_model, 'found related model')
related_json = related_model.toJSON()
assert.equal(test_model.id, related_json.ownerish_id, "Serialized the foreign id. Expected: #{test_model.id}. Actual: #{related_json.ownerish_id}")
done()
it 'Can create a model and load a related model by id (belongsTo)', (done) ->
Flat.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
flat_id = test_model.id
new_model = new Owner({flat_id: flat_id})
new_model.save (err) ->
assert.ok(!err, "No errors: #{err}")
new_model.get 'flat', (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found related model')
assert.equal(flat_id, flat.id, 'Loaded model is correct')
done()
patchAddTests = (unload) ->
it "Can manually add a relationship by related_id (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
Reverse.cursor({id: {$ne: reverse.id}, $one: true}).toJSON (err, another_reverse_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_reverse_json, "loaded another model.")
assert.ok(reverse.id isnt another_reverse_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchAdd 'reverse', another_reverse_json.id, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_reverse = owner.get('reverse')
assert.ok(updated_reverse.id is another_reverse_json.id, "Set the id. Expected: #{another_reverse_json.id}. Actual: #{updated_reverse.id}")
owner.get 'reverse', (err, updated_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_reverse, "loaded another model.")
assert.equal(updated_reverse.get('owner_id'), owner.id, "owner_id is correct.")
assert.ok(_.isEqual(_.pick(updated_reverse.toJSON(), PICK_KEYS), _.pick(another_reverse_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_reverse_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_reverse.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related json (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
Reverse.cursor({id: {$ne: reverse.id}, $one: true}).toJSON (err, another_reverse_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_reverse_json, "loaded another model.")
assert.ok(reverse.id isnt another_reverse_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchAdd 'reverse', another_reverse_json, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_reverse = owner.get('reverse')
assert.ok(updated_reverse.id is another_reverse_json.id, "Set the id. Expected: #{another_reverse_json.id}. Actual: #{updated_reverse.id}")
owner.get 'reverse', (err, updated_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_reverse, "loaded another model.")
assert.equal(updated_reverse.get('owner_id'), owner.id, "owner_id is correct.")
assert.ok(_.isEqual(_.pick(updated_reverse.toJSON(), PICK_KEYS), _.pick(another_reverse_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_reverse_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_reverse.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related model (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
Reverse.cursor({id: {$ne: reverse.id}}).toModel (err, another_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_reverse, "loaded another model.")
assert.ok(reverse.id isnt another_reverse.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchAdd 'reverse', another_reverse, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_reverse = owner.get('reverse')
assert.ok(updated_reverse.id is another_reverse.id, "Set the id. Expected: #{another_reverse.id}. Actual: #{updated_reverse.id}")
owner.get 'reverse', (err, updated_reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_reverse, "loaded another model.")
assert.equal(updated_reverse.get('owner_id'), owner.id, "owner_id is correct.")
assert.ok(_.isEqual(_.pick(updated_reverse.toJSON(), PICK_KEYS), _.pick(another_reverse.toJSON(), PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_reverse.toJSON(), PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_reverse.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related_id (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model.")
Owner.cursor({id: {$ne: owner.id}, $one: true}).toJSON (err, another_owner_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_owner_json, "loaded another model.")
assert.ok(owner.id isnt another_owner_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchAdd 'owner', another_owner_json.id, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_owner = reverse.get('owner')
assert.ok(updated_owner.id is another_owner_json.id, "Set the id. Expected: #{another_owner_json.id}. Actual: #{updated_owner.id}")
reverse.get 'owner', (err, updated_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_owner, "loaded another model.")
assert.equal(updated_owner.get('reverse_id'), reverse.id, "reverse_id is correct.")
assert.ok(_.isEqual(_.pick(updated_owner.toJSON(), PICK_KEYS), _.pick(another_owner_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_owner_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_owner.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related json (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model.")
Owner.cursor({id: {$ne: owner.id}, $one: true}).toJSON (err, another_owner_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_owner_json, "loaded another model.")
assert.ok(owner.id isnt another_owner_json.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchAdd 'owner', another_owner_json, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_owner = reverse.get('owner')
assert.ok(updated_owner.id is another_owner_json.id, "Set the id. Expected: #{another_owner_json.id}. Actual: #{updated_owner.id}")
reverse.get 'owner', (err, updated_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_owner, "loaded another model.")
assert.equal(updated_owner.get('reverse_id'), reverse.id, "reverse_id is correct.")
assert.ok(_.isEqual(_.pick(updated_owner.toJSON(), PICK_KEYS), _.pick(another_owner_json, PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_owner_json, PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_owner.toJSON(), PICK_KEYS))}")
done()
it "Can manually add a relationship by related model (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model.")
Owner.cursor({id: {$ne: owner.id}}).toModel (err, another_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(another_owner, "loaded another model.")
assert.ok(owner.id isnt another_owner.id, "loaded a model with a different id.")
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchAdd 'owner', another_owner, (err) ->
assert.ok(!err, "No errors: #{err}")
updated_owner = reverse.get('owner')
assert.ok(updated_owner.id is another_owner.id, "Set the id. Expected: #{another_owner.id}. Actual: #{updated_owner.id}")
reverse.get 'owner', (err, updated_owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(updated_owner, "loaded another model.")
assert.equal(updated_owner.get('reverse_id'), reverse.id, "reverse_id is correct.")
assert.ok(_.isEqual(_.pick(updated_owner.toJSON(), PICK_KEYS), _.pick(another_owner.toJSON(), PICK_KEYS)), "Set the id. Expected: #{JSONUtils.stringify(_.pick(another_owner.toJSON(), PICK_KEYS))}. Actual: #{JSONUtils.stringify(_.pick(updated_owner.toJSON(), PICK_KEYS))}")
done()
patchAddTests(false)
patchAddTests(true)
patchRemoveTests = (unload) ->
it "Can manually delete a relationship by related_id (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', destroyed_model.id, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by related_json (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', destroyed_model.toJSON(), (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by related model (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', destroyed_model, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by array related of model (hasOne)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, "loaded correct model.")
destroyed_model = reverse
if unload
BackboneORM.model_cache.reset() # reset cache
owner = new Owner({id: owner.id})
owner.patchRemove 'reverse', [destroyed_model], (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner.get('reverse'), "destroyed in memory relationship.")
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
Owner.findOne owner.id, (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found owners')
owner.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, "loaded correct models.")
done()
it "Can manually delete a relationship by related_id (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', destroyed_model.id, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
it "Can manually delete a relationship by related_json (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', destroyed_model.toJSON(), (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
it "Can manually delete a relationship by related_model (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', destroyed_model, (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
it "Can manually delete a relationship by array of related_model (belongsTo)#{if unload then ' with unloaded model' else ''}", (done) ->
# TODO: implement embedded find
return done() if options.embed
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, "loaded correct model")
destroyed_model = owner
if unload
BackboneORM.model_cache.reset() # reset cache
reverse = new Reverse({id: reverse.id})
reverse.patchRemove 'owner', [destroyed_model], (err) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse.get('owner'), "destroyed in memory relationship.")
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
Reverse.findOne reverse.id, (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found reverse')
assert.ok(!reverse.get('owner'), 'destroyed correct model')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(!owner, 'destroyed correct model')
done()
patchRemoveTests(false)
patchRemoveTests(true)
it 'Can create a model and update the relationship (belongsTo)', (done) ->
related_key = 'flat'
related_id_accessor = 'flat_id'
Owner.cursor().include(related_key).toModel (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
owner_id = owner.id
related = owner.get(related_key)
related_id = related.id
assert.ok(related, 'included related')
(attributes = {})[related_key] = related
new_owner = new Owner(attributes)
owner1 = null; new_owner1 = null; new_owner_id = null
assert.equal(related, owner.get(related_key), "Didn't modify previous related. Expected: #{related}. Actual: #{owner.get(related_key)}")
assert.equal(related_id, owner.get(related_id_accessor), "Got related_id from previous related. Expected: #{related_id}. Actual: #{owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
queue = new Queue(1)
queue.defer (callback) -> new_owner.save callback
queue.defer (callback) -> owner.save callback
# make sure nothing changed after save
queue.defer (callback) ->
new_owner_id = new_owner.id
assert.ok(new_owner_id, 'had an id after after')
assert.equal(related, owner.get(related_key), "Didn't modify previous related. Expected: #{related}. Actual: #{owner.get(related_key)}")
assert.equal(related_id, owner.get(related_id_accessor), "Got related_id from previous related. Expected: #{related_id}. Actual: #{owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
callback()
# load
queue.defer (callback) -> Owner.find owner_id, (err, _owner) -> callback(err, owner1 = _owner)
queue.defer (callback) -> Owner.find new_owner_id, (err, _owner) -> callback(err, new_owner1 = _owner)
# check
queue.defer (callback) ->
assert.equal(related_id, owner1.get(related_id_accessor), "Got related_id from reloaded previous related. Expected: #{related_id}. Actual: #{owner1.get(related_id_accessor)}")
assert.equal(related_id, new_owner1.get(related_id_accessor), "Got related_id from reloaded copied related. Expected: #{related_id}. Actual: #{new_owner1.get(related_id_accessor)}")
owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(related_id, related.id, "Loaded related from previous related. Expected: #{related_id}. Actual: #{related.id}")
new_owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(related_id, related.id, "Loaded related from previous related. Expected: #{related_id}. Actual: #{related.id}")
callback()
queue.await done
it 'Can create a model and update the relationship (hasOne)', (done) ->
# TODO: implement embedded set - should clone in set or the caller needed to clone? (problem is sharing an in memory instance)
return done() if options.embed
related_key = 'PI:KEY:<KEY>END_PI'
related_id_accessor = 'reverse_id'
Owner.cursor().include(related_key).toModel (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
related = owner.get(related_key)
owner_id = owner.id
related_id = related.id
assert.ok(related, 'included related')
(attributes = {})[related_key] = related
new_owner = new Owner(attributes)
owner1 = null; new_owner1 = null; new_owner_id = null
assert.equal(null, owner.get(related_key), "Modified previous related. Expected: #{null}. Actual: #{owner.get(related_key)}")
assert.equal(null, owner.get(related_id_accessor), "Failed to get related_id from previous related. Expected: #{null}. Actual: #{new_owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
queue = new Queue(1)
queue.defer (callback) -> new_owner.save callback
queue.defer (callback) -> owner.save callback
# make sure nothing changed after save
queue.defer (callback) ->
new_owner_id = new_owner.id
assert.ok(new_owner_id, 'had an id after after')
assert.equal(null, owner.get(related_key), "Modified previous related. Expected: #{null}. Actual: #{owner.get(related_key)}")
assert.equal(null, owner.get(related_id_accessor), "Got related_id from previous related. Expected: #{null}. Actual: #{new_owner.get(related_id_accessor)}")
assert.equal(related, new_owner.get(related_key), "Copied related. Expected: #{related}. Actual: #{new_owner.get(related_key)}")
assert.equal(related_id, new_owner.get(related_id_accessor), "Got related_id from copied related. Expected: #{related_id}. Actual: #{new_owner.get(related_id_accessor)}")
callback()
# load
queue.defer (callback) -> Owner.find owner_id, (err, _owner) -> callback(err, owner1 = _owner)
queue.defer (callback) -> Owner.find new_owner_id, (err, _owner) -> callback(err, new_owner1 = _owner)
# check
queue.defer (callback) ->
owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(null, related, "Failed to loaded related from previous related. Expected: #{null}. Actual: #{related}")
assert.equal(null, owner1.get(related_id_accessor), "Failed to get related_id from reloaded previous related. Expected: #{null}. Actual: #{owner1.get(related_id_accessor)}")
new_owner1.get related_key, (err, related) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(related_id, related.id, "Loaded related from previous related. Expected: #{related_id}. Actual: #{related.id}")
assert.equal(related_id, new_owner1.get(related_id_accessor), "Got related_id from reloaded copied related. Expected: #{related_id}. Actual: #{new_owner1.get(related_id_accessor)}")
callback()
queue.await done
# TODO: should the related model be loaded to save?
it.skip 'Can create a related model by id (hasOne)', (done) ->
Reverse.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
reverse_id = test_model.id
new_model = new Owner()
new_model.save (err) ->
assert.ok(!err, "No errors: #{err}")
new_model.set({reverse_id: reverse_id})
new_model.save (err) ->
assert.ok(!err, "No errors: #{err}")
new_model.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(reverse_id, reverse.id, 'Loaded model is correct')
done()
it 'Handles a get query for a belongsTo relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'flat', (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found related model')
if test_model.relationIsEmbedded('flat')
assert.deepEqual(test_model.toJSON().flat, flat.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().flat)}. Actual: #{JSONUtils.stringify(flat.toJSON())}")
else
assert.deepEqual(test_model.toJSON().flat_id, flat.id, "Serialized id only. Expected: #{test_model.toJSON().flat_id}. Actual: #{flat.id}")
assert.equal(test_model.get('flat_id'), flat.id, "\nExpected: #{test_model.get('flat_id')}\nActual: #{flat.id}")
done()
it 'Handles a get query for a hasOne relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(test_model.id, reverse.get('owner_id'), "\nExpected: #{test_model.id}\nActual: #{reverse.get('owner_id')}")
assert.equal(test_model.id, reverse.toJSON().owner_id, "\nReverse toJSON has an owner_id. Expected: #{test_model.id}\nActual: #{reverse.toJSON().owner_id}")
if test_model.relationIsEmbedded('reverse')
assert.deepEqual(test_model.toJSON().reverse, reverse.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().reverse)}. Actual: #{JSONUtils.stringify(reverse.toJSON())}")
assert.ok(!test_model.toJSON().reverse_id, 'No reverese_id in owner json')
done()
it 'Can retrieve an id for a hasOne relation via async virtual method', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse_id', (err, id) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(id, 'found id')
done()
it 'Can retrieve a belongsTo id synchronously and then a model asynchronously from get methods', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
assert.ok(test_model.get('flat_id'), 'Has the belongsTo id')
test_model.get 'flat', (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'loaded model')
assert.equal(test_model.get('flat_id'), flat.id, "\nExpected: #{test_model.get('flat_id')}\nActual: #{flat.id}")
done()
it 'Handles a get query for a hasOne and belongsTo two sided relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(test_model.id, reverse.get('owner_id'), "\nExpected: #{test_model.id}\nActual: #{reverse.get('owner_id')}")
assert.equal(test_model.id, reverse.toJSON().owner_id, "\nReverse toJSON has an owner_id. Expected: #{test_model.id}\nActual: #{reverse.toJSON().owner_id}")
if test_model.relationIsEmbedded('reverse')
assert.deepEqual(test_model.toJSON().reverse, reverse.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().reverse)}. Actual: #{JSONUtils.stringify(reverse.toJSON())}")
assert.ok(!test_model.toJSON().reverse_id, 'No reverse_id in owner json')
reverse.get 'owner', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found original model')
assert.deepEqual(reverse.toJSON().owner_id, owner.id, "Serialized id only. Expected: #{reverse.toJSON().owner_id}. Actual: #{owner.id}")
if Owner.cache
assert.deepEqual(test_model.toJSON(), owner.toJSON(), "\nExpected: #{JSONUtils.stringify(test_model.toJSON())}\nActual: #{JSONUtils.stringify(owner.toJSON())}")
else
assert.equal(test_model.id, owner.id, "\nExpected: #{test_model.id}\nActual: #{owner.id}")
done()
it 'Appends json for a related model', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
JSONUtils.renderRelated test_model, 'reverse', ['id', 'created_at'], (err, related_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(related_json.id, "reverse has an id")
assert.ok(related_json.created_at, "reverse has a created_at")
assert.ok(!related_json.updated_at, "reverse doesn't have updated_at")
JSONUtils.renderRelated test_model, 'flat', ['id', 'created_at'], (err, related_json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(related_json.id, "flat has an id")
# assert.ok(related_json.created_at, "flat has a created_at")
assert.ok(!related_json.updated_at, "flat doesn't have updated_at")
done()
# TODO: delay the returning of memory models related models to test lazy loading properly
it 'Fetches a relation from the store if not present', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
fetched_owner = new Owner({id: test_model.id})
fetched_owner.fetch (err) ->
assert.ok(!err, "No errors: #{err}")
delete fetched_owner.attributes.reverse
fetched_owner.get 'reverse', (err, reverse) ->
if fetched_owner.relationIsEmbedded('reverse')
assert.ok(!err, "No errors: #{err}")
assert.ok(!reverse, 'Cannot yet load the model') # TODO: implement a fetch from the related model
done()
else
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'loaded the model lazily')
assert.equal(reverse.get('owner_id'), test_model.id)
done()
# assert.equal(reverse, null, 'has not loaded the model initially')
it 'Has an id loaded for a belongsTo and not for a hasOne relation', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
assert.ok(test_model.get('flat_id'), 'belongsTo id is loaded')
# assert.ok(!test_model.get('reverse_id'), 'hasOne id is not loaded')
done()
it 'Handles a get query for a hasOne and belongsTo two sided relation as "as" fields', (done) ->
Owner.findOne (err, test_model) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(test_model, 'found model')
test_model.get 'reverse_as', (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found related model')
assert.equal(test_model.id, reverse.get('owner_as_id'), "\nExpected: #{test_model.id}\nActual: #{reverse.get('owner_as_id')}")
assert.equal(test_model.id, reverse.toJSON().owner_as_id, "\nReverse toJSON has an owner_id. Expected: #{test_model.id}\nActual: #{reverse.toJSON().owner_as_id}")
if test_model.relationIsEmbedded('reverse_as')
assert.deepEqual(test_model.toJSON().reverse_as, reverse.toJSON(), "Serialized embed. Expected: #{JSONUtils.stringify(test_model.toJSON().reverse)}. Actual: #{JSONUtils.stringify(reverse.toJSON())}")
assert.ok(!test_model.toJSON().reverse_as_id, 'No reverse_as_id in owner json')
reverse.get 'owner_as', (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found original model')
assert.deepEqual(reverse.toJSON().owner_as_id, owner.id, "Serialized id only. Expected: #{reverse.toJSON().owner_as_id}. Actual: #{owner.id}")
if Owner.cache
assert.deepEqual(test_model.toJSON(), owner.toJSON(), "\nExpected: #{JSONUtils.stringify(test_model.toJSON())}\nActual: #{JSONUtils.stringify(owner.toJSON())}")
else
assert.equal(test_model.id, owner.id, "\nExpected: #{test_model.id}\nActual: #{owner.id}")
done()
it 'Can include a related (belongsTo) model', (done) ->
Owner.cursor({$one: true}).include('flat').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, 'found model')
assert.ok(json.flat, "Has a related flat")
assert.ok(json.flat.id, "Related model has an id")
unless Owner.relationIsEmbedded('flat') # TODO: confirm this is correct
assert.equal(json.flat_id, json.flat.id, "\nRelated model has the correct id: Expected: #{json.flat_id}\nActual: #{json.flat.id}")
done()
it 'Can include a related (hasOne) model', (done) ->
Owner.cursor({$one: true}).include('reverse').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, 'found model')
assert.ok(json.reverse, "Has a related reverse")
assert.ok(json.reverse.id, "Related model has an id")
assert.equal(json.id, json.reverse.owner_id, "\nRelated model has the correct id: Expected: #{json.id}\nActual: #{json.reverse.owner_id}")
done()
it 'Can include multiple related models', (done) ->
Owner.cursor({$one: true}).include('reverse', 'flat').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, 'found model')
assert.ok(json.reverse, "Has a related reverse")
assert.ok(json.reverse.id, "Related model has an id")
assert.ok(json.flat, "Has a related flat")
assert.ok(json.flat.id, "Included model has an id")
unless Owner.relationIsEmbedded('flat') # TODO: confirm this is correct
assert.equal(json.flat_id, json.flat.id, "\nIncluded model has the correct id: Expected: #{json.flat_id}\nActual: #{json.flat.id}")
assert.equal(json.id, json.reverse.owner_id, "\nIncluded model has the correct id: Expected: #{json.id}\nActual: #{json.reverse.owner_id}")
done()
it 'Can query on a related (belongsTo) model property', (done) ->
Flat.findOne (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found model')
Owner.cursor({$one: true, 'flat.id': flat.id}).toJSON (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
unless Owner.relationIsEmbedded('flat') # TODO: confirm this is correct
assert.equal(flat.id, owner.flat_id, "\nRelated model has the correct id: Expected: #{flat.id}\nActual: #{owner.flat_id}")
done()
it 'Can query on a related (belongsTo) model property when the relation is included', (done) ->
Flat.findOne (err, flat) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(flat, 'found model')
Owner.cursor({$one: true, 'flat.name': flat.get('name')}).include('flat').toJSON (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
assert.ok(owner.flat, "Has a related flat")
assert.ok(owner.flat.id, "Included model has an id")
assert.equal(flat.id, owner.flat.id, "\nIncluded model has the correct id: Expected: #{flat.id}\nActual: #{owner.flat.id}")
assert.equal(flat.get('name'), owner.flat.name, "\nIncluded model has the correct name: Expected: #{flat.get('name')}\nActual: #{owner.flat.name}")
done()
it 'Can query on a related (hasOne) model', (done) ->
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'Reverse found model')
Owner.cursor({$one: true, 'reverse.name': reverse.get('name')}).toJSON (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'Owner found model')
unless Owner.relationIsEmbedded('reverse') # TODO: confirm this is correct
assert.equal(reverse.get('owner_id'), owner.id, "\nRelated model has the correct id: Expected: #{reverse.get('owner_id')}\nActual: #{owner.id}")
done()
it 'Can query on a related (hasOne) model property when the relation is included', (done) ->
Reverse.findOne (err, reverse) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(reverse, 'found model')
Owner.cursor({'reverse.name': reverse.get('name')}).include('reverse').toJSON (err, json) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(json, "found json")
assert.equal(json.length, 1, "json has the correct number or results. Expecting: 1. Actual #{json.length}")
owner = json[0]
assert.ok(owner.reverse, "Has a related reverse")
assert.ok(owner.reverse.id, "Related model has an id")
unless Owner.relationIsEmbedded('reverse') # TODO: confirm this is correct
assert.equal(reverse.get('owner_id'), owner.id, "\nRelated model has the correct id: Expected: #{reverse.get('owner_id')}\nActual: #{owner.id}")
assert.equal(reverse.get('name'), owner.reverse.name, "\nIncluded model has the correct name: Expected: #{reverse.get('name')}\nActual: #{owner.reverse.name}")
done()
it 'Should be able to count relationships', (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
Reverse.count {owner_id: owner.id}, (err, count) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(1, count, "Counted reverses. Expected: 1. Actual: #{count}")
done()
it 'Should be able to count relationships with paging', (done) ->
# TODO: implement embedded find
return done() if options.embed
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'found model')
Reverse.cursor({owner_id: owner.id, $page: true}).toJSON (err, paging_info) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(0, paging_info.offset, "Has offset. Expected: 0. Actual: #{paging_info.offset}")
assert.equal(1, paging_info.total_rows, "Counted reverses. Expected: 1. Actual: #{paging_info.total_rows}")
done()
backlinkTests = (virtual) ->
it "Should update backlinks using set (#{if virtual then 'virtual' else 'no modifiers'})", (done) ->
# TODO: implement embedded
return done() if options.embed
checkReverseFn = (reverse, expected_owner) -> return (callback) ->
assert.ok(reverse, 'Reverse exists')
assert.equal(expected_owner, reverse.get('owner'), "Reverse owner is correct. Expected: #{expected_owner}. Actual: #{reverse.get('owner')}")
callback()
Owner.cursor().limit(2).include('reverse').toModels (err, owners) ->
if virtual # set as virtual relationship after including reverse
relation = Owner.relation('reverse')
relation.virtual = true
assert.ok(!err, "No errors: #{err}")
assert.equal(2, owners.length, "Found owners. Expected: 2. Actual: #{owners.length}")
owner0 = owners[0]; owner0_id = owner0.id; reverse0 = owner0.get('reverse')
owner1 = owners[1]; owner1_id = owner1.id; reverse1 = owner1.get('reverse')
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(owner1.get('reverse'), "Owner1 has 1 reverse.")
queue = new Queue(1)
queue.defer checkReverseFn(reverse0, owner0)
queue.defer checkReverseFn(reverse1, owner1)
queue.defer (callback) ->
owner0.set({reverse: reverse1})
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(!owner1.get('reverse'), "Owner1 has no reverse.")
queue.defer checkReverseFn(reverse1, owner0) # confirm it also is related
queue.defer checkReverseFn(reverse0, owner0) # confirm it stayed
assert.equal(null, owner1.get('reverse'), "Owner's reverse is cleared.\nExpected: #{null}.\nActual: #{JSONUtils.stringify(owner1.get('reverse'))}")
callback()
# save and recheck
queue.defer (callback) -> owner0.save callback
queue.defer (callback) -> owner1.save callback
queue.defer (callback) ->
BackboneORM.model_cache.reset() # reset cache
Owner.cursor({$ids: [owner0.id, owner1.id]}).limit(2).include('reverse').toModels (err, owners) ->
assert.ok(!err, "No errors: #{err}")
assert.equal(2, owners.length, "Found owners post-save. Expected: 2. Actual: #{owners.length}")
# lookup owners
owner0 = owner1 = null
for owner in owners
if owner.id is owner0_id
owner0 = owner
else if owner.id is owner1_id
owner1 = owner
assert(owner0, 'refound owner0')
assert(owner1, 'refound owner1')
reverse0b = owner0.get('reverse')
reverse1b = owner1.get('reverse')
if virtual
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(owner1.get('reverse'), "Owner1 has 1 reverse.")
else
assert.ok(owner0.get('reverse'), "Owner0 has 1 reverse.")
assert.ok(!owner1.get('reverse'), "Owner1 has no reverse.")
queue.defer checkReverseFn(reverse0b, owner0) # confirm it moved
# TODO: determine reason on SQL for updated_at missing
# assert.deepEqual(reverse1.toJSON(), reverse0b.toJSON(), "Reverse is cleared.\nExpected: #{JSONUtils.stringify(reverse1.toJSON())}.\nActual: #{JSONUtils.stringify(reverse0b.toJSON())}")
assert.deepEqual(_.pick(reverse1.toJSON(), 'created_at'), _.pick(reverse0b.toJSON(), 'created_at'), "Reverse is cleared.\nExpected: #{JSONUtils.stringify(_.pick(reverse1.toJSON(), 'updated_at', 'created_at'))}.\nActual: #{JSONUtils.stringify(_.pick(reverse0b.toJSON(), 'updated_at', 'created_at'))}")
assert.equal(null, owner1.get('reverse'), "Owner's reverse is cleared.\nExpected: #{null}.\nActual: #{JSONUtils.stringify(owner1.get('reverse'))}")
callback()
queue.await (err) ->
assert.ok(!err, "No errors: #{err}")
done()
backlinkTests(false)
backlinkTests(true)
it 'does not serialize virtual attributes', (done) ->
json_key = if options.embed then 'PI:KEY:<KEY>END_PI' else 'PI:KEY:<KEY>END_PI'
Owner.findOne (err, owner) ->
assert.ok(!err, "No errors: #{err}")
assert.ok(owner, 'Owners found')
flat_id = owner.get('flat').id
json = owner.toJSON()
assert.ok(json.hasOwnProperty(json_key), 'Serialized flat')
relation = owner.relation('flat')
relation.virtual = true
virtual_json = owner.toJSON()
assert.ok(!virtual_json.hasOwnProperty(json_key), 'Did not serialize flat')
owner_with_flat = new Owner(json)
assert.equal(owner_with_flat.get('flat').id, flat_id, 'Virtual with flat was deserialized')
owner_with_virtual_flat = new Owner(virtual_json)
assert.equal(owner_with_virtual_flat.get('flat'), null, 'Virtual without flat was deserialized')
done()
# owner.save {flat: null}, (err) ->
# assert.ok(!err, "No errors: #{err}")
# BackboneORM.model_cache.reset() # reset cache
# Owner.find owner.id, (err, loaded_owner) ->
# assert.ok(!err, "No errors: #{err}")
# assert.equal(loaded_owner.get('flat').id, flat_id, 'Virtual flat is not saved')
# done()
|
[
{
"context": "s to: Helpers -> getProjects\n#\n# Author(s): Cyrus Manouchehrian\n# Will Zuill\n######################",
"end": 1180,
"score": 0.999894380569458,
"start": 1161,
"tag": "NAME",
"value": "Cyrus Manouchehrian"
},
{
"context": " Author(s): Cyrus Man... | src/srl-openapi-proxy.coffee | cyrusm86/srl_chatbot | 0 | ###
Copyright 2016 Hewlett-Packard Development Company, L.P.
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.
###
StormRunnerApi = require './libs/stormrunnerApiAdapter.js'
Helpers = require './helpers'
querystring = require "querystring"
mockData = require "./mockData"
url = require('url')
################################################################################
# Name: proxy/GetProjects
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getProjects
#
# Called from: stormrunner-bot-logic.coffee - show me all the projects
#
# Calls to: Helpers -> getProjects
#
# Author(s): Cyrus Manouchehrian
# Will Zuill
################################################################################
module.exports = (robot) ->
#listening to proxy command - get projects
robot.router.get '/hubot/stormrunner/proxy/getProjects', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
robot.logger.debug "Getting Projects... refresh=#{query.refresh}"
#with success, go to Helpers.getProjects function to get projects
projs = Helpers.getProjects(robot,query.refresh)
res.send projs
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Projects : \n #{error}"
res.status(500).send "Error retrieving Projects"
################################################################################
# Name: proxy/getTests
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getTests
#
# Called from: stormrunner-bot-logic.coffee - list tests for project (.*)
#
# Calls to: Helpers -> getTests(robot,project)
#
# Author(s): Cyrus Manouchehrian
# Will Zuill
################################################################################
#listening to proxy command - get test
robot.router.get '/hubot/stormrunner/proxy/getTests', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing, parses out project ID or project name
project= query.project
robot.logger.debug "Getting Tests... refresh=#{query.refresh}"
#upon success, go to Helpers.GetTests function to get tests
tests = Helpers.getTests(robot,project)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
################################################################################
# Name: proxy/getRuns
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getRuns
#
# Called from: stormrunner-bot-logic.coffee -
# show latest run for test (.*) in project (.*)
# list status for last (.*) runs for test (.*) in project (.*)
# show runs for test (.*) in project (.*)
#
# Calls to: Helpers -> getRuns(robot,project,testid)
#
# Author(s): Cyrus Manouchehrian
# Will Zuill
################################################################################
#listening to proxy command - getRuns
robot.router.get '/hubot/stormrunner/proxy/getRuns', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing the url, project id or project name is retrieved
project = query.project
#from parsing the url, the test id is retrieved
testid = query.TestID
robot.logger.debug "Getting Run Results... refresh=#{query.refresh}"
#upon success, go to Helpers.getRuns function to get runs
tests = Helpers.getRuns(robot,project,testid)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
################################################################################
# Name: proxy/getRunResults
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getRunResults
#
# Called from: stormrunner-bot-logic.coffee -
# show full results for run id (.*)
#
# Calls to: Helpers -> getRunResults(robot,runid)
#
# Author(s): Cyrus Manouchehrian
# Will Zuill
################################################################################
#listening to proxy command - getRunResults
robot.router.get '/hubot/stormrunner/proxy/getRunResults', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing the url, run id is retrieved
runid = query.runid
robot.logger.debug "Getting Tests... refresh=#{query.refresh}"
#upon success, go to Helpers.getRunResults to run results
tests = Helpers.getRunResults(robot,runid)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
###############################################################################
# Name: proxy/getRuns
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getRuns
#
# Called from: stormrunner-bot-logic.coffee -
# show latest run for test (.*) in project (.*)
# list status for last (.*) runs for test (.*) in project (.*)
# show runs for test (.*) in project (.*)
#
# Calls to: Helpers -> getRuns(robot,project,testid)
#
# Author(s): Cyrus Manouchehrian
# Will Zuill
################################################################################
#listening to proxy command - getRuns
robot.router.get '/hubot/stormrunner/proxy/postRun', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing the url, project id or project name is retrieved
project = query.project
#from parsing the url, the test id is retrieved
testid = query.TestID
robot.logger.debug "Getting Run Results... refresh=#{query.refresh}"
#upon success, go to Helpers.getRuns function to get runs
tests = Helpers.postRun(robot,project,testid)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
################################################################################
robot.router.get '/hubot/stormrunner/proxy/setProject', (req, res) ->
try
query = querystring.parse(url.parse(req.url).query)
strProject = query.project
robot.logger.debug "Setting the project... refresh=#{query.refresh}"
project = Helpers.setProject(robot,strProject)
res.send project
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error setting Project: \n #{error}"
res.status(500).send "Error setting Project"
################################################################################
robot.router.post '/hubot/stormrunner/proxy/jenkinsNotifer', (req, res) ->
try
query = querystring.parse(url.parse(req.url).query)
data = req.body
strUsername = query.user
strRoom = query.room
strMessage = ""
strPhase = data.build.phase
# if the username has been passed in, add a '@' symbol to the front and
# set that as the channel
if strUsername
strChannel = "@" + strUsername
# if the room has been passed in, add a '#' symbol to the front and
# set that as the channel
else if strRoom
strChannel = "#" + strRoom
else
strChannel = "#general" # default channel
# Depending on the phase of the build - post a message to the room.
if strPhase == "STARTED"
strMessage = "Hey - Just wanted to let you know that the Jenkins Job entitled '" + data.name + "' with build number: " + data.build.number + " has started."
else if strPhase == "COMPLETED"
strDay = StormRunnerApi.getDayOfTheWeek()
if data.build.status == "FAILURE"
strStatusMess = "Unfortunately, the build failed. This must be " + strDay + ". I never could get the hang of " + strDay + "s."
else
strStatusMess = "Good news. The build was successful. Now, go and make sure you put cover sheets on your TPS reports."
strMessage = "Sorry to bother you, but Jenkins Job entitled '" + data.name + "' with build number: " + data.build.number + " is complete. " + strStatusMess
# if we do have a message (i.e. we have been passed a status we want to post about) then post the message to the previously defined channel
if strMessage
msgData =
{
channel: strChannel
text: strMessage
}
Helpers.sendCustomMessage(robot,msgData)
catch error
robot.logger.error "There's a problem with the Jenkins Notifer : \n #{error}"
res.status(500).send "Error sending message to Hubot"
| 91533 | ###
Copyright 2016 Hewlett-Packard Development Company, L.P.
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.
###
StormRunnerApi = require './libs/stormrunnerApiAdapter.js'
Helpers = require './helpers'
querystring = require "querystring"
mockData = require "./mockData"
url = require('url')
################################################################################
# Name: proxy/GetProjects
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getProjects
#
# Called from: stormrunner-bot-logic.coffee - show me all the projects
#
# Calls to: Helpers -> getProjects
#
# Author(s): <NAME>
# <NAME>
################################################################################
module.exports = (robot) ->
#listening to proxy command - get projects
robot.router.get '/hubot/stormrunner/proxy/getProjects', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
robot.logger.debug "Getting Projects... refresh=#{query.refresh}"
#with success, go to Helpers.getProjects function to get projects
projs = Helpers.getProjects(robot,query.refresh)
res.send projs
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Projects : \n #{error}"
res.status(500).send "Error retrieving Projects"
################################################################################
# Name: proxy/getTests
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getTests
#
# Called from: stormrunner-bot-logic.coffee - list tests for project (.*)
#
# Calls to: Helpers -> getTests(robot,project)
#
# Author(s): <NAME>
# <NAME>
################################################################################
#listening to proxy command - get test
robot.router.get '/hubot/stormrunner/proxy/getTests', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing, parses out project ID or project name
project= query.project
robot.logger.debug "Getting Tests... refresh=#{query.refresh}"
#upon success, go to Helpers.GetTests function to get tests
tests = Helpers.getTests(robot,project)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
################################################################################
# Name: proxy/getRuns
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getRuns
#
# Called from: stormrunner-bot-logic.coffee -
# show latest run for test (.*) in project (.*)
# list status for last (.*) runs for test (.*) in project (.*)
# show runs for test (.*) in project (.*)
#
# Calls to: Helpers -> getRuns(robot,project,testid)
#
# Author(s): <NAME>
# <NAME>
################################################################################
#listening to proxy command - getRuns
robot.router.get '/hubot/stormrunner/proxy/getRuns', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing the url, project id or project name is retrieved
project = query.project
#from parsing the url, the test id is retrieved
testid = query.TestID
robot.logger.debug "Getting Run Results... refresh=#{query.refresh}"
#upon success, go to Helpers.getRuns function to get runs
tests = Helpers.getRuns(robot,project,testid)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
################################################################################
# Name: proxy/getRunResults
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getRunResults
#
# Called from: stormrunner-bot-logic.coffee -
# show full results for run id (.*)
#
# Calls to: Helpers -> getRunResults(robot,runid)
#
# Author(s): <NAME>
# <NAME>
################################################################################
#listening to proxy command - getRunResults
robot.router.get '/hubot/stormrunner/proxy/getRunResults', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing the url, run id is retrieved
runid = query.runid
robot.logger.debug "Getting Tests... refresh=#{query.refresh}"
#upon success, go to Helpers.getRunResults to run results
tests = Helpers.getRunResults(robot,runid)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
###############################################################################
# Name: proxy/getRuns
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getRuns
#
# Called from: stormrunner-bot-logic.coffee -
# show latest run for test (.*) in project (.*)
# list status for last (.*) runs for test (.*) in project (.*)
# show runs for test (.*) in project (.*)
#
# Calls to: Helpers -> getRuns(robot,project,testid)
#
# Author(s): <NAME>
# <NAME>
################################################################################
#listening to proxy command - getRuns
robot.router.get '/hubot/stormrunner/proxy/postRun', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing the url, project id or project name is retrieved
project = query.project
#from parsing the url, the test id is retrieved
testid = query.TestID
robot.logger.debug "Getting Run Results... refresh=#{query.refresh}"
#upon success, go to Helpers.getRuns function to get runs
tests = Helpers.postRun(robot,project,testid)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
################################################################################
robot.router.get '/hubot/stormrunner/proxy/setProject', (req, res) ->
try
query = querystring.parse(url.parse(req.url).query)
strProject = query.project
robot.logger.debug "Setting the project... refresh=#{query.refresh}"
project = Helpers.setProject(robot,strProject)
res.send project
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error setting Project: \n #{error}"
res.status(500).send "Error setting Project"
################################################################################
robot.router.post '/hubot/stormrunner/proxy/jenkinsNotifer', (req, res) ->
try
query = querystring.parse(url.parse(req.url).query)
data = req.body
strUsername = query.user
strRoom = query.room
strMessage = ""
strPhase = data.build.phase
# if the username has been passed in, add a '@' symbol to the front and
# set that as the channel
if strUsername
strChannel = "@" + strUsername
# if the room has been passed in, add a '#' symbol to the front and
# set that as the channel
else if strRoom
strChannel = "#" + strRoom
else
strChannel = "#general" # default channel
# Depending on the phase of the build - post a message to the room.
if strPhase == "STARTED"
strMessage = "Hey - Just wanted to let you know that the Jenkins Job entitled '" + data.name + "' with build number: " + data.build.number + " has started."
else if strPhase == "COMPLETED"
strDay = StormRunnerApi.getDayOfTheWeek()
if data.build.status == "FAILURE"
strStatusMess = "Unfortunately, the build failed. This must be " + strDay + ". I never could get the hang of " + strDay + "s."
else
strStatusMess = "Good news. The build was successful. Now, go and make sure you put cover sheets on your TPS reports."
strMessage = "Sorry to bother you, but Jenkins Job entitled '" + data.name + "' with build number: " + data.build.number + " is complete. " + strStatusMess
# if we do have a message (i.e. we have been passed a status we want to post about) then post the message to the previously defined channel
if strMessage
msgData =
{
channel: strChannel
text: strMessage
}
Helpers.sendCustomMessage(robot,msgData)
catch error
robot.logger.error "There's a problem with the Jenkins Notifer : \n #{error}"
res.status(500).send "Error sending message to Hubot"
| true | ###
Copyright 2016 Hewlett-Packard Development Company, L.P.
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.
###
StormRunnerApi = require './libs/stormrunnerApiAdapter.js'
Helpers = require './helpers'
querystring = require "querystring"
mockData = require "./mockData"
url = require('url')
################################################################################
# Name: proxy/GetProjects
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getProjects
#
# Called from: stormrunner-bot-logic.coffee - show me all the projects
#
# Calls to: Helpers -> getProjects
#
# Author(s): PI:NAME:<NAME>END_PI
# PI:NAME:<NAME>END_PI
################################################################################
module.exports = (robot) ->
#listening to proxy command - get projects
robot.router.get '/hubot/stormrunner/proxy/getProjects', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
robot.logger.debug "Getting Projects... refresh=#{query.refresh}"
#with success, go to Helpers.getProjects function to get projects
projs = Helpers.getProjects(robot,query.refresh)
res.send projs
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Projects : \n #{error}"
res.status(500).send "Error retrieving Projects"
################################################################################
# Name: proxy/getTests
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getTests
#
# Called from: stormrunner-bot-logic.coffee - list tests for project (.*)
#
# Calls to: Helpers -> getTests(robot,project)
#
# Author(s): PI:NAME:<NAME>END_PI
# PI:NAME:<NAME>END_PI
################################################################################
#listening to proxy command - get test
robot.router.get '/hubot/stormrunner/proxy/getTests', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing, parses out project ID or project name
project= query.project
robot.logger.debug "Getting Tests... refresh=#{query.refresh}"
#upon success, go to Helpers.GetTests function to get tests
tests = Helpers.getTests(robot,project)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
################################################################################
# Name: proxy/getRuns
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getRuns
#
# Called from: stormrunner-bot-logic.coffee -
# show latest run for test (.*) in project (.*)
# list status for last (.*) runs for test (.*) in project (.*)
# show runs for test (.*) in project (.*)
#
# Calls to: Helpers -> getRuns(robot,project,testid)
#
# Author(s): PI:NAME:<NAME>END_PI
# PI:NAME:<NAME>END_PI
################################################################################
#listening to proxy command - getRuns
robot.router.get '/hubot/stormrunner/proxy/getRuns', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing the url, project id or project name is retrieved
project = query.project
#from parsing the url, the test id is retrieved
testid = query.TestID
robot.logger.debug "Getting Run Results... refresh=#{query.refresh}"
#upon success, go to Helpers.getRuns function to get runs
tests = Helpers.getRuns(robot,project,testid)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
################################################################################
# Name: proxy/getRunResults
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getRunResults
#
# Called from: stormrunner-bot-logic.coffee -
# show full results for run id (.*)
#
# Calls to: Helpers -> getRunResults(robot,runid)
#
# Author(s): PI:NAME:<NAME>END_PI
# PI:NAME:<NAME>END_PI
################################################################################
#listening to proxy command - getRunResults
robot.router.get '/hubot/stormrunner/proxy/getRunResults', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing the url, run id is retrieved
runid = query.runid
robot.logger.debug "Getting Tests... refresh=#{query.refresh}"
#upon success, go to Helpers.getRunResults to run results
tests = Helpers.getRunResults(robot,runid)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
###############################################################################
# Name: proxy/getRuns
#
# Description: This acts as the local web server. It will parse the query
# url and then send the request to Helpers.getRuns
#
# Called from: stormrunner-bot-logic.coffee -
# show latest run for test (.*) in project (.*)
# list status for last (.*) runs for test (.*) in project (.*)
# show runs for test (.*) in project (.*)
#
# Calls to: Helpers -> getRuns(robot,project,testid)
#
# Author(s): PI:NAME:<NAME>END_PI
# PI:NAME:<NAME>END_PI
################################################################################
#listening to proxy command - getRuns
robot.router.get '/hubot/stormrunner/proxy/postRun', (req, res) ->
try
#parses the url sent from stormrunner-bot-logic
query = querystring.parse(url.parse(req.url).query)
#from parsing the url, project id or project name is retrieved
project = query.project
#from parsing the url, the test id is retrieved
testid = query.TestID
robot.logger.debug "Getting Run Results... refresh=#{query.refresh}"
#upon success, go to Helpers.getRuns function to get runs
tests = Helpers.postRun(robot,project,testid)
res.send tests
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error getting Tests : \n #{error}"
res.status(500).send "Error retrieving Tests"
################################################################################
robot.router.get '/hubot/stormrunner/proxy/setProject', (req, res) ->
try
query = querystring.parse(url.parse(req.url).query)
strProject = query.project
robot.logger.debug "Setting the project... refresh=#{query.refresh}"
project = Helpers.setProject(robot,strProject)
res.send project
catch error
#if there is an error, catch it and output the error for possible
#troubleshoot
robot.logger.error "Error setting Project: \n #{error}"
res.status(500).send "Error setting Project"
################################################################################
robot.router.post '/hubot/stormrunner/proxy/jenkinsNotifer', (req, res) ->
try
query = querystring.parse(url.parse(req.url).query)
data = req.body
strUsername = query.user
strRoom = query.room
strMessage = ""
strPhase = data.build.phase
# if the username has been passed in, add a '@' symbol to the front and
# set that as the channel
if strUsername
strChannel = "@" + strUsername
# if the room has been passed in, add a '#' symbol to the front and
# set that as the channel
else if strRoom
strChannel = "#" + strRoom
else
strChannel = "#general" # default channel
# Depending on the phase of the build - post a message to the room.
if strPhase == "STARTED"
strMessage = "Hey - Just wanted to let you know that the Jenkins Job entitled '" + data.name + "' with build number: " + data.build.number + " has started."
else if strPhase == "COMPLETED"
strDay = StormRunnerApi.getDayOfTheWeek()
if data.build.status == "FAILURE"
strStatusMess = "Unfortunately, the build failed. This must be " + strDay + ". I never could get the hang of " + strDay + "s."
else
strStatusMess = "Good news. The build was successful. Now, go and make sure you put cover sheets on your TPS reports."
strMessage = "Sorry to bother you, but Jenkins Job entitled '" + data.name + "' with build number: " + data.build.number + " is complete. " + strStatusMess
# if we do have a message (i.e. we have been passed a status we want to post about) then post the message to the previously defined channel
if strMessage
msgData =
{
channel: strChannel
text: strMessage
}
Helpers.sendCustomMessage(robot,msgData)
catch error
robot.logger.error "There's a problem with the Jenkins Notifer : \n #{error}"
res.status(500).send "Error sending message to Hubot"
|
[
{
"context": " @collection = new Luca.Collection([id:\"1\",name:\"jon\"])\n @field = new Luca.fields.CheckboxArray(col",
"end": 111,
"score": 0.9983407258987427,
"start": 108,
"tag": "NAME",
"value": "jon"
}
] | spec/javascripts/components/fields/checkbox_array_spec.coffee | datapimp/luca | 4 | describe 'The Checkbox Array Field', ->
beforeEach ->
@collection = new Luca.Collection([id:"1",name:"jon"])
@field = new Luca.fields.CheckboxArray(collection: @collection)
$('body').append("<div id='jasmine-helper' style='display:none' />")
$('#jasmine-helper').html( @field.render().el )
it "should render checkboxes", ->
expect( @field.checkboxesRendered ).toEqual true
| 86113 | describe 'The Checkbox Array Field', ->
beforeEach ->
@collection = new Luca.Collection([id:"1",name:"<NAME>"])
@field = new Luca.fields.CheckboxArray(collection: @collection)
$('body').append("<div id='jasmine-helper' style='display:none' />")
$('#jasmine-helper').html( @field.render().el )
it "should render checkboxes", ->
expect( @field.checkboxesRendered ).toEqual true
| true | describe 'The Checkbox Array Field', ->
beforeEach ->
@collection = new Luca.Collection([id:"1",name:"PI:NAME:<NAME>END_PI"])
@field = new Luca.fields.CheckboxArray(collection: @collection)
$('body').append("<div id='jasmine-helper' style='display:none' />")
$('#jasmine-helper').html( @field.render().el )
it "should render checkboxes", ->
expect( @field.checkboxesRendered ).toEqual true
|
[
{
"context": " 'exponent': ''\n 'AED':\n 'name': 'UAE Dirham'\n 'code': '784'\n 'country': 'UNITED",
"end": 299,
"score": 0.9976462125778198,
"start": 289,
"tag": "NAME",
"value": "UAE Dirham"
},
{
"context": " 'exponent': '2'\n 'ALL':\n '... | src/genesis/helpers/currency.coffee | Pogix3m/genesis.js | 2 | bd = require 'bigdecimal'
_ = require "underscore"
class Currency
constructor: ->
@iso4217 =
'':
'name': 'No universal currency'
'code': ''
'country': 'SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS'
'exponent': ''
'AED':
'name': 'UAE Dirham'
'code': '784'
'country': 'UNITED ARAB EMIRATES (THE)'
'exponent': '2'
'AFN':
'name': 'Afghani'
'code': '971'
'country': 'AFGHANISTAN'
'exponent': '2'
'ALL':
'name': 'Lek'
'code': '008'
'country': 'ALBANIA'
'exponent': '2'
'AMD':
'name': 'Armenian Dram'
'code': '051'
'country': 'ARMENIA'
'exponent': '2'
'ANG':
'name': 'Netherlands Antillean Guilder'
'code': '532'
'country': 'SINT MAARTEN (DUTCH PART)'
'exponent': '2'
'AOA':
'name': 'Kwanza'
'code': '973'
'country': 'ANGOLA'
'exponent': '2'
'ARS':
'name': 'Argentine Peso'
'code': '032'
'country': 'ARGENTINA'
'exponent': '2'
'AUD':
'name': 'Australian Dollar'
'code': '036'
'country': 'TUVALU'
'exponent': '2'
'AWG':
'name': 'Aruban Florin'
'code': '533'
'country': 'ARUBA'
'exponent': '2'
'AZN':
'name': 'Azerbaijanian Manat'
'code': '944'
'country': 'AZERBAIJAN'
'exponent': '2'
'BAM':
'name': 'Convertible Mark'
'code': '977'
'country': 'BOSNIA AND HERZEGOVINA'
'exponent': '2'
'BBD':
'name': 'Barbados Dollar'
'code': '052'
'country': 'BARBADOS'
'exponent': '2'
'BDT':
'name': 'Taka'
'code': '050'
'country': 'BANGLADESH'
'exponent': '2'
'BGN':
'name': 'Bulgarian Lev'
'code': '975'
'country': 'BULGARIA'
'exponent': '2'
'BHD':
'name': 'Bahraini Dinar'
'code': '048'
'country': 'BAHRAIN'
'exponent': '3'
'BIF':
'name': 'Burundi Franc'
'code': '108'
'country': 'BURUNDI'
'exponent': '0'
'BMD':
'name': 'Bermudian Dollar'
'code': '060'
'country': 'BERMUDA'
'exponent': '2'
'BND':
'name': 'Brunei Dollar'
'code': '096'
'country': 'BRUNEI DARUSSALAM'
'exponent': '2'
'BOB':
'name': 'Boliviano'
'code': '068'
'country': 'BOLIVIA (PLURINATIONAL STATE OF)'
'exponent': '2'
'BOV':
'name': 'Mvdol'
'code': '984'
'country': 'BOLIVIA (PLURINATIONAL STATE OF)'
'exponent': '2'
'BRL':
'name': 'Brazilian Real'
'code': '986'
'country': 'BRAZIL'
'exponent': '2'
'BSD':
'name': 'Bahamian Dollar'
'code': '044'
'country': 'BAHAMAS (THE)'
'exponent': '2'
'BTN':
'name': 'Ngultrum'
'code': '064'
'country': 'BHUTAN'
'exponent': '2'
'BWP':
'name': 'Pula'
'code': '072'
'country': 'BOTSWANA'
'exponent': '2'
'BYR':
'name': 'Belarussian Ruble'
'code': '974'
'country': 'BELARUS'
'exponent': '0'
'BZD':
'name': 'Belize Dollar'
'code': '084'
'country': 'BELIZE'
'exponent': '2'
'CAD':
'name': 'Canadian Dollar'
'code': '124'
'country': 'CANADA'
'exponent': '2'
'CDF':
'name': 'Congolese Franc'
'code': '976'
'country': 'CONGO (THE DEMOCRATIC REPUBLIC OF THE)'
'exponent': '2'
'CHE':
'name': 'WIR Euro'
'code': '947'
'country': 'SWITZERLAND'
'exponent': '2'
'CHF':
'name': 'Swiss Franc'
'code': '756'
'country': 'SWITZERLAND'
'exponent': '2'
'CHW':
'name': 'WIR Franc'
'code': '948'
'country': 'SWITZERLAND'
'exponent': '2'
'CLF':
'name': 'Unidad de Fomento'
'code': '990'
'country': 'CHILE'
'exponent': '4'
'CLP':
'name': 'Chilean Peso'
'code': '152'
'country': 'CHILE'
'exponent': '0'
'CNY':
'name': 'Yuan Renminbi'
'code': '156'
'country': 'CHINA'
'exponent': '2'
'COP':
'name': 'Colombian Peso'
'code': '170'
'country': 'COLOMBIA'
'exponent': '2'
'COU':
'name': 'Unidad de Valor Real'
'code': '970'
'country': 'COLOMBIA'
'exponent': '2'
'CRC':
'name': 'Costa Rican Colon'
'code': '188'
'country': 'COSTA RICA'
'exponent': '2'
'CUC':
'name': 'Peso Convertible'
'code': '931'
'country': 'CUBA'
'exponent': '2'
'CUP':
'name': 'Cuban Peso'
'code': '192'
'country': 'CUBA'
'exponent': '2'
'CVE':
'name': 'Cabo Verde Escudo'
'code': '132'
'country': 'CABO VERDE'
'exponent': '2'
'CZK':
'name': 'Czech Koruna'
'code': '203'
'country': 'CZECH REPUBLIC (THE)'
'exponent': '2'
'DJF':
'name': 'Djibouti Franc'
'code': '262'
'country': 'DJIBOUTI'
'exponent': '0'
'DKK':
'name': 'Danish Krone'
'code': '208'
'country': 'GREENLAND'
'exponent': '2'
'DOP':
'name': 'Dominican Peso'
'code': '214'
'country': 'DOMINICAN REPUBLIC (THE)'
'exponent': '2'
'DZD':
'name': 'Algerian Dinar'
'code': '012'
'country': 'ALGERIA'
'exponent': '2'
'EGP':
'name': 'Egyptian Pound'
'code': '818'
'country': 'EGYPT'
'exponent': '2'
'ERN':
'name': 'Nakfa'
'code': '232'
'country': 'ERITREA'
'exponent': '2'
'ETB':
'name': 'Ethiopian Birr'
'code': '230'
'country': 'ETHIOPIA'
'exponent': '2'
'EUR':
'name': 'Euro'
'code': '978'
'country': 'SPAIN'
'exponent': '2'
'FJD':
'name': 'Fiji Dollar'
'code': '242'
'country': 'FIJI'
'exponent': '2'
'FKP':
'name': 'Falkland Islands Pound'
'code': '238'
'country': 'FALKLAND ISLANDS (THE) [MALVINAS]'
'exponent': '2'
'GBP':
'name': 'Pound Sterling'
'code': '826'
'country': 'UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)'
'exponent': '2'
'GEL':
'name': 'Lari'
'code': '981'
'country': 'GEORGIA'
'exponent': '2'
'GHS':
'name': 'Ghana Cedi'
'code': '936'
'country': 'GHANA'
'exponent': '2'
'GIP':
'name': 'Gibraltar Pound'
'code': '292'
'country': 'GIBRALTAR'
'exponent': '2'
'GMD':
'name': 'Dalasi'
'code': '270'
'country': 'GAMBIA (THE)'
'exponent': '2'
'GNF':
'name': 'Guinea Franc'
'code': '324'
'country': 'GUINEA'
'exponent': '0'
'GTQ':
'name': 'Quetzal'
'code': '320'
'country': 'GUATEMALA'
'exponent': '2'
'GYD':
'name': 'Guyana Dollar'
'code': '328'
'country': 'GUYANA'
'exponent': '2'
'HKD':
'name': 'Hong Kong Dollar'
'code': '344'
'country': 'HONG KONG'
'exponent': '2'
'HNL':
'name': 'Lempira'
'code': '340'
'country': 'HONDURAS'
'exponent': '2'
'HRK':
'name': 'Kuna'
'code': '191'
'country': 'CROATIA'
'exponent': '2'
'HTG':
'name': 'Gourde'
'code': '332'
'country': 'HAITI'
'exponent': '2'
'HUF':
'name': 'Forint'
'code': '348'
'country': 'HUNGARY'
'exponent': '2'
'IDR':
'name': 'Rupiah'
'code': '360'
'country': 'INDONESIA'
'exponent': '2'
'ILS':
'name': 'New Israeli Sheqel'
'code': '376'
'country': 'ISRAEL'
'exponent': '2'
'INR':
'name': 'Indian Rupee'
'code': '356'
'country': 'INDIA'
'exponent': '2'
'IQD':
'name': 'Iraqi Dinar'
'code': '368'
'country': 'IRAQ'
'exponent': '3'
'IRR':
'name': 'Iranian Rial'
'code': '364'
'country': 'IRAN (ISLAMIC REPUBLIC OF)'
'exponent': '2'
'ISK':
'name': 'Iceland Krona'
'code': '352'
'country': 'ICELAND'
'exponent': '0'
'JMD':
'name': 'Jamaican Dollar'
'code': '388'
'country': 'JAMAICA'
'exponent': '2'
'JOD':
'name': 'Jordanian Dinar'
'code': '400'
'country': 'JORDAN'
'exponent': '3'
'JPY':
'name': 'Yen'
'code': '392'
'country': 'JAPAN'
'exponent': '0'
'KES':
'name': 'Kenyan Shilling'
'code': '404'
'country': 'KENYA'
'exponent': '2'
'KGS':
'name': 'Som'
'code': '417'
'country': 'KYRGYZSTAN'
'exponent': '2'
'KHR':
'name': 'Riel'
'code': '116'
'country': 'CAMBODIA'
'exponent': '2'
'KMF':
'name': 'Comoro Franc'
'code': '174'
'country': 'COMOROS (THE)'
'exponent': '0'
'KPW':
'name': 'North Korean Won'
'code': '408'
'country': 'KOREA (THE DEMOCRATIC PEOPLE’S REPUBLIC OF)'
'exponent': '2'
'KRW':
'name': 'Won'
'code': '410'
'country': 'KOREA (THE REPUBLIC OF)'
'exponent': '0'
'KWD':
'name': 'Kuwaiti Dinar'
'code': '414'
'country': 'KUWAIT'
'exponent': '3'
'KYD':
'name': 'Cayman Islands Dollar'
'code': '136'
'country': 'CAYMAN ISLANDS (THE)'
'exponent': '2'
'KZT':
'name': 'Tenge'
'code': '398'
'country': 'KAZAKHSTAN'
'exponent': '2'
'LAK':
'name': 'Kip'
'code': '418'
'country': 'LAO PEOPLE’S DEMOCRATIC REPUBLIC (THE)'
'exponent': '2'
'LBP':
'name': 'Lebanese Pound'
'code': '422'
'country': 'LEBANON'
'exponent': '2'
'LKR':
'name': 'Sri Lanka Rupee'
'code': '144'
'country': 'SRI LANKA'
'exponent': '2'
'LRD':
'name': 'Liberian Dollar'
'code': '430'
'country': 'LIBERIA'
'exponent': '2'
'LSL':
'name': 'Loti'
'code': '426'
'country': 'LESOTHO'
'exponent': '2'
'LYD':
'name': 'Libyan Dinar'
'code': '434'
'country': 'LIBYA'
'exponent': '3'
'MAD':
'name': 'Moroccan Dirham'
'code': '504'
'country': 'WESTERN SAHARA'
'exponent': '2'
'MDL':
'name': 'Moldovan Leu'
'code': '498'
'country': 'MOLDOVA (THE REPUBLIC OF)'
'exponent': '2'
'MGA':
'name': 'Malagasy Ariary'
'code': '969'
'country': 'MADAGASCAR'
'exponent': '2'
'MKD':
'name': 'Denar'
'code': '807'
'country': 'MACEDONIA (THE FORMER YUGOSLAV REPUBLIC OF)'
'exponent': '2'
'MMK':
'name': 'Kyat'
'code': '104'
'country': 'MYANMAR'
'exponent': '2'
'MNT':
'name': 'Tugrik'
'code': '496'
'country': 'MONGOLIA'
'exponent': '2'
'MOP':
'name': 'Pataca'
'code': '446'
'country': 'MACAO'
'exponent': '2'
'MRO':
'name': 'Ouguiya'
'code': '478'
'country': 'MAURITANIA'
'exponent': '2'
'MUR':
'name': 'Mauritius Rupee'
'code': '480'
'country': 'MAURITIUS'
'exponent': '2'
'MVR':
'name': 'Rufiyaa'
'code': '462'
'country': 'MALDIVES'
'exponent': '2'
'MWK':
'name': 'Kwacha'
'code': '454'
'country': 'MALAWI'
'exponent': '2'
'MXN':
'name': 'Mexican Peso'
'code': '484'
'country': 'MEXICO'
'exponent': '2'
'MXV':
'name': 'Mexican Unidad de Inversion (UDI)'
'code': '979'
'country': 'MEXICO'
'exponent': '2'
'MYR':
'name': 'Malaysian Ringgit'
'code': '458'
'country': 'MALAYSIA'
'exponent': '2'
'MZN':
'name': 'Mozambique Metical'
'code': '943'
'country': 'MOZAMBIQUE'
'exponent': '2'
'NAD':
'name': 'Namibia Dollar'
'code': '516'
'country': 'NAMIBIA'
'exponent': '2'
'NGN':
'name': 'Naira'
'code': '566'
'country': 'NIGERIA'
'exponent': '2'
'NIO':
'name': 'Cordoba Oro'
'code': '558'
'country': 'NICARAGUA'
'exponent': '2'
'NOK':
'name': 'Norwegian Krone'
'code': '578'
'country': 'SVALBARD AND JAN MAYEN'
'exponent': '2'
'NPR':
'name': 'Nepalese Rupee'
'code': '524'
'country': 'NEPAL'
'exponent': '2'
'NZD':
'name': 'New Zealand Dollar'
'code': '554'
'country': 'TOKELAU'
'exponent': '2'
'OMR':
'name': 'Rial Omani'
'code': '512'
'country': 'OMAN'
'exponent': '3'
'PAB':
'name': 'Balboa'
'code': '590'
'country': 'PANAMA'
'exponent': '2'
'PEN':
'name': 'Nuevo Sol'
'code': '604'
'country': 'PERU'
'exponent': '2'
'PGK':
'name': 'Kina'
'code': '598'
'country': 'PAPUA NEW GUINEA'
'exponent': '2'
'PHP':
'name': 'Philippine Peso'
'code': '608'
'country': 'PHILIPPINES (THE)'
'exponent': '2'
'PKR':
'name': 'Pakistan Rupee'
'code': '586'
'country': 'PAKISTAN'
'exponent': '2'
'PLN':
'name': 'Zloty'
'code': '985'
'country': 'POLAND'
'exponent': '2'
'PYG':
'name': 'Guarani'
'code': '600'
'country': 'PARAGUAY'
'exponent': '0'
'QAR':
'name': 'Qatari Rial'
'code': '634'
'country': 'QATAR'
'exponent': '2'
'RON':
'name': 'Romanian Leu'
'code': '946'
'country': 'ROMANIA'
'exponent': '2'
'RSD':
'name': 'Serbian Dinar'
'code': '941'
'country': 'SERBIA'
'exponent': '2'
'RUB':
'name': 'Russian Ruble'
'code': '643'
'country': 'RUSSIAN FEDERATION (THE)'
'exponent': '2'
'RWF':
'name': 'Rwanda Franc'
'code': '646'
'country': 'RWANDA'
'exponent': '0'
'SAR':
'name': 'Saudi Riyal'
'code': '682'
'country': 'SAUDI ARABIA'
'exponent': '2'
'SBD':
'name': 'Solomon Islands Dollar'
'code': '090'
'country': 'SOLOMON ISLANDS'
'exponent': '2'
'SCR':
'name': 'Seychelles Rupee'
'code': '690'
'country': 'SEYCHELLES'
'exponent': '2'
'SDG':
'name': 'Sudanese Pound'
'code': '938'
'country': 'SUDAN (THE)'
'exponent': '2'
'SEK':
'name': 'Swedish Krona'
'code': '752'
'country': 'SWEDEN'
'exponent': '2'
'SGD':
'name': 'Singapore Dollar'
'code': '702'
'country': 'SINGAPORE'
'exponent': '2'
'SHP':
'name': 'Saint Helena Pound'
'code': '654'
'country': 'SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA'
'exponent': '2'
'SLL':
'name': 'Leone'
'code': '694'
'country': 'SIERRA LEONE'
'exponent': '2'
'SOS':
'name': 'Somali Shilling'
'code': '706'
'country': 'SOMALIA'
'exponent': '2'
'SRD':
'name': 'Surinam Dollar'
'code': '968'
'country': 'SURINAME'
'exponent': '2'
'SSP':
'name': 'South Sudanese Pound'
'code': '728'
'country': 'SOUTH SUDAN'
'exponent': '2'
'STD':
'name': 'Dobra'
'code': '678'
'country': 'SAO TOME AND PRINCIPE'
'exponent': '2'
'SVC':
'name': 'El Salvador Colon'
'code': '222'
'country': 'EL SALVADOR'
'exponent': '2'
'SYP':
'name': 'Syrian Pound'
'code': '760'
'country': 'SYRIAN ARAB REPUBLIC'
'exponent': '2'
'SZL':
'name': 'Lilangeni'
'code': '748'
'country': 'SWAZILAND'
'exponent': '2'
'THB':
'name': 'Baht'
'code': '764'
'country': 'THAILAND'
'exponent': '2'
'TJS':
'name': 'Somoni'
'code': '972'
'country': 'TAJIKISTAN'
'exponent': '2'
'TMT':
'name': 'Turkmenistan New Manat'
'code': '934'
'country': 'TURKMENISTAN'
'exponent': '2'
'TND':
'name': 'Tunisian Dinar'
'code': '788'
'country': 'TUNISIA'
'exponent': '3'
'TOP':
'name': 'Pa’anga'
'code': '776'
'country': 'TONGA'
'exponent': '2'
'TRY':
'name': 'Turkish Lira'
'code': '949'
'country': 'TURKEY'
'exponent': '2'
'TTD':
'name': 'Trinidad and Tobago Dollar'
'code': '780'
'country': 'TRINIDAD AND TOBAGO'
'exponent': '2'
'TWD':
'name': 'New Taiwan Dollar'
'code': '901'
'country': 'TAIWAN (PROVINCE OF CHINA)'
'exponent': '2'
'TZS':
'name': 'Tanzanian Shilling'
'code': '834'
'country': 'TANZANIA, UNITED REPUBLIC OF'
'exponent': '2'
'UAH':
'name': 'Hryvnia'
'code': '980'
'country': 'UKRAINE'
'exponent': '2'
'UGX':
'name': 'Uganda Shilling'
'code': '800'
'country': 'UGANDA'
'exponent': '0'
'USD':
'name': 'US Dollar'
'code': '840'
'country': 'VIRGIN ISLANDS (U.S.)'
'exponent': '2'
'USN':
'name': 'US Dollar (Next day)'
'code': '997'
'country': 'UNITED STATES OF AMERICA (THE)'
'exponent': '2'
'UYI':
'name': 'Uruguay Peso en Unidades Indexadas (URUIURUI)'
'code': '940'
'country': 'URUGUAY'
'exponent': '0'
'UYU':
'name': 'Peso Uruguayo'
'code': '858'
'country': 'URUGUAY'
'exponent': '2'
'UZS':
'name': 'Uzbekistan Sum'
'code': '860'
'country': 'UZBEKISTAN'
'exponent': '2'
'VEF':
'name': 'Bolivar'
'code': '937'
'country': 'VENEZUELA (BOLIVARIAN REPUBLIC OF)'
'exponent': '2'
'VND':
'name': 'Dong'
'code': '704'
'country': 'VIET NAM'
'exponent': '0'
'VUV':
'name': 'Vatu'
'code': '548'
'country': 'VANUATU'
'exponent': '0'
'WST':
'name': 'Tala'
'code': '882'
'country': 'SAMOA'
'exponent': '2'
'XAF':
'name': 'CFA Franc BEAC'
'code': '950'
'country': 'GABON'
'exponent': '0'
'XAG':
'name': 'Silver'
'code': '961'
'country': 'ZZ11_Silver'
'exponent': 'N.A.'
'XAU':
'name': 'Gold'
'code': '959'
'country': 'ZZ08_Gold'
'exponent': 'N.A.'
'XBA':
'name': 'Bond Markets Unit European Composite Unit (EURCO)'
'code': '955'
'country': 'ZZ01_Bond Markets Unit European_EURCO'
'exponent': 'N.A.'
'XBB':
'name': 'Bond Markets Unit European Monetary Unit (E.M.U.-6)'
'code': '956'
'country': 'ZZ02_Bond Markets Unit European_EMU-6'
'exponent': 'N.A.'
'XBC':
'name': 'Bond Markets Unit European Unit of Account 9 (E.U.A.-9)'
'code': '957'
'country': 'ZZ03_Bond Markets Unit European_EUA-9'
'exponent': 'N.A.'
'XBD':
'name': 'Bond Markets Unit European Unit of Account 17 (E.U.A.-17)'
'code': '958'
'country': 'ZZ04_Bond Markets Unit European_EUA-17'
'exponent': 'N.A.'
'XCD':
'name': 'East Caribbean Dollar'
'code': '951'
'country': 'SAINT VINCENT AND THE GRENADINES'
'exponent': '2'
'XDR':
'name': 'SDR (Special Drawing Right)'
'code': '960'
'country': 'INTERNATIONAL MONETARY FUND (IMF) '
'exponent': 'N.A.'
'XOF':
'name': 'CFA Franc BCEAO'
'code': '952'
'country': 'TOGO'
'exponent': '0'
'XPD':
'name': 'Palladium'
'code': '964'
'country': 'ZZ09_Palladium'
'exponent': 'N.A.'
'XPF':
'name': 'CFP Franc'
'code': '953'
'country': 'WALLIS AND FUTUNA'
'exponent': '0'
'XPT':
'name': 'Platinum'
'code': '962'
'country': 'ZZ10_Platinum'
'exponent': 'N.A.'
'XSU':
'name': 'Sucre'
'code': '994'
'country': 'SISTEMA UNITARIO DE COMPENSACION REGIONAL DE PAGOS "SUCRE"'
'exponent': 'N.A.'
'XTS':
'name': 'Codes specifically reserved for testing purposes'
'code': '963'
'country': 'ZZ06_Testing_Code'
'exponent': 'N.A.'
'XUA':
'name': 'ADB Unit of Account'
'code': '965'
'country': 'MEMBER COUNTRIES OF THE AFRICAN DEVELOPMENT BANK GROUP'
'exponent': 'N.A.'
'XXX':
'name': 'The codes assigned for transactions where no currency is involved'
'code': '999'
'country': 'ZZ07_No_Currency'
'exponent': 'N.A.'
'YER':
'name': 'Yemeni Rial'
'code': '886'
'country': 'YEMEN'
'exponent': '2'
'ZAR':
'name': 'Rand'
'code': '710'
'country': 'SOUTH AFRICA'
'exponent': '2'
'ZMW':
'name': 'Zambian Kwacha'
'code': '967'
'country': 'ZAMBIA'
'exponent': '2'
'ZWL':
'name': 'Zimbabwe Dollar'
'code': '932'
'country': 'ZIMBABWE'
'exponent': '2'
###
Convert currency to its Cent value, based on ISO4217A table
###
convertToMinorUnits: (amount, currency) ->
exponent = @iso4217[currency].exponent
minor = new bd
.BigDecimal(amount)
.scaleByPowerOfTen exponent
.toBigInteger()
return minor.toString()
###
Convert currency back to its nominal value
###
convertToNominalUnits: (amount, currency) ->
exponent = @iso4217[currency].exponent
nominal = new bd
.BigDecimal(amount)
.scaleByPowerOfTen -exponent
.setScale Number(exponent), bd.RoundingMode.DOWN()
return nominal.toPlainString()
getCurrencies: ->
_.compact _.keys @iso4217
module.exports = Currency | 34389 | bd = require 'bigdecimal'
_ = require "underscore"
class Currency
constructor: ->
@iso4217 =
'':
'name': 'No universal currency'
'code': ''
'country': 'SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS'
'exponent': ''
'AED':
'name': '<NAME>'
'code': '784'
'country': 'UNITED ARAB EMIRATES (THE)'
'exponent': '2'
'AFN':
'name': 'Afghani'
'code': '971'
'country': 'AFGHANISTAN'
'exponent': '2'
'ALL':
'name': '<NAME>'
'code': '008'
'country': 'ALBANIA'
'exponent': '2'
'AMD':
'name': 'Armenian D<NAME>'
'code': '051'
'country': 'ARMENIA'
'exponent': '2'
'ANG':
'name': 'Netherlands Antillean Guilder'
'code': '532'
'country': 'SINT MAARTEN (DUTCH PART)'
'exponent': '2'
'AOA':
'name': 'K<NAME>'
'code': '973'
'country': 'ANGOLA'
'exponent': '2'
'ARS':
'name': 'Argentine Peso'
'code': '032'
'country': 'ARGENTINA'
'exponent': '2'
'AUD':
'name': 'Australian Dollar'
'code': '036'
'country': 'TUVALU'
'exponent': '2'
'AWG':
'name': '<NAME>'
'code': '533'
'country': 'ARUBA'
'exponent': '2'
'AZN':
'name': 'Azerbaijanian Manat'
'code': '944'
'country': 'AZERBAIJAN'
'exponent': '2'
'BAM':
'name': 'Convertible Mark'
'code': '977'
'country': 'BOSNIA AND HERZEGOVINA'
'exponent': '2'
'BBD':
'name': '<NAME>'
'code': '052'
'country': 'BARBADOS'
'exponent': '2'
'BDT':
'name': '<NAME>'
'code': '050'
'country': 'BANGLADESH'
'exponent': '2'
'BGN':
'name': 'Bulgarian Le<NAME>'
'code': '975'
'country': 'BULGARIA'
'exponent': '2'
'BHD':
'name': '<NAME>'
'code': '048'
'country': 'BAHRAIN'
'exponent': '3'
'BIF':
'name': '<NAME>'
'code': '108'
'country': 'BURUNDI'
'exponent': '0'
'BMD':
'name': '<NAME>'
'code': '060'
'country': 'BERMUDA'
'exponent': '2'
'BND':
'name': '<NAME>'
'code': '096'
'country': 'BRUNEI DARUSSALAM'
'exponent': '2'
'BOB':
'name': '<NAME>'
'code': '068'
'country': 'BOLIVIA (PLURINATIONAL STATE OF)'
'exponent': '2'
'BOV':
'name': '<NAME>'
'code': '984'
'country': 'BOLIVIA (PLURINATIONAL STATE OF)'
'exponent': '2'
'BRL':
'name': 'Brazilian Real'
'code': '986'
'country': 'BRAZIL'
'exponent': '2'
'BSD':
'name': 'Bahamian D<NAME>'
'code': '044'
'country': 'BAHAMAS (THE)'
'exponent': '2'
'BTN':
'name': '<NAME>'
'code': '064'
'country': 'BHUTAN'
'exponent': '2'
'BWP':
'name': '<NAME>'
'code': '072'
'country': 'BOTSWANA'
'exponent': '2'
'BYR':
'name': 'Belar<NAME> R<NAME>'
'code': '974'
'country': 'BELARUS'
'exponent': '0'
'BZD':
'name': '<NAME>'
'code': '084'
'country': 'BELIZE'
'exponent': '2'
'CAD':
'name': 'Canadian <NAME>'
'code': '124'
'country': 'CANADA'
'exponent': '2'
'CDF':
'name': '<NAME>'
'code': '976'
'country': 'CONGO (THE DEMOCRATIC REPUBLIC OF THE)'
'exponent': '2'
'CHE':
'name': '<NAME>'
'code': '947'
'country': 'SWITZERLAND'
'exponent': '2'
'CHF':
'name': '<NAME>'
'code': '756'
'country': 'SWITZERLAND'
'exponent': '2'
'CHW':
'name': '<NAME>'
'code': '948'
'country': 'SWITZERLAND'
'exponent': '2'
'CLF':
'name': 'Unidad de F<NAME>o'
'code': '990'
'country': 'CHILE'
'exponent': '4'
'CLP':
'name': '<NAME>'
'code': '152'
'country': 'CHILE'
'exponent': '0'
'CNY':
'name': '<NAME>'
'code': '156'
'country': 'CHINA'
'exponent': '2'
'COP':
'name': 'Colombian Peso'
'code': '170'
'country': 'COLOMBIA'
'exponent': '2'
'COU':
'name': 'Unidad de Valor Real'
'code': '970'
'country': 'COLOMBIA'
'exponent': '2'
'CRC':
'name': '<NAME>'
'code': '188'
'country': 'COSTA RICA'
'exponent': '2'
'CUC':
'name': 'Peso Convertible'
'code': '931'
'country': 'CUBA'
'exponent': '2'
'CUP':
'name': 'Cuban Peso'
'code': '192'
'country': 'CUBA'
'exponent': '2'
'CVE':
'name': '<NAME>'
'code': '132'
'country': 'CABO VERDE'
'exponent': '2'
'CZK':
'name': 'Czech Koruna'
'code': '203'
'country': 'CZECH REPUBLIC (THE)'
'exponent': '2'
'DJF':
'name': '<NAME>'
'code': '262'
'country': 'DJIBOUTI'
'exponent': '0'
'DKK':
'name': '<NAME>'
'code': '208'
'country': 'GREENLAND'
'exponent': '2'
'DOP':
'name': 'Dominican Peso'
'code': '214'
'country': 'DOMINICAN REPUBLIC (THE)'
'exponent': '2'
'DZD':
'name': 'Al<NAME> D<NAME>'
'code': '012'
'country': 'ALGERIA'
'exponent': '2'
'EGP':
'name': 'Egyptian Pound'
'code': '818'
'country': 'EGYPT'
'exponent': '2'
'ERN':
'name': '<NAME>'
'code': '232'
'country': 'ERITREA'
'exponent': '2'
'ETB':
'name': 'Ethiopian Birr'
'code': '230'
'country': 'ETHIOPIA'
'exponent': '2'
'EUR':
'name': 'Euro'
'code': '978'
'country': 'SPAIN'
'exponent': '2'
'FJD':
'name': 'Fiji Dollar'
'code': '242'
'country': 'FIJI'
'exponent': '2'
'FKP':
'name': 'Falkland Islands Pound'
'code': '238'
'country': 'FALKLAND ISLANDS (THE) [MALVINAS]'
'exponent': '2'
'GBP':
'name': 'Pound S<NAME>ling'
'code': '826'
'country': 'UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)'
'exponent': '2'
'GEL':
'name': '<NAME>'
'code': '981'
'country': 'GEORGIA'
'exponent': '2'
'GHS':
'name': '<NAME>'
'code': '936'
'country': 'GHANA'
'exponent': '2'
'GIP':
'name': 'G<NAME>ar <NAME>'
'code': '292'
'country': 'GIBRALTAR'
'exponent': '2'
'GMD':
'name': '<NAME>'
'code': '270'
'country': 'GAMBIA (THE)'
'exponent': '2'
'GNF':
'name': '<NAME>'
'code': '324'
'country': 'GUINEA'
'exponent': '0'
'GTQ':
'name': 'Quetzal'
'code': '320'
'country': 'GUATEMALA'
'exponent': '2'
'GYD':
'name': 'Guyana Dollar'
'code': '328'
'country': 'GUYANA'
'exponent': '2'
'HKD':
'name': 'Hong Kong Dollar'
'code': '344'
'country': 'HONG KONG'
'exponent': '2'
'HNL':
'name': '<NAME>'
'code': '340'
'country': 'HONDURAS'
'exponent': '2'
'HRK':
'name': '<NAME>'
'code': '191'
'country': 'CROATIA'
'exponent': '2'
'HTG':
'name': '<NAME>'
'code': '332'
'country': 'HAITI'
'exponent': '2'
'HUF':
'name': '<NAME>'
'code': '348'
'country': 'HUNGARY'
'exponent': '2'
'IDR':
'name': '<NAME>'
'code': '360'
'country': 'INDONESIA'
'exponent': '2'
'ILS':
'name': 'New Israeli Sheqel'
'code': '376'
'country': 'ISRAEL'
'exponent': '2'
'INR':
'name': 'Indian Rupee'
'code': '356'
'country': 'INDIA'
'exponent': '2'
'IQD':
'name': '<NAME>qi <NAME>'
'code': '368'
'country': 'IRAQ'
'exponent': '3'
'IRR':
'name': 'Iranian Rial'
'code': '364'
'country': 'IRAN (ISLAMIC REPUBLIC OF)'
'exponent': '2'
'ISK':
'name': 'Icel<NAME>'
'code': '352'
'country': 'ICELAND'
'exponent': '0'
'JMD':
'name': 'Jamaican Dollar'
'code': '388'
'country': 'JAMAICA'
'exponent': '2'
'JOD':
'name': 'Jordanian Dinar'
'code': '400'
'country': 'JORDAN'
'exponent': '3'
'JPY':
'name': '<NAME>'
'code': '392'
'country': 'JAPAN'
'exponent': '0'
'KES':
'name': '<NAME>'
'code': '404'
'country': 'KENYA'
'exponent': '2'
'KGS':
'name': '<NAME>'
'code': '417'
'country': 'KYRGYZSTAN'
'exponent': '2'
'KHR':
'name': '<NAME>'
'code': '116'
'country': 'CAMBODIA'
'exponent': '2'
'KMF':
'name': '<NAME>'
'code': '174'
'country': 'COMOROS (THE)'
'exponent': '0'
'KPW':
'name': '<NAME>'
'code': '408'
'country': 'KOREA (THE DEMOCRATIC PEOPLE’S REPUBLIC OF)'
'exponent': '2'
'KRW':
'name': '<NAME>'
'code': '410'
'country': 'KOREA (THE REPUBLIC OF)'
'exponent': '0'
'KWD':
'name': '<NAME>'
'code': '414'
'country': 'KUWAIT'
'exponent': '3'
'KYD':
'name': '<NAME>'
'code': '136'
'country': 'CAYMAN ISLANDS (THE)'
'exponent': '2'
'KZT':
'name': '<NAME>'
'code': '398'
'country': 'KAZAKHSTAN'
'exponent': '2'
'LAK':
'name': '<NAME>'
'code': '418'
'country': 'LAO PEOPLE’S DEMOCRATIC REPUBLIC (THE)'
'exponent': '2'
'LBP':
'name': 'Lebanese Pound'
'code': '422'
'country': 'LEBANON'
'exponent': '2'
'LKR':
'name': '<NAME>'
'code': '144'
'country': 'SRI LANKA'
'exponent': '2'
'LRD':
'name': 'Li<NAME>'
'code': '430'
'country': 'LIBERIA'
'exponent': '2'
'LSL':
'name': '<NAME>'
'code': '426'
'country': 'LESOTHO'
'exponent': '2'
'LYD':
'name': '<NAME>'
'code': '434'
'country': 'LIBYA'
'exponent': '3'
'MAD':
'name': '<NAME>'
'code': '504'
'country': 'WESTERN SAHARA'
'exponent': '2'
'MDL':
'name': '<NAME>'
'code': '498'
'country': 'MOLDOVA (THE REPUBLIC OF)'
'exponent': '2'
'MGA':
'name': '<NAME>'
'code': '969'
'country': 'MADAGASCAR'
'exponent': '2'
'MKD':
'name': '<NAME>'
'code': '807'
'country': 'MACEDONIA (THE FORMER YUGOSLAV REPUBLIC OF)'
'exponent': '2'
'MMK':
'name': '<NAME>'
'code': '104'
'country': 'MYANMAR'
'exponent': '2'
'MNT':
'name': '<NAME>'
'code': '496'
'country': 'MONGOLIA'
'exponent': '2'
'MOP':
'name': '<NAME>'
'code': '446'
'country': 'MACAO'
'exponent': '2'
'MRO':
'name': '<NAME>'
'code': '478'
'country': 'MAURITANIA'
'exponent': '2'
'MUR':
'name': '<NAME>'
'code': '480'
'country': 'MAURITIUS'
'exponent': '2'
'MVR':
'name': '<NAME>'
'code': '462'
'country': 'MALDIVES'
'exponent': '2'
'MWK':
'name': '<NAME>'
'code': '454'
'country': 'MALAWI'
'exponent': '2'
'MXN':
'name': 'Mex<NAME>'
'code': '484'
'country': 'MEXICO'
'exponent': '2'
'MXV':
'name': 'Mexican Unidad de Inversion (UDI)'
'code': '979'
'country': 'MEXICO'
'exponent': '2'
'MYR':
'name': 'Mal<NAME>'
'code': '458'
'country': 'MALAYSIA'
'exponent': '2'
'MZN':
'name': 'Mozamb<NAME>'
'code': '943'
'country': 'MOZAMBIQUE'
'exponent': '2'
'NAD':
'name': '<NAME>'
'code': '516'
'country': 'NAMIBIA'
'exponent': '2'
'NGN':
'name': '<NAME>'
'code': '566'
'country': 'NIGERIA'
'exponent': '2'
'NIO':
'name': '<NAME>'
'code': '558'
'country': 'NICARAGUA'
'exponent': '2'
'NOK':
'name': 'Norwegian Kr<NAME>'
'code': '578'
'country': 'SVALBARD AND JAN MAYEN'
'exponent': '2'
'NPR':
'name': 'Nepale<NAME> R<NAME>'
'code': '524'
'country': 'NEPAL'
'exponent': '2'
'NZD':
'name': 'New Zealand Dollar'
'code': '554'
'country': 'TOKELAU'
'exponent': '2'
'OMR':
'name': '<NAME>'
'code': '512'
'country': 'OMAN'
'exponent': '3'
'PAB':
'name': '<NAME>'
'code': '590'
'country': 'PANAMA'
'exponent': '2'
'PEN':
'name': '<NAME>'
'code': '604'
'country': 'PERU'
'exponent': '2'
'PGK':
'name': '<NAME>'
'code': '598'
'country': 'PAPUA NEW GUINEA'
'exponent': '2'
'PHP':
'name': '<NAME>'
'code': '608'
'country': 'PHILIPPINES (THE)'
'exponent': '2'
'PKR':
'name': 'Pakistan Rupee'
'code': '586'
'country': 'PAKISTAN'
'exponent': '2'
'PLN':
'name': '<NAME>'
'code': '985'
'country': 'POLAND'
'exponent': '2'
'PYG':
'name': '<NAME>'
'code': '600'
'country': 'PARAGUAY'
'exponent': '0'
'QAR':
'name': '<NAME>'
'code': '634'
'country': 'QATAR'
'exponent': '2'
'RON':
'name': '<NAME>'
'code': '946'
'country': 'ROMANIA'
'exponent': '2'
'RSD':
'name': '<NAME>'
'code': '941'
'country': 'SERBIA'
'exponent': '2'
'RUB':
'name': 'Russian Ruble'
'code': '643'
'country': 'RUSSIAN FEDERATION (THE)'
'exponent': '2'
'RWF':
'name': '<NAME>'
'code': '646'
'country': 'RWANDA'
'exponent': '0'
'SAR':
'name': '<NAME>'
'code': '682'
'country': 'SAUDI ARABIA'
'exponent': '2'
'SBD':
'name': 'Solomon Islands Dollar'
'code': '090'
'country': 'SOLOMON ISLANDS'
'exponent': '2'
'SCR':
'name': 'Seychelles Rupee'
'code': '690'
'country': 'SEYCHELLES'
'exponent': '2'
'SDG':
'name': '<NAME>'
'code': '938'
'country': 'SUDAN (THE)'
'exponent': '2'
'SEK':
'name': 'Swedish Krona'
'code': '752'
'country': 'SWEDEN'
'exponent': '2'
'SGD':
'name': 'Singapore D<NAME>'
'code': '702'
'country': 'SINGAPORE'
'exponent': '2'
'SHP':
'name': '<NAME>'
'code': '654'
'country': 'SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA'
'exponent': '2'
'SLL':
'name': '<NAME>'
'code': '694'
'country': 'SIERRA LEONE'
'exponent': '2'
'SOS':
'name': '<NAME>'
'code': '706'
'country': 'SOMALIA'
'exponent': '2'
'SRD':
'name': '<NAME>in<NAME>'
'code': '968'
'country': 'SURINAME'
'exponent': '2'
'SSP':
'name': '<NAME> Sudanese P<NAME>'
'code': '728'
'country': 'SOUTH SUDAN'
'exponent': '2'
'STD':
'name': '<NAME>'
'code': '678'
'country': 'SAO TOME AND PRINCIPE'
'exponent': '2'
'SVC':
'name': '<NAME>'
'code': '222'
'country': 'EL SALVADOR'
'exponent': '2'
'SYP':
'name': '<NAME>'
'code': '760'
'country': 'SYRIAN ARAB REPUBLIC'
'exponent': '2'
'SZL':
'name': '<NAME>'
'code': '748'
'country': 'SWAZILAND'
'exponent': '2'
'THB':
'name': '<NAME>'
'code': '764'
'country': 'THAILAND'
'exponent': '2'
'TJS':
'name': '<NAME>'
'code': '972'
'country': 'TAJIKISTAN'
'exponent': '2'
'TMT':
'name': 'Turkmenistan New Manat'
'code': '934'
'country': 'TURKMENISTAN'
'exponent': '2'
'TND':
'name': '<NAME>'
'code': '788'
'country': 'TUNISIA'
'exponent': '3'
'TOP':
'name': '<NAME>'
'code': '776'
'country': 'TONGA'
'exponent': '2'
'TRY':
'name': 'Tur<NAME>ish <NAME>'
'code': '949'
'country': 'TURKEY'
'exponent': '2'
'TTD':
'name': 'Trinidad and Tobago Dollar'
'code': '780'
'country': 'TRINIDAD AND TOBAGO'
'exponent': '2'
'TWD':
'name': '<NAME>'
'code': '901'
'country': 'TAIWAN (PROVINCE OF CHINA)'
'exponent': '2'
'TZS':
'name': '<NAME>'
'code': '834'
'country': 'TANZANIA, UNITED REPUBLIC OF'
'exponent': '2'
'UAH':
'name': '<NAME>'
'code': '980'
'country': 'UKRAINE'
'exponent': '2'
'UGX':
'name': '<NAME>'
'code': '800'
'country': 'UGANDA'
'exponent': '0'
'USD':
'name': 'US D<NAME>'
'code': '840'
'country': 'VIRGIN ISLANDS (U.S.)'
'exponent': '2'
'USN':
'name': 'US Dollar (Next day)'
'code': '997'
'country': 'UNITED STATES OF AMERICA (THE)'
'exponent': '2'
'UYI':
'name': 'Uruguay Peso en Unidades Indexadas (URUIURUI)'
'code': '940'
'country': 'URUGUAY'
'exponent': '0'
'UYU':
'name': '<NAME>'
'code': '858'
'country': 'URUGUAY'
'exponent': '2'
'UZS':
'name': '<NAME>kistan Sum'
'code': '860'
'country': 'UZBEKISTAN'
'exponent': '2'
'VEF':
'name': '<NAME>'
'code': '937'
'country': 'VENEZUELA (BOLIVARIAN REPUBLIC OF)'
'exponent': '2'
'VND':
'name': '<NAME>'
'code': '704'
'country': 'VIET NAM'
'exponent': '0'
'VUV':
'name': '<NAME>'
'code': '548'
'country': 'VANUATU'
'exponent': '0'
'WST':
'name': '<NAME>'
'code': '882'
'country': 'SAMOA'
'exponent': '2'
'XAF':
'name': 'CFA Franc BEAC'
'code': '950'
'country': 'GABON'
'exponent': '0'
'XAG':
'name': '<NAME>'
'code': '961'
'country': 'ZZ11_Silver'
'exponent': 'N.A.'
'XAU':
'name': '<NAME>'
'code': '959'
'country': 'ZZ08_Gold'
'exponent': 'N.A.'
'XBA':
'name': 'Bond Markets Unit European Composite Unit (EURCO)'
'code': '955'
'country': 'ZZ01_Bond Markets Unit European_EURCO'
'exponent': 'N.A.'
'XBB':
'name': 'Bond Markets Unit European Monetary Unit (E.M.U.-6)'
'code': '956'
'country': 'ZZ02_Bond Markets Unit European_EMU-6'
'exponent': 'N.A.'
'XBC':
'name': 'Bond Markets Unit European Unit of Account 9 (E.U.A.-9)'
'code': '957'
'country': 'ZZ03_Bond Markets Unit European_EUA-9'
'exponent': 'N.A.'
'XBD':
'name': 'Bond Markets Unit European Unit of Account 17 (E.U.A.-17)'
'code': '958'
'country': 'ZZ04_Bond Markets Unit European_EUA-17'
'exponent': 'N.A.'
'XCD':
'name': 'East Caribbean Dollar'
'code': '951'
'country': 'SAINT VINCENT AND THE GRENADINES'
'exponent': '2'
'XDR':
'name': 'SDR (Special Drawing Right)'
'code': '960'
'country': 'INTERNATIONAL MONETARY FUND (IMF) '
'exponent': 'N.A.'
'XOF':
'name': '<NAME>'
'code': '952'
'country': 'TOGO'
'exponent': '0'
'XPD':
'name': '<NAME>'
'code': '964'
'country': 'ZZ09_Palladium'
'exponent': 'N.A.'
'XPF':
'name': '<NAME>'
'code': '953'
'country': 'WALLIS AND FUTUNA'
'exponent': '0'
'XPT':
'name': '<NAME>'
'code': '962'
'country': 'ZZ10_Platinum'
'exponent': 'N.A.'
'XSU':
'name': '<NAME>'
'code': '994'
'country': 'SISTEMA UNITARIO DE COMPENSACION REGIONAL DE PAGOS "SUCRE"'
'exponent': 'N.A.'
'XTS':
'name': 'Codes specifically reserved for testing purposes'
'code': '963'
'country': 'ZZ06_Testing_Code'
'exponent': 'N.A.'
'XUA':
'name': 'ADB Unit of Account'
'code': '965'
'country': 'MEMBER COUNTRIES OF THE AFRICAN DEVELOPMENT BANK GROUP'
'exponent': 'N.A.'
'XXX':
'name': 'The codes assigned for transactions where no currency is involved'
'code': '999'
'country': 'ZZ07_No_Currency'
'exponent': 'N.A.'
'YER':
'name': '<NAME>'
'code': '886'
'country': 'YEMEN'
'exponent': '2'
'ZAR':
'name': '<NAME>'
'code': '710'
'country': 'SOUTH AFRICA'
'exponent': '2'
'ZMW':
'name': '<NAME>'
'code': '967'
'country': 'ZAMBIA'
'exponent': '2'
'ZWL':
'name': 'Zimbabwe D<NAME>'
'code': '932'
'country': 'ZIMBABWE'
'exponent': '2'
###
Convert currency to its Cent value, based on ISO4217A table
###
convertToMinorUnits: (amount, currency) ->
exponent = @iso4217[currency].exponent
minor = new bd
.BigDecimal(amount)
.scaleByPowerOfTen exponent
.toBigInteger()
return minor.toString()
###
Convert currency back to its nominal value
###
convertToNominalUnits: (amount, currency) ->
exponent = @iso4217[currency].exponent
nominal = new bd
.BigDecimal(amount)
.scaleByPowerOfTen -exponent
.setScale Number(exponent), bd.RoundingMode.DOWN()
return nominal.toPlainString()
getCurrencies: ->
_.compact _.keys @iso4217
module.exports = Currency | true | bd = require 'bigdecimal'
_ = require "underscore"
class Currency
constructor: ->
@iso4217 =
'':
'name': 'No universal currency'
'code': ''
'country': 'SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS'
'exponent': ''
'AED':
'name': 'PI:NAME:<NAME>END_PI'
'code': '784'
'country': 'UNITED ARAB EMIRATES (THE)'
'exponent': '2'
'AFN':
'name': 'Afghani'
'code': '971'
'country': 'AFGHANISTAN'
'exponent': '2'
'ALL':
'name': 'PI:NAME:<NAME>END_PI'
'code': '008'
'country': 'ALBANIA'
'exponent': '2'
'AMD':
'name': 'Armenian DPI:NAME:<NAME>END_PI'
'code': '051'
'country': 'ARMENIA'
'exponent': '2'
'ANG':
'name': 'Netherlands Antillean Guilder'
'code': '532'
'country': 'SINT MAARTEN (DUTCH PART)'
'exponent': '2'
'AOA':
'name': 'KPI:NAME:<NAME>END_PI'
'code': '973'
'country': 'ANGOLA'
'exponent': '2'
'ARS':
'name': 'Argentine Peso'
'code': '032'
'country': 'ARGENTINA'
'exponent': '2'
'AUD':
'name': 'Australian Dollar'
'code': '036'
'country': 'TUVALU'
'exponent': '2'
'AWG':
'name': 'PI:NAME:<NAME>END_PI'
'code': '533'
'country': 'ARUBA'
'exponent': '2'
'AZN':
'name': 'Azerbaijanian Manat'
'code': '944'
'country': 'AZERBAIJAN'
'exponent': '2'
'BAM':
'name': 'Convertible Mark'
'code': '977'
'country': 'BOSNIA AND HERZEGOVINA'
'exponent': '2'
'BBD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '052'
'country': 'BARBADOS'
'exponent': '2'
'BDT':
'name': 'PI:NAME:<NAME>END_PI'
'code': '050'
'country': 'BANGLADESH'
'exponent': '2'
'BGN':
'name': 'Bulgarian LePI:NAME:<NAME>END_PI'
'code': '975'
'country': 'BULGARIA'
'exponent': '2'
'BHD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '048'
'country': 'BAHRAIN'
'exponent': '3'
'BIF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '108'
'country': 'BURUNDI'
'exponent': '0'
'BMD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '060'
'country': 'BERMUDA'
'exponent': '2'
'BND':
'name': 'PI:NAME:<NAME>END_PI'
'code': '096'
'country': 'BRUNEI DARUSSALAM'
'exponent': '2'
'BOB':
'name': 'PI:NAME:<NAME>END_PI'
'code': '068'
'country': 'BOLIVIA (PLURINATIONAL STATE OF)'
'exponent': '2'
'BOV':
'name': 'PI:NAME:<NAME>END_PI'
'code': '984'
'country': 'BOLIVIA (PLURINATIONAL STATE OF)'
'exponent': '2'
'BRL':
'name': 'Brazilian Real'
'code': '986'
'country': 'BRAZIL'
'exponent': '2'
'BSD':
'name': 'Bahamian DPI:NAME:<NAME>END_PI'
'code': '044'
'country': 'BAHAMAS (THE)'
'exponent': '2'
'BTN':
'name': 'PI:NAME:<NAME>END_PI'
'code': '064'
'country': 'BHUTAN'
'exponent': '2'
'BWP':
'name': 'PI:NAME:<NAME>END_PI'
'code': '072'
'country': 'BOTSWANA'
'exponent': '2'
'BYR':
'name': 'BelarPI:NAME:<NAME>END_PI RPI:NAME:<NAME>END_PI'
'code': '974'
'country': 'BELARUS'
'exponent': '0'
'BZD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '084'
'country': 'BELIZE'
'exponent': '2'
'CAD':
'name': 'Canadian PI:NAME:<NAME>END_PI'
'code': '124'
'country': 'CANADA'
'exponent': '2'
'CDF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '976'
'country': 'CONGO (THE DEMOCRATIC REPUBLIC OF THE)'
'exponent': '2'
'CHE':
'name': 'PI:NAME:<NAME>END_PI'
'code': '947'
'country': 'SWITZERLAND'
'exponent': '2'
'CHF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '756'
'country': 'SWITZERLAND'
'exponent': '2'
'CHW':
'name': 'PI:NAME:<NAME>END_PI'
'code': '948'
'country': 'SWITZERLAND'
'exponent': '2'
'CLF':
'name': 'Unidad de FPI:NAME:<NAME>END_PIo'
'code': '990'
'country': 'CHILE'
'exponent': '4'
'CLP':
'name': 'PI:NAME:<NAME>END_PI'
'code': '152'
'country': 'CHILE'
'exponent': '0'
'CNY':
'name': 'PI:NAME:<NAME>END_PI'
'code': '156'
'country': 'CHINA'
'exponent': '2'
'COP':
'name': 'Colombian Peso'
'code': '170'
'country': 'COLOMBIA'
'exponent': '2'
'COU':
'name': 'Unidad de Valor Real'
'code': '970'
'country': 'COLOMBIA'
'exponent': '2'
'CRC':
'name': 'PI:NAME:<NAME>END_PI'
'code': '188'
'country': 'COSTA RICA'
'exponent': '2'
'CUC':
'name': 'Peso Convertible'
'code': '931'
'country': 'CUBA'
'exponent': '2'
'CUP':
'name': 'Cuban Peso'
'code': '192'
'country': 'CUBA'
'exponent': '2'
'CVE':
'name': 'PI:NAME:<NAME>END_PI'
'code': '132'
'country': 'CABO VERDE'
'exponent': '2'
'CZK':
'name': 'Czech Koruna'
'code': '203'
'country': 'CZECH REPUBLIC (THE)'
'exponent': '2'
'DJF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '262'
'country': 'DJIBOUTI'
'exponent': '0'
'DKK':
'name': 'PI:NAME:<NAME>END_PI'
'code': '208'
'country': 'GREENLAND'
'exponent': '2'
'DOP':
'name': 'Dominican Peso'
'code': '214'
'country': 'DOMINICAN REPUBLIC (THE)'
'exponent': '2'
'DZD':
'name': 'AlPI:NAME:<NAME>END_PI DPI:NAME:<NAME>END_PI'
'code': '012'
'country': 'ALGERIA'
'exponent': '2'
'EGP':
'name': 'Egyptian Pound'
'code': '818'
'country': 'EGYPT'
'exponent': '2'
'ERN':
'name': 'PI:NAME:<NAME>END_PI'
'code': '232'
'country': 'ERITREA'
'exponent': '2'
'ETB':
'name': 'Ethiopian Birr'
'code': '230'
'country': 'ETHIOPIA'
'exponent': '2'
'EUR':
'name': 'Euro'
'code': '978'
'country': 'SPAIN'
'exponent': '2'
'FJD':
'name': 'Fiji Dollar'
'code': '242'
'country': 'FIJI'
'exponent': '2'
'FKP':
'name': 'Falkland Islands Pound'
'code': '238'
'country': 'FALKLAND ISLANDS (THE) [MALVINAS]'
'exponent': '2'
'GBP':
'name': 'Pound SPI:NAME:<NAME>END_PIling'
'code': '826'
'country': 'UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)'
'exponent': '2'
'GEL':
'name': 'PI:NAME:<NAME>END_PI'
'code': '981'
'country': 'GEORGIA'
'exponent': '2'
'GHS':
'name': 'PI:NAME:<NAME>END_PI'
'code': '936'
'country': 'GHANA'
'exponent': '2'
'GIP':
'name': 'GPI:NAME:<NAME>END_PIar PI:NAME:<NAME>END_PI'
'code': '292'
'country': 'GIBRALTAR'
'exponent': '2'
'GMD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '270'
'country': 'GAMBIA (THE)'
'exponent': '2'
'GNF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '324'
'country': 'GUINEA'
'exponent': '0'
'GTQ':
'name': 'Quetzal'
'code': '320'
'country': 'GUATEMALA'
'exponent': '2'
'GYD':
'name': 'Guyana Dollar'
'code': '328'
'country': 'GUYANA'
'exponent': '2'
'HKD':
'name': 'Hong Kong Dollar'
'code': '344'
'country': 'HONG KONG'
'exponent': '2'
'HNL':
'name': 'PI:NAME:<NAME>END_PI'
'code': '340'
'country': 'HONDURAS'
'exponent': '2'
'HRK':
'name': 'PI:NAME:<NAME>END_PI'
'code': '191'
'country': 'CROATIA'
'exponent': '2'
'HTG':
'name': 'PI:NAME:<NAME>END_PI'
'code': '332'
'country': 'HAITI'
'exponent': '2'
'HUF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '348'
'country': 'HUNGARY'
'exponent': '2'
'IDR':
'name': 'PI:NAME:<NAME>END_PI'
'code': '360'
'country': 'INDONESIA'
'exponent': '2'
'ILS':
'name': 'New Israeli Sheqel'
'code': '376'
'country': 'ISRAEL'
'exponent': '2'
'INR':
'name': 'Indian Rupee'
'code': '356'
'country': 'INDIA'
'exponent': '2'
'IQD':
'name': 'PI:NAME:<NAME>END_PIqi PI:NAME:<NAME>END_PI'
'code': '368'
'country': 'IRAQ'
'exponent': '3'
'IRR':
'name': 'Iranian Rial'
'code': '364'
'country': 'IRAN (ISLAMIC REPUBLIC OF)'
'exponent': '2'
'ISK':
'name': 'IcelPI:NAME:<NAME>END_PI'
'code': '352'
'country': 'ICELAND'
'exponent': '0'
'JMD':
'name': 'Jamaican Dollar'
'code': '388'
'country': 'JAMAICA'
'exponent': '2'
'JOD':
'name': 'Jordanian Dinar'
'code': '400'
'country': 'JORDAN'
'exponent': '3'
'JPY':
'name': 'PI:NAME:<NAME>END_PI'
'code': '392'
'country': 'JAPAN'
'exponent': '0'
'KES':
'name': 'PI:NAME:<NAME>END_PI'
'code': '404'
'country': 'KENYA'
'exponent': '2'
'KGS':
'name': 'PI:NAME:<NAME>END_PI'
'code': '417'
'country': 'KYRGYZSTAN'
'exponent': '2'
'KHR':
'name': 'PI:NAME:<NAME>END_PI'
'code': '116'
'country': 'CAMBODIA'
'exponent': '2'
'KMF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '174'
'country': 'COMOROS (THE)'
'exponent': '0'
'KPW':
'name': 'PI:NAME:<NAME>END_PI'
'code': '408'
'country': 'KOREA (THE DEMOCRATIC PEOPLE’S REPUBLIC OF)'
'exponent': '2'
'KRW':
'name': 'PI:NAME:<NAME>END_PI'
'code': '410'
'country': 'KOREA (THE REPUBLIC OF)'
'exponent': '0'
'KWD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '414'
'country': 'KUWAIT'
'exponent': '3'
'KYD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '136'
'country': 'CAYMAN ISLANDS (THE)'
'exponent': '2'
'KZT':
'name': 'PI:NAME:<NAME>END_PI'
'code': '398'
'country': 'KAZAKHSTAN'
'exponent': '2'
'LAK':
'name': 'PI:NAME:<NAME>END_PI'
'code': '418'
'country': 'LAO PEOPLE’S DEMOCRATIC REPUBLIC (THE)'
'exponent': '2'
'LBP':
'name': 'Lebanese Pound'
'code': '422'
'country': 'LEBANON'
'exponent': '2'
'LKR':
'name': 'PI:NAME:<NAME>END_PI'
'code': '144'
'country': 'SRI LANKA'
'exponent': '2'
'LRD':
'name': 'LiPI:NAME:<NAME>END_PI'
'code': '430'
'country': 'LIBERIA'
'exponent': '2'
'LSL':
'name': 'PI:NAME:<NAME>END_PI'
'code': '426'
'country': 'LESOTHO'
'exponent': '2'
'LYD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '434'
'country': 'LIBYA'
'exponent': '3'
'MAD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '504'
'country': 'WESTERN SAHARA'
'exponent': '2'
'MDL':
'name': 'PI:NAME:<NAME>END_PI'
'code': '498'
'country': 'MOLDOVA (THE REPUBLIC OF)'
'exponent': '2'
'MGA':
'name': 'PI:NAME:<NAME>END_PI'
'code': '969'
'country': 'MADAGASCAR'
'exponent': '2'
'MKD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '807'
'country': 'MACEDONIA (THE FORMER YUGOSLAV REPUBLIC OF)'
'exponent': '2'
'MMK':
'name': 'PI:NAME:<NAME>END_PI'
'code': '104'
'country': 'MYANMAR'
'exponent': '2'
'MNT':
'name': 'PI:NAME:<NAME>END_PI'
'code': '496'
'country': 'MONGOLIA'
'exponent': '2'
'MOP':
'name': 'PI:NAME:<NAME>END_PI'
'code': '446'
'country': 'MACAO'
'exponent': '2'
'MRO':
'name': 'PI:NAME:<NAME>END_PI'
'code': '478'
'country': 'MAURITANIA'
'exponent': '2'
'MUR':
'name': 'PI:NAME:<NAME>END_PI'
'code': '480'
'country': 'MAURITIUS'
'exponent': '2'
'MVR':
'name': 'PI:NAME:<NAME>END_PI'
'code': '462'
'country': 'MALDIVES'
'exponent': '2'
'MWK':
'name': 'PI:NAME:<NAME>END_PI'
'code': '454'
'country': 'MALAWI'
'exponent': '2'
'MXN':
'name': 'MexPI:NAME:<NAME>END_PI'
'code': '484'
'country': 'MEXICO'
'exponent': '2'
'MXV':
'name': 'Mexican Unidad de Inversion (UDI)'
'code': '979'
'country': 'MEXICO'
'exponent': '2'
'MYR':
'name': 'MalPI:NAME:<NAME>END_PI'
'code': '458'
'country': 'MALAYSIA'
'exponent': '2'
'MZN':
'name': 'MozambPI:NAME:<NAME>END_PI'
'code': '943'
'country': 'MOZAMBIQUE'
'exponent': '2'
'NAD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '516'
'country': 'NAMIBIA'
'exponent': '2'
'NGN':
'name': 'PI:NAME:<NAME>END_PI'
'code': '566'
'country': 'NIGERIA'
'exponent': '2'
'NIO':
'name': 'PI:NAME:<NAME>END_PI'
'code': '558'
'country': 'NICARAGUA'
'exponent': '2'
'NOK':
'name': 'Norwegian KrPI:NAME:<NAME>END_PI'
'code': '578'
'country': 'SVALBARD AND JAN MAYEN'
'exponent': '2'
'NPR':
'name': 'NepalePI:NAME:<NAME>END_PI RPI:NAME:<NAME>END_PI'
'code': '524'
'country': 'NEPAL'
'exponent': '2'
'NZD':
'name': 'New Zealand Dollar'
'code': '554'
'country': 'TOKELAU'
'exponent': '2'
'OMR':
'name': 'PI:NAME:<NAME>END_PI'
'code': '512'
'country': 'OMAN'
'exponent': '3'
'PAB':
'name': 'PI:NAME:<NAME>END_PI'
'code': '590'
'country': 'PANAMA'
'exponent': '2'
'PEN':
'name': 'PI:NAME:<NAME>END_PI'
'code': '604'
'country': 'PERU'
'exponent': '2'
'PGK':
'name': 'PI:NAME:<NAME>END_PI'
'code': '598'
'country': 'PAPUA NEW GUINEA'
'exponent': '2'
'PHP':
'name': 'PI:NAME:<NAME>END_PI'
'code': '608'
'country': 'PHILIPPINES (THE)'
'exponent': '2'
'PKR':
'name': 'Pakistan Rupee'
'code': '586'
'country': 'PAKISTAN'
'exponent': '2'
'PLN':
'name': 'PI:NAME:<NAME>END_PI'
'code': '985'
'country': 'POLAND'
'exponent': '2'
'PYG':
'name': 'PI:NAME:<NAME>END_PI'
'code': '600'
'country': 'PARAGUAY'
'exponent': '0'
'QAR':
'name': 'PI:NAME:<NAME>END_PI'
'code': '634'
'country': 'QATAR'
'exponent': '2'
'RON':
'name': 'PI:NAME:<NAME>END_PI'
'code': '946'
'country': 'ROMANIA'
'exponent': '2'
'RSD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '941'
'country': 'SERBIA'
'exponent': '2'
'RUB':
'name': 'Russian Ruble'
'code': '643'
'country': 'RUSSIAN FEDERATION (THE)'
'exponent': '2'
'RWF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '646'
'country': 'RWANDA'
'exponent': '0'
'SAR':
'name': 'PI:NAME:<NAME>END_PI'
'code': '682'
'country': 'SAUDI ARABIA'
'exponent': '2'
'SBD':
'name': 'Solomon Islands Dollar'
'code': '090'
'country': 'SOLOMON ISLANDS'
'exponent': '2'
'SCR':
'name': 'Seychelles Rupee'
'code': '690'
'country': 'SEYCHELLES'
'exponent': '2'
'SDG':
'name': 'PI:NAME:<NAME>END_PI'
'code': '938'
'country': 'SUDAN (THE)'
'exponent': '2'
'SEK':
'name': 'Swedish Krona'
'code': '752'
'country': 'SWEDEN'
'exponent': '2'
'SGD':
'name': 'Singapore DPI:NAME:<NAME>END_PI'
'code': '702'
'country': 'SINGAPORE'
'exponent': '2'
'SHP':
'name': 'PI:NAME:<NAME>END_PI'
'code': '654'
'country': 'SAINT HELENA, ASCENSION AND TRISTAN DA CUNHA'
'exponent': '2'
'SLL':
'name': 'PI:NAME:<NAME>END_PI'
'code': '694'
'country': 'SIERRA LEONE'
'exponent': '2'
'SOS':
'name': 'PI:NAME:<NAME>END_PI'
'code': '706'
'country': 'SOMALIA'
'exponent': '2'
'SRD':
'name': 'PI:NAME:<NAME>END_PIinPI:NAME:<NAME>END_PI'
'code': '968'
'country': 'SURINAME'
'exponent': '2'
'SSP':
'name': 'PI:NAME:<NAME>END_PI Sudanese PPI:NAME:<NAME>END_PI'
'code': '728'
'country': 'SOUTH SUDAN'
'exponent': '2'
'STD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '678'
'country': 'SAO TOME AND PRINCIPE'
'exponent': '2'
'SVC':
'name': 'PI:NAME:<NAME>END_PI'
'code': '222'
'country': 'EL SALVADOR'
'exponent': '2'
'SYP':
'name': 'PI:NAME:<NAME>END_PI'
'code': '760'
'country': 'SYRIAN ARAB REPUBLIC'
'exponent': '2'
'SZL':
'name': 'PI:NAME:<NAME>END_PI'
'code': '748'
'country': 'SWAZILAND'
'exponent': '2'
'THB':
'name': 'PI:NAME:<NAME>END_PI'
'code': '764'
'country': 'THAILAND'
'exponent': '2'
'TJS':
'name': 'PI:NAME:<NAME>END_PI'
'code': '972'
'country': 'TAJIKISTAN'
'exponent': '2'
'TMT':
'name': 'Turkmenistan New Manat'
'code': '934'
'country': 'TURKMENISTAN'
'exponent': '2'
'TND':
'name': 'PI:NAME:<NAME>END_PI'
'code': '788'
'country': 'TUNISIA'
'exponent': '3'
'TOP':
'name': 'PI:NAME:<NAME>END_PI'
'code': '776'
'country': 'TONGA'
'exponent': '2'
'TRY':
'name': 'TurPI:NAME:<NAME>END_PIish PI:NAME:<NAME>END_PI'
'code': '949'
'country': 'TURKEY'
'exponent': '2'
'TTD':
'name': 'Trinidad and Tobago Dollar'
'code': '780'
'country': 'TRINIDAD AND TOBAGO'
'exponent': '2'
'TWD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '901'
'country': 'TAIWAN (PROVINCE OF CHINA)'
'exponent': '2'
'TZS':
'name': 'PI:NAME:<NAME>END_PI'
'code': '834'
'country': 'TANZANIA, UNITED REPUBLIC OF'
'exponent': '2'
'UAH':
'name': 'PI:NAME:<NAME>END_PI'
'code': '980'
'country': 'UKRAINE'
'exponent': '2'
'UGX':
'name': 'PI:NAME:<NAME>END_PI'
'code': '800'
'country': 'UGANDA'
'exponent': '0'
'USD':
'name': 'US DPI:NAME:<NAME>END_PI'
'code': '840'
'country': 'VIRGIN ISLANDS (U.S.)'
'exponent': '2'
'USN':
'name': 'US Dollar (Next day)'
'code': '997'
'country': 'UNITED STATES OF AMERICA (THE)'
'exponent': '2'
'UYI':
'name': 'Uruguay Peso en Unidades Indexadas (URUIURUI)'
'code': '940'
'country': 'URUGUAY'
'exponent': '0'
'UYU':
'name': 'PI:NAME:<NAME>END_PI'
'code': '858'
'country': 'URUGUAY'
'exponent': '2'
'UZS':
'name': 'PI:NAME:<NAME>END_PIkistan Sum'
'code': '860'
'country': 'UZBEKISTAN'
'exponent': '2'
'VEF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '937'
'country': 'VENEZUELA (BOLIVARIAN REPUBLIC OF)'
'exponent': '2'
'VND':
'name': 'PI:NAME:<NAME>END_PI'
'code': '704'
'country': 'VIET NAM'
'exponent': '0'
'VUV':
'name': 'PI:NAME:<NAME>END_PI'
'code': '548'
'country': 'VANUATU'
'exponent': '0'
'WST':
'name': 'PI:NAME:<NAME>END_PI'
'code': '882'
'country': 'SAMOA'
'exponent': '2'
'XAF':
'name': 'CFA Franc BEAC'
'code': '950'
'country': 'GABON'
'exponent': '0'
'XAG':
'name': 'PI:NAME:<NAME>END_PI'
'code': '961'
'country': 'ZZ11_Silver'
'exponent': 'N.A.'
'XAU':
'name': 'PI:NAME:<NAME>END_PI'
'code': '959'
'country': 'ZZ08_Gold'
'exponent': 'N.A.'
'XBA':
'name': 'Bond Markets Unit European Composite Unit (EURCO)'
'code': '955'
'country': 'ZZ01_Bond Markets Unit European_EURCO'
'exponent': 'N.A.'
'XBB':
'name': 'Bond Markets Unit European Monetary Unit (E.M.U.-6)'
'code': '956'
'country': 'ZZ02_Bond Markets Unit European_EMU-6'
'exponent': 'N.A.'
'XBC':
'name': 'Bond Markets Unit European Unit of Account 9 (E.U.A.-9)'
'code': '957'
'country': 'ZZ03_Bond Markets Unit European_EUA-9'
'exponent': 'N.A.'
'XBD':
'name': 'Bond Markets Unit European Unit of Account 17 (E.U.A.-17)'
'code': '958'
'country': 'ZZ04_Bond Markets Unit European_EUA-17'
'exponent': 'N.A.'
'XCD':
'name': 'East Caribbean Dollar'
'code': '951'
'country': 'SAINT VINCENT AND THE GRENADINES'
'exponent': '2'
'XDR':
'name': 'SDR (Special Drawing Right)'
'code': '960'
'country': 'INTERNATIONAL MONETARY FUND (IMF) '
'exponent': 'N.A.'
'XOF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '952'
'country': 'TOGO'
'exponent': '0'
'XPD':
'name': 'PI:NAME:<NAME>END_PI'
'code': '964'
'country': 'ZZ09_Palladium'
'exponent': 'N.A.'
'XPF':
'name': 'PI:NAME:<NAME>END_PI'
'code': '953'
'country': 'WALLIS AND FUTUNA'
'exponent': '0'
'XPT':
'name': 'PI:NAME:<NAME>END_PI'
'code': '962'
'country': 'ZZ10_Platinum'
'exponent': 'N.A.'
'XSU':
'name': 'PI:NAME:<NAME>END_PI'
'code': '994'
'country': 'SISTEMA UNITARIO DE COMPENSACION REGIONAL DE PAGOS "SUCRE"'
'exponent': 'N.A.'
'XTS':
'name': 'Codes specifically reserved for testing purposes'
'code': '963'
'country': 'ZZ06_Testing_Code'
'exponent': 'N.A.'
'XUA':
'name': 'ADB Unit of Account'
'code': '965'
'country': 'MEMBER COUNTRIES OF THE AFRICAN DEVELOPMENT BANK GROUP'
'exponent': 'N.A.'
'XXX':
'name': 'The codes assigned for transactions where no currency is involved'
'code': '999'
'country': 'ZZ07_No_Currency'
'exponent': 'N.A.'
'YER':
'name': 'PI:NAME:<NAME>END_PI'
'code': '886'
'country': 'YEMEN'
'exponent': '2'
'ZAR':
'name': 'PI:NAME:<NAME>END_PI'
'code': '710'
'country': 'SOUTH AFRICA'
'exponent': '2'
'ZMW':
'name': 'PI:NAME:<NAME>END_PI'
'code': '967'
'country': 'ZAMBIA'
'exponent': '2'
'ZWL':
'name': 'Zimbabwe DPI:NAME:<NAME>END_PI'
'code': '932'
'country': 'ZIMBABWE'
'exponent': '2'
###
Convert currency to its Cent value, based on ISO4217A table
###
convertToMinorUnits: (amount, currency) ->
exponent = @iso4217[currency].exponent
minor = new bd
.BigDecimal(amount)
.scaleByPowerOfTen exponent
.toBigInteger()
return minor.toString()
###
Convert currency back to its nominal value
###
convertToNominalUnits: (amount, currency) ->
exponent = @iso4217[currency].exponent
nominal = new bd
.BigDecimal(amount)
.scaleByPowerOfTen -exponent
.setScale Number(exponent), bd.RoundingMode.DOWN()
return nominal.toPlainString()
getCurrencies: ->
_.compact _.keys @iso4217
module.exports = Currency |
[
{
"context": "#\n# Usefull Constants\n# @author : David Ronai / @Makio64 / makiopolis.com\n#\n\nclass Constants\n\n\t",
"end": 45,
"score": 0.9998668432235718,
"start": 34,
"tag": "NAME",
"value": "David Ronai"
},
{
"context": "#\n# Usefull Constants\n# @author : David Ronai / @Makio... | test/src/coffee/core/Constants.coffee | Makio64/christmasxp2015 | 65 | #
# Usefull Constants
# @author : David Ronai / @Makio64 / makiopolis.com
#
class Constants
@PI2 = Math.PI*2
@M2PI = 2/Math.PI
@M4PI = 4/Math.PI
@M8PI = 8/Math.PI
@RAD2DEGREE = 180 / Math.PI
@DEGREE2RAD = Math.PI / 180
@SQRT2 = Math.sqrt(2)
@DEBUG = true
@ZERO = new THREE.Vector3(0)
constructor:()->
console.warning('Dude... there is no interest to instanciate Constants, use static variable only')
return
module.exports = Constants
| 219559 | #
# Usefull Constants
# @author : <NAME> / @Makio64 / m<EMAIL>
#
class Constants
@PI2 = Math.PI*2
@M2PI = 2/Math.PI
@M4PI = 4/Math.PI
@M8PI = 8/Math.PI
@RAD2DEGREE = 180 / Math.PI
@DEGREE2RAD = Math.PI / 180
@SQRT2 = Math.sqrt(2)
@DEBUG = true
@ZERO = new THREE.Vector3(0)
constructor:()->
console.warning('Dude... there is no interest to instanciate Constants, use static variable only')
return
module.exports = Constants
| true | #
# Usefull Constants
# @author : PI:NAME:<NAME>END_PI / @Makio64 / mPI:EMAIL:<EMAIL>END_PI
#
class Constants
@PI2 = Math.PI*2
@M2PI = 2/Math.PI
@M4PI = 4/Math.PI
@M8PI = 8/Math.PI
@RAD2DEGREE = 180 / Math.PI
@DEGREE2RAD = Math.PI / 180
@SQRT2 = Math.sqrt(2)
@DEBUG = true
@ZERO = new THREE.Vector3(0)
constructor:()->
console.warning('Dude... there is no interest to instanciate Constants, use static variable only')
return
module.exports = Constants
|
[
{
"context": "//localhost:3000/'\n\npusher_keys = \n production: '19beda1f7e2ca403abab'\n staging: '1f4ef2d9292c6ac10cdc'\n development:",
"end": 403,
"score": 0.9996153116226196,
"start": 383,
"tag": "KEY",
"value": "19beda1f7e2ca403abab"
},
{
"context": "\n production: '19beda1... | app/config.coffee | aredotna/ps1expo | 0 | config =
api: {}
pusher: {}
errbit: {}
production = yes # MUST BE YES/NO
staging = false # MUST BE TRUE/FALSE
environment =
if production
'production'
else if staging
'staging'
else
'development'
environments =
production: 'http://api.are.na/'
staging: 'http://staging.are.na/'
development: 'http://localhost:3000/'
pusher_keys =
production: '19beda1f7e2ca403abab'
staging: '1f4ef2d9292c6ac10cdc'
development: '944c5f601f3a394785f0'
config.env = environment
config.api.root = environments[environment]
config.api.versionRoot = "#{config.api.root}v2"
config.pusher.key = pusher_keys[environment]
module.exports = config | 69791 | config =
api: {}
pusher: {}
errbit: {}
production = yes # MUST BE YES/NO
staging = false # MUST BE TRUE/FALSE
environment =
if production
'production'
else if staging
'staging'
else
'development'
environments =
production: 'http://api.are.na/'
staging: 'http://staging.are.na/'
development: 'http://localhost:3000/'
pusher_keys =
production: '<KEY>'
staging: '<KEY>'
development: '944c5f601f3a394785f0'
config.env = environment
config.api.root = environments[environment]
config.api.versionRoot = "#{config.api.root}v2"
config.pusher.key = pusher_keys[environment]
module.exports = config | true | config =
api: {}
pusher: {}
errbit: {}
production = yes # MUST BE YES/NO
staging = false # MUST BE TRUE/FALSE
environment =
if production
'production'
else if staging
'staging'
else
'development'
environments =
production: 'http://api.are.na/'
staging: 'http://staging.are.na/'
development: 'http://localhost:3000/'
pusher_keys =
production: 'PI:KEY:<KEY>END_PI'
staging: 'PI:KEY:<KEY>END_PI'
development: '944c5f601f3a394785f0'
config.env = environment
config.api.root = environments[environment]
config.api.versionRoot = "#{config.api.root}v2"
config.pusher.key = pusher_keys[environment]
module.exports = config |
[
{
"context": "gs off to ipfs.\n [(No Title)](https://github.com/wesharehoodies/slate-react-rich-text-editor/tree/part-2)\n \n \n ",
"end": 286,
"score": 0.9871376156806946,
"start": 272,
"tag": "USERNAME",
"value": "wesharehoodies"
},
{
"context": "nEE993UM4jikk | [ENGR003](https:... | notes/aa9ff3c2-4ec8-49df-8664-d9eef5d92c26.cson | wikiGrandfleet/gravRepo | 0 | createdAt: "2018-09-25T01:44:28.157Z"
updatedAt: "2018-10-04T04:33:46.024Z"
type: "MARKDOWN_NOTE"
folder: "5cef29a72e245ea24273"
title: "IPFS Dapp"
content: '''
### IPFS Dapp
Add text editor eventually and send things off to ipfs.
[(No Title)](https://github.com/wesharehoodies/slate-react-rich-text-editor/tree/part-2)
Uploading reports and recording hashes here for now.
(https://gateway.ipfs.io/ipfs/QmXcnZAg2VJMqrGYWkNHNqvDkFAbTcrXJ9QbN5WiQCEmed)
(https://gateway.ipfs.io/ipfs/QmZb7crH2YYqwvq5d2pCjZxAovzqXkhWwnEE993UM4jikk)
https://ipfs.io/ipfs/QmeQegoUZ3YMNpgUvinU424FtrMUYNNHgQafmaThrzG9nZ
[](https://gateway.ipfs.io/ipfs/QmSE4qrynVfCU1Vevhvaeav6RWtN5vFKSn3KaC3GuSKPvq)
|Filename | IPFS Hash| url |
| ---| ---| ---|
| ENGR001 Report | QmSE4qrynVfCU1Vevhvaeav6RWtN5vFKSn3KaC3GuSKPvq | [ENGR001](https://gateway.ipfs.io/ipfs/QmSE4qrynVfCU1Vevhvaeav6RWtN5vFKSn3KaC3GuSKPvq) |
| ENGR002 Report |fill in | fillin |
| ENGR003 Report | QmZb7crH2YYqwvq5d2pCjZxAovzqXkhWwnEE993UM4jikk | [ENGR003](https://gateway.ipfs.io/ipfs/QmZb7crH2YYqwvq5d2pCjZxAovzqXkhWwnEE993UM4jikk) |
| ENGR446 Report | QmeQegoUZ3YMNpgUvinU424FtrMUYNNHgQafmaThrzG9nZ |[ENGR446](https://ipfs.io/ipfs/QmeQegoUZ3YMNpgUvinU424FtrMUYNNHgQafmaThrzG9nZ) |
'''
tags: []
isStarred: false
isTrashed: false
| 130172 | createdAt: "2018-09-25T01:44:28.157Z"
updatedAt: "2018-10-04T04:33:46.024Z"
type: "MARKDOWN_NOTE"
folder: "5cef29a72e245ea24273"
title: "IPFS Dapp"
content: '''
### IPFS Dapp
Add text editor eventually and send things off to ipfs.
[(No Title)](https://github.com/wesharehoodies/slate-react-rich-text-editor/tree/part-2)
Uploading reports and recording hashes here for now.
(https://gateway.ipfs.io/ipfs/QmXcnZAg2VJMqrGYWkNHNqvDkFAbTcrXJ9QbN5WiQCEmed)
(https://gateway.ipfs.io/ipfs/QmZb7crH2YYqwvq5d2pCjZxAovzqXkhWwnEE993UM4jikk)
https://ipfs.io/ipfs/QmeQegoUZ3YMNpgUvinU424FtrMUYNNHgQafmaThrzG9nZ
[](https://gateway.ipfs.io/ipfs/QmSE4qrynVfCU1Vevhvaeav6RWtN5vFKSn3KaC3GuSKPvq)
|Filename | IPFS Hash| url |
| ---| ---| ---|
| ENGR001 Report | QmSE4qrynVfCU1Vevhvaeav6RWtN5vFKSn3KaC3GuSKPvq | [ENGR001](https://gateway.ipfs.io/ipfs/QmSE4qrynVfCU1Vevhvaeav6RWtN5vFKSn3KaC3GuSKPvq) |
| ENGR002 Report |fill in | fillin |
| ENGR003 Report | QmZb7crH2YYqwvq5d2pCjZxAovzqXkhWwnEE993UM4jikk | [ENGR003](https://gateway.ipfs.io/<KEY>) |
| ENGR446 Report | QmeQegoUZ3YMNpgUvinU424FtrMUYNNHgQafmaThrzG9nZ |[ENGR446](https://ipfs.io/ipfs/QmeQegoUZ3YMNpgUvinU424FtrMUY<KEY>HgQafmaThrzG9nZ) |
'''
tags: []
isStarred: false
isTrashed: false
| true | createdAt: "2018-09-25T01:44:28.157Z"
updatedAt: "2018-10-04T04:33:46.024Z"
type: "MARKDOWN_NOTE"
folder: "5cef29a72e245ea24273"
title: "IPFS Dapp"
content: '''
### IPFS Dapp
Add text editor eventually and send things off to ipfs.
[(No Title)](https://github.com/wesharehoodies/slate-react-rich-text-editor/tree/part-2)
Uploading reports and recording hashes here for now.
(https://gateway.ipfs.io/ipfs/QmXcnZAg2VJMqrGYWkNHNqvDkFAbTcrXJ9QbN5WiQCEmed)
(https://gateway.ipfs.io/ipfs/QmZb7crH2YYqwvq5d2pCjZxAovzqXkhWwnEE993UM4jikk)
https://ipfs.io/ipfs/QmeQegoUZ3YMNpgUvinU424FtrMUYNNHgQafmaThrzG9nZ
[](https://gateway.ipfs.io/ipfs/QmSE4qrynVfCU1Vevhvaeav6RWtN5vFKSn3KaC3GuSKPvq)
|Filename | IPFS Hash| url |
| ---| ---| ---|
| ENGR001 Report | QmSE4qrynVfCU1Vevhvaeav6RWtN5vFKSn3KaC3GuSKPvq | [ENGR001](https://gateway.ipfs.io/ipfs/QmSE4qrynVfCU1Vevhvaeav6RWtN5vFKSn3KaC3GuSKPvq) |
| ENGR002 Report |fill in | fillin |
| ENGR003 Report | QmZb7crH2YYqwvq5d2pCjZxAovzqXkhWwnEE993UM4jikk | [ENGR003](https://gateway.ipfs.io/PI:KEY:<KEY>END_PI) |
| ENGR446 Report | QmeQegoUZ3YMNpgUvinU424FtrMUYNNHgQafmaThrzG9nZ |[ENGR446](https://ipfs.io/ipfs/QmeQegoUZ3YMNpgUvinU424FtrMUYPI:KEY:<KEY>END_PIHgQafmaThrzG9nZ) |
'''
tags: []
isStarred: false
isTrashed: false
|
[
{
"context": " Schema __dirname + '/..', database: '', username: DBUSER, password: DBPASS\nschema.log = (q) -> console.log",
"end": 217,
"score": 0.960623562335968,
"start": 211,
"tag": "USERNAME",
"value": "DBUSER"
},
{
"context": "+ '/..', database: '', username: DBUSER, password: ... | test/migration.coffee | BlakeLucchesi/mysql-adapter | 10 | juggling = require('jugglingdb')
Schema = juggling.Schema
Text = Schema.Text
DBNAME = 'myapp_test'
DBUSER = 'root'
DBPASS = ''
DBENGINE = 'mysql'
schema = new Schema __dirname + '/..', database: '', username: DBUSER, password: DBPASS
schema.log = (q) -> console.log q
query = (sql, cb) ->
schema.adapter.query sql, cb
User = schema.define 'User',
email: { type: String, null: false, index: true }
name: String
bio: Text
order: Number
password: String
birthDate: Date
pendingPeriod: Number
createdByAdmin: Boolean
, indexes:
index1:
columns: 'email, createdByAdmin'
withBlankDatabase = (cb) ->
db = schema.settings.database = DBNAME
query 'DROP DATABASE IF EXISTS ' + db, (err) ->
query 'CREATE DATABASE ' + db, (err) ->
query 'USE '+ db, cb
getFields = (model, cb) ->
query 'SHOW FIELDS FROM ' + model, (err, res) ->
if err
cb err
else
fields = {}
res.forEach (field) -> fields[field.Field] = field
cb err, fields
getIndexes = (model, cb) ->
query 'SHOW INDEXES FROM ' + model, (err, res) ->
if err
console.log err
cb err
else
indexes = {}
# Note: this will only show the first key of compound keys
res.forEach (index) ->
indexes[index.Key_name] = index if parseInt(index.Seq_in_index, 10) == 1
cb err, indexes
it = (name, testCases) ->
module.exports[name] = testCases
it 'should run migration', (test) ->
withBlankDatabase (err) ->
schema.automigrate ->
getFields 'User', (err, fields) ->
test.deepEqual fields,
id:
Field: 'id'
Type: 'int(11)'
Null: 'NO'
Key: 'PRI'
Default: null
Extra: 'auto_increment'
email:
Field: 'email'
Type: 'varchar(255)'
Null: 'NO'
Key: 'MUL'
Default: null
Extra: ''
name:
Field: 'name'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
bio:
Field: 'bio'
Type: 'text'
Null: 'YES'
Key: ''
Default: null
Extra: ''
order:
Field: 'order'
Type: 'int(11)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
password:
Field: 'password'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
birthDate:
Field: 'birthDate'
Type: 'datetime'
Null: 'YES'
Key: ''
Default: null
Extra: ''
pendingPeriod:
Field: 'pendingPeriod'
Type: 'int(11)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
createdByAdmin:
Field: 'createdByAdmin'
Type: 'tinyint(1)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
# Once gain, getIdexes truncates multi-key indexes to the first member. Hence index1 is correct.
getIndexes 'User', (err, fields) ->
test.deepEqual fields,
PRIMARY:
Table: 'User'
Non_unique: 0
Key_name: 'PRIMARY'
Seq_in_index: 1
Column_name: 'id'
Collation: 'A'
Cardinality: 0
Sub_part: null
Packed: null
Null: ''
Index_type: 'BTREE'
Comment: ''
Index_comment: ''
email:
Table: 'User'
Non_unique: 1
Key_name: 'email'
Seq_in_index: 1
Column_name: 'email'
Collation: 'A'
Cardinality: 0
Sub_part: null
Packed: null
Null: ''
Index_type: 'BTREE'
Comment: ''
Index_comment: ''
index1:
Table: 'User'
Non_unique: 1
Key_name: 'index1'
Seq_in_index: 1
Column_name: 'email'
Collation: 'A'
Cardinality: 0
Sub_part: null
Packed: null
Null: ''
Index_type: 'BTREE'
Comment: ''
Index_comment: ''
test.done()
it 'should autoupgrade', (test) ->
userExists = (cb) ->
query 'SELECT * FROM User', (err, res) ->
cb(not err and res[0].email == 'test@example.com')
User.create email: 'test@example.com', (err, user) ->
test.ok not err
userExists (yep) ->
test.ok yep
User.defineProperty 'email', type: String
User.defineProperty 'name', type: String, limit: 50
User.defineProperty 'newProperty', type: Number
User.defineProperty 'pendingPeriod', false
schema.autoupdate (err) ->
getFields 'User', (err, fields) ->
# change nullable for email
test.equal fields.email.Null, 'YES', 'Email is not null'
# change type of name
test.equal fields.name.Type, 'varchar(50)', 'Name is not varchar(50)'
# add new column
test.ok fields.newProperty, 'New column was not added'
if fields.newProperty
test.equal fields.newProperty.Type, 'int(11)', 'New column type is not int(11)'
# drop column
test.ok not fields.pendingPeriod, 'drop column'
# user still exists
userExists (yep) ->
test.ok yep
test.done()
it "record should be updated", (done) ->
userExists = (cb) ->
query "SELECT * FROM UserData", (err, res) ->
cb not err and res[0].email is "yourname@newname.com"
UserData.update
where:
id: "1"
update:
email: "yourname@newname.com"
, (err, o) ->
userExists (yep) ->
assert.ok yep, "Email has changed"
# err when where missing
UserData.update
update:
email: "yourname@newname.com"
, (err, o) ->
assert.equal err, "Where or Update fields are missing", " no error when where field is missing "
# err when where update
UserData.update
where:
id: "1"
, (err, o) ->
assert.equal err, "Where or Update fields are missing", " no error when update field is missing "
done()
it 'should check actuality of schema', (test) ->
# drop column
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.defineProperty 'email', false
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
test.done()
it 'should add single-column index', (test) ->
User.defineProperty 'email', type: String, index: { kind: 'FULLTEXT', type: 'HASH'}
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok ixs.email && ixs.email.Column_name == 'email'
console.log(ixs)
test.equal ixs.email.Index_type, 'BTREE', 'default index type'
test.done()
it 'should change type of single-column index', (test) ->
User.defineProperty 'email', type: String, index: { type: 'BTREE' }
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok ixs.email && ixs.email.Column_name == 'email'
test.equal ixs.email.Index_type, 'BTREE'
test.done()
it 'should remove single-column index', (test) ->
User.defineProperty 'email', type: String, index: false
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok !ixs.email
test.done()
it 'should update multi-column index when order of columns changed', (test) ->
User.schema.adapter._models.User.settings.indexes.index1.columns = 'createdByAdmin, email'
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.equals ixs.index1.Column_name, 'createdByAdmin'
test.done()
it 'test', (test) ->
User.defineProperty 'email', type: String, index: true
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
test.done()
it 'should disconnect when done', (test) ->
schema.disconnect()
test.done()
| 215023 | juggling = require('jugglingdb')
Schema = juggling.Schema
Text = Schema.Text
DBNAME = 'myapp_test'
DBUSER = 'root'
DBPASS = ''
DBENGINE = 'mysql'
schema = new Schema __dirname + '/..', database: '', username: DBUSER, password: <PASSWORD>
schema.log = (q) -> console.log q
query = (sql, cb) ->
schema.adapter.query sql, cb
User = schema.define 'User',
email: { type: String, null: false, index: true }
name: String
bio: Text
order: Number
password: String
birthDate: Date
pendingPeriod: Number
createdByAdmin: Boolean
, indexes:
index1:
columns: 'email, createdByAdmin'
withBlankDatabase = (cb) ->
db = schema.settings.database = DBNAME
query 'DROP DATABASE IF EXISTS ' + db, (err) ->
query 'CREATE DATABASE ' + db, (err) ->
query 'USE '+ db, cb
getFields = (model, cb) ->
query 'SHOW FIELDS FROM ' + model, (err, res) ->
if err
cb err
else
fields = {}
res.forEach (field) -> fields[field.Field] = field
cb err, fields
getIndexes = (model, cb) ->
query 'SHOW INDEXES FROM ' + model, (err, res) ->
if err
console.log err
cb err
else
indexes = {}
# Note: this will only show the first key of compound keys
res.forEach (index) ->
indexes[index.Key_name] = index if parseInt(index.Seq_in_index, 10) == 1
cb err, indexes
it = (name, testCases) ->
module.exports[name] = testCases
it 'should run migration', (test) ->
withBlankDatabase (err) ->
schema.automigrate ->
getFields 'User', (err, fields) ->
test.deepEqual fields,
id:
Field: 'id'
Type: 'int(11)'
Null: 'NO'
Key: 'PRI'
Default: null
Extra: 'auto_increment'
email:
Field: 'email'
Type: 'varchar(255)'
Null: 'NO'
Key: 'MUL'
Default: null
Extra: ''
name:
Field: 'name'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
bio:
Field: 'bio'
Type: 'text'
Null: 'YES'
Key: ''
Default: null
Extra: ''
order:
Field: 'order'
Type: 'int(11)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
password:
Field: '<PASSWORD>'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
birthDate:
Field: 'birthDate'
Type: 'datetime'
Null: 'YES'
Key: ''
Default: null
Extra: ''
pendingPeriod:
Field: 'pendingPeriod'
Type: 'int(11)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
createdByAdmin:
Field: 'createdByAdmin'
Type: 'tinyint(1)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
# Once gain, getIdexes truncates multi-key indexes to the first member. Hence index1 is correct.
getIndexes 'User', (err, fields) ->
test.deepEqual fields,
PRIMARY:
Table: 'User'
Non_unique: 0
Key_name: 'PRIMARY'
Seq_in_index: 1
Column_name: 'id'
Collation: 'A'
Cardinality: 0
Sub_part: null
Packed: null
Null: ''
Index_type: 'BTREE'
Comment: ''
Index_comment: ''
email:
Table: 'User'
Non_unique: 1
Key_name: 'email'
Seq_in_index: 1
Column_name: 'email'
Collation: 'A'
Cardinality: 0
Sub_part: null
Packed: null
Null: ''
Index_type: 'BTREE'
Comment: ''
Index_comment: ''
index1:
Table: 'User'
Non_unique: 1
Key_name: 'index1'
Seq_in_index: 1
Column_name: 'email'
Collation: 'A'
Cardinality: 0
Sub_part: null
Packed: null
Null: ''
Index_type: 'BTREE'
Comment: ''
Index_comment: ''
test.done()
it 'should autoupgrade', (test) ->
userExists = (cb) ->
query 'SELECT * FROM User', (err, res) ->
cb(not err and res[0].email == '<EMAIL>')
User.create email: '<EMAIL>', (err, user) ->
test.ok not err
userExists (yep) ->
test.ok yep
User.defineProperty 'email', type: String
User.defineProperty 'name', type: String, limit: 50
User.defineProperty 'newProperty', type: Number
User.defineProperty 'pendingPeriod', false
schema.autoupdate (err) ->
getFields 'User', (err, fields) ->
# change nullable for email
test.equal fields.email.Null, 'YES', 'Email is not null'
# change type of name
test.equal fields.name.Type, 'varchar(50)', 'Name is not varchar(50)'
# add new column
test.ok fields.newProperty, 'New column was not added'
if fields.newProperty
test.equal fields.newProperty.Type, 'int(11)', 'New column type is not int(11)'
# drop column
test.ok not fields.pendingPeriod, 'drop column'
# user still exists
userExists (yep) ->
test.ok yep
test.done()
it "record should be updated", (done) ->
userExists = (cb) ->
query "SELECT * FROM UserData", (err, res) ->
cb not err and res[0].email is "<EMAIL>"
UserData.update
where:
id: "1"
update:
email: "<EMAIL>"
, (err, o) ->
userExists (yep) ->
assert.ok yep, "Email has changed"
# err when where missing
UserData.update
update:
email: "<EMAIL>"
, (err, o) ->
assert.equal err, "Where or Update fields are missing", " no error when where field is missing "
# err when where update
UserData.update
where:
id: "1"
, (err, o) ->
assert.equal err, "Where or Update fields are missing", " no error when update field is missing "
done()
it 'should check actuality of schema', (test) ->
# drop column
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.defineProperty 'email', false
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
test.done()
it 'should add single-column index', (test) ->
User.defineProperty 'email', type: String, index: { kind: 'FULLTEXT', type: 'HASH'}
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok ixs.email && ixs.email.Column_name == 'email'
console.log(ixs)
test.equal ixs.email.Index_type, 'BTREE', 'default index type'
test.done()
it 'should change type of single-column index', (test) ->
User.defineProperty 'email', type: String, index: { type: 'BTREE' }
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok ixs.email && ixs.email.Column_name == 'email'
test.equal ixs.email.Index_type, 'BTREE'
test.done()
it 'should remove single-column index', (test) ->
User.defineProperty 'email', type: String, index: false
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok !ixs.email
test.done()
it 'should update multi-column index when order of columns changed', (test) ->
User.schema.adapter._models.User.settings.indexes.index1.columns = 'createdByAdmin, email'
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.equals ixs.index1.Column_name, 'createdByAdmin'
test.done()
it 'test', (test) ->
User.defineProperty 'email', type: String, index: true
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
test.done()
it 'should disconnect when done', (test) ->
schema.disconnect()
test.done()
| true | juggling = require('jugglingdb')
Schema = juggling.Schema
Text = Schema.Text
DBNAME = 'myapp_test'
DBUSER = 'root'
DBPASS = ''
DBENGINE = 'mysql'
schema = new Schema __dirname + '/..', database: '', username: DBUSER, password: PI:PASSWORD:<PASSWORD>END_PI
schema.log = (q) -> console.log q
query = (sql, cb) ->
schema.adapter.query sql, cb
User = schema.define 'User',
email: { type: String, null: false, index: true }
name: String
bio: Text
order: Number
password: String
birthDate: Date
pendingPeriod: Number
createdByAdmin: Boolean
, indexes:
index1:
columns: 'email, createdByAdmin'
withBlankDatabase = (cb) ->
db = schema.settings.database = DBNAME
query 'DROP DATABASE IF EXISTS ' + db, (err) ->
query 'CREATE DATABASE ' + db, (err) ->
query 'USE '+ db, cb
getFields = (model, cb) ->
query 'SHOW FIELDS FROM ' + model, (err, res) ->
if err
cb err
else
fields = {}
res.forEach (field) -> fields[field.Field] = field
cb err, fields
getIndexes = (model, cb) ->
query 'SHOW INDEXES FROM ' + model, (err, res) ->
if err
console.log err
cb err
else
indexes = {}
# Note: this will only show the first key of compound keys
res.forEach (index) ->
indexes[index.Key_name] = index if parseInt(index.Seq_in_index, 10) == 1
cb err, indexes
it = (name, testCases) ->
module.exports[name] = testCases
it 'should run migration', (test) ->
withBlankDatabase (err) ->
schema.automigrate ->
getFields 'User', (err, fields) ->
test.deepEqual fields,
id:
Field: 'id'
Type: 'int(11)'
Null: 'NO'
Key: 'PRI'
Default: null
Extra: 'auto_increment'
email:
Field: 'email'
Type: 'varchar(255)'
Null: 'NO'
Key: 'MUL'
Default: null
Extra: ''
name:
Field: 'name'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
bio:
Field: 'bio'
Type: 'text'
Null: 'YES'
Key: ''
Default: null
Extra: ''
order:
Field: 'order'
Type: 'int(11)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
password:
Field: 'PI:PASSWORD:<PASSWORD>END_PI'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
birthDate:
Field: 'birthDate'
Type: 'datetime'
Null: 'YES'
Key: ''
Default: null
Extra: ''
pendingPeriod:
Field: 'pendingPeriod'
Type: 'int(11)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
createdByAdmin:
Field: 'createdByAdmin'
Type: 'tinyint(1)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
# Once gain, getIdexes truncates multi-key indexes to the first member. Hence index1 is correct.
getIndexes 'User', (err, fields) ->
test.deepEqual fields,
PRIMARY:
Table: 'User'
Non_unique: 0
Key_name: 'PRIMARY'
Seq_in_index: 1
Column_name: 'id'
Collation: 'A'
Cardinality: 0
Sub_part: null
Packed: null
Null: ''
Index_type: 'BTREE'
Comment: ''
Index_comment: ''
email:
Table: 'User'
Non_unique: 1
Key_name: 'email'
Seq_in_index: 1
Column_name: 'email'
Collation: 'A'
Cardinality: 0
Sub_part: null
Packed: null
Null: ''
Index_type: 'BTREE'
Comment: ''
Index_comment: ''
index1:
Table: 'User'
Non_unique: 1
Key_name: 'index1'
Seq_in_index: 1
Column_name: 'email'
Collation: 'A'
Cardinality: 0
Sub_part: null
Packed: null
Null: ''
Index_type: 'BTREE'
Comment: ''
Index_comment: ''
test.done()
it 'should autoupgrade', (test) ->
userExists = (cb) ->
query 'SELECT * FROM User', (err, res) ->
cb(not err and res[0].email == 'PI:EMAIL:<EMAIL>END_PI')
User.create email: 'PI:EMAIL:<EMAIL>END_PI', (err, user) ->
test.ok not err
userExists (yep) ->
test.ok yep
User.defineProperty 'email', type: String
User.defineProperty 'name', type: String, limit: 50
User.defineProperty 'newProperty', type: Number
User.defineProperty 'pendingPeriod', false
schema.autoupdate (err) ->
getFields 'User', (err, fields) ->
# change nullable for email
test.equal fields.email.Null, 'YES', 'Email is not null'
# change type of name
test.equal fields.name.Type, 'varchar(50)', 'Name is not varchar(50)'
# add new column
test.ok fields.newProperty, 'New column was not added'
if fields.newProperty
test.equal fields.newProperty.Type, 'int(11)', 'New column type is not int(11)'
# drop column
test.ok not fields.pendingPeriod, 'drop column'
# user still exists
userExists (yep) ->
test.ok yep
test.done()
it "record should be updated", (done) ->
userExists = (cb) ->
query "SELECT * FROM UserData", (err, res) ->
cb not err and res[0].email is "PI:EMAIL:<EMAIL>END_PI"
UserData.update
where:
id: "1"
update:
email: "PI:EMAIL:<EMAIL>END_PI"
, (err, o) ->
userExists (yep) ->
assert.ok yep, "Email has changed"
# err when where missing
UserData.update
update:
email: "PI:EMAIL:<EMAIL>END_PI"
, (err, o) ->
assert.equal err, "Where or Update fields are missing", " no error when where field is missing "
# err when where update
UserData.update
where:
id: "1"
, (err, o) ->
assert.equal err, "Where or Update fields are missing", " no error when update field is missing "
done()
it 'should check actuality of schema', (test) ->
# drop column
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.defineProperty 'email', false
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
test.done()
it 'should add single-column index', (test) ->
User.defineProperty 'email', type: String, index: { kind: 'FULLTEXT', type: 'HASH'}
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok ixs.email && ixs.email.Column_name == 'email'
console.log(ixs)
test.equal ixs.email.Index_type, 'BTREE', 'default index type'
test.done()
it 'should change type of single-column index', (test) ->
User.defineProperty 'email', type: String, index: { type: 'BTREE' }
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok ixs.email && ixs.email.Column_name == 'email'
test.equal ixs.email.Index_type, 'BTREE'
test.done()
it 'should remove single-column index', (test) ->
User.defineProperty 'email', type: String, index: false
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok !ixs.email
test.done()
it 'should update multi-column index when order of columns changed', (test) ->
User.schema.adapter._models.User.settings.indexes.index1.columns = 'createdByAdmin, email'
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.equals ixs.index1.Column_name, 'createdByAdmin'
test.done()
it 'test', (test) ->
User.defineProperty 'email', type: String, index: true
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
test.done()
it 'should disconnect when done', (test) ->
schema.disconnect()
test.done()
|
[
{
"context": "ves, linked to points in 0, 1, or 2 scatterplots\n# Karl W Broman\n\niplotCurves = (curve_data, scatter1_data, scatte",
"end": 101,
"score": 0.9998623728752136,
"start": 88,
"tag": "NAME",
"value": "Karl W Broman"
}
] | inst/charts/iplotCurves.coffee | FourchettesDeInterActive/qtlcharts | 0 | # iplotCurves: Plot of a bunch of curves, linked to points in 0, 1, or 2 scatterplots
# Karl W Broman
iplotCurves = (curve_data, scatter1_data, scatter2_data, chartOpts) ->
# chartOpts start
htop = chartOpts?.htop ? 500 # height of curves chart in pixels
hbot = chartOpts?.hbot ? 500 # height of scatterplots in pixels
width = chartOpts?.width ? 1000 # width of chart in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of background rectangle
pointcolor = chartOpts?.pointcolor ? chartOpts?.color ? null # vector of colors for points in scatterplots
pointstroke = chartOpts?.pointstroke ? "black" # color of line outline for points in scatterplots
pointsize = chartOpts?.pointsize ? 3 # size of points in scatterplots
pointcolorhilit = chartOpts?.pointcolorhilit ? chartOpts?.colorhilit ? null # vector of colors for points in scatterplots, when highlighted
pointsizehilit = chartOpts?.pointsizehilit ? 6 # zie of points in scatterplot, when highlighted
strokecolor = chartOpts?.strokecolor ? chartOpts?.color ? null # vector of colors of curves
strokecolorhilit = chartOpts?.strokecolorhilit ? chartOpts?.colorhilit ? null # vector of colors of curves, when highlighted
strokewidth = chartOpts?.strokewidth ? 2 # line width of curves
strokewidthhilit = chartOpts?.strokewidthhilit ? 2 # line widths of curves, when highlighted
curves_xlim = chartOpts?.curves_xlim ? null # x-axis limits in curve plot
curves_ylim = chartOpts?.curves_ylim ? null # y-axis limits in curve plot
curves_nxticks = chartOpts?.curves_nxticks ? 5 # no. ticks on x-axis in curve plot
curves_xticks = chartOpts?.curves_xticks ? null # vector of tick positions on x-axis in curve plot
curves_nyticks = chartOpts?.curves_nyticks ? 5 # no. ticks on y-axis in curve plot
curves_yticks = chartOpts?.curves_yticks ? null # vector of tick positions on y-axis in curve plot
curves_title = chartOpts?.curves_title ? "" # title for curve plot
curves_xlab = chartOpts?.curves_xlab ? chartOpts?.xlab ? "X" # x-axis label for curve plot
curves_ylab = chartOpts?.curves_ylab ? chartOpts?.ylab ? "Y" # y-axis label for curve plot
scat1_xlim = chartOpts?.scat1_xlim ? null # x-axis limits in first scatterplot
scat1_ylim = chartOpts?.scat1_ylim ? null # y-axis limits in first scatterplot
scat1_xNA = chartOpts?.scat1_xNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in first scatterplot (handle=T/F, force=T/F, width, gap)
scat1_yNA = chartOpts?.scat1_yNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in first scatterplot (handle=T/F, force=T/F, width, gap)
scat1_nxticks = chartOpts?.scat1_nxticks ? 5 # no. ticks on x-axis in first scatterplot
scat1_xticks = chartOpts?.scat1_xticks ? null # vector of tick positions on x-axis in first scatterplot
scat1_nyticks = chartOpts?.scat1_nyticks ? 5 # no. ticks on y-axis in first scatterplot
scat1_yticks = chartOpts?.scat1_yticks ? null # vector of tick positions on y-axis in first scatterplot
scat1_title = chartOpts?.scat1_title ? "" # title for first scatterplot
scat1_xlab = chartOpts?.scat1_xlab ? "X" # x-axis label for first scatterplot
scat1_ylab = chartOpts?.scat1_ylab ? "Y" # y-axis label for first scatterplot
scat2_xlim = chartOpts?.scat2_xlim ? null # x-axis limits in second scatterplot
scat2_ylim = chartOpts?.scat2_ylim ? null # y-axis limits in second scatterplot
scat2_xNA = chartOpts?.scat2_xNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in second scatterplot (handle=T/F, force=T/F, width, gap)
scat2_yNA = chartOpts?.scat2_yNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in second scatterplot (handle=T/F, force=T/F, width, gap)
scat2_nxticks = chartOpts?.scat2_nxticks ? 5 # no. ticks on x-axis in second scatterplot
scat2_xticks = chartOpts?.scat2_xticks ? null # vector of tick positions on x-axis in second scatterplot
scat2_nyticks = chartOpts?.scat2_nyticks ? 5 # no. ticks on y-axis in second scatterplot
scat2_yticks = chartOpts?.scat2_yticks ? null # vector of tick positions on y-axis in second scatterplot
scat2_title = chartOpts?.scat2_title ? "" # title for second scatterplot
scat2_xlab = chartOpts?.scat2_xlab ? "X" # x-axis label for second scatterplot
scat2_ylab = chartOpts?.scat2_ylab ? "Y" # y-axis label for second scatterplot
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
# number of scatterplots
nscatter = (scatter1_data?) + (scatter2_data?)
totalh = if nscatter==0 then (htop + margin.top + margin.bottom) else (htop + hbot + 2*(margin.top + margin.bottom))
totalw = width + margin.left + margin.right
wbot = (width - margin.left - margin.right)/2
# Select the svg element, if it exists.
svg = d3.select("div##{chartdivid}")
.append("svg")
.attr("height", totalh)
.attr("width", totalw)
# groups of colors
nind = curve_data.data.length
group = curve_data?.group ? (1 for i in curve_data.data)
ngroup = d3.max(group)
group = (g-1 for g in group) # changed from (1,2,3,...) to (0,1,2,...)
# colors of the points in the different groups
pointcolor = pointcolor ? selectGroupColors(ngroup, "light")
pointcolorhilit = pointcolorhilit ? selectGroupColors(ngroup, "dark")
strokecolor = strokecolor ? selectGroupColors(ngroup, "light")
strokecolorhilit = strokecolorhilit ? selectGroupColors(ngroup, "dark")
## configure the three charts
mycurvechart = curvechart().width(width)
.height(htop)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.rectcolor(rectcolor)
.strokecolor(strokecolor)
.strokecolorhilit(strokecolorhilit)
.strokewidth(strokewidth)
.strokewidthhilit(strokewidthhilit)
.xlim(curves_xlim)
.ylim(curves_ylim)
.nxticks(curves_nxticks)
.xticks(curves_xticks)
.nyticks(curves_nyticks)
.yticks(curves_yticks)
.title(curves_title)
.xlab(curves_xlab)
.ylab(curves_ylab)
if nscatter > 0
myscatterplot1 = scatterplot().width(wbot)
.height(hbot)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.rectcolor(rectcolor)
.pointcolor(pointcolor)
.pointstroke(pointstroke)
.pointsize(pointsize)
.xlim(scat1_xlim)
.ylim(scat1_ylim)
.xNA(scat1_xNA)
.yNA(scat1_yNA)
.nxticks(scat1_nxticks)
.xticks(scat1_xticks)
.nyticks(scat1_nyticks)
.yticks(scat1_yticks)
.title(scat1_title)
.xlab(scat1_xlab)
.ylab(scat1_ylab)
if nscatter == 2
myscatterplot2 = scatterplot().width(wbot)
.height(hbot)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.rectcolor(rectcolor)
.pointcolor(pointcolor)
.pointstroke(pointstroke)
.pointsize(pointsize)
.xlim(scat2_xlim)
.ylim(scat2_ylim)
.xNA(scat2_xNA)
.yNA(scat2_yNA)
.nxticks(scat2_nxticks)
.xticks(scat2_xticks)
.nyticks(scat2_nyticks)
.yticks(scat2_yticks)
.title(scat2_title)
.xlab(scat2_xlab)
.ylab(scat2_ylab)
## now make the actual charts
g_curves = svg.append("g")
.attr("id", "curvechart")
.datum(curve_data)
.call(mycurvechart)
shiftdown = htop+margin.top+margin.bottom
if nscatter > 0
g_scat1 = svg.append("g")
.attr("id", "scatterplot1")
.attr("transform", "translate(0,#{shiftdown})")
.datum(scatter1_data)
.call(myscatterplot1)
if nscatter == 2
g_scat2 = svg.append("g")
.attr("id", "scatterplot2")
.attr("transform", "translate(#{wbot+margin.left+margin.right},#{shiftdown})")
.datum(scatter2_data)
.call(myscatterplot2)
points1 = myscatterplot1.pointsSelect() if nscatter > 0
points2 = myscatterplot2.pointsSelect() if nscatter == 2
allpoints = [points1] if nscatter == 1
allpoints = [points1, points2] if nscatter == 2
curves = mycurvechart.curvesSelect()
# expand pointcolor and pointcolorhilit to length of group
pointcolor = expand2vector(pointcolor, ngroup)
pointcolorhilit = expand2vector(pointcolorhilit, ngroup)
strokecolor = expand2vector(strokecolor, ngroup)
strokecolorhilit = expand2vector(strokecolorhilit, ngroup)
curves.on "mouseover", (d,i) ->
d3.select(this).attr("stroke", strokecolorhilit[group[i]]).moveToFront()
d3.selectAll("circle.pt#{i}").attr("r", pointsizehilit) if nscatter > 0
d3.selectAll("circle.pt#{i}").attr("fill", pointcolorhilit[group[i]]) if nscatter > 0
.on "mouseout", (d,i) ->
d3.select(this).attr("stroke", strokecolor[group[i]]).moveToBack()
d3.selectAll("circle.pt#{i}").attr("r", pointsize) if nscatter > 0
d3.selectAll("circle.pt#{i}").attr("fill", pointcolor[group[i]]) if nscatter > 0
if nscatter > 0
allpoints.forEach (points) ->
points.on "mouseover", (d,i) ->
d3.selectAll("circle.pt#{i}").attr("r", pointsizehilit)
d3.selectAll("circle.pt#{i}").attr("fill", pointcolorhilit[group[i]])
d3.select("path.path#{i}").attr("stroke", strokecolorhilit[group[i]]).moveToFront()
.on "mouseout", (d,i) ->
d3.selectAll("circle.pt#{i}").attr("r", pointsize)
d3.selectAll("circle.pt#{i}").attr("fill", pointcolor[group[i]])
d3.select("path.path#{i}").attr("stroke", strokecolor[group[i]]).moveToBack()
| 26986 | # iplotCurves: Plot of a bunch of curves, linked to points in 0, 1, or 2 scatterplots
# <NAME>
iplotCurves = (curve_data, scatter1_data, scatter2_data, chartOpts) ->
# chartOpts start
htop = chartOpts?.htop ? 500 # height of curves chart in pixels
hbot = chartOpts?.hbot ? 500 # height of scatterplots in pixels
width = chartOpts?.width ? 1000 # width of chart in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of background rectangle
pointcolor = chartOpts?.pointcolor ? chartOpts?.color ? null # vector of colors for points in scatterplots
pointstroke = chartOpts?.pointstroke ? "black" # color of line outline for points in scatterplots
pointsize = chartOpts?.pointsize ? 3 # size of points in scatterplots
pointcolorhilit = chartOpts?.pointcolorhilit ? chartOpts?.colorhilit ? null # vector of colors for points in scatterplots, when highlighted
pointsizehilit = chartOpts?.pointsizehilit ? 6 # zie of points in scatterplot, when highlighted
strokecolor = chartOpts?.strokecolor ? chartOpts?.color ? null # vector of colors of curves
strokecolorhilit = chartOpts?.strokecolorhilit ? chartOpts?.colorhilit ? null # vector of colors of curves, when highlighted
strokewidth = chartOpts?.strokewidth ? 2 # line width of curves
strokewidthhilit = chartOpts?.strokewidthhilit ? 2 # line widths of curves, when highlighted
curves_xlim = chartOpts?.curves_xlim ? null # x-axis limits in curve plot
curves_ylim = chartOpts?.curves_ylim ? null # y-axis limits in curve plot
curves_nxticks = chartOpts?.curves_nxticks ? 5 # no. ticks on x-axis in curve plot
curves_xticks = chartOpts?.curves_xticks ? null # vector of tick positions on x-axis in curve plot
curves_nyticks = chartOpts?.curves_nyticks ? 5 # no. ticks on y-axis in curve plot
curves_yticks = chartOpts?.curves_yticks ? null # vector of tick positions on y-axis in curve plot
curves_title = chartOpts?.curves_title ? "" # title for curve plot
curves_xlab = chartOpts?.curves_xlab ? chartOpts?.xlab ? "X" # x-axis label for curve plot
curves_ylab = chartOpts?.curves_ylab ? chartOpts?.ylab ? "Y" # y-axis label for curve plot
scat1_xlim = chartOpts?.scat1_xlim ? null # x-axis limits in first scatterplot
scat1_ylim = chartOpts?.scat1_ylim ? null # y-axis limits in first scatterplot
scat1_xNA = chartOpts?.scat1_xNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in first scatterplot (handle=T/F, force=T/F, width, gap)
scat1_yNA = chartOpts?.scat1_yNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in first scatterplot (handle=T/F, force=T/F, width, gap)
scat1_nxticks = chartOpts?.scat1_nxticks ? 5 # no. ticks on x-axis in first scatterplot
scat1_xticks = chartOpts?.scat1_xticks ? null # vector of tick positions on x-axis in first scatterplot
scat1_nyticks = chartOpts?.scat1_nyticks ? 5 # no. ticks on y-axis in first scatterplot
scat1_yticks = chartOpts?.scat1_yticks ? null # vector of tick positions on y-axis in first scatterplot
scat1_title = chartOpts?.scat1_title ? "" # title for first scatterplot
scat1_xlab = chartOpts?.scat1_xlab ? "X" # x-axis label for first scatterplot
scat1_ylab = chartOpts?.scat1_ylab ? "Y" # y-axis label for first scatterplot
scat2_xlim = chartOpts?.scat2_xlim ? null # x-axis limits in second scatterplot
scat2_ylim = chartOpts?.scat2_ylim ? null # y-axis limits in second scatterplot
scat2_xNA = chartOpts?.scat2_xNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in second scatterplot (handle=T/F, force=T/F, width, gap)
scat2_yNA = chartOpts?.scat2_yNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in second scatterplot (handle=T/F, force=T/F, width, gap)
scat2_nxticks = chartOpts?.scat2_nxticks ? 5 # no. ticks on x-axis in second scatterplot
scat2_xticks = chartOpts?.scat2_xticks ? null # vector of tick positions on x-axis in second scatterplot
scat2_nyticks = chartOpts?.scat2_nyticks ? 5 # no. ticks on y-axis in second scatterplot
scat2_yticks = chartOpts?.scat2_yticks ? null # vector of tick positions on y-axis in second scatterplot
scat2_title = chartOpts?.scat2_title ? "" # title for second scatterplot
scat2_xlab = chartOpts?.scat2_xlab ? "X" # x-axis label for second scatterplot
scat2_ylab = chartOpts?.scat2_ylab ? "Y" # y-axis label for second scatterplot
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
# number of scatterplots
nscatter = (scatter1_data?) + (scatter2_data?)
totalh = if nscatter==0 then (htop + margin.top + margin.bottom) else (htop + hbot + 2*(margin.top + margin.bottom))
totalw = width + margin.left + margin.right
wbot = (width - margin.left - margin.right)/2
# Select the svg element, if it exists.
svg = d3.select("div##{chartdivid}")
.append("svg")
.attr("height", totalh)
.attr("width", totalw)
# groups of colors
nind = curve_data.data.length
group = curve_data?.group ? (1 for i in curve_data.data)
ngroup = d3.max(group)
group = (g-1 for g in group) # changed from (1,2,3,...) to (0,1,2,...)
# colors of the points in the different groups
pointcolor = pointcolor ? selectGroupColors(ngroup, "light")
pointcolorhilit = pointcolorhilit ? selectGroupColors(ngroup, "dark")
strokecolor = strokecolor ? selectGroupColors(ngroup, "light")
strokecolorhilit = strokecolorhilit ? selectGroupColors(ngroup, "dark")
## configure the three charts
mycurvechart = curvechart().width(width)
.height(htop)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.rectcolor(rectcolor)
.strokecolor(strokecolor)
.strokecolorhilit(strokecolorhilit)
.strokewidth(strokewidth)
.strokewidthhilit(strokewidthhilit)
.xlim(curves_xlim)
.ylim(curves_ylim)
.nxticks(curves_nxticks)
.xticks(curves_xticks)
.nyticks(curves_nyticks)
.yticks(curves_yticks)
.title(curves_title)
.xlab(curves_xlab)
.ylab(curves_ylab)
if nscatter > 0
myscatterplot1 = scatterplot().width(wbot)
.height(hbot)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.rectcolor(rectcolor)
.pointcolor(pointcolor)
.pointstroke(pointstroke)
.pointsize(pointsize)
.xlim(scat1_xlim)
.ylim(scat1_ylim)
.xNA(scat1_xNA)
.yNA(scat1_yNA)
.nxticks(scat1_nxticks)
.xticks(scat1_xticks)
.nyticks(scat1_nyticks)
.yticks(scat1_yticks)
.title(scat1_title)
.xlab(scat1_xlab)
.ylab(scat1_ylab)
if nscatter == 2
myscatterplot2 = scatterplot().width(wbot)
.height(hbot)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.rectcolor(rectcolor)
.pointcolor(pointcolor)
.pointstroke(pointstroke)
.pointsize(pointsize)
.xlim(scat2_xlim)
.ylim(scat2_ylim)
.xNA(scat2_xNA)
.yNA(scat2_yNA)
.nxticks(scat2_nxticks)
.xticks(scat2_xticks)
.nyticks(scat2_nyticks)
.yticks(scat2_yticks)
.title(scat2_title)
.xlab(scat2_xlab)
.ylab(scat2_ylab)
## now make the actual charts
g_curves = svg.append("g")
.attr("id", "curvechart")
.datum(curve_data)
.call(mycurvechart)
shiftdown = htop+margin.top+margin.bottom
if nscatter > 0
g_scat1 = svg.append("g")
.attr("id", "scatterplot1")
.attr("transform", "translate(0,#{shiftdown})")
.datum(scatter1_data)
.call(myscatterplot1)
if nscatter == 2
g_scat2 = svg.append("g")
.attr("id", "scatterplot2")
.attr("transform", "translate(#{wbot+margin.left+margin.right},#{shiftdown})")
.datum(scatter2_data)
.call(myscatterplot2)
points1 = myscatterplot1.pointsSelect() if nscatter > 0
points2 = myscatterplot2.pointsSelect() if nscatter == 2
allpoints = [points1] if nscatter == 1
allpoints = [points1, points2] if nscatter == 2
curves = mycurvechart.curvesSelect()
# expand pointcolor and pointcolorhilit to length of group
pointcolor = expand2vector(pointcolor, ngroup)
pointcolorhilit = expand2vector(pointcolorhilit, ngroup)
strokecolor = expand2vector(strokecolor, ngroup)
strokecolorhilit = expand2vector(strokecolorhilit, ngroup)
curves.on "mouseover", (d,i) ->
d3.select(this).attr("stroke", strokecolorhilit[group[i]]).moveToFront()
d3.selectAll("circle.pt#{i}").attr("r", pointsizehilit) if nscatter > 0
d3.selectAll("circle.pt#{i}").attr("fill", pointcolorhilit[group[i]]) if nscatter > 0
.on "mouseout", (d,i) ->
d3.select(this).attr("stroke", strokecolor[group[i]]).moveToBack()
d3.selectAll("circle.pt#{i}").attr("r", pointsize) if nscatter > 0
d3.selectAll("circle.pt#{i}").attr("fill", pointcolor[group[i]]) if nscatter > 0
if nscatter > 0
allpoints.forEach (points) ->
points.on "mouseover", (d,i) ->
d3.selectAll("circle.pt#{i}").attr("r", pointsizehilit)
d3.selectAll("circle.pt#{i}").attr("fill", pointcolorhilit[group[i]])
d3.select("path.path#{i}").attr("stroke", strokecolorhilit[group[i]]).moveToFront()
.on "mouseout", (d,i) ->
d3.selectAll("circle.pt#{i}").attr("r", pointsize)
d3.selectAll("circle.pt#{i}").attr("fill", pointcolor[group[i]])
d3.select("path.path#{i}").attr("stroke", strokecolor[group[i]]).moveToBack()
| true | # iplotCurves: Plot of a bunch of curves, linked to points in 0, 1, or 2 scatterplots
# PI:NAME:<NAME>END_PI
iplotCurves = (curve_data, scatter1_data, scatter2_data, chartOpts) ->
# chartOpts start
htop = chartOpts?.htop ? 500 # height of curves chart in pixels
hbot = chartOpts?.hbot ? 500 # height of scatterplots in pixels
width = chartOpts?.width ? 1000 # width of chart in pixels
margin = chartOpts?.margin ? {left:60, top:40, right:40, bottom: 40, inner:5} # margins in pixels (left, top, right, bottom, inner)
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # position of axis labels in pixels (xtitle, ytitle, xlabel, ylabel)
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
rectcolor = chartOpts?.rectcolor ? "#E6E6E6" # color of background rectangle
pointcolor = chartOpts?.pointcolor ? chartOpts?.color ? null # vector of colors for points in scatterplots
pointstroke = chartOpts?.pointstroke ? "black" # color of line outline for points in scatterplots
pointsize = chartOpts?.pointsize ? 3 # size of points in scatterplots
pointcolorhilit = chartOpts?.pointcolorhilit ? chartOpts?.colorhilit ? null # vector of colors for points in scatterplots, when highlighted
pointsizehilit = chartOpts?.pointsizehilit ? 6 # zie of points in scatterplot, when highlighted
strokecolor = chartOpts?.strokecolor ? chartOpts?.color ? null # vector of colors of curves
strokecolorhilit = chartOpts?.strokecolorhilit ? chartOpts?.colorhilit ? null # vector of colors of curves, when highlighted
strokewidth = chartOpts?.strokewidth ? 2 # line width of curves
strokewidthhilit = chartOpts?.strokewidthhilit ? 2 # line widths of curves, when highlighted
curves_xlim = chartOpts?.curves_xlim ? null # x-axis limits in curve plot
curves_ylim = chartOpts?.curves_ylim ? null # y-axis limits in curve plot
curves_nxticks = chartOpts?.curves_nxticks ? 5 # no. ticks on x-axis in curve plot
curves_xticks = chartOpts?.curves_xticks ? null # vector of tick positions on x-axis in curve plot
curves_nyticks = chartOpts?.curves_nyticks ? 5 # no. ticks on y-axis in curve plot
curves_yticks = chartOpts?.curves_yticks ? null # vector of tick positions on y-axis in curve plot
curves_title = chartOpts?.curves_title ? "" # title for curve plot
curves_xlab = chartOpts?.curves_xlab ? chartOpts?.xlab ? "X" # x-axis label for curve plot
curves_ylab = chartOpts?.curves_ylab ? chartOpts?.ylab ? "Y" # y-axis label for curve plot
scat1_xlim = chartOpts?.scat1_xlim ? null # x-axis limits in first scatterplot
scat1_ylim = chartOpts?.scat1_ylim ? null # y-axis limits in first scatterplot
scat1_xNA = chartOpts?.scat1_xNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in first scatterplot (handle=T/F, force=T/F, width, gap)
scat1_yNA = chartOpts?.scat1_yNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in first scatterplot (handle=T/F, force=T/F, width, gap)
scat1_nxticks = chartOpts?.scat1_nxticks ? 5 # no. ticks on x-axis in first scatterplot
scat1_xticks = chartOpts?.scat1_xticks ? null # vector of tick positions on x-axis in first scatterplot
scat1_nyticks = chartOpts?.scat1_nyticks ? 5 # no. ticks on y-axis in first scatterplot
scat1_yticks = chartOpts?.scat1_yticks ? null # vector of tick positions on y-axis in first scatterplot
scat1_title = chartOpts?.scat1_title ? "" # title for first scatterplot
scat1_xlab = chartOpts?.scat1_xlab ? "X" # x-axis label for first scatterplot
scat1_ylab = chartOpts?.scat1_ylab ? "Y" # y-axis label for first scatterplot
scat2_xlim = chartOpts?.scat2_xlim ? null # x-axis limits in second scatterplot
scat2_ylim = chartOpts?.scat2_ylim ? null # y-axis limits in second scatterplot
scat2_xNA = chartOpts?.scat2_xNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in second scatterplot (handle=T/F, force=T/F, width, gap)
scat2_yNA = chartOpts?.scat2_yNA ? {handle:true, force:false, width:15, gap:10} # treatment of missing values for x variable in second scatterplot (handle=T/F, force=T/F, width, gap)
scat2_nxticks = chartOpts?.scat2_nxticks ? 5 # no. ticks on x-axis in second scatterplot
scat2_xticks = chartOpts?.scat2_xticks ? null # vector of tick positions on x-axis in second scatterplot
scat2_nyticks = chartOpts?.scat2_nyticks ? 5 # no. ticks on y-axis in second scatterplot
scat2_yticks = chartOpts?.scat2_yticks ? null # vector of tick positions on y-axis in second scatterplot
scat2_title = chartOpts?.scat2_title ? "" # title for second scatterplot
scat2_xlab = chartOpts?.scat2_xlab ? "X" # x-axis label for second scatterplot
scat2_ylab = chartOpts?.scat2_ylab ? "Y" # y-axis label for second scatterplot
# chartOpts end
chartdivid = chartOpts?.chartdivid ? 'chart'
# number of scatterplots
nscatter = (scatter1_data?) + (scatter2_data?)
totalh = if nscatter==0 then (htop + margin.top + margin.bottom) else (htop + hbot + 2*(margin.top + margin.bottom))
totalw = width + margin.left + margin.right
wbot = (width - margin.left - margin.right)/2
# Select the svg element, if it exists.
svg = d3.select("div##{chartdivid}")
.append("svg")
.attr("height", totalh)
.attr("width", totalw)
# groups of colors
nind = curve_data.data.length
group = curve_data?.group ? (1 for i in curve_data.data)
ngroup = d3.max(group)
group = (g-1 for g in group) # changed from (1,2,3,...) to (0,1,2,...)
# colors of the points in the different groups
pointcolor = pointcolor ? selectGroupColors(ngroup, "light")
pointcolorhilit = pointcolorhilit ? selectGroupColors(ngroup, "dark")
strokecolor = strokecolor ? selectGroupColors(ngroup, "light")
strokecolorhilit = strokecolorhilit ? selectGroupColors(ngroup, "dark")
## configure the three charts
mycurvechart = curvechart().width(width)
.height(htop)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.rectcolor(rectcolor)
.strokecolor(strokecolor)
.strokecolorhilit(strokecolorhilit)
.strokewidth(strokewidth)
.strokewidthhilit(strokewidthhilit)
.xlim(curves_xlim)
.ylim(curves_ylim)
.nxticks(curves_nxticks)
.xticks(curves_xticks)
.nyticks(curves_nyticks)
.yticks(curves_yticks)
.title(curves_title)
.xlab(curves_xlab)
.ylab(curves_ylab)
if nscatter > 0
myscatterplot1 = scatterplot().width(wbot)
.height(hbot)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.rectcolor(rectcolor)
.pointcolor(pointcolor)
.pointstroke(pointstroke)
.pointsize(pointsize)
.xlim(scat1_xlim)
.ylim(scat1_ylim)
.xNA(scat1_xNA)
.yNA(scat1_yNA)
.nxticks(scat1_nxticks)
.xticks(scat1_xticks)
.nyticks(scat1_nyticks)
.yticks(scat1_yticks)
.title(scat1_title)
.xlab(scat1_xlab)
.ylab(scat1_ylab)
if nscatter == 2
myscatterplot2 = scatterplot().width(wbot)
.height(hbot)
.margin(margin)
.axispos(axispos)
.titlepos(titlepos)
.rectcolor(rectcolor)
.pointcolor(pointcolor)
.pointstroke(pointstroke)
.pointsize(pointsize)
.xlim(scat2_xlim)
.ylim(scat2_ylim)
.xNA(scat2_xNA)
.yNA(scat2_yNA)
.nxticks(scat2_nxticks)
.xticks(scat2_xticks)
.nyticks(scat2_nyticks)
.yticks(scat2_yticks)
.title(scat2_title)
.xlab(scat2_xlab)
.ylab(scat2_ylab)
## now make the actual charts
g_curves = svg.append("g")
.attr("id", "curvechart")
.datum(curve_data)
.call(mycurvechart)
shiftdown = htop+margin.top+margin.bottom
if nscatter > 0
g_scat1 = svg.append("g")
.attr("id", "scatterplot1")
.attr("transform", "translate(0,#{shiftdown})")
.datum(scatter1_data)
.call(myscatterplot1)
if nscatter == 2
g_scat2 = svg.append("g")
.attr("id", "scatterplot2")
.attr("transform", "translate(#{wbot+margin.left+margin.right},#{shiftdown})")
.datum(scatter2_data)
.call(myscatterplot2)
points1 = myscatterplot1.pointsSelect() if nscatter > 0
points2 = myscatterplot2.pointsSelect() if nscatter == 2
allpoints = [points1] if nscatter == 1
allpoints = [points1, points2] if nscatter == 2
curves = mycurvechart.curvesSelect()
# expand pointcolor and pointcolorhilit to length of group
pointcolor = expand2vector(pointcolor, ngroup)
pointcolorhilit = expand2vector(pointcolorhilit, ngroup)
strokecolor = expand2vector(strokecolor, ngroup)
strokecolorhilit = expand2vector(strokecolorhilit, ngroup)
curves.on "mouseover", (d,i) ->
d3.select(this).attr("stroke", strokecolorhilit[group[i]]).moveToFront()
d3.selectAll("circle.pt#{i}").attr("r", pointsizehilit) if nscatter > 0
d3.selectAll("circle.pt#{i}").attr("fill", pointcolorhilit[group[i]]) if nscatter > 0
.on "mouseout", (d,i) ->
d3.select(this).attr("stroke", strokecolor[group[i]]).moveToBack()
d3.selectAll("circle.pt#{i}").attr("r", pointsize) if nscatter > 0
d3.selectAll("circle.pt#{i}").attr("fill", pointcolor[group[i]]) if nscatter > 0
if nscatter > 0
allpoints.forEach (points) ->
points.on "mouseover", (d,i) ->
d3.selectAll("circle.pt#{i}").attr("r", pointsizehilit)
d3.selectAll("circle.pt#{i}").attr("fill", pointcolorhilit[group[i]])
d3.select("path.path#{i}").attr("stroke", strokecolorhilit[group[i]]).moveToFront()
.on "mouseout", (d,i) ->
d3.selectAll("circle.pt#{i}").attr("r", pointsize)
d3.selectAll("circle.pt#{i}").attr("fill", pointcolor[group[i]])
d3.select("path.path#{i}").attr("stroke", strokecolor[group[i]]).moveToBack()
|
[
{
"context": "ducts: ->\n products = [\n {\n name: \"HTC Wildfire\", description: \"Old android phone\",\n manuf",
"end": 111,
"score": 0.6804338097572327,
"start": 99,
"tag": "NAME",
"value": "HTC Wildfire"
}
] | server/lib/fixtures.coffee | lucassus/angular-coffee-seed | 2 | faker = require("Faker")
module.exports =
products: ->
products = [
{
name: "HTC Wildfire", description: "Old android phone",
manufacturer: "HTC",
price: 499.99, discount: 10
}
{ name: "iPhone", price: 2500 }
{ name: "Nexus One", price: 1000, discount: 7 }
{ name: "Nexus 7", price: 1200, discount: 12 }
{ name: "Samsung Galaxy Note", price: 2699, discount: 0 }
{ name: "Samsung S4", price: 3000, discount: 2 }
]
for product in products
product.description ?= faker.Lorem.paragraphs(3)
product.manufacturer ?= faker.Company.companyName()
product.headline ?= faker.Company.catchPhrase()
products
| 24573 | faker = require("Faker")
module.exports =
products: ->
products = [
{
name: "<NAME>", description: "Old android phone",
manufacturer: "HTC",
price: 499.99, discount: 10
}
{ name: "iPhone", price: 2500 }
{ name: "Nexus One", price: 1000, discount: 7 }
{ name: "Nexus 7", price: 1200, discount: 12 }
{ name: "Samsung Galaxy Note", price: 2699, discount: 0 }
{ name: "Samsung S4", price: 3000, discount: 2 }
]
for product in products
product.description ?= faker.Lorem.paragraphs(3)
product.manufacturer ?= faker.Company.companyName()
product.headline ?= faker.Company.catchPhrase()
products
| true | faker = require("Faker")
module.exports =
products: ->
products = [
{
name: "PI:NAME:<NAME>END_PI", description: "Old android phone",
manufacturer: "HTC",
price: 499.99, discount: 10
}
{ name: "iPhone", price: 2500 }
{ name: "Nexus One", price: 1000, discount: 7 }
{ name: "Nexus 7", price: 1200, discount: 12 }
{ name: "Samsung Galaxy Note", price: 2699, discount: 0 }
{ name: "Samsung S4", price: 3000, discount: 2 }
]
for product in products
product.description ?= faker.Lorem.paragraphs(3)
product.manufacturer ?= faker.Company.companyName()
product.headline ?= faker.Company.catchPhrase()
products
|
[
{
"context": ".lint(nodes(\n '''\n field = 'howdy'\n obj =\n \"#{field}\": 1\n",
"end": 6326,
"score": 0.545425534248352,
"start": 6323,
"tag": "NAME",
"value": "how"
}
] | test/ScopeLinter/unused.coffee | zmillman/coffeescope | 0 | "use strict"
{nodes} = require "coffeescript"
ScopeLinter = require "../../src/ScopeLinter"
describe "ScopeLinter/unused", ->
it "matches trivial cases", ->
ScopeLinter.default().lint(nodes(
"""
foo = "bar"
{bar} = "bar"
"""
), {
unused_variables: true
}).should.have.length(2)
ScopeLinter.default().lint(nodes(
"""
(foo) ->
undefined
({foo}) ->
undefined
({foo} = {foo: bar}) ->
undefined
"""
), {
unused_arguments: true
}).should.have.length(3)
it "matches classes", ->
ScopeLinter.default().lint(nodes(
"""
class Foo
"""
), {
unused_classes: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
class Foo
class Bar extends Foo
"""
), {
unused_classes: true
}).should.have.length(1)
it "supports classes as properties", ->
ScopeLinter.default().lint(nodes(
"""
PROP = "Bar"
obj = {}
class obj.Foo
class obj[PROP]
"""
), {
unused_classes: true,
unused_variables: true
}).should.have.length(0)
it "ignores assigned classes", ->
ScopeLinter.default().lint(nodes(
"""
Bar = class Foo
Bar
"""
), {
unused_classes: true
}).should.have.length(0)
ScopeLinter.default().lint(nodes(
"""
class Foo
Baz = class Bar extends Foo
Baz
"""
), {
unused_classes: true
}).should.have.length(0)
it "matches recursive assignments", ->
ScopeLinter.default().lint(nodes(
"""
intervalId = setInterval ->
clearInterval intervalId
, 50
"""
), {
unused_variables: true
}).should.have.length(0)
it "doesn't match named classes that are part of an assignment", ->
ScopeLinter.default().lint(nodes(
"""
Bar = class Foo
Bar
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches for loops", ->
ScopeLinter.default().lint(nodes(
"""
for i in [1,2,3,4]
undefined
for i, index in [1,2,3,4]
undefined
for i in [0..4]
undefined
for i of {foo: "bar"}
undefined
for i, index of {foo: "bar"}
undefined
"""
), {
unused_variables: true
}).should.have.length(7)
it "issues multiple errors for the same value", ->
ScopeLinter.default().lint(nodes(
"""
foo = "bar"
{foo} = "bar"
"""
), {
unused_variables: true
}).should.have.length(2)
it "ignores object literals", ->
ScopeLinter.default().lint(nodes(
"""
{bar: "baz"}
"""
), {
unused_arguments: true
unused_variables: true
}).should.have.length(0)
it "matches indirect access", ->
ScopeLinter.default().lint(nodes(
"""
foo = {}
foo[bar]
foo.bar
foo[0]
foo.bar()
"""
), {
unused_variables: true
}).should.have.length(0)
it "ignores builtins", ->
ScopeLinter.default().lint(nodes(
"""
foo = ->
undefined
foo()
"""
), {
unused_arguments: true
unused_variables: true
}).should.have.length(0)
it "ignores arguments when instructed", ->
ScopeLinter.default().lint(nodes(
"""
(foo) ->
undefined
"""
), {
unused_arguments: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
(foo) ->
undefined
"""
), {
unused_arguments: false
}).should.have.length(0)
it "supports special symbol names", ->
ScopeLinter.default().lint(nodes(
"""
constructor = 123
"""
), {
unused_variables: true
}).should.have.length(1)
it "matches destructured defaults", ->
ScopeLinter.default().lint(nodes(
"""
defaultVal = 0
{ property = defaultVal } = {}
property
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches nested destructured expressions", ->
ScopeLinter.default().lint(nodes(
"""
{ property: nested: val } = { property: nested: 1 }
val
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches do statements", ->
ScopeLinter.default().lint(nodes(
"""
for v, k in {foo: "bar"}
do (v, k) ->
console.log(v, k)
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches ranges", ->
ScopeLinter.default().lint(nodes(
"""
MAX_LENGTH = 3
str = 'foobar'
console.log str[...MAX_LENGTH]
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches explicit do statements", ->
ScopeLinter.default().lint(nodes(
"""
afn = (fn) -> fn()
do afn ->
null
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches composed string field objects", ->
ScopeLinter.default().lint(nodes(
'''
field = 'howdy'
obj =
"#{field}": 1
obj
'''
), {
unused_variables: true
}).should.have.length(0)
it "matches this assignments", ->
ScopeLinter.default().lint(nodes(
"""
normalize = (node) -> 'foo'
class Poll extends Driver
constructor: ->
super arguments...
@deferrals = {}
defer: (node) ->
@deferrals[normalize(node)] = _.now()
return
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles imports", ->
ScopeLinter.default().lint(nodes(
"""
import _ from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import * as underscore from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import { now } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import { now as currentTimestamp } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import { first, last } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(2)
ScopeLinter.default().lint(nodes(
"""
import utilityBelt, { each } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(2)
it "handles export of a default global", ->
ScopeLinter.default().lint(nodes(
"""
export default Math
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of a function", ->
ScopeLinter.default().lint(nodes(
"""
square = (x) -> x * x
export { square }
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of an inline function", ->
ScopeLinter.default().lint(nodes(
"""
export square = (x) -> x * x
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of an inline class", ->
ScopeLinter.default().lint(nodes(
"""
export class Mathematics
least: (x, y) -> if x < y then x else y
"""
), {
unused_classes: true
}).should.have.length(0)
it "handles export splat from an import", ->
ScopeLinter.default().lint(nodes(
"""
export * from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export from a destructured import", ->
ScopeLinter.default().lint(nodes(
"""
export { max, min } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of a default class and an aliased function", ->
ScopeLinter.default().lint(nodes(
"""
class Mathematics
least: (x, y) -> if x < y then x else y
square = (x) -> x * x
export { Mathematics as default, square as squareAlias }
"""
), {
unused_variables: true
unused_classes: true
}).should.have.length(0)
| 153689 | "use strict"
{nodes} = require "coffeescript"
ScopeLinter = require "../../src/ScopeLinter"
describe "ScopeLinter/unused", ->
it "matches trivial cases", ->
ScopeLinter.default().lint(nodes(
"""
foo = "bar"
{bar} = "bar"
"""
), {
unused_variables: true
}).should.have.length(2)
ScopeLinter.default().lint(nodes(
"""
(foo) ->
undefined
({foo}) ->
undefined
({foo} = {foo: bar}) ->
undefined
"""
), {
unused_arguments: true
}).should.have.length(3)
it "matches classes", ->
ScopeLinter.default().lint(nodes(
"""
class Foo
"""
), {
unused_classes: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
class Foo
class Bar extends Foo
"""
), {
unused_classes: true
}).should.have.length(1)
it "supports classes as properties", ->
ScopeLinter.default().lint(nodes(
"""
PROP = "Bar"
obj = {}
class obj.Foo
class obj[PROP]
"""
), {
unused_classes: true,
unused_variables: true
}).should.have.length(0)
it "ignores assigned classes", ->
ScopeLinter.default().lint(nodes(
"""
Bar = class Foo
Bar
"""
), {
unused_classes: true
}).should.have.length(0)
ScopeLinter.default().lint(nodes(
"""
class Foo
Baz = class Bar extends Foo
Baz
"""
), {
unused_classes: true
}).should.have.length(0)
it "matches recursive assignments", ->
ScopeLinter.default().lint(nodes(
"""
intervalId = setInterval ->
clearInterval intervalId
, 50
"""
), {
unused_variables: true
}).should.have.length(0)
it "doesn't match named classes that are part of an assignment", ->
ScopeLinter.default().lint(nodes(
"""
Bar = class Foo
Bar
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches for loops", ->
ScopeLinter.default().lint(nodes(
"""
for i in [1,2,3,4]
undefined
for i, index in [1,2,3,4]
undefined
for i in [0..4]
undefined
for i of {foo: "bar"}
undefined
for i, index of {foo: "bar"}
undefined
"""
), {
unused_variables: true
}).should.have.length(7)
it "issues multiple errors for the same value", ->
ScopeLinter.default().lint(nodes(
"""
foo = "bar"
{foo} = "bar"
"""
), {
unused_variables: true
}).should.have.length(2)
it "ignores object literals", ->
ScopeLinter.default().lint(nodes(
"""
{bar: "baz"}
"""
), {
unused_arguments: true
unused_variables: true
}).should.have.length(0)
it "matches indirect access", ->
ScopeLinter.default().lint(nodes(
"""
foo = {}
foo[bar]
foo.bar
foo[0]
foo.bar()
"""
), {
unused_variables: true
}).should.have.length(0)
it "ignores builtins", ->
ScopeLinter.default().lint(nodes(
"""
foo = ->
undefined
foo()
"""
), {
unused_arguments: true
unused_variables: true
}).should.have.length(0)
it "ignores arguments when instructed", ->
ScopeLinter.default().lint(nodes(
"""
(foo) ->
undefined
"""
), {
unused_arguments: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
(foo) ->
undefined
"""
), {
unused_arguments: false
}).should.have.length(0)
it "supports special symbol names", ->
ScopeLinter.default().lint(nodes(
"""
constructor = 123
"""
), {
unused_variables: true
}).should.have.length(1)
it "matches destructured defaults", ->
ScopeLinter.default().lint(nodes(
"""
defaultVal = 0
{ property = defaultVal } = {}
property
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches nested destructured expressions", ->
ScopeLinter.default().lint(nodes(
"""
{ property: nested: val } = { property: nested: 1 }
val
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches do statements", ->
ScopeLinter.default().lint(nodes(
"""
for v, k in {foo: "bar"}
do (v, k) ->
console.log(v, k)
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches ranges", ->
ScopeLinter.default().lint(nodes(
"""
MAX_LENGTH = 3
str = 'foobar'
console.log str[...MAX_LENGTH]
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches explicit do statements", ->
ScopeLinter.default().lint(nodes(
"""
afn = (fn) -> fn()
do afn ->
null
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches composed string field objects", ->
ScopeLinter.default().lint(nodes(
'''
field = '<NAME>dy'
obj =
"#{field}": 1
obj
'''
), {
unused_variables: true
}).should.have.length(0)
it "matches this assignments", ->
ScopeLinter.default().lint(nodes(
"""
normalize = (node) -> 'foo'
class Poll extends Driver
constructor: ->
super arguments...
@deferrals = {}
defer: (node) ->
@deferrals[normalize(node)] = _.now()
return
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles imports", ->
ScopeLinter.default().lint(nodes(
"""
import _ from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import * as underscore from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import { now } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import { now as currentTimestamp } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import { first, last } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(2)
ScopeLinter.default().lint(nodes(
"""
import utilityBelt, { each } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(2)
it "handles export of a default global", ->
ScopeLinter.default().lint(nodes(
"""
export default Math
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of a function", ->
ScopeLinter.default().lint(nodes(
"""
square = (x) -> x * x
export { square }
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of an inline function", ->
ScopeLinter.default().lint(nodes(
"""
export square = (x) -> x * x
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of an inline class", ->
ScopeLinter.default().lint(nodes(
"""
export class Mathematics
least: (x, y) -> if x < y then x else y
"""
), {
unused_classes: true
}).should.have.length(0)
it "handles export splat from an import", ->
ScopeLinter.default().lint(nodes(
"""
export * from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export from a destructured import", ->
ScopeLinter.default().lint(nodes(
"""
export { max, min } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of a default class and an aliased function", ->
ScopeLinter.default().lint(nodes(
"""
class Mathematics
least: (x, y) -> if x < y then x else y
square = (x) -> x * x
export { Mathematics as default, square as squareAlias }
"""
), {
unused_variables: true
unused_classes: true
}).should.have.length(0)
| true | "use strict"
{nodes} = require "coffeescript"
ScopeLinter = require "../../src/ScopeLinter"
describe "ScopeLinter/unused", ->
it "matches trivial cases", ->
ScopeLinter.default().lint(nodes(
"""
foo = "bar"
{bar} = "bar"
"""
), {
unused_variables: true
}).should.have.length(2)
ScopeLinter.default().lint(nodes(
"""
(foo) ->
undefined
({foo}) ->
undefined
({foo} = {foo: bar}) ->
undefined
"""
), {
unused_arguments: true
}).should.have.length(3)
it "matches classes", ->
ScopeLinter.default().lint(nodes(
"""
class Foo
"""
), {
unused_classes: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
class Foo
class Bar extends Foo
"""
), {
unused_classes: true
}).should.have.length(1)
it "supports classes as properties", ->
ScopeLinter.default().lint(nodes(
"""
PROP = "Bar"
obj = {}
class obj.Foo
class obj[PROP]
"""
), {
unused_classes: true,
unused_variables: true
}).should.have.length(0)
it "ignores assigned classes", ->
ScopeLinter.default().lint(nodes(
"""
Bar = class Foo
Bar
"""
), {
unused_classes: true
}).should.have.length(0)
ScopeLinter.default().lint(nodes(
"""
class Foo
Baz = class Bar extends Foo
Baz
"""
), {
unused_classes: true
}).should.have.length(0)
it "matches recursive assignments", ->
ScopeLinter.default().lint(nodes(
"""
intervalId = setInterval ->
clearInterval intervalId
, 50
"""
), {
unused_variables: true
}).should.have.length(0)
it "doesn't match named classes that are part of an assignment", ->
ScopeLinter.default().lint(nodes(
"""
Bar = class Foo
Bar
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches for loops", ->
ScopeLinter.default().lint(nodes(
"""
for i in [1,2,3,4]
undefined
for i, index in [1,2,3,4]
undefined
for i in [0..4]
undefined
for i of {foo: "bar"}
undefined
for i, index of {foo: "bar"}
undefined
"""
), {
unused_variables: true
}).should.have.length(7)
it "issues multiple errors for the same value", ->
ScopeLinter.default().lint(nodes(
"""
foo = "bar"
{foo} = "bar"
"""
), {
unused_variables: true
}).should.have.length(2)
it "ignores object literals", ->
ScopeLinter.default().lint(nodes(
"""
{bar: "baz"}
"""
), {
unused_arguments: true
unused_variables: true
}).should.have.length(0)
it "matches indirect access", ->
ScopeLinter.default().lint(nodes(
"""
foo = {}
foo[bar]
foo.bar
foo[0]
foo.bar()
"""
), {
unused_variables: true
}).should.have.length(0)
it "ignores builtins", ->
ScopeLinter.default().lint(nodes(
"""
foo = ->
undefined
foo()
"""
), {
unused_arguments: true
unused_variables: true
}).should.have.length(0)
it "ignores arguments when instructed", ->
ScopeLinter.default().lint(nodes(
"""
(foo) ->
undefined
"""
), {
unused_arguments: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
(foo) ->
undefined
"""
), {
unused_arguments: false
}).should.have.length(0)
it "supports special symbol names", ->
ScopeLinter.default().lint(nodes(
"""
constructor = 123
"""
), {
unused_variables: true
}).should.have.length(1)
it "matches destructured defaults", ->
ScopeLinter.default().lint(nodes(
"""
defaultVal = 0
{ property = defaultVal } = {}
property
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches nested destructured expressions", ->
ScopeLinter.default().lint(nodes(
"""
{ property: nested: val } = { property: nested: 1 }
val
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches do statements", ->
ScopeLinter.default().lint(nodes(
"""
for v, k in {foo: "bar"}
do (v, k) ->
console.log(v, k)
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches ranges", ->
ScopeLinter.default().lint(nodes(
"""
MAX_LENGTH = 3
str = 'foobar'
console.log str[...MAX_LENGTH]
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches explicit do statements", ->
ScopeLinter.default().lint(nodes(
"""
afn = (fn) -> fn()
do afn ->
null
"""
), {
unused_variables: true
}).should.have.length(0)
it "matches composed string field objects", ->
ScopeLinter.default().lint(nodes(
'''
field = 'PI:NAME:<NAME>END_PIdy'
obj =
"#{field}": 1
obj
'''
), {
unused_variables: true
}).should.have.length(0)
it "matches this assignments", ->
ScopeLinter.default().lint(nodes(
"""
normalize = (node) -> 'foo'
class Poll extends Driver
constructor: ->
super arguments...
@deferrals = {}
defer: (node) ->
@deferrals[normalize(node)] = _.now()
return
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles imports", ->
ScopeLinter.default().lint(nodes(
"""
import _ from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import * as underscore from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import { now } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import { now as currentTimestamp } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(1)
ScopeLinter.default().lint(nodes(
"""
import { first, last } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(2)
ScopeLinter.default().lint(nodes(
"""
import utilityBelt, { each } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(2)
it "handles export of a default global", ->
ScopeLinter.default().lint(nodes(
"""
export default Math
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of a function", ->
ScopeLinter.default().lint(nodes(
"""
square = (x) -> x * x
export { square }
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of an inline function", ->
ScopeLinter.default().lint(nodes(
"""
export square = (x) -> x * x
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of an inline class", ->
ScopeLinter.default().lint(nodes(
"""
export class Mathematics
least: (x, y) -> if x < y then x else y
"""
), {
unused_classes: true
}).should.have.length(0)
it "handles export splat from an import", ->
ScopeLinter.default().lint(nodes(
"""
export * from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export from a destructured import", ->
ScopeLinter.default().lint(nodes(
"""
export { max, min } from 'underscore'
"""
), {
unused_variables: true
}).should.have.length(0)
it "handles export of a default class and an aliased function", ->
ScopeLinter.default().lint(nodes(
"""
class Mathematics
least: (x, y) -> if x < y then x else y
square = (x) -> x * x
export { Mathematics as default, square as squareAlias }
"""
), {
unused_variables: true
unused_classes: true
}).should.have.length(0)
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9993589520454407,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": "mmon.mustCall((name, cb) ->\n assert.equal name, \"hello\"\n assert.equal cb, listener1\n r... | test/simple/test-event-emitter-remove-listeners.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.
listener1 = ->
console.log "listener1"
count++
return
listener2 = ->
console.log "listener2"
count++
return
listener3 = ->
console.log "listener3"
count++
return
remove1 = ->
assert 0
return
remove2 = ->
assert 0
return
common = require("../common")
assert = require("assert")
events = require("events")
count = 0
e1 = new events.EventEmitter()
e1.on "hello", listener1
e1.on "removeListener", common.mustCall((name, cb) ->
assert.equal name, "hello"
assert.equal cb, listener1
return
)
e1.removeListener "hello", listener1
assert.deepEqual [], e1.listeners("hello")
e2 = new events.EventEmitter()
e2.on "hello", listener1
e2.on "removeListener", assert.fail
e2.removeListener "hello", listener2
assert.deepEqual [listener1], e2.listeners("hello")
e3 = new events.EventEmitter()
e3.on "hello", listener1
e3.on "hello", listener2
e3.on "removeListener", common.mustCall((name, cb) ->
assert.equal name, "hello"
assert.equal cb, listener1
return
)
e3.removeListener "hello", listener1
assert.deepEqual [listener2], e3.listeners("hello")
e4 = new events.EventEmitter()
e4.on "removeListener", common.mustCall((name, cb) ->
return if cb isnt remove1
@removeListener "quux", remove2
@emit "quux"
return
, 2)
e4.on "quux", remove1
e4.on "quux", remove2
e4.removeListener "quux", remove1
| 129059 | # 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.
listener1 = ->
console.log "listener1"
count++
return
listener2 = ->
console.log "listener2"
count++
return
listener3 = ->
console.log "listener3"
count++
return
remove1 = ->
assert 0
return
remove2 = ->
assert 0
return
common = require("../common")
assert = require("assert")
events = require("events")
count = 0
e1 = new events.EventEmitter()
e1.on "hello", listener1
e1.on "removeListener", common.mustCall((name, cb) ->
assert.equal name, "hello"
assert.equal cb, listener1
return
)
e1.removeListener "hello", listener1
assert.deepEqual [], e1.listeners("hello")
e2 = new events.EventEmitter()
e2.on "hello", listener1
e2.on "removeListener", assert.fail
e2.removeListener "hello", listener2
assert.deepEqual [listener1], e2.listeners("hello")
e3 = new events.EventEmitter()
e3.on "hello", listener1
e3.on "hello", listener2
e3.on "removeListener", common.mustCall((name, cb) ->
assert.equal name, "<NAME>"
assert.equal cb, listener1
return
)
e3.removeListener "hello", listener1
assert.deepEqual [listener2], e3.listeners("hello")
e4 = new events.EventEmitter()
e4.on "removeListener", common.mustCall((name, cb) ->
return if cb isnt remove1
@removeListener "quux", remove2
@emit "quux"
return
, 2)
e4.on "quux", remove1
e4.on "quux", remove2
e4.removeListener "quux", remove1
| 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.
listener1 = ->
console.log "listener1"
count++
return
listener2 = ->
console.log "listener2"
count++
return
listener3 = ->
console.log "listener3"
count++
return
remove1 = ->
assert 0
return
remove2 = ->
assert 0
return
common = require("../common")
assert = require("assert")
events = require("events")
count = 0
e1 = new events.EventEmitter()
e1.on "hello", listener1
e1.on "removeListener", common.mustCall((name, cb) ->
assert.equal name, "hello"
assert.equal cb, listener1
return
)
e1.removeListener "hello", listener1
assert.deepEqual [], e1.listeners("hello")
e2 = new events.EventEmitter()
e2.on "hello", listener1
e2.on "removeListener", assert.fail
e2.removeListener "hello", listener2
assert.deepEqual [listener1], e2.listeners("hello")
e3 = new events.EventEmitter()
e3.on "hello", listener1
e3.on "hello", listener2
e3.on "removeListener", common.mustCall((name, cb) ->
assert.equal name, "PI:NAME:<NAME>END_PI"
assert.equal cb, listener1
return
)
e3.removeListener "hello", listener1
assert.deepEqual [listener2], e3.listeners("hello")
e4 = new events.EventEmitter()
e4.on "removeListener", common.mustCall((name, cb) ->
return if cb isnt remove1
@removeListener "quux", remove2
@emit "quux"
return
, 2)
e4.on "quux", remove1
e4.on "quux", remove2
e4.removeListener "quux", remove1
|
[
{
"context": "\t\"modules/localStorage\"\n], (App) ->\n\tCACHE_KEY = \"countlyEvents\"\n\n\tApp.factory \"event_tracking\", (localStorage) -",
"end": 80,
"score": 0.9937960505485535,
"start": 67,
"tag": "KEY",
"value": "countlyEvents"
}
] | public/coffee/main/event.coffee | bowlofstew/web-sharelatex | 0 | define [
"base"
"modules/localStorage"
], (App) ->
CACHE_KEY = "countlyEvents"
App.factory "event_tracking", (localStorage) ->
_getEventCache = () ->
eventCache = localStorage CACHE_KEY
# Initialize as an empy object if the event cache is still empty.
if !eventCache?
eventCache = {}
localStorage CACHE_KEY, eventCache
return eventCache
_eventInCache = (key) ->
curCache = _getEventCache()
curCache[key] || false
_addEventToCache = (key) ->
curCache = _getEventCache()
curCache[key] = true
localStorage CACHE_KEY, curCache
return {
send: (category, action, label, value)->
ga('send', 'event', category, action, label, value)
sendCountly: (key, segmentation) ->
eventData = { key }
eventData.segmentation = segmentation if segmentation?
Countly?.q.push([ "add_event", eventData ])
sendCountlySampled: (key, segmentation) ->
@sendCountly key, segmentation if Math.random() < .01
sendCountlyOnce: (key, segmentation) ->
if ! _eventInCache(key)
_addEventToCache(key)
@sendCountly key, segmentation
}
# App.directive "countlyTrack", () ->
# return {
# restrict: "A"
# scope: false,
# link: (scope, el, attrs) ->
# eventKey = attrs.countlyTrack
# if (eventKey?)
# el.on "click", () ->
# console.log eventKey
# }
#header
$('.navbar a').on "click", (e)->
href = $(e.target).attr("href")
if href?
ga('send', 'event', 'navigation', 'top menu bar', href)
| 197522 | define [
"base"
"modules/localStorage"
], (App) ->
CACHE_KEY = "<KEY>"
App.factory "event_tracking", (localStorage) ->
_getEventCache = () ->
eventCache = localStorage CACHE_KEY
# Initialize as an empy object if the event cache is still empty.
if !eventCache?
eventCache = {}
localStorage CACHE_KEY, eventCache
return eventCache
_eventInCache = (key) ->
curCache = _getEventCache()
curCache[key] || false
_addEventToCache = (key) ->
curCache = _getEventCache()
curCache[key] = true
localStorage CACHE_KEY, curCache
return {
send: (category, action, label, value)->
ga('send', 'event', category, action, label, value)
sendCountly: (key, segmentation) ->
eventData = { key }
eventData.segmentation = segmentation if segmentation?
Countly?.q.push([ "add_event", eventData ])
sendCountlySampled: (key, segmentation) ->
@sendCountly key, segmentation if Math.random() < .01
sendCountlyOnce: (key, segmentation) ->
if ! _eventInCache(key)
_addEventToCache(key)
@sendCountly key, segmentation
}
# App.directive "countlyTrack", () ->
# return {
# restrict: "A"
# scope: false,
# link: (scope, el, attrs) ->
# eventKey = attrs.countlyTrack
# if (eventKey?)
# el.on "click", () ->
# console.log eventKey
# }
#header
$('.navbar a').on "click", (e)->
href = $(e.target).attr("href")
if href?
ga('send', 'event', 'navigation', 'top menu bar', href)
| true | define [
"base"
"modules/localStorage"
], (App) ->
CACHE_KEY = "PI:KEY:<KEY>END_PI"
App.factory "event_tracking", (localStorage) ->
_getEventCache = () ->
eventCache = localStorage CACHE_KEY
# Initialize as an empy object if the event cache is still empty.
if !eventCache?
eventCache = {}
localStorage CACHE_KEY, eventCache
return eventCache
_eventInCache = (key) ->
curCache = _getEventCache()
curCache[key] || false
_addEventToCache = (key) ->
curCache = _getEventCache()
curCache[key] = true
localStorage CACHE_KEY, curCache
return {
send: (category, action, label, value)->
ga('send', 'event', category, action, label, value)
sendCountly: (key, segmentation) ->
eventData = { key }
eventData.segmentation = segmentation if segmentation?
Countly?.q.push([ "add_event", eventData ])
sendCountlySampled: (key, segmentation) ->
@sendCountly key, segmentation if Math.random() < .01
sendCountlyOnce: (key, segmentation) ->
if ! _eventInCache(key)
_addEventToCache(key)
@sendCountly key, segmentation
}
# App.directive "countlyTrack", () ->
# return {
# restrict: "A"
# scope: false,
# link: (scope, el, attrs) ->
# eventKey = attrs.countlyTrack
# if (eventKey?)
# el.on "click", () ->
# console.log eventKey
# }
#header
$('.navbar a').on "click", (e)->
href = $(e.target).attr("href")
if href?
ga('send', 'event', 'navigation', 'top menu bar', href)
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9984683394432068,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/pummel/test-stream-pipe-multi.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.
# Test that having a bunch of streams piping in parallel
# doesn't break anything.
FakeStream = ->
Stream.apply this
@wait = false
@writable = true
@readable = true
return
common = require("../common")
assert = require("assert")
Stream = require("stream").Stream
rr = []
ww = []
cnt = 100
chunks = 1000
chunkSize = 250
data = new Buffer(chunkSize)
wclosed = 0
rclosed = 0
FakeStream:: = Object.create(Stream::)
FakeStream::write = (chunk) ->
console.error @ID, "write", @wait
process.nextTick @emit.bind(this, "drain") if @wait
@wait = not @wait
@wait
FakeStream::end = ->
@emit "end"
process.nextTick @close.bind(this)
return
# noop - closes happen automatically on end.
FakeStream::close = ->
@emit "close"
return
# expect all streams to close properly.
process.on "exit", ->
assert.equal cnt, wclosed, "writable streams closed"
assert.equal cnt, rclosed, "readable streams closed"
return
i = 0
while i < chunkSize
chunkSize[i] = i % 256
i++
i = 0
while i < cnt
r = new FakeStream()
r.on "close", ->
console.error @ID, "read close"
rclosed++
return
rr.push r
w = new FakeStream()
w.on "close", ->
console.error @ID, "write close"
wclosed++
return
ww.push w
r.ID = w.ID = i
r.pipe w
i++
# now start passing through data
# simulate a relatively fast async stream.
rr.forEach (r) ->
step = ->
r.emit "data", data
if --cnt is 0
r.end()
return
return if paused
process.nextTick step
return
cnt = chunks
paused = false
r.on "pause", ->
paused = true
return
r.on "resume", ->
paused = false
step()
return
process.nextTick step
return
| 98259 | # 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.
# Test that having a bunch of streams piping in parallel
# doesn't break anything.
FakeStream = ->
Stream.apply this
@wait = false
@writable = true
@readable = true
return
common = require("../common")
assert = require("assert")
Stream = require("stream").Stream
rr = []
ww = []
cnt = 100
chunks = 1000
chunkSize = 250
data = new Buffer(chunkSize)
wclosed = 0
rclosed = 0
FakeStream:: = Object.create(Stream::)
FakeStream::write = (chunk) ->
console.error @ID, "write", @wait
process.nextTick @emit.bind(this, "drain") if @wait
@wait = not @wait
@wait
FakeStream::end = ->
@emit "end"
process.nextTick @close.bind(this)
return
# noop - closes happen automatically on end.
FakeStream::close = ->
@emit "close"
return
# expect all streams to close properly.
process.on "exit", ->
assert.equal cnt, wclosed, "writable streams closed"
assert.equal cnt, rclosed, "readable streams closed"
return
i = 0
while i < chunkSize
chunkSize[i] = i % 256
i++
i = 0
while i < cnt
r = new FakeStream()
r.on "close", ->
console.error @ID, "read close"
rclosed++
return
rr.push r
w = new FakeStream()
w.on "close", ->
console.error @ID, "write close"
wclosed++
return
ww.push w
r.ID = w.ID = i
r.pipe w
i++
# now start passing through data
# simulate a relatively fast async stream.
rr.forEach (r) ->
step = ->
r.emit "data", data
if --cnt is 0
r.end()
return
return if paused
process.nextTick step
return
cnt = chunks
paused = false
r.on "pause", ->
paused = true
return
r.on "resume", ->
paused = false
step()
return
process.nextTick step
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# Test that having a bunch of streams piping in parallel
# doesn't break anything.
FakeStream = ->
Stream.apply this
@wait = false
@writable = true
@readable = true
return
common = require("../common")
assert = require("assert")
Stream = require("stream").Stream
rr = []
ww = []
cnt = 100
chunks = 1000
chunkSize = 250
data = new Buffer(chunkSize)
wclosed = 0
rclosed = 0
FakeStream:: = Object.create(Stream::)
FakeStream::write = (chunk) ->
console.error @ID, "write", @wait
process.nextTick @emit.bind(this, "drain") if @wait
@wait = not @wait
@wait
FakeStream::end = ->
@emit "end"
process.nextTick @close.bind(this)
return
# noop - closes happen automatically on end.
FakeStream::close = ->
@emit "close"
return
# expect all streams to close properly.
process.on "exit", ->
assert.equal cnt, wclosed, "writable streams closed"
assert.equal cnt, rclosed, "readable streams closed"
return
i = 0
while i < chunkSize
chunkSize[i] = i % 256
i++
i = 0
while i < cnt
r = new FakeStream()
r.on "close", ->
console.error @ID, "read close"
rclosed++
return
rr.push r
w = new FakeStream()
w.on "close", ->
console.error @ID, "write close"
wclosed++
return
ww.push w
r.ID = w.ID = i
r.pipe w
i++
# now start passing through data
# simulate a relatively fast async stream.
rr.forEach (r) ->
step = ->
r.emit "data", data
if --cnt is 0
r.end()
return
return if paused
process.nextTick step
return
cnt = chunks
paused = false
r.on "pause", ->
paused = true
return
r.on "resume", ->
paused = false
step()
return
process.nextTick step
return
|
[
{
"context": ".name\n switch f.mappedType\n when 'username' then @credential.username\n when 'passwo",
"end": 2377,
"score": 0.9928306937217712,
"start": 2369,
"tag": "USERNAME",
"value": "username"
},
{
"context": "sername\n when 'password' then @cr... | src/models/tasks/watch_static_page_task.coffee | nodeswork/nodeswork-watchmen | 0 | _ = require 'underscore'
co = require 'co'
nodeswork = require 'nodeswork'
winston = require 'winston'
CredentialSchemaPlugin = require '../credential_plugin'
module.exports = WatchStaticPageTaskSchema = nodeswork.Models.Task.schema.extend {
user:
type: Number
required: yes
session:
type: nodeswork.mongoose.Schema.ObjectId
ref: 'Session'
required: yes
headers: nodeswork.mongoose.Schema.Types.Mixed
url:
type: String
required: yes
authProcess:
needLogin:
type: Boolean
default: false
identifyUrl: String
matchPatterns: [
name: String
patternType:
type: String
enum: ['ATTRIBUTE']
regex: String
]
}
.plugin CredentialSchemaPlugin
WatchStaticPageTaskSchema.methods.execute = (nw) -> co =>
yield @populate('session').execPopulate()
# logout = yield @session.request {
# url: 'http://www.departementfeminin.com/en/deconnexion.php'
# headers: @headers
# gzip: true
# }
# console.log 'logout'
if @authProcess.needLogin
loginFormDetection = yield @isUserLogin()
if loginFormDetection?
winston.info 'Login form detected.'
yield @login loginFormDetection
winston.info 'User logined.'
window = yield @session.request {
url: @url
headers: @headers
gzip: true
jsdom: true
}
content = window.$('body').text()
_.each @matchPatterns, (pattern) ->
reg = new RegExp pattern.regex, "i"
matches = reg.exec content
console.log reg, matches?.length
WatchStaticPageTaskSchema.methods.isUserLogin = () -> co =>
console.log 'identifyUrl', @authProcess.identifyUrl
identifyWindow = yield @session.request {
url: @authProcess.identifyUrl
headers: @headers
gzip: true
jsdom: true
}
detections = @detectLoginForm @authProcess.identifyUrl, identifyWindow
loginFormDetection = _.find detections, (x) -> x.itemType == 'LOGIN_FORM'
WatchStaticPageTaskSchema.methods.login = (loginDetection) -> co =>
form = _.extend {}, loginDetection.form.defaultFields, (
_.chain loginDetection.form.inputFields
.map (f) => [
f.name
switch f.mappedType
when 'username' then @credential.username
when 'password' then @credential.password
]
.object()
.value()
)
try
res = yield @session.request {
url: loginDetection.form.action
method: 'POST'
form: form
headers: @headers
gzip: true
followRedirect: true
}
console.log 'res', res
catch
winston.info 'Login successfully.'
WatchStaticPageTaskSchema.methods.detectLoginForm = (sourceUrl, window) ->
$ = window.$
detections = []
forms = window.$('form')
for form in forms
unless (action = $(form).attr('action'))
continue
unless (method = $(form).attr('method')) == 'post'
continue
$inputs = $(form).find(':input')
detection = {
sourceUrl: sourceUrl
form:
action: action
method: method
defaultFields: {}
inputFields: []
}
_.each $inputs, (input) ->
switch input.type
when 'hidden'
detection.form.defaultFields[input.name] = $(input).val() ? ''
when 'submit'
detection.form.submit = $(input).text().trim()
else
detection.form.inputFields.push {
name: input.name, inputType: input.type
}
fieldsCounter = _.countBy detection.form.inputFields, (field) ->
field.mappedType = switch
when field.inputType == 'password' then 'password'
when field.inputType == 'email' then 'username'
when field.name == 'username' then 'username'
else 'others'
if fieldsCounter.username == 1 and fieldsCounter.password == 1
detection.itemType = 'LOGIN_FORM'
detection.autofillable = !fieldsCounter.others
if detection.itemType? then detections.push detection
detections
| 164689 | _ = require 'underscore'
co = require 'co'
nodeswork = require 'nodeswork'
winston = require 'winston'
CredentialSchemaPlugin = require '../credential_plugin'
module.exports = WatchStaticPageTaskSchema = nodeswork.Models.Task.schema.extend {
user:
type: Number
required: yes
session:
type: nodeswork.mongoose.Schema.ObjectId
ref: 'Session'
required: yes
headers: nodeswork.mongoose.Schema.Types.Mixed
url:
type: String
required: yes
authProcess:
needLogin:
type: Boolean
default: false
identifyUrl: String
matchPatterns: [
name: String
patternType:
type: String
enum: ['ATTRIBUTE']
regex: String
]
}
.plugin CredentialSchemaPlugin
WatchStaticPageTaskSchema.methods.execute = (nw) -> co =>
yield @populate('session').execPopulate()
# logout = yield @session.request {
# url: 'http://www.departementfeminin.com/en/deconnexion.php'
# headers: @headers
# gzip: true
# }
# console.log 'logout'
if @authProcess.needLogin
loginFormDetection = yield @isUserLogin()
if loginFormDetection?
winston.info 'Login form detected.'
yield @login loginFormDetection
winston.info 'User logined.'
window = yield @session.request {
url: @url
headers: @headers
gzip: true
jsdom: true
}
content = window.$('body').text()
_.each @matchPatterns, (pattern) ->
reg = new RegExp pattern.regex, "i"
matches = reg.exec content
console.log reg, matches?.length
WatchStaticPageTaskSchema.methods.isUserLogin = () -> co =>
console.log 'identifyUrl', @authProcess.identifyUrl
identifyWindow = yield @session.request {
url: @authProcess.identifyUrl
headers: @headers
gzip: true
jsdom: true
}
detections = @detectLoginForm @authProcess.identifyUrl, identifyWindow
loginFormDetection = _.find detections, (x) -> x.itemType == 'LOGIN_FORM'
WatchStaticPageTaskSchema.methods.login = (loginDetection) -> co =>
form = _.extend {}, loginDetection.form.defaultFields, (
_.chain loginDetection.form.inputFields
.map (f) => [
f.name
switch f.mappedType
when 'username' then @credential.username
when 'password' then @credential.<PASSWORD>
]
.object()
.value()
)
try
res = yield @session.request {
url: loginDetection.form.action
method: 'POST'
form: form
headers: @headers
gzip: true
followRedirect: true
}
console.log 'res', res
catch
winston.info 'Login successfully.'
WatchStaticPageTaskSchema.methods.detectLoginForm = (sourceUrl, window) ->
$ = window.$
detections = []
forms = window.$('form')
for form in forms
unless (action = $(form).attr('action'))
continue
unless (method = $(form).attr('method')) == 'post'
continue
$inputs = $(form).find(':input')
detection = {
sourceUrl: sourceUrl
form:
action: action
method: method
defaultFields: {}
inputFields: []
}
_.each $inputs, (input) ->
switch input.type
when 'hidden'
detection.form.defaultFields[input.name] = $(input).val() ? ''
when 'submit'
detection.form.submit = $(input).text().trim()
else
detection.form.inputFields.push {
name: input.name, inputType: input.type
}
fieldsCounter = _.countBy detection.form.inputFields, (field) ->
field.mappedType = switch
when field.inputType == 'password' then 'password'
when field.inputType == 'email' then 'username'
when field.name == 'username' then 'username'
else 'others'
if fieldsCounter.username == 1 and fieldsCounter.password == 1
detection.itemType = 'LOGIN_FORM'
detection.autofillable = !fieldsCounter.others
if detection.itemType? then detections.push detection
detections
| true | _ = require 'underscore'
co = require 'co'
nodeswork = require 'nodeswork'
winston = require 'winston'
CredentialSchemaPlugin = require '../credential_plugin'
module.exports = WatchStaticPageTaskSchema = nodeswork.Models.Task.schema.extend {
user:
type: Number
required: yes
session:
type: nodeswork.mongoose.Schema.ObjectId
ref: 'Session'
required: yes
headers: nodeswork.mongoose.Schema.Types.Mixed
url:
type: String
required: yes
authProcess:
needLogin:
type: Boolean
default: false
identifyUrl: String
matchPatterns: [
name: String
patternType:
type: String
enum: ['ATTRIBUTE']
regex: String
]
}
.plugin CredentialSchemaPlugin
WatchStaticPageTaskSchema.methods.execute = (nw) -> co =>
yield @populate('session').execPopulate()
# logout = yield @session.request {
# url: 'http://www.departementfeminin.com/en/deconnexion.php'
# headers: @headers
# gzip: true
# }
# console.log 'logout'
if @authProcess.needLogin
loginFormDetection = yield @isUserLogin()
if loginFormDetection?
winston.info 'Login form detected.'
yield @login loginFormDetection
winston.info 'User logined.'
window = yield @session.request {
url: @url
headers: @headers
gzip: true
jsdom: true
}
content = window.$('body').text()
_.each @matchPatterns, (pattern) ->
reg = new RegExp pattern.regex, "i"
matches = reg.exec content
console.log reg, matches?.length
WatchStaticPageTaskSchema.methods.isUserLogin = () -> co =>
console.log 'identifyUrl', @authProcess.identifyUrl
identifyWindow = yield @session.request {
url: @authProcess.identifyUrl
headers: @headers
gzip: true
jsdom: true
}
detections = @detectLoginForm @authProcess.identifyUrl, identifyWindow
loginFormDetection = _.find detections, (x) -> x.itemType == 'LOGIN_FORM'
WatchStaticPageTaskSchema.methods.login = (loginDetection) -> co =>
form = _.extend {}, loginDetection.form.defaultFields, (
_.chain loginDetection.form.inputFields
.map (f) => [
f.name
switch f.mappedType
when 'username' then @credential.username
when 'password' then @credential.PI:PASSWORD:<PASSWORD>END_PI
]
.object()
.value()
)
try
res = yield @session.request {
url: loginDetection.form.action
method: 'POST'
form: form
headers: @headers
gzip: true
followRedirect: true
}
console.log 'res', res
catch
winston.info 'Login successfully.'
WatchStaticPageTaskSchema.methods.detectLoginForm = (sourceUrl, window) ->
$ = window.$
detections = []
forms = window.$('form')
for form in forms
unless (action = $(form).attr('action'))
continue
unless (method = $(form).attr('method')) == 'post'
continue
$inputs = $(form).find(':input')
detection = {
sourceUrl: sourceUrl
form:
action: action
method: method
defaultFields: {}
inputFields: []
}
_.each $inputs, (input) ->
switch input.type
when 'hidden'
detection.form.defaultFields[input.name] = $(input).val() ? ''
when 'submit'
detection.form.submit = $(input).text().trim()
else
detection.form.inputFields.push {
name: input.name, inputType: input.type
}
fieldsCounter = _.countBy detection.form.inputFields, (field) ->
field.mappedType = switch
when field.inputType == 'password' then 'password'
when field.inputType == 'email' then 'username'
when field.name == 'username' then 'username'
else 'others'
if fieldsCounter.username == 1 and fieldsCounter.password == 1
detection.itemType = 'LOGIN_FORM'
detection.autofillable = !fieldsCounter.others
if detection.itemType? then detections.push detection
detections
|
[
{
"context": "s.google.com/a/hyperbotic.com/spreadsheet/pub?key=0AvVyfy1LBTe3dFdIa1ItMTN2Q0k4R05qV2VtbWYzbFE&output=html\")\n\n Hy.Pages.StartPage.addObserver",
"end": 968,
"score": 0.9996896386146545,
"start": 924,
"tag": "KEY",
"value": "0AvVyfy1LBTe3dFdIa1ItMTN2Q0k4R05qV2VtbWYzbFE"
}... | app-src/console_app.coffee | hyperbotic/crowdgame-trivially-pro | 0 | # ==================================================================================================================
#
# IT IS REALLY IMPORTANT THAT App-level event handlers return null.
# Ti.App.addEventListener("eventName", (event)=>null)
#
#
class ConsoleApp extends Hy.UI.Application
gInstance = null
# ----------------------------------------------------------------------------------------------------------------
@get: ()-> gInstance
# ----------------------------------------------------------------------------------------------------------------
constructor: (backgroundWindow, tempImage)->
gInstance = this
@playerNetwork = null
@initializingPlayerNetwork = false
@numPlayerNetworkInitializationAttempts = 0
super backgroundWindow, tempImage
this.initSetup()
# HACK V1.0.2
# Ti.UI.Clipboard.setText("https://docs.google.com/a/hyperbotic.com/spreadsheet/pub?key=0AvVyfy1LBTe3dFdIa1ItMTN2Q0k4R05qV2VtbWYzbFE&output=html")
Hy.Pages.StartPage.addObserver this
this
# ----------------------------------------------------------------------------------------------------------------
getContest: ()-> @contest
# ----------------------------------------------------------------------------------------------------------------
getPlayerNetwork: ()-> @playerNetwork
# ----------------------------------------------------------------------------------------------------------------
initSetup: ()->
@initFnChain = []
options = if (newUrl = this.checkURLArg())?
{page: Hy.Pages.PageState.ContentOptions, fn_completed: ()=>this.doURLArg(newUrl)}
else
{page: Hy.Pages.PageState.Start}
initFnSpecs = [
{label: "Trace", init: ()=>Hy.Trace.init(this)}
{label: "Analytics", init: ()=>@analytics = Hy.Analytics.Analytics.init()}
{label: "Customization", init: ()=>Hy.Customize.init((c, o)=>this.customizationActivated(c, o))}
# {label: "CommerceManager", init: ()=>Hy.Commerce.CommerceManager.init()} #2.7
{label: "SoundManager", init: ()=>Hy.Media.SoundManager.init()}
{label: "Network Service", init: ()=>this.initNetwork()}
{label: "DownloadCache", init: ()=>Hy.Network.DownloadCache.init()}
{label: "Update Service", init: ()=>Hy.Update.UpdateService.init()}
{label: "ContentManager", init: ()=>Hy.Content.ContentManager.init()}
{label: "Console Player", init: ()=>Hy.Player.ConsolePlayer.init()}
# {label: "CommerceManagerInventory", init: ()=>Hy.Commerce.CommerceManager.inventoryManagedFeatures()} #2.7
{label: "Page/Video", init: ()=>this.initPageState()}
# Should be the last one
{label: "Customization", init: ()=>this.applyInitialCustomization(options)}
]
for initFnSpec in initFnSpecs
this.addInitStep(initFnSpec.label, initFnSpec.init)
this
# ----------------------------------------------------------------------------------------------------------------
initPageState: ()->
@pageState = Hy.Pages.PageState.init(this)
this
# ----------------------------------------------------------------------------------------------------------------
doneWithPageState: ()->
@pageState?.stop()
@pageState = null
Hy.Pages.PageState.doneWithPageState()
this
# ----------------------------------------------------------------------------------------------------------------
addInitStep: (label, fn)->
@initFnChain.push({label: label, init: fn})
this
# ----------------------------------------------------------------------------------------------------------------
isInitCompleted: ()-> @initFnChain.length is 0
# ----------------------------------------------------------------------------------------------------------------
init: ()->
super
Hy.Utils.MemInfo.init()
Hy.Utils.MemInfo.log "INITIALIZING (init #=#{_.size(@initFnChain)})"
@timedOperation = new Hy.Utils.TimedOperation("INITIALIZATION")
fnExecute = ()=>
while not this.isInitCompleted()
fnSpec = _.first(@initFnChain)
fnSpec.init()
@initFnChain.shift()
@timedOperation.mark(fnSpec.label)
null
fnExecute()
this
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "ConsoleApp::start"
super
@analytics?.logApplicationLaunch()
this
# ----------------------------------------------------------------------------------------------------------------
# Triggered when the app is backgrounded. Have to work quick here. Do the important stuff first
pause: (evt)->
Hy.Trace.debug "ConsoleApp::pause (ENTER)"
this.getPage()?.pause()
@playerNetwork?.pause()
Hy.Network.NetworkService.get().pause()
super evt
Hy.Trace.debug "ConsoleApp::pause (EXIT)"
# ----------------------------------------------------------------------------------------------------------------
# Triggered at the start of the process of being foregrounded. Nothing to do here.
resume: (evt)->
Hy.Trace.debug "ConsoleApp::resume (ENTER page=#{this.getPage()?.constructor.name})"
super evt
Hy.Trace.debug "ConsoleApp::resume (EXIT page=#{this.getPage()?.constructor.name})"
# ----------------------------------------------------------------------------------------------------------------
# Triggered when app is fully foregrounded.
resumed: (evt)->
Hy.Trace.debug "ConsoleApp::resumed (ENTER page=#{this.getPage()?.constructor.name})"
super
this.init()
Hy.Network.NetworkService.get().resumed()
Hy.Network.NetworkService.get().setImmediate()
@playerNetwork?.resumed()
if (newUrl = this.checkURLArg())?
this.doURLArg(newUrl)
else
this.resumedPage()
Hy.Trace.debug "ConsoleApp::resumed (EXIT page=#{this.getPage()?.constructor.name})"
# ----------------------------------------------------------------------------------------------------------------
#
# To handle the edge case where we were backgrounded while transitioning to a new page.
# In the more complex cases, the tactic for handling this is to simply go back to the previous page.
# This approach seems to be needed when the page is based on a web view and requires images to load
#
resumedPage: ()->
Hy.Trace.debug "ConsoleApp::resumedPage (ENTER (transitioning=#{@pageState.isTransitioning()?})"
fn = null
if @pageState.isTransitioning()?
stopTransitioning = true
switch (oldPageState = @pageState.getOldPageState())
when Hy.Pages.PageState.Start, null, Hy.Pages.PageState.Splash
fn = ()=>this.showStartPage()
when Hy.Pages.PageState.Any, Hy.Pages.PageState.None
new Hy.Utils.ErrorMessage("fatal", "Console App", "Unexpected state \"#{oldPageState}\" in resumedPage") #will display popup dialog
fn = ()=>this.showStartPage()
else # About, ContentOptions, Join, Question, Answer, Scoreboard, Completed, Options
stopTransitioning = false
null
if stopTransitioning
@pageState.stopTransitioning()
else
if not this.getPage()?
fn = ()=>this.showStartPage()
Hy.Trace.debug "ConsoleApp::resumedPage (EXIT: \"#{fn?}\")"
if fn?
fn()
else
@pageState.resumed()
remotePage = this.remotePlayerMapPage()
@playerNetwork?.sendAll(remotePage.op, remotePage.data)
this
# ----------------------------------------------------------------------------------------------------------------
showPage: (newPageState, fn_newPageInit, postFunctions = [])->
Hy.Trace.debug "ConsoleApp::showPage (ENTER #{newPageState} #{@pageState?.display()})"
fn_showPage = ()=>
Hy.Trace.debug "ConsoleApp::showPage (FIRING #{newPageState} #{@pageState.display()})"
@pageState?.showPage(newPageState, fn_newPageInit, postFunctions)
f = ()=> Hy.Utils.Deferral.create(0, ()=>fn_showPage())
if (newPageState1 = @pageState.isTransitioning())?
if newPageState1 isnt newPageState
@pageState.addPostTransitionAction(f)
else
f()
Hy.Trace.debug "ConsoleApp::showPage (EXIT #{newPageState} #{@pageState.display()})"
this
# ----------------------------------------------------------------------------------------------------------------
showSplashPage: (postFunctions = [])->
if not @splashShown?
this.showPage(Hy.Pages.PageState.Splash, ((page)=>page.initialize()), postFunctions)
@splashShown = true
null
# ----------------------------------------------------------------------------------------------------------------
initNetwork: ()->
Hy.Network.NetworkService.init().setImmediate()
Hy.Network.NetworkService.addObserver this
# ----------------------------------------------------------------------------------------------------------------
# Called by NetworkService when there's a change in the network scenery (since ConsoleApp is an "observer")
#
obs_networkChanged: (evt = null)->
Hy.Trace.debug "ConsoleApp::obs_networkChanged (online=#{Hy.Network.NetworkService.isOnline()})"
super
fn = ()=>
Hy.Trace.debugM "ConsoleApp::obs_networkChanged (FIRING)"
this.initPlayerNetwork()
if not @pageState.isTransitioning()?
this.getPage()?.obs_networkChanged(evt)
null
# If we're in the middle of initialization, postpone this step
if this.isInitCompleted()
fn()
else
this.addInitStep("obs_networkChanged (ADDED)", ()=>fn())
Hy.Trace.debugM "ConsoleApp::obs_networkChanged (DEFERRING)"
this
# ----------------------------------------------------------------------------------------------------------------
initPlayerNetwork: ()->
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (ENTER)"
playerNetwork = null
if @playerNetwork?
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (EXIT Already Initialized)"
return this
if Hy.Network.PlayerNetwork.isSingleUserMode()
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (SINGLE USER MODE)"
return this
if @initializingPlayerNetwork
# Since this function may be called multiple times, in case of a suspend/resume during
# initialization, or due to a change in the network status
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (ALREADY INITIALIZING)"
return this
if not Hy.Network.NetworkService.isOnline()
# Postpone initializing PlayerNetwork subsystem - we don't want to hold up the UI waiting for the device to go online
return
@initializingPlayerNetwork = true
if ++@numPlayerNetworkInitializationAttempts > Hy.Config.PlayerNetwork.kMaxNumInitializationAttempts
m = "Could not initialize after #{@numPlayerNetworkInitializationAttempts-1} attempts."
m += "\nRemote Players may not be able to connect"
new Hy.Utils.ErrorMessage("warning", "Player Network", m) #will display popup dialog
return
handlerSpecs =
fnError: (error, errorState)=>
m = "Player Network (#{@numPlayerNetworkInitializationAttempts})"
new Hy.Utils.ErrorMessage(errorState, m, error) #will display popup dialog
switch errorState
when "fatal"
this.obs_networkChanged() # to update UI.
when "retry"
this.stopPlayerNetwork()
Hy.Utils.Deferral.create(Hy.Config.PlayerNetwork.kTimeBetweenInitializationAttempts, ()=>this.obs_networkChanged()) # to update UI and make another init attempt
when "warning"
null
null
fnReady: ()=>
Hy.Trace.debug "ConsoleApp::initPlayerNetwork (fnReady)"
@initializingPlayerNetwork = false
@numPlayerNetworkInitializationAttempts = 0
@playerNetwork = playerNetwork
this.playerNetworkReadyForUser()
null
fnMessageReceived: (connection, op, data)=>this.remotePlayerMessage(connection, op, data)
fnAddPlayer: (connection, label, majorVersion, minorVersion)=>this.remotePlayerAdded(connection, label, majorVersion, minorVersion)
fnRemovePlayer: (connection)=>this.remotePlayerRemoved(connection)
fnPlayerStatusChange: (connection, status)=>this.remotePlayerStatusChanged(connection, status)
fnServiceStatusChange: (serviceStatus)=>
#this.serviceStatusChange(serviceStatus)
this.obs_networkChanged() # to update UI
null
playerNetwork = Hy.Network.PlayerNetwork.create(handlerSpecs)
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (EXIT)"
this
# ----------------------------------------------------------------------------------------------------------------
stopPlayerNetwork: ()->
@initializingPlayerNetwork = false
@playerNetwork?.stop()
@playerNetwork = null
this
# ----------------------------------------------------------------------------------------------------------------
playerNetworkReadyForUser: ()->
Hy.Trace.debug "ConsoleApp::playerNetworkReadyForUser"
@timedOperation.mark("Network Ready")
fireEvent = true
if (newPageState = @pageState.isTransitioning())?
if newPageState is Hy.Pages.PageState.Splash
this.showStartPage()
else
if this.getPage()?
if this.getPage().getState() is Hy.Pages.PageState.Splash
this.showStartPage()
fireEvent = false
else
this.getPage().resumed()
remotePage = this.remotePlayerMapPage()
@playerNetwork?.sendAll(remotePage.op, remotePage.data)
else
this.showStartPage()
if fireEvent
this.obs_networkChanged()
null
# ----------------------------------------------------------------------------------------------------------------
playerNetworkReadyForUser2: ()->
Hy.Trace.debug "ConsoleApp::playerNetworkReadyForUser"
@timedOperation.mark("Network Ready")
fireEvent = true
if this.getPage()?
if this.getPage().getState() is Hy.Pages.PageState.Splash
this.showStartPage()
fireEvent = false
else
this.getPage().resumed()
remotePage = this.remotePlayerMapPage()
@playerNetwork?.sendAll(remotePage.op, remotePage.data)
else
if (newPageState = @pageState.isTransitioning())?
if newPageState is Hy.Pages.PageState.Splash
this.showStartPage()
if fireEvent
this.obs_networkChanged()
null
# ----------------------------------------------------------------------------------------------------------------
serviceStatusChange: (serviceStatus)->
Hy.Trace.debug "ConsoleApp::serviceStatusChange"
this
# ----------------------------------------------------------------------------------------------------------------
showAboutPage: ()->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.About, (page)=>page.initialize())
# ----------------------------------------------------------------------------------------------------------------
showGameOptionsPage: ()->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.GameOptions, (page)=>page.initialize())
# ----------------------------------------------------------------------------------------------------------------
showJoinCodeInfoPage: ()->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.JoinCodeInfo, (page)=>page.initialize())
# ----------------------------------------------------------------------------------------------------------------
# Show the start page, and then execute the specified functions
#
showStartPage: (postFunctions = [])->
Hy.Trace.debug "ConsoleApp::showStartPage"
@questionChallengeInProgress = false
this.showPage(Hy.Pages.PageState.Start, ((page)=>page.initialize()), postFunctions)
@playerNetwork?.sendAll("prepForContest", {})
this
# ----------------------------------------------------------------------------------------------------------------
# Invoked from "StartPage" when the enabled state of the Start Button changes.
#
obs_startPageStartButtonStateChanged: (state, reason)->
@playerNetwork?.sendAll("prepForContest", {startEnabled: state, reason: reason})
this
# ----------------------------------------------------------------------------------------------------------------
# Invoked from Page "StartPage" when "Start Game" button is touched
#
contestStart: ()->
page = this.getPage()
Hy.Media.SoundManager.get().playEvent("gameStart")
page.contentPacksLoadingStart()
if this.loadQuestions()
@nQuestions = @contest.contestQuestions.length
@iQuestion = 0
@nAnswered = 0 # number of times at least one player responded
page.contentPacksLoadingCompleted()
Hy.Player.ConsolePlayer.findConsolePlayer().setHasAnswered(false)
Hy.Network.NetworkService.get().setSuspended()
@playerNetwork?.sendAll('startContest', {})
this.showCurrentQuestion()
@analytics?.logContestStart()
else
page.contentPacksLoadingCompleted()
page.resetStartButtonClicked()
this
# ----------------------------------------------------------------------------------------------------------------
#
loadQuestions: ()->
fnEdgeCaseError = (message)=>
new Hy.Utils.ErrorMessage("fatal", "Console App Options", message) #will display popup dialog
false
contentManager = Hy.Content.ContentManager.get()
this.getPage().contentPacksLoading("Loading topics...")
@contentLoadTimer = new Hy.Utils.TimedOperation("INITIAL CONTENT LOAD")
totalNumQuestions = 0
for contentPack in (contentPacks = _.select(contentManager.getLatestContentPacksOKToDisplay(), (c)=>c.isSelected()))
# Edge case: content pack isn't actually local...!
if contentPack.isReadyForPlay()
contentPack.load()
totalNumQuestions += contentPack.getNumRecords()
else
return fnEdgeCaseError("Topic \"#{contentPack.getDisplayName()}\" not ready for play. Please unselect it")
numSelectedContentPacks = _.size(contentPacks)
@contentLoadTimer.mark("done")
# Edge case: Shouldn't be here if no topics chosen...
if numSelectedContentPacks is 0
return fnEdgeCaseError("No topics chosen - Please choose one or more topics and try again")
# Edge case: corruption in the option
if not (numQuestionsNeeded = Hy.Options.numQuestions.getValue())? or not Hy.Options.numQuestions.isValidValue(numQuestionsNeeded)
fnEdgeCaseError("Invalid \"Number of Questions\" option, resetting to 5 (#{numQuestionsNeeded})")
numQuestionsNeeded = 5
Hy.Options.numQuestions.setValue(numQuestionsNeeded)
# this.getPage().panelNumberOfQuestions.syncCurrentChoiceWithAppOption() # No longer on this page
# Special Case: numQuestions is -1, means "Play as many questions as possible, up to some limit"
if numQuestionsNeeded is -1
# Enforce max number
numQuestionsNeeded = Math.min(totalNumQuestions, Hy.Config.Dynamics.maxNumQuestions)
# Edge case: Shouldn't really be in this situation, either: not enough questions!
# We should be able to set numQuestionsNeeded to a lower value to make it work, since
# we know that the min number of questions in any contest is 5.
if (shortfall = (numQuestionsNeeded - totalNumQuestions)) > 0
for choice in Hy.Options.numQuestions.getChoices().slice(0).reverse()
if choice isnt -1
if (shortfall = (choice-totalNumQuestions)) <= 0
numQuestionsNeeded = choice
Hy.Options.numQuestions.setValue(numQuestionsNeeded)
# this.getPage().panelNumberOfQuestions.syncCurrentChoiceWithAppOption() # No longer on this page
this.getPage().contentPacksLoading("Number of questions reduced to accomodate selected topics...")
break
# Something's wrong: apparently have a contest with fewer than 5 questions
if shortfall > 0
return fnEdgeCaseError("Not enough questions - Please choose more topics and try again (requested=#{numQuestionsNeeded} shortfall=#{shortfall})")
this.getPage().contentPacksLoading("Selecting questions...")
# Edge case: if number of selected content packs > number of requested questions...
numQuestionsPerPack = Math.max(1, Math.floor(numQuestionsNeeded / numSelectedContentPacks))
@contest = new Hy.Contest.Contest()
# This loop should always terminate because we know there are more than enough questions
contentPacks = Hy.Utils.Array.shuffle(contentPacks)
index = -1
numQuestionsFound = 0
while numQuestionsFound < numQuestionsNeeded
if index < (numSelectedContentPacks - 1)
index++
else
index = 0
numQuestionsPerPack = 1 # To fill in the remainder
contentPack = contentPacks[index]
numQuestionsFound += (numQuestionsAdded = @contest.addQuestions(contentPack, numQuestionsPerPack))
if numQuestionsAdded < numQuestionsPerPack
Hy.Trace.debug "ConsoleApp::loadQuestions (NOT ENOUGH QUESTIONS FOUND pack=#{contentPack.getProductID()} #requested=#{numQuestionsPerPack} #found=#{numQuestionsAdded})"
# return false # We should be ok, because we know there are enough questions in total...
for contestQuestion in @contest.getQuestions()
question = contestQuestion.getQuestion()
Hy.Trace.debug "ConsoleApp::contestStart (question ##{question.id} #{question.topic})"
true
# ----------------------------------------------------------------------------------------------------------------
contestPaused: (remotePage)->
@playerNetwork?.sendAll('gamePaused', {page: remotePage})
this
# ----------------------------------------------------------------------------------------------------------------
contestRestart: (completed = true)->
# set this before showing the Start Page
Hy.Network.NetworkService.get().setImmediate()
this.showStartPage()
# this.logContestEnd(completed, @nQuestions, @nAnswered, @contest)
this
# ----------------------------------------------------------------------------------------------------------------
# Player requested that we skip to the final Scoreboard
#
contestForceFinish: ()->
this.contestCompleted()
this
# ----------------------------------------------------------------------------------------------------------------
contestCompleted: ()->
Hy.Trace.debug("ConsoleApp::contestCompleted")
fnNotify = ()=>
if not (Hy.Network.PlayerNetwork.isSingleUserMode() or Hy.Player.Player.isConsolePlayerOnly())
for o in (leaderboard = this.getPage().getLeaderboard())
for player in o.group
Hy.Trace.debug("ConsoleApp::contestCompleted (score: #{o.score} player#: #{player})")
@playerNetwork?.sendAll('contestCompleted', {leaderboard: leaderboard})
null
iQuestion = @iQuestion # By the time the init function below is called, @iQuestion will have been nulled out
Hy.Network.NetworkService.get().setImmediate()
this.showPage(Hy.Pages.PageState.Completed, ((page)=>page.initialize()), [()=>fnNotify()])
Hy.Network.NetworkService.get().setImmediate()
this.logContestEnd(true, @iQuestion, @nAnswered, @contest)
@nQuestions = null
@iQuestion = null
@cq = null
Hy.Utils.MemInfo.log "Contest Completed"
this
# ----------------------------------------------------------------------------------------------------------------
showQuestionChallengePage: (startingDelay)->
someText = @cq.question.question
someText = someText.substr(0, Math.min(30, someText.length))
Hy.Trace.debug "ConsoleApp::showQuestionChallengePage (#=#{@iQuestion} question=#{@cq.question.id}/#{someText})"
@currentPageHadResponses = false #set to true if at least one player responded to current question
@questionChallengeInProgress = true
# we copy these here to avoid possible issues with variable bindings, when the callbacks below are invoked
cq = @cq
iQuestion = @iQuestion
nQuestions = @nQuestions
fnNotify = ()=>@playerNetwork?.sendAll('showQuestion', {questionId: cq.question.id})
nSeconds = Hy.Options.secondsPerQuestion.choices[Hy.Options.secondsPerQuestion.index]
if not nSeconds? or not (nSeconds >= 10 and nSeconds <= 570) # this is brittle. HACK
error = "INVALID nSeconds: #{nSeconds}"
Hy.Trace.debug "ConsoleApp (#{error})"
new Hy.Utils.ErrorMessage("fatal", "Console App Options", error) #will display popup dialog
nSeconds = 10
Hy.Options.secondsPerQuestion.setIndex(0)
# this.getPage().panelSecondsPerQuestion.syncCurrentChoiceWithAppOption() # No longer on this page
controlInfo =
fnPause: (isPaused)=>if isPaused then this.contestPaused("showQuestion") else fnNotify()
fnCompleted: ()=>this.challengeCompleted()
countdownSeconds: nSeconds
startingDelay: startingDelay
questionSpec =
contestQuestion: cq
iQuestion: iQuestion
nQuestions: nQuestions
this.showPage(Hy.Pages.PageState.Question, ((page)=>page.initialize("question", controlInfo, questionSpec)), [()=>fnNotify()])
# ----------------------------------------------------------------------------------------------------------------
challengeCompleted: (finishedEarly=false)->
if @questionChallengeInProgress
Hy.Media.SoundManager.get().playEvent("challengeCompleted")
this.getPage().animateCountdownQuestionCompleted()
this.getPage().stop() #haltCountdown() #adding this here to ensure that countdown stops immediately, avoid overlapping countdowns
@questionChallengeInProgress = false
@cq.setUsed()
@nAnswered++ if @currentPageHadResponses
this.showQuestionAnswerPage()
# ----------------------------------------------------------------------------------------------------------------
showQuestionAnswerPage: ()->
# Hy.Trace.debug "ConsoleApp::showQuestionAnswerPage(#=#{@iQuestion} question=#{@cq.question.id} Responses=#{@currentPageHadResponses} nAnswered=#{@nAnswered})"
responseVector = []
# Tell the remotes if we received their responses in time
for response in Hy.Contest.ContestResponse.selectByQuestionID(@cq.question.id)
responseVector.push {player: response.getPlayer().getIndex(), score: response.getScore()}
fnNotify = ()=>@playerNetwork?.sendAll('revealAnswer', {questionId: @cq.question.id, indexCorrectAnswer: @cq.indexCorrectAnswer, responses:responseVector})
controlInfo =
fnPause: (isPaused)=>if isPaused then this.contestPaused("revealAnswer") else fnNotify()
fnCompleted: ()=>this.questionAnswerCompleted()
countdownSeconds: Hy.Config.Dynamics.revealAnswerTime
startingDelay: 0
this.showPage(Hy.Pages.PageState.Answer, ((page)=>page.initialize("answer", controlInfo)), [()=>fnNotify()])
# ----------------------------------------------------------------------------------------------------------------
questionAnswerCompleted: ()->
Hy.Trace.debug "ConsoleApp::questionAnswerCompleted(#=#{@iQuestion} question=#{@cq.question.id})"
@iQuestion++
if @iQuestion >= @nQuestions
this.contestCompleted()
else
this.showCurrentQuestion()
this
# ----------------------------------------------------------------------------------------------------------------
showCurrentQuestion: ()->
Hy.Trace.debug "ConsoleApp::showCurrentQuestion(#=#{@iQuestion})"
@cq = @contest.contestQuestions[@iQuestion]
if @iQuestion >= @nQuestions
this.contestCompleted()
else
this.showQuestionChallengePage(500)
this
# ----------------------------------------------------------------------------------------------------------------
remotePlayerAdded: (connection, label, majorVersion, minorVersion)->
Hy.Trace.debug "ConsoleApp::remotePlayerAdded (##{connection}/#{label})"
s = "?"
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
player.reactivate()
s = "EXISTING"
else
player = Hy.Player.RemotePlayer.create(connection, label, majorVersion, minorVersion)
@analytics?.logNewPlayer(Hy.Player.Player.count() - 1 ) # Don't count the console player
s = "NEW"
Hy.Media.SoundManager.get().playEvent("remotePlayerJoined")
remotePage = this.remotePlayerMapPage()
currentResponse = null
if @cq?
currentResponse = Hy.Contest.ContestResponse.selectByQuestionIDAndPlayer @cq.question.id, player
Hy.Trace.debug "ConsoleApp::remotePlayerAdded (#{s} #{player.dumpStr()} page=#{remotePage.op} currentAnswerIndex=#{if currentResponse? then currentResponse.answerIndex else -1})"
op = "welcome"
data = {}
data.index = player.index
data.page = remotePage
data.questionId = (if @cq? then @cq.question.id else -1)
data.answerIndex = (if currentResponse? then currentResponse.answerIndex else -1)
data.score = player.score()
data.playerName = player.getName()
@playerNetwork?.sendSingle(player.getConnection(), op, data)
player
# ----------------------------------------------------------------------------------------------------------------
remotePlayerRemoved: (connection)->
Hy.Trace.debug "ConsoleApp::remotePlayerRemoved (#{connection})"
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
Hy.Trace.debug "ConsoleApp::remotePlayerRemoved (#{player.dumpStr()})"
player.destroy()
this
# ----------------------------------------------------------------------------------------------------------------
remotePlayerStatusChanged: (connection, status)->
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
Hy.Trace.debug "ConsoleApp::remotePlayerStatusChanged (status=#{status} #{player.dumpStr()})"
if status
player.reactivate()
else
player.deactivate()
this
# ----------------------------------------------------------------------------------------------------------------
remotePlayerMessage: (connection, op, data)->
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
if op is "playerNameChangeRequest"
this.doPlayerNameChangeRequest(player, data)
else
if @pageState.isTransitioning()
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (IGNORING, in Page Transition)"
else
if not this.doGameOp(player, op, data)
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (UNKNOWN OP #{op} #{connection})"
else
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (UNKNOWN PLAYER #{connection})"
this
# ----------------------------------------------------------------------------------------------------------------
doPlayerNameChangeRequest: (player, data)->
result = player.setName(data.name)
if result.errorMessage?
data.errorMessage = result.errorMessage
else
data.givenName = result.givenName
@playerNetwork?.sendSingle(player.getConnection(), "playerNameChangeRequestResponse", data)
true
# ----------------------------------------------------------------------------------------------------------------
doGameOp: (player, op, data)->
handled = true
switch op
when "answer"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (Answered: question=#{data.questionId} answer=#{data.answerIndex} player=#{player.dumpStr()})"
this.playerAnswered(player, data.questionId, data.answerIndex)
when "pauseRequested"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (pauseRequested: player=#{player.dumpStr()})"
if this.getPage()?
switch this.getPage().getState()
when Hy.Pages.PageState.Question, Hy.Pages.PageState.Answer
if not this.getPage().isPaused()
this.getPage().fnPauseClick()
when "continueRequested"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (continueRequested: player=#{player.dumpStr()})"
if this.getPage()?
switch this.getPage().getState()
when Hy.Pages.PageState.Question, Hy.Pages.PageState.Answer
if this.getPage().isPaused()
this.getPage().fnClickContinueGame()
when "newGameRequested"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (newGameRequested: player=#{player.dumpStr()})"
if this.getPage()?
switch this.getPage().getState()
when Hy.Pages.PageState.Start
this.getPage().fnClickStartGame()
when Hy.Pages.PageState.Completed
this.getPage().fnClickPlayAgain()
when Hy.Pages.PageState.Question, Hy.Pages.PageState.Answer
if this.getPage().isPaused()
this.getPage().fnClickNewGame()
else
handled = false
handled
# ----------------------------------------------------------------------------------------------------------------
remotePlayerMapPage: ()->
page = this.getPage()
remotePage = if page?
switch page.constructor.name
when "SplashPage"
{op: "introPage"}
when "StartPage"
[state, reason] = page.getStartEnabled()
{op: "prepForContest", data: {startEnabled:state, reason: reason}}
when "AboutPage", "ContentOptionsPage", "JoinCodeInfoPage", "GameOptionsPage"
{op: "aboutPage"}
when "QuestionPage"
if page.isPaused()
{op: "gamePaused"}
else
if @questionChallengeInProgress && page.getCountdownValue() > 5
{op: "showQuestion", data: {questionId: (if @cq? then @cq.question.id else -1)}}
else
{op: "waitingForQuestion"}
when "ContestCompletedPage"
{op: "contestCompleted"}
else
{op: "prepForContest"}
else
{op: "prepForContest"}
remotePage
# ----------------------------------------------------------------------------------------------------------------
consolePlayerAnswered: (answerIndex)->
Hy.Player.ConsolePlayer.findConsolePlayer().setHasAnswered(true)
this.playerAnswered(Hy.Player.ConsolePlayer.findConsolePlayer(), @cq.question.id, answerIndex)
this
# ----------------------------------------------------------------------------------------------------------------
playerAnswered: (player, questionId, answerIndex)->
if not this.answeringAllowed(questionId)
return
isConsole = player.isKind(Hy.Player.Player.kKindConsole)
responses = Hy.Contest.ContestResponse.selectByQuestionID(questionId)
if (r = this.playerAlreadyAnswered(player, responses))?
# Hy.Trace.debug "ConsoleApp::playerAnswered(Player already answered! questionId=#{questionId}, answerIndex (last time)=#{r.answerIndex} answerIndex (this time)=#{answerIndex} player => #{player.index})"
return
cq = Hy.Contest.ContestQuestion.findByQuestionID(@contest.contestQuestions, questionId)
isCorrectAnswer = cq.indexCorrectAnswer is answerIndex
# Hy.Trace.debug "ConsoleApp::playerAnswered(#=#{@iQuestion} questionId=#{questionId} answerIndex=#{answerIndex} correct=#{cq.indexCorrectAnswer} #{if isCorrectAnswer then "CORRECT" else "INCORRECT"} player=#{player.index}/#{player.label})"
response = player.buildResponse(cq, answerIndex, this.getPage().getCountdownStartValue(), this.getPage().getCountdownValue())
this.getPage().playerAnswered(response)
@currentPageHadResponses = true
firstCorrectMode = Hy.Options.firstCorrect.getValue() is "yes"
# if all remote players have answered OR if the console player answers, end this challenge
done = if isConsole
true
else
if firstCorrectMode and isCorrectAnswer
true
else
activeRemotePlayers = Hy.Player.Player.getActivePlayersByKind(Hy.Player.Player.kKindRemote)
if (activeRemotePlayers.length is responses.length+1)
true
else
false
if done
this.challengeCompleted(true)
this
# ----------------------------------------------------------------------------------------------------------------
playerAlreadyAnswered: (player, responses)->
return _.detect(responses, (r)=>r.player.index is player.index)
# ----------------------------------------------------------------------------------------------------------------
answeringAllowed: (questionId)->
(@questionChallengeInProgress is true) && (questionId is @cq.question.id)
# ----------------------------------------------------------------------------------------------------------------
logContestEnd: (completed, nQuestions, nAnswered, contest)->
numUserCreatedQuestions = 0
topics = []
for contestQuestion in contest.getQuestions()
if contestQuestion.wasUsed()
# Find the contentPack via the topic, which is really a ProductID
if (contentPack = Hy.Content.ContentPack.findLatestVersion(topic = contestQuestion.getQuestion().topic))?
if contentPack.isThirdParty()
numUserCreatedQuestions++
else
topics.push(topic)
@analytics?.logContestEnd(completed, nQuestions, nAnswered, topics, numUserCreatedQuestions)
this
# ----------------------------------------------------------------------------------------------------------------
userCreatedContentAction: (action, context = null, fn_showPage = null, url = null)->
contentManager = Hy.Content.ContentManager.get()
if fn_showPage?
fn_showPage([(page)=>this.userCreatedContentAction(action, context, null, url)])
else
switch action
when "refresh"
contentManager.userCreatedContentRefreshRequested(context)
when "delete"
contentManager.userCreatedContentDeleteRequested(context)
when "upsell"
contentManager.userCreatedContentUpsell()
when "buy"
contentManager.userCreatedContentBuyFeature()
when "add"
contentManager.userCreatedContentAddRequested(url)
when "samples"
contentManager.userCreatedContentLoadSamples()
when "info"
this.showContentOptionsPage()
this
# ----------------------------------------------------------------------------------------------------------------
showContentOptionsPage: (postFunctions = [])->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.ContentOptions, ((page)=>page.initialize()), postFunctions)
# ----------------------------------------------------------------------------------------------------------------
restoreAction: ()->
this.showStartPage([(page)=>Hy.Content.ContentManager.get().restore()])
this
# ----------------------------------------------------------------------------------------------------------------
applyInitialCustomization: (options = {page: Hy.Pages.PageState.Start})->
if (c = Hy.Content.ContentManager.getCurrentCustomization())?
Hy.Customize.activate(c, options)
else
this.customizationActivated(null, options)
this
# ----------------------------------------------------------------------------------------------------------------
#
# options.page = page to restart onto
#
# options.fn_completed = function to call when done
# options.page = page to transition to when done
#
customizationActivated: (customization = null, options = null)->
Hy.Trace.debug "ConsoleApp::customizationActivated (ENTER #{customization?})"
#
# Approach:
#
# Transition to black screen
# Clear all existing page instances cached via PageState
# Restart on the ContentOptions Page
#
fn_pageState = ()=>
this.doneWithPageState()
this.initPageState()
null
fn_showPage = ()=>
switch options.page
when Hy.Pages.PageState.Start
this.showStartPage([fn_completed])
when Hy.Pages.PageState.ContentOptions
this.showContentOptionsPage([fn_completed])
null
fn_playerNetwork = ()=>
if Hy.Network.PlayerNetwork.isSingleUserMode()
this.stopPlayerNetwork()
else
this.initPlayerNetwork()
null
fn_completed = ()=>
fn_playerNetwork()
options.fn_completed?()
null
fns = [fn_pageState, fn_showPage]
Hy.Utils.Deferral.create(0, ()=>f?() for f in fns)
this
# ----------------------------------------------------------------------------------------------------------------
#
# We're here because the app was launched, or resumed, because the user is trying to
# open a url of the form:
#
# triviapro://args
#
# where "triviallypro" is specified in info.plist/CFBundleURLSchemes
#
# Let's support this form:
#
# triviapro://contest=url
#
doURLArg: (url)->
if url.match(/^triviapro:\/\/customcontest=/)?
if (i = url.indexOf("=")) isnt -1
contestURL = url.substr(i+1)
this.userCreatedContentAction("add", null, ((actions)=>this.showContentOptionsPage(actions)), contestURL)
this
# ==================================================================================================================
# assign to global namespace:
Hy.ConsoleApp = ConsoleApp
| 182122 | # ==================================================================================================================
#
# IT IS REALLY IMPORTANT THAT App-level event handlers return null.
# Ti.App.addEventListener("eventName", (event)=>null)
#
#
class ConsoleApp extends Hy.UI.Application
gInstance = null
# ----------------------------------------------------------------------------------------------------------------
@get: ()-> gInstance
# ----------------------------------------------------------------------------------------------------------------
constructor: (backgroundWindow, tempImage)->
gInstance = this
@playerNetwork = null
@initializingPlayerNetwork = false
@numPlayerNetworkInitializationAttempts = 0
super backgroundWindow, tempImage
this.initSetup()
# HACK V1.0.2
# Ti.UI.Clipboard.setText("https://docs.google.com/a/hyperbotic.com/spreadsheet/pub?key=<KEY>&output=html")
Hy.Pages.StartPage.addObserver this
this
# ----------------------------------------------------------------------------------------------------------------
getContest: ()-> @contest
# ----------------------------------------------------------------------------------------------------------------
getPlayerNetwork: ()-> @playerNetwork
# ----------------------------------------------------------------------------------------------------------------
initSetup: ()->
@initFnChain = []
options = if (newUrl = this.checkURLArg())?
{page: Hy.Pages.PageState.ContentOptions, fn_completed: ()=>this.doURLArg(newUrl)}
else
{page: Hy.Pages.PageState.Start}
initFnSpecs = [
{label: "Trace", init: ()=>Hy.Trace.init(this)}
{label: "Analytics", init: ()=>@analytics = Hy.Analytics.Analytics.init()}
{label: "Customization", init: ()=>Hy.Customize.init((c, o)=>this.customizationActivated(c, o))}
# {label: "CommerceManager", init: ()=>Hy.Commerce.CommerceManager.init()} #2.7
{label: "SoundManager", init: ()=>Hy.Media.SoundManager.init()}
{label: "Network Service", init: ()=>this.initNetwork()}
{label: "DownloadCache", init: ()=>Hy.Network.DownloadCache.init()}
{label: "Update Service", init: ()=>Hy.Update.UpdateService.init()}
{label: "ContentManager", init: ()=>Hy.Content.ContentManager.init()}
{label: "Console Player", init: ()=>Hy.Player.ConsolePlayer.init()}
# {label: "CommerceManagerInventory", init: ()=>Hy.Commerce.CommerceManager.inventoryManagedFeatures()} #2.7
{label: "Page/Video", init: ()=>this.initPageState()}
# Should be the last one
{label: "Customization", init: ()=>this.applyInitialCustomization(options)}
]
for initFnSpec in initFnSpecs
this.addInitStep(initFnSpec.label, initFnSpec.init)
this
# ----------------------------------------------------------------------------------------------------------------
initPageState: ()->
@pageState = Hy.Pages.PageState.init(this)
this
# ----------------------------------------------------------------------------------------------------------------
doneWithPageState: ()->
@pageState?.stop()
@pageState = null
Hy.Pages.PageState.doneWithPageState()
this
# ----------------------------------------------------------------------------------------------------------------
addInitStep: (label, fn)->
@initFnChain.push({label: label, init: fn})
this
# ----------------------------------------------------------------------------------------------------------------
isInitCompleted: ()-> @initFnChain.length is 0
# ----------------------------------------------------------------------------------------------------------------
init: ()->
super
Hy.Utils.MemInfo.init()
Hy.Utils.MemInfo.log "INITIALIZING (init #=#{_.size(@initFnChain)})"
@timedOperation = new Hy.Utils.TimedOperation("INITIALIZATION")
fnExecute = ()=>
while not this.isInitCompleted()
fnSpec = _.first(@initFnChain)
fnSpec.init()
@initFnChain.shift()
@timedOperation.mark(fnSpec.label)
null
fnExecute()
this
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "ConsoleApp::start"
super
@analytics?.logApplicationLaunch()
this
# ----------------------------------------------------------------------------------------------------------------
# Triggered when the app is backgrounded. Have to work quick here. Do the important stuff first
pause: (evt)->
Hy.Trace.debug "ConsoleApp::pause (ENTER)"
this.getPage()?.pause()
@playerNetwork?.pause()
Hy.Network.NetworkService.get().pause()
super evt
Hy.Trace.debug "ConsoleApp::pause (EXIT)"
# ----------------------------------------------------------------------------------------------------------------
# Triggered at the start of the process of being foregrounded. Nothing to do here.
resume: (evt)->
Hy.Trace.debug "ConsoleApp::resume (ENTER page=#{this.getPage()?.constructor.name})"
super evt
Hy.Trace.debug "ConsoleApp::resume (EXIT page=#{this.getPage()?.constructor.name})"
# ----------------------------------------------------------------------------------------------------------------
# Triggered when app is fully foregrounded.
resumed: (evt)->
Hy.Trace.debug "ConsoleApp::resumed (ENTER page=#{this.getPage()?.constructor.name})"
super
this.init()
Hy.Network.NetworkService.get().resumed()
Hy.Network.NetworkService.get().setImmediate()
@playerNetwork?.resumed()
if (newUrl = this.checkURLArg())?
this.doURLArg(newUrl)
else
this.resumedPage()
Hy.Trace.debug "ConsoleApp::resumed (EXIT page=#{this.getPage()?.constructor.name})"
# ----------------------------------------------------------------------------------------------------------------
#
# To handle the edge case where we were backgrounded while transitioning to a new page.
# In the more complex cases, the tactic for handling this is to simply go back to the previous page.
# This approach seems to be needed when the page is based on a web view and requires images to load
#
resumedPage: ()->
Hy.Trace.debug "ConsoleApp::resumedPage (ENTER (transitioning=#{@pageState.isTransitioning()?})"
fn = null
if @pageState.isTransitioning()?
stopTransitioning = true
switch (oldPageState = @pageState.getOldPageState())
when Hy.Pages.PageState.Start, null, Hy.Pages.PageState.Splash
fn = ()=>this.showStartPage()
when Hy.Pages.PageState.Any, Hy.Pages.PageState.None
new Hy.Utils.ErrorMessage("fatal", "Console App", "Unexpected state \"#{oldPageState}\" in resumedPage") #will display popup dialog
fn = ()=>this.showStartPage()
else # About, ContentOptions, Join, Question, Answer, Scoreboard, Completed, Options
stopTransitioning = false
null
if stopTransitioning
@pageState.stopTransitioning()
else
if not this.getPage()?
fn = ()=>this.showStartPage()
Hy.Trace.debug "ConsoleApp::resumedPage (EXIT: \"#{fn?}\")"
if fn?
fn()
else
@pageState.resumed()
remotePage = this.remotePlayerMapPage()
@playerNetwork?.sendAll(remotePage.op, remotePage.data)
this
# ----------------------------------------------------------------------------------------------------------------
showPage: (newPageState, fn_newPageInit, postFunctions = [])->
Hy.Trace.debug "ConsoleApp::showPage (ENTER #{newPageState} #{@pageState?.display()})"
fn_showPage = ()=>
Hy.Trace.debug "ConsoleApp::showPage (FIRING #{newPageState} #{@pageState.display()})"
@pageState?.showPage(newPageState, fn_newPageInit, postFunctions)
f = ()=> Hy.Utils.Deferral.create(0, ()=>fn_showPage())
if (newPageState1 = @pageState.isTransitioning())?
if newPageState1 isnt newPageState
@pageState.addPostTransitionAction(f)
else
f()
Hy.Trace.debug "ConsoleApp::showPage (EXIT #{newPageState} #{@pageState.display()})"
this
# ----------------------------------------------------------------------------------------------------------------
showSplashPage: (postFunctions = [])->
if not @splashShown?
this.showPage(Hy.Pages.PageState.Splash, ((page)=>page.initialize()), postFunctions)
@splashShown = true
null
# ----------------------------------------------------------------------------------------------------------------
initNetwork: ()->
Hy.Network.NetworkService.init().setImmediate()
Hy.Network.NetworkService.addObserver this
# ----------------------------------------------------------------------------------------------------------------
# Called by NetworkService when there's a change in the network scenery (since ConsoleApp is an "observer")
#
obs_networkChanged: (evt = null)->
Hy.Trace.debug "ConsoleApp::obs_networkChanged (online=#{Hy.Network.NetworkService.isOnline()})"
super
fn = ()=>
Hy.Trace.debugM "ConsoleApp::obs_networkChanged (FIRING)"
this.initPlayerNetwork()
if not @pageState.isTransitioning()?
this.getPage()?.obs_networkChanged(evt)
null
# If we're in the middle of initialization, postpone this step
if this.isInitCompleted()
fn()
else
this.addInitStep("obs_networkChanged (ADDED)", ()=>fn())
Hy.Trace.debugM "ConsoleApp::obs_networkChanged (DEFERRING)"
this
# ----------------------------------------------------------------------------------------------------------------
initPlayerNetwork: ()->
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (ENTER)"
playerNetwork = null
if @playerNetwork?
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (EXIT Already Initialized)"
return this
if Hy.Network.PlayerNetwork.isSingleUserMode()
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (SINGLE USER MODE)"
return this
if @initializingPlayerNetwork
# Since this function may be called multiple times, in case of a suspend/resume during
# initialization, or due to a change in the network status
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (ALREADY INITIALIZING)"
return this
if not Hy.Network.NetworkService.isOnline()
# Postpone initializing PlayerNetwork subsystem - we don't want to hold up the UI waiting for the device to go online
return
@initializingPlayerNetwork = true
if ++@numPlayerNetworkInitializationAttempts > Hy.Config.PlayerNetwork.kMaxNumInitializationAttempts
m = "Could not initialize after #{@numPlayerNetworkInitializationAttempts-1} attempts."
m += "\nRemote Players may not be able to connect"
new Hy.Utils.ErrorMessage("warning", "Player Network", m) #will display popup dialog
return
handlerSpecs =
fnError: (error, errorState)=>
m = "Player Network (#{@numPlayerNetworkInitializationAttempts})"
new Hy.Utils.ErrorMessage(errorState, m, error) #will display popup dialog
switch errorState
when "fatal"
this.obs_networkChanged() # to update UI.
when "retry"
this.stopPlayerNetwork()
Hy.Utils.Deferral.create(Hy.Config.PlayerNetwork.kTimeBetweenInitializationAttempts, ()=>this.obs_networkChanged()) # to update UI and make another init attempt
when "warning"
null
null
fnReady: ()=>
Hy.Trace.debug "ConsoleApp::initPlayerNetwork (fnReady)"
@initializingPlayerNetwork = false
@numPlayerNetworkInitializationAttempts = 0
@playerNetwork = playerNetwork
this.playerNetworkReadyForUser()
null
fnMessageReceived: (connection, op, data)=>this.remotePlayerMessage(connection, op, data)
fnAddPlayer: (connection, label, majorVersion, minorVersion)=>this.remotePlayerAdded(connection, label, majorVersion, minorVersion)
fnRemovePlayer: (connection)=>this.remotePlayerRemoved(connection)
fnPlayerStatusChange: (connection, status)=>this.remotePlayerStatusChanged(connection, status)
fnServiceStatusChange: (serviceStatus)=>
#this.serviceStatusChange(serviceStatus)
this.obs_networkChanged() # to update UI
null
playerNetwork = Hy.Network.PlayerNetwork.create(handlerSpecs)
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (EXIT)"
this
# ----------------------------------------------------------------------------------------------------------------
stopPlayerNetwork: ()->
@initializingPlayerNetwork = false
@playerNetwork?.stop()
@playerNetwork = null
this
# ----------------------------------------------------------------------------------------------------------------
playerNetworkReadyForUser: ()->
Hy.Trace.debug "ConsoleApp::playerNetworkReadyForUser"
@timedOperation.mark("Network Ready")
fireEvent = true
if (newPageState = @pageState.isTransitioning())?
if newPageState is Hy.Pages.PageState.Splash
this.showStartPage()
else
if this.getPage()?
if this.getPage().getState() is Hy.Pages.PageState.Splash
this.showStartPage()
fireEvent = false
else
this.getPage().resumed()
remotePage = this.remotePlayerMapPage()
@playerNetwork?.sendAll(remotePage.op, remotePage.data)
else
this.showStartPage()
if fireEvent
this.obs_networkChanged()
null
# ----------------------------------------------------------------------------------------------------------------
playerNetworkReadyForUser2: ()->
Hy.Trace.debug "ConsoleApp::playerNetworkReadyForUser"
@timedOperation.mark("Network Ready")
fireEvent = true
if this.getPage()?
if this.getPage().getState() is Hy.Pages.PageState.Splash
this.showStartPage()
fireEvent = false
else
this.getPage().resumed()
remotePage = this.remotePlayerMapPage()
@playerNetwork?.sendAll(remotePage.op, remotePage.data)
else
if (newPageState = @pageState.isTransitioning())?
if newPageState is Hy.Pages.PageState.Splash
this.showStartPage()
if fireEvent
this.obs_networkChanged()
null
# ----------------------------------------------------------------------------------------------------------------
serviceStatusChange: (serviceStatus)->
Hy.Trace.debug "ConsoleApp::serviceStatusChange"
this
# ----------------------------------------------------------------------------------------------------------------
showAboutPage: ()->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.About, (page)=>page.initialize())
# ----------------------------------------------------------------------------------------------------------------
showGameOptionsPage: ()->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.GameOptions, (page)=>page.initialize())
# ----------------------------------------------------------------------------------------------------------------
showJoinCodeInfoPage: ()->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.JoinCodeInfo, (page)=>page.initialize())
# ----------------------------------------------------------------------------------------------------------------
# Show the start page, and then execute the specified functions
#
showStartPage: (postFunctions = [])->
Hy.Trace.debug "ConsoleApp::showStartPage"
@questionChallengeInProgress = false
this.showPage(Hy.Pages.PageState.Start, ((page)=>page.initialize()), postFunctions)
@playerNetwork?.sendAll("prepForContest", {})
this
# ----------------------------------------------------------------------------------------------------------------
# Invoked from "StartPage" when the enabled state of the Start Button changes.
#
obs_startPageStartButtonStateChanged: (state, reason)->
@playerNetwork?.sendAll("prepForContest", {startEnabled: state, reason: reason})
this
# ----------------------------------------------------------------------------------------------------------------
# Invoked from Page "StartPage" when "Start Game" button is touched
#
contestStart: ()->
page = this.getPage()
Hy.Media.SoundManager.get().playEvent("gameStart")
page.contentPacksLoadingStart()
if this.loadQuestions()
@nQuestions = @contest.contestQuestions.length
@iQuestion = 0
@nAnswered = 0 # number of times at least one player responded
page.contentPacksLoadingCompleted()
Hy.Player.ConsolePlayer.findConsolePlayer().setHasAnswered(false)
Hy.Network.NetworkService.get().setSuspended()
@playerNetwork?.sendAll('startContest', {})
this.showCurrentQuestion()
@analytics?.logContestStart()
else
page.contentPacksLoadingCompleted()
page.resetStartButtonClicked()
this
# ----------------------------------------------------------------------------------------------------------------
#
loadQuestions: ()->
fnEdgeCaseError = (message)=>
new Hy.Utils.ErrorMessage("fatal", "Console App Options", message) #will display popup dialog
false
contentManager = Hy.Content.ContentManager.get()
this.getPage().contentPacksLoading("Loading topics...")
@contentLoadTimer = new Hy.Utils.TimedOperation("INITIAL CONTENT LOAD")
totalNumQuestions = 0
for contentPack in (contentPacks = _.select(contentManager.getLatestContentPacksOKToDisplay(), (c)=>c.isSelected()))
# Edge case: content pack isn't actually local...!
if contentPack.isReadyForPlay()
contentPack.load()
totalNumQuestions += contentPack.getNumRecords()
else
return fnEdgeCaseError("Topic \"#{contentPack.getDisplayName()}\" not ready for play. Please unselect it")
numSelectedContentPacks = _.size(contentPacks)
@contentLoadTimer.mark("done")
# Edge case: Shouldn't be here if no topics chosen...
if numSelectedContentPacks is 0
return fnEdgeCaseError("No topics chosen - Please choose one or more topics and try again")
# Edge case: corruption in the option
if not (numQuestionsNeeded = Hy.Options.numQuestions.getValue())? or not Hy.Options.numQuestions.isValidValue(numQuestionsNeeded)
fnEdgeCaseError("Invalid \"Number of Questions\" option, resetting to 5 (#{numQuestionsNeeded})")
numQuestionsNeeded = 5
Hy.Options.numQuestions.setValue(numQuestionsNeeded)
# this.getPage().panelNumberOfQuestions.syncCurrentChoiceWithAppOption() # No longer on this page
# Special Case: numQuestions is -1, means "Play as many questions as possible, up to some limit"
if numQuestionsNeeded is -1
# Enforce max number
numQuestionsNeeded = Math.min(totalNumQuestions, Hy.Config.Dynamics.maxNumQuestions)
# Edge case: Shouldn't really be in this situation, either: not enough questions!
# We should be able to set numQuestionsNeeded to a lower value to make it work, since
# we know that the min number of questions in any contest is 5.
if (shortfall = (numQuestionsNeeded - totalNumQuestions)) > 0
for choice in Hy.Options.numQuestions.getChoices().slice(0).reverse()
if choice isnt -1
if (shortfall = (choice-totalNumQuestions)) <= 0
numQuestionsNeeded = choice
Hy.Options.numQuestions.setValue(numQuestionsNeeded)
# this.getPage().panelNumberOfQuestions.syncCurrentChoiceWithAppOption() # No longer on this page
this.getPage().contentPacksLoading("Number of questions reduced to accomodate selected topics...")
break
# Something's wrong: apparently have a contest with fewer than 5 questions
if shortfall > 0
return fnEdgeCaseError("Not enough questions - Please choose more topics and try again (requested=#{numQuestionsNeeded} shortfall=#{shortfall})")
this.getPage().contentPacksLoading("Selecting questions...")
# Edge case: if number of selected content packs > number of requested questions...
numQuestionsPerPack = Math.max(1, Math.floor(numQuestionsNeeded / numSelectedContentPacks))
@contest = new Hy.Contest.Contest()
# This loop should always terminate because we know there are more than enough questions
contentPacks = Hy.Utils.Array.shuffle(contentPacks)
index = -1
numQuestionsFound = 0
while numQuestionsFound < numQuestionsNeeded
if index < (numSelectedContentPacks - 1)
index++
else
index = 0
numQuestionsPerPack = 1 # To fill in the remainder
contentPack = contentPacks[index]
numQuestionsFound += (numQuestionsAdded = @contest.addQuestions(contentPack, numQuestionsPerPack))
if numQuestionsAdded < numQuestionsPerPack
Hy.Trace.debug "ConsoleApp::loadQuestions (NOT ENOUGH QUESTIONS FOUND pack=#{contentPack.getProductID()} #requested=#{numQuestionsPerPack} #found=#{numQuestionsAdded})"
# return false # We should be ok, because we know there are enough questions in total...
for contestQuestion in @contest.getQuestions()
question = contestQuestion.getQuestion()
Hy.Trace.debug "ConsoleApp::contestStart (question ##{question.id} #{question.topic})"
true
# ----------------------------------------------------------------------------------------------------------------
contestPaused: (remotePage)->
@playerNetwork?.sendAll('gamePaused', {page: remotePage})
this
# ----------------------------------------------------------------------------------------------------------------
contestRestart: (completed = true)->
# set this before showing the Start Page
Hy.Network.NetworkService.get().setImmediate()
this.showStartPage()
# this.logContestEnd(completed, @nQuestions, @nAnswered, @contest)
this
# ----------------------------------------------------------------------------------------------------------------
# Player requested that we skip to the final Scoreboard
#
contestForceFinish: ()->
this.contestCompleted()
this
# ----------------------------------------------------------------------------------------------------------------
contestCompleted: ()->
Hy.Trace.debug("ConsoleApp::contestCompleted")
fnNotify = ()=>
if not (Hy.Network.PlayerNetwork.isSingleUserMode() or Hy.Player.Player.isConsolePlayerOnly())
for o in (leaderboard = this.getPage().getLeaderboard())
for player in o.group
Hy.Trace.debug("ConsoleApp::contestCompleted (score: #{o.score} player#: #{player})")
@playerNetwork?.sendAll('contestCompleted', {leaderboard: leaderboard})
null
iQuestion = @iQuestion # By the time the init function below is called, @iQuestion will have been nulled out
Hy.Network.NetworkService.get().setImmediate()
this.showPage(Hy.Pages.PageState.Completed, ((page)=>page.initialize()), [()=>fnNotify()])
Hy.Network.NetworkService.get().setImmediate()
this.logContestEnd(true, @iQuestion, @nAnswered, @contest)
@nQuestions = null
@iQuestion = null
@cq = null
Hy.Utils.MemInfo.log "Contest Completed"
this
# ----------------------------------------------------------------------------------------------------------------
showQuestionChallengePage: (startingDelay)->
someText = @cq.question.question
someText = someText.substr(0, Math.min(30, someText.length))
Hy.Trace.debug "ConsoleApp::showQuestionChallengePage (#=#{@iQuestion} question=#{@cq.question.id}/#{someText})"
@currentPageHadResponses = false #set to true if at least one player responded to current question
@questionChallengeInProgress = true
# we copy these here to avoid possible issues with variable bindings, when the callbacks below are invoked
cq = @cq
iQuestion = @iQuestion
nQuestions = @nQuestions
fnNotify = ()=>@playerNetwork?.sendAll('showQuestion', {questionId: cq.question.id})
nSeconds = Hy.Options.secondsPerQuestion.choices[Hy.Options.secondsPerQuestion.index]
if not nSeconds? or not (nSeconds >= 10 and nSeconds <= 570) # this is brittle. HACK
error = "INVALID nSeconds: #{nSeconds}"
Hy.Trace.debug "ConsoleApp (#{error})"
new Hy.Utils.ErrorMessage("fatal", "Console App Options", error) #will display popup dialog
nSeconds = 10
Hy.Options.secondsPerQuestion.setIndex(0)
# this.getPage().panelSecondsPerQuestion.syncCurrentChoiceWithAppOption() # No longer on this page
controlInfo =
fnPause: (isPaused)=>if isPaused then this.contestPaused("showQuestion") else fnNotify()
fnCompleted: ()=>this.challengeCompleted()
countdownSeconds: nSeconds
startingDelay: startingDelay
questionSpec =
contestQuestion: cq
iQuestion: iQuestion
nQuestions: nQuestions
this.showPage(Hy.Pages.PageState.Question, ((page)=>page.initialize("question", controlInfo, questionSpec)), [()=>fnNotify()])
# ----------------------------------------------------------------------------------------------------------------
challengeCompleted: (finishedEarly=false)->
if @questionChallengeInProgress
Hy.Media.SoundManager.get().playEvent("challengeCompleted")
this.getPage().animateCountdownQuestionCompleted()
this.getPage().stop() #haltCountdown() #adding this here to ensure that countdown stops immediately, avoid overlapping countdowns
@questionChallengeInProgress = false
@cq.setUsed()
@nAnswered++ if @currentPageHadResponses
this.showQuestionAnswerPage()
# ----------------------------------------------------------------------------------------------------------------
showQuestionAnswerPage: ()->
# Hy.Trace.debug "ConsoleApp::showQuestionAnswerPage(#=#{@iQuestion} question=#{@cq.question.id} Responses=#{@currentPageHadResponses} nAnswered=#{@nAnswered})"
responseVector = []
# Tell the remotes if we received their responses in time
for response in Hy.Contest.ContestResponse.selectByQuestionID(@cq.question.id)
responseVector.push {player: response.getPlayer().getIndex(), score: response.getScore()}
fnNotify = ()=>@playerNetwork?.sendAll('revealAnswer', {questionId: @cq.question.id, indexCorrectAnswer: @cq.indexCorrectAnswer, responses:responseVector})
controlInfo =
fnPause: (isPaused)=>if isPaused then this.contestPaused("revealAnswer") else fnNotify()
fnCompleted: ()=>this.questionAnswerCompleted()
countdownSeconds: Hy.Config.Dynamics.revealAnswerTime
startingDelay: 0
this.showPage(Hy.Pages.PageState.Answer, ((page)=>page.initialize("answer", controlInfo)), [()=>fnNotify()])
# ----------------------------------------------------------------------------------------------------------------
questionAnswerCompleted: ()->
Hy.Trace.debug "ConsoleApp::questionAnswerCompleted(#=#{@iQuestion} question=#{@cq.question.id})"
@iQuestion++
if @iQuestion >= @nQuestions
this.contestCompleted()
else
this.showCurrentQuestion()
this
# ----------------------------------------------------------------------------------------------------------------
showCurrentQuestion: ()->
Hy.Trace.debug "ConsoleApp::showCurrentQuestion(#=#{@iQuestion})"
@cq = @contest.contestQuestions[@iQuestion]
if @iQuestion >= @nQuestions
this.contestCompleted()
else
this.showQuestionChallengePage(500)
this
# ----------------------------------------------------------------------------------------------------------------
remotePlayerAdded: (connection, label, majorVersion, minorVersion)->
Hy.Trace.debug "ConsoleApp::remotePlayerAdded (##{connection}/#{label})"
s = "?"
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
player.reactivate()
s = "EXISTING"
else
player = Hy.Player.RemotePlayer.create(connection, label, majorVersion, minorVersion)
@analytics?.logNewPlayer(Hy.Player.Player.count() - 1 ) # Don't count the console player
s = "NEW"
Hy.Media.SoundManager.get().playEvent("remotePlayerJoined")
remotePage = this.remotePlayerMapPage()
currentResponse = null
if @cq?
currentResponse = Hy.Contest.ContestResponse.selectByQuestionIDAndPlayer @cq.question.id, player
Hy.Trace.debug "ConsoleApp::remotePlayerAdded (#{s} #{player.dumpStr()} page=#{remotePage.op} currentAnswerIndex=#{if currentResponse? then currentResponse.answerIndex else -1})"
op = "welcome"
data = {}
data.index = player.index
data.page = remotePage
data.questionId = (if @cq? then @cq.question.id else -1)
data.answerIndex = (if currentResponse? then currentResponse.answerIndex else -1)
data.score = player.score()
data.playerName = player.getName()
@playerNetwork?.sendSingle(player.getConnection(), op, data)
player
# ----------------------------------------------------------------------------------------------------------------
remotePlayerRemoved: (connection)->
Hy.Trace.debug "ConsoleApp::remotePlayerRemoved (#{connection})"
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
Hy.Trace.debug "ConsoleApp::remotePlayerRemoved (#{player.dumpStr()})"
player.destroy()
this
# ----------------------------------------------------------------------------------------------------------------
remotePlayerStatusChanged: (connection, status)->
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
Hy.Trace.debug "ConsoleApp::remotePlayerStatusChanged (status=#{status} #{player.dumpStr()})"
if status
player.reactivate()
else
player.deactivate()
this
# ----------------------------------------------------------------------------------------------------------------
remotePlayerMessage: (connection, op, data)->
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
if op is "playerNameChangeRequest"
this.doPlayerNameChangeRequest(player, data)
else
if @pageState.isTransitioning()
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (IGNORING, in Page Transition)"
else
if not this.doGameOp(player, op, data)
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (UNKNOWN OP #{op} #{connection})"
else
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (UNKNOWN PLAYER #{connection})"
this
# ----------------------------------------------------------------------------------------------------------------
doPlayerNameChangeRequest: (player, data)->
result = player.setName(data.name)
if result.errorMessage?
data.errorMessage = result.errorMessage
else
data.givenName = result.givenName
@playerNetwork?.sendSingle(player.getConnection(), "playerNameChangeRequestResponse", data)
true
# ----------------------------------------------------------------------------------------------------------------
doGameOp: (player, op, data)->
handled = true
switch op
when "answer"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (Answered: question=#{data.questionId} answer=#{data.answerIndex} player=#{player.dumpStr()})"
this.playerAnswered(player, data.questionId, data.answerIndex)
when "pauseRequested"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (pauseRequested: player=#{player.dumpStr()})"
if this.getPage()?
switch this.getPage().getState()
when Hy.Pages.PageState.Question, Hy.Pages.PageState.Answer
if not this.getPage().isPaused()
this.getPage().fnPauseClick()
when "continueRequested"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (continueRequested: player=#{player.dumpStr()})"
if this.getPage()?
switch this.getPage().getState()
when Hy.Pages.PageState.Question, Hy.Pages.PageState.Answer
if this.getPage().isPaused()
this.getPage().fnClickContinueGame()
when "newGameRequested"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (newGameRequested: player=#{player.dumpStr()})"
if this.getPage()?
switch this.getPage().getState()
when Hy.Pages.PageState.Start
this.getPage().fnClickStartGame()
when Hy.Pages.PageState.Completed
this.getPage().fnClickPlayAgain()
when Hy.Pages.PageState.Question, Hy.Pages.PageState.Answer
if this.getPage().isPaused()
this.getPage().fnClickNewGame()
else
handled = false
handled
# ----------------------------------------------------------------------------------------------------------------
remotePlayerMapPage: ()->
page = this.getPage()
remotePage = if page?
switch page.constructor.name
when "SplashPage"
{op: "introPage"}
when "StartPage"
[state, reason] = page.getStartEnabled()
{op: "prepForContest", data: {startEnabled:state, reason: reason}}
when "AboutPage", "ContentOptionsPage", "JoinCodeInfoPage", "GameOptionsPage"
{op: "aboutPage"}
when "QuestionPage"
if page.isPaused()
{op: "gamePaused"}
else
if @questionChallengeInProgress && page.getCountdownValue() > 5
{op: "showQuestion", data: {questionId: (if @cq? then @cq.question.id else -1)}}
else
{op: "waitingForQuestion"}
when "ContestCompletedPage"
{op: "contestCompleted"}
else
{op: "prepForContest"}
else
{op: "prepForContest"}
remotePage
# ----------------------------------------------------------------------------------------------------------------
consolePlayerAnswered: (answerIndex)->
Hy.Player.ConsolePlayer.findConsolePlayer().setHasAnswered(true)
this.playerAnswered(Hy.Player.ConsolePlayer.findConsolePlayer(), @cq.question.id, answerIndex)
this
# ----------------------------------------------------------------------------------------------------------------
playerAnswered: (player, questionId, answerIndex)->
if not this.answeringAllowed(questionId)
return
isConsole = player.isKind(Hy.Player.Player.kKindConsole)
responses = Hy.Contest.ContestResponse.selectByQuestionID(questionId)
if (r = this.playerAlreadyAnswered(player, responses))?
# Hy.Trace.debug "ConsoleApp::playerAnswered(Player already answered! questionId=#{questionId}, answerIndex (last time)=#{r.answerIndex} answerIndex (this time)=#{answerIndex} player => #{player.index})"
return
cq = Hy.Contest.ContestQuestion.findByQuestionID(@contest.contestQuestions, questionId)
isCorrectAnswer = cq.indexCorrectAnswer is answerIndex
# Hy.Trace.debug "ConsoleApp::playerAnswered(#=#{@iQuestion} questionId=#{questionId} answerIndex=#{answerIndex} correct=#{cq.indexCorrectAnswer} #{if isCorrectAnswer then "CORRECT" else "INCORRECT"} player=#{player.index}/#{player.label})"
response = player.buildResponse(cq, answerIndex, this.getPage().getCountdownStartValue(), this.getPage().getCountdownValue())
this.getPage().playerAnswered(response)
@currentPageHadResponses = true
firstCorrectMode = Hy.Options.firstCorrect.getValue() is "yes"
# if all remote players have answered OR if the console player answers, end this challenge
done = if isConsole
true
else
if firstCorrectMode and isCorrectAnswer
true
else
activeRemotePlayers = Hy.Player.Player.getActivePlayersByKind(Hy.Player.Player.kKindRemote)
if (activeRemotePlayers.length is responses.length+1)
true
else
false
if done
this.challengeCompleted(true)
this
# ----------------------------------------------------------------------------------------------------------------
playerAlreadyAnswered: (player, responses)->
return _.detect(responses, (r)=>r.player.index is player.index)
# ----------------------------------------------------------------------------------------------------------------
answeringAllowed: (questionId)->
(@questionChallengeInProgress is true) && (questionId is @cq.question.id)
# ----------------------------------------------------------------------------------------------------------------
logContestEnd: (completed, nQuestions, nAnswered, contest)->
numUserCreatedQuestions = 0
topics = []
for contestQuestion in contest.getQuestions()
if contestQuestion.wasUsed()
# Find the contentPack via the topic, which is really a ProductID
if (contentPack = Hy.Content.ContentPack.findLatestVersion(topic = contestQuestion.getQuestion().topic))?
if contentPack.isThirdParty()
numUserCreatedQuestions++
else
topics.push(topic)
@analytics?.logContestEnd(completed, nQuestions, nAnswered, topics, numUserCreatedQuestions)
this
# ----------------------------------------------------------------------------------------------------------------
userCreatedContentAction: (action, context = null, fn_showPage = null, url = null)->
contentManager = Hy.Content.ContentManager.get()
if fn_showPage?
fn_showPage([(page)=>this.userCreatedContentAction(action, context, null, url)])
else
switch action
when "refresh"
contentManager.userCreatedContentRefreshRequested(context)
when "delete"
contentManager.userCreatedContentDeleteRequested(context)
when "upsell"
contentManager.userCreatedContentUpsell()
when "buy"
contentManager.userCreatedContentBuyFeature()
when "add"
contentManager.userCreatedContentAddRequested(url)
when "samples"
contentManager.userCreatedContentLoadSamples()
when "info"
this.showContentOptionsPage()
this
# ----------------------------------------------------------------------------------------------------------------
showContentOptionsPage: (postFunctions = [])->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.ContentOptions, ((page)=>page.initialize()), postFunctions)
# ----------------------------------------------------------------------------------------------------------------
restoreAction: ()->
this.showStartPage([(page)=>Hy.Content.ContentManager.get().restore()])
this
# ----------------------------------------------------------------------------------------------------------------
applyInitialCustomization: (options = {page: Hy.Pages.PageState.Start})->
if (c = Hy.Content.ContentManager.getCurrentCustomization())?
Hy.Customize.activate(c, options)
else
this.customizationActivated(null, options)
this
# ----------------------------------------------------------------------------------------------------------------
#
# options.page = page to restart onto
#
# options.fn_completed = function to call when done
# options.page = page to transition to when done
#
customizationActivated: (customization = null, options = null)->
Hy.Trace.debug "ConsoleApp::customizationActivated (ENTER #{customization?})"
#
# Approach:
#
# Transition to black screen
# Clear all existing page instances cached via PageState
# Restart on the ContentOptions Page
#
fn_pageState = ()=>
this.doneWithPageState()
this.initPageState()
null
fn_showPage = ()=>
switch options.page
when Hy.Pages.PageState.Start
this.showStartPage([fn_completed])
when Hy.Pages.PageState.ContentOptions
this.showContentOptionsPage([fn_completed])
null
fn_playerNetwork = ()=>
if Hy.Network.PlayerNetwork.isSingleUserMode()
this.stopPlayerNetwork()
else
this.initPlayerNetwork()
null
fn_completed = ()=>
fn_playerNetwork()
options.fn_completed?()
null
fns = [fn_pageState, fn_showPage]
Hy.Utils.Deferral.create(0, ()=>f?() for f in fns)
this
# ----------------------------------------------------------------------------------------------------------------
#
# We're here because the app was launched, or resumed, because the user is trying to
# open a url of the form:
#
# triviapro://args
#
# where "triviallypro" is specified in info.plist/CFBundleURLSchemes
#
# Let's support this form:
#
# triviapro://contest=url
#
doURLArg: (url)->
if url.match(/^triviapro:\/\/customcontest=/)?
if (i = url.indexOf("=")) isnt -1
contestURL = url.substr(i+1)
this.userCreatedContentAction("add", null, ((actions)=>this.showContentOptionsPage(actions)), contestURL)
this
# ==================================================================================================================
# assign to global namespace:
Hy.ConsoleApp = ConsoleApp
| true | # ==================================================================================================================
#
# IT IS REALLY IMPORTANT THAT App-level event handlers return null.
# Ti.App.addEventListener("eventName", (event)=>null)
#
#
class ConsoleApp extends Hy.UI.Application
gInstance = null
# ----------------------------------------------------------------------------------------------------------------
@get: ()-> gInstance
# ----------------------------------------------------------------------------------------------------------------
constructor: (backgroundWindow, tempImage)->
gInstance = this
@playerNetwork = null
@initializingPlayerNetwork = false
@numPlayerNetworkInitializationAttempts = 0
super backgroundWindow, tempImage
this.initSetup()
# HACK V1.0.2
# Ti.UI.Clipboard.setText("https://docs.google.com/a/hyperbotic.com/spreadsheet/pub?key=PI:KEY:<KEY>END_PI&output=html")
Hy.Pages.StartPage.addObserver this
this
# ----------------------------------------------------------------------------------------------------------------
getContest: ()-> @contest
# ----------------------------------------------------------------------------------------------------------------
getPlayerNetwork: ()-> @playerNetwork
# ----------------------------------------------------------------------------------------------------------------
initSetup: ()->
@initFnChain = []
options = if (newUrl = this.checkURLArg())?
{page: Hy.Pages.PageState.ContentOptions, fn_completed: ()=>this.doURLArg(newUrl)}
else
{page: Hy.Pages.PageState.Start}
initFnSpecs = [
{label: "Trace", init: ()=>Hy.Trace.init(this)}
{label: "Analytics", init: ()=>@analytics = Hy.Analytics.Analytics.init()}
{label: "Customization", init: ()=>Hy.Customize.init((c, o)=>this.customizationActivated(c, o))}
# {label: "CommerceManager", init: ()=>Hy.Commerce.CommerceManager.init()} #2.7
{label: "SoundManager", init: ()=>Hy.Media.SoundManager.init()}
{label: "Network Service", init: ()=>this.initNetwork()}
{label: "DownloadCache", init: ()=>Hy.Network.DownloadCache.init()}
{label: "Update Service", init: ()=>Hy.Update.UpdateService.init()}
{label: "ContentManager", init: ()=>Hy.Content.ContentManager.init()}
{label: "Console Player", init: ()=>Hy.Player.ConsolePlayer.init()}
# {label: "CommerceManagerInventory", init: ()=>Hy.Commerce.CommerceManager.inventoryManagedFeatures()} #2.7
{label: "Page/Video", init: ()=>this.initPageState()}
# Should be the last one
{label: "Customization", init: ()=>this.applyInitialCustomization(options)}
]
for initFnSpec in initFnSpecs
this.addInitStep(initFnSpec.label, initFnSpec.init)
this
# ----------------------------------------------------------------------------------------------------------------
initPageState: ()->
@pageState = Hy.Pages.PageState.init(this)
this
# ----------------------------------------------------------------------------------------------------------------
doneWithPageState: ()->
@pageState?.stop()
@pageState = null
Hy.Pages.PageState.doneWithPageState()
this
# ----------------------------------------------------------------------------------------------------------------
addInitStep: (label, fn)->
@initFnChain.push({label: label, init: fn})
this
# ----------------------------------------------------------------------------------------------------------------
isInitCompleted: ()-> @initFnChain.length is 0
# ----------------------------------------------------------------------------------------------------------------
init: ()->
super
Hy.Utils.MemInfo.init()
Hy.Utils.MemInfo.log "INITIALIZING (init #=#{_.size(@initFnChain)})"
@timedOperation = new Hy.Utils.TimedOperation("INITIALIZATION")
fnExecute = ()=>
while not this.isInitCompleted()
fnSpec = _.first(@initFnChain)
fnSpec.init()
@initFnChain.shift()
@timedOperation.mark(fnSpec.label)
null
fnExecute()
this
# ----------------------------------------------------------------------------------------------------------------
start: ()->
Hy.Trace.debug "ConsoleApp::start"
super
@analytics?.logApplicationLaunch()
this
# ----------------------------------------------------------------------------------------------------------------
# Triggered when the app is backgrounded. Have to work quick here. Do the important stuff first
pause: (evt)->
Hy.Trace.debug "ConsoleApp::pause (ENTER)"
this.getPage()?.pause()
@playerNetwork?.pause()
Hy.Network.NetworkService.get().pause()
super evt
Hy.Trace.debug "ConsoleApp::pause (EXIT)"
# ----------------------------------------------------------------------------------------------------------------
# Triggered at the start of the process of being foregrounded. Nothing to do here.
resume: (evt)->
Hy.Trace.debug "ConsoleApp::resume (ENTER page=#{this.getPage()?.constructor.name})"
super evt
Hy.Trace.debug "ConsoleApp::resume (EXIT page=#{this.getPage()?.constructor.name})"
# ----------------------------------------------------------------------------------------------------------------
# Triggered when app is fully foregrounded.
resumed: (evt)->
Hy.Trace.debug "ConsoleApp::resumed (ENTER page=#{this.getPage()?.constructor.name})"
super
this.init()
Hy.Network.NetworkService.get().resumed()
Hy.Network.NetworkService.get().setImmediate()
@playerNetwork?.resumed()
if (newUrl = this.checkURLArg())?
this.doURLArg(newUrl)
else
this.resumedPage()
Hy.Trace.debug "ConsoleApp::resumed (EXIT page=#{this.getPage()?.constructor.name})"
# ----------------------------------------------------------------------------------------------------------------
#
# To handle the edge case where we were backgrounded while transitioning to a new page.
# In the more complex cases, the tactic for handling this is to simply go back to the previous page.
# This approach seems to be needed when the page is based on a web view and requires images to load
#
resumedPage: ()->
Hy.Trace.debug "ConsoleApp::resumedPage (ENTER (transitioning=#{@pageState.isTransitioning()?})"
fn = null
if @pageState.isTransitioning()?
stopTransitioning = true
switch (oldPageState = @pageState.getOldPageState())
when Hy.Pages.PageState.Start, null, Hy.Pages.PageState.Splash
fn = ()=>this.showStartPage()
when Hy.Pages.PageState.Any, Hy.Pages.PageState.None
new Hy.Utils.ErrorMessage("fatal", "Console App", "Unexpected state \"#{oldPageState}\" in resumedPage") #will display popup dialog
fn = ()=>this.showStartPage()
else # About, ContentOptions, Join, Question, Answer, Scoreboard, Completed, Options
stopTransitioning = false
null
if stopTransitioning
@pageState.stopTransitioning()
else
if not this.getPage()?
fn = ()=>this.showStartPage()
Hy.Trace.debug "ConsoleApp::resumedPage (EXIT: \"#{fn?}\")"
if fn?
fn()
else
@pageState.resumed()
remotePage = this.remotePlayerMapPage()
@playerNetwork?.sendAll(remotePage.op, remotePage.data)
this
# ----------------------------------------------------------------------------------------------------------------
showPage: (newPageState, fn_newPageInit, postFunctions = [])->
Hy.Trace.debug "ConsoleApp::showPage (ENTER #{newPageState} #{@pageState?.display()})"
fn_showPage = ()=>
Hy.Trace.debug "ConsoleApp::showPage (FIRING #{newPageState} #{@pageState.display()})"
@pageState?.showPage(newPageState, fn_newPageInit, postFunctions)
f = ()=> Hy.Utils.Deferral.create(0, ()=>fn_showPage())
if (newPageState1 = @pageState.isTransitioning())?
if newPageState1 isnt newPageState
@pageState.addPostTransitionAction(f)
else
f()
Hy.Trace.debug "ConsoleApp::showPage (EXIT #{newPageState} #{@pageState.display()})"
this
# ----------------------------------------------------------------------------------------------------------------
showSplashPage: (postFunctions = [])->
if not @splashShown?
this.showPage(Hy.Pages.PageState.Splash, ((page)=>page.initialize()), postFunctions)
@splashShown = true
null
# ----------------------------------------------------------------------------------------------------------------
initNetwork: ()->
Hy.Network.NetworkService.init().setImmediate()
Hy.Network.NetworkService.addObserver this
# ----------------------------------------------------------------------------------------------------------------
# Called by NetworkService when there's a change in the network scenery (since ConsoleApp is an "observer")
#
obs_networkChanged: (evt = null)->
Hy.Trace.debug "ConsoleApp::obs_networkChanged (online=#{Hy.Network.NetworkService.isOnline()})"
super
fn = ()=>
Hy.Trace.debugM "ConsoleApp::obs_networkChanged (FIRING)"
this.initPlayerNetwork()
if not @pageState.isTransitioning()?
this.getPage()?.obs_networkChanged(evt)
null
# If we're in the middle of initialization, postpone this step
if this.isInitCompleted()
fn()
else
this.addInitStep("obs_networkChanged (ADDED)", ()=>fn())
Hy.Trace.debugM "ConsoleApp::obs_networkChanged (DEFERRING)"
this
# ----------------------------------------------------------------------------------------------------------------
initPlayerNetwork: ()->
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (ENTER)"
playerNetwork = null
if @playerNetwork?
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (EXIT Already Initialized)"
return this
if Hy.Network.PlayerNetwork.isSingleUserMode()
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (SINGLE USER MODE)"
return this
if @initializingPlayerNetwork
# Since this function may be called multiple times, in case of a suspend/resume during
# initialization, or due to a change in the network status
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (ALREADY INITIALIZING)"
return this
if not Hy.Network.NetworkService.isOnline()
# Postpone initializing PlayerNetwork subsystem - we don't want to hold up the UI waiting for the device to go online
return
@initializingPlayerNetwork = true
if ++@numPlayerNetworkInitializationAttempts > Hy.Config.PlayerNetwork.kMaxNumInitializationAttempts
m = "Could not initialize after #{@numPlayerNetworkInitializationAttempts-1} attempts."
m += "\nRemote Players may not be able to connect"
new Hy.Utils.ErrorMessage("warning", "Player Network", m) #will display popup dialog
return
handlerSpecs =
fnError: (error, errorState)=>
m = "Player Network (#{@numPlayerNetworkInitializationAttempts})"
new Hy.Utils.ErrorMessage(errorState, m, error) #will display popup dialog
switch errorState
when "fatal"
this.obs_networkChanged() # to update UI.
when "retry"
this.stopPlayerNetwork()
Hy.Utils.Deferral.create(Hy.Config.PlayerNetwork.kTimeBetweenInitializationAttempts, ()=>this.obs_networkChanged()) # to update UI and make another init attempt
when "warning"
null
null
fnReady: ()=>
Hy.Trace.debug "ConsoleApp::initPlayerNetwork (fnReady)"
@initializingPlayerNetwork = false
@numPlayerNetworkInitializationAttempts = 0
@playerNetwork = playerNetwork
this.playerNetworkReadyForUser()
null
fnMessageReceived: (connection, op, data)=>this.remotePlayerMessage(connection, op, data)
fnAddPlayer: (connection, label, majorVersion, minorVersion)=>this.remotePlayerAdded(connection, label, majorVersion, minorVersion)
fnRemovePlayer: (connection)=>this.remotePlayerRemoved(connection)
fnPlayerStatusChange: (connection, status)=>this.remotePlayerStatusChanged(connection, status)
fnServiceStatusChange: (serviceStatus)=>
#this.serviceStatusChange(serviceStatus)
this.obs_networkChanged() # to update UI
null
playerNetwork = Hy.Network.PlayerNetwork.create(handlerSpecs)
Hy.Trace.debugM "ConsoleApp::initPlayerNetwork (EXIT)"
this
# ----------------------------------------------------------------------------------------------------------------
stopPlayerNetwork: ()->
@initializingPlayerNetwork = false
@playerNetwork?.stop()
@playerNetwork = null
this
# ----------------------------------------------------------------------------------------------------------------
playerNetworkReadyForUser: ()->
Hy.Trace.debug "ConsoleApp::playerNetworkReadyForUser"
@timedOperation.mark("Network Ready")
fireEvent = true
if (newPageState = @pageState.isTransitioning())?
if newPageState is Hy.Pages.PageState.Splash
this.showStartPage()
else
if this.getPage()?
if this.getPage().getState() is Hy.Pages.PageState.Splash
this.showStartPage()
fireEvent = false
else
this.getPage().resumed()
remotePage = this.remotePlayerMapPage()
@playerNetwork?.sendAll(remotePage.op, remotePage.data)
else
this.showStartPage()
if fireEvent
this.obs_networkChanged()
null
# ----------------------------------------------------------------------------------------------------------------
playerNetworkReadyForUser2: ()->
Hy.Trace.debug "ConsoleApp::playerNetworkReadyForUser"
@timedOperation.mark("Network Ready")
fireEvent = true
if this.getPage()?
if this.getPage().getState() is Hy.Pages.PageState.Splash
this.showStartPage()
fireEvent = false
else
this.getPage().resumed()
remotePage = this.remotePlayerMapPage()
@playerNetwork?.sendAll(remotePage.op, remotePage.data)
else
if (newPageState = @pageState.isTransitioning())?
if newPageState is Hy.Pages.PageState.Splash
this.showStartPage()
if fireEvent
this.obs_networkChanged()
null
# ----------------------------------------------------------------------------------------------------------------
serviceStatusChange: (serviceStatus)->
Hy.Trace.debug "ConsoleApp::serviceStatusChange"
this
# ----------------------------------------------------------------------------------------------------------------
showAboutPage: ()->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.About, (page)=>page.initialize())
# ----------------------------------------------------------------------------------------------------------------
showGameOptionsPage: ()->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.GameOptions, (page)=>page.initialize())
# ----------------------------------------------------------------------------------------------------------------
showJoinCodeInfoPage: ()->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.JoinCodeInfo, (page)=>page.initialize())
# ----------------------------------------------------------------------------------------------------------------
# Show the start page, and then execute the specified functions
#
showStartPage: (postFunctions = [])->
Hy.Trace.debug "ConsoleApp::showStartPage"
@questionChallengeInProgress = false
this.showPage(Hy.Pages.PageState.Start, ((page)=>page.initialize()), postFunctions)
@playerNetwork?.sendAll("prepForContest", {})
this
# ----------------------------------------------------------------------------------------------------------------
# Invoked from "StartPage" when the enabled state of the Start Button changes.
#
obs_startPageStartButtonStateChanged: (state, reason)->
@playerNetwork?.sendAll("prepForContest", {startEnabled: state, reason: reason})
this
# ----------------------------------------------------------------------------------------------------------------
# Invoked from Page "StartPage" when "Start Game" button is touched
#
contestStart: ()->
page = this.getPage()
Hy.Media.SoundManager.get().playEvent("gameStart")
page.contentPacksLoadingStart()
if this.loadQuestions()
@nQuestions = @contest.contestQuestions.length
@iQuestion = 0
@nAnswered = 0 # number of times at least one player responded
page.contentPacksLoadingCompleted()
Hy.Player.ConsolePlayer.findConsolePlayer().setHasAnswered(false)
Hy.Network.NetworkService.get().setSuspended()
@playerNetwork?.sendAll('startContest', {})
this.showCurrentQuestion()
@analytics?.logContestStart()
else
page.contentPacksLoadingCompleted()
page.resetStartButtonClicked()
this
# ----------------------------------------------------------------------------------------------------------------
#
loadQuestions: ()->
fnEdgeCaseError = (message)=>
new Hy.Utils.ErrorMessage("fatal", "Console App Options", message) #will display popup dialog
false
contentManager = Hy.Content.ContentManager.get()
this.getPage().contentPacksLoading("Loading topics...")
@contentLoadTimer = new Hy.Utils.TimedOperation("INITIAL CONTENT LOAD")
totalNumQuestions = 0
for contentPack in (contentPacks = _.select(contentManager.getLatestContentPacksOKToDisplay(), (c)=>c.isSelected()))
# Edge case: content pack isn't actually local...!
if contentPack.isReadyForPlay()
contentPack.load()
totalNumQuestions += contentPack.getNumRecords()
else
return fnEdgeCaseError("Topic \"#{contentPack.getDisplayName()}\" not ready for play. Please unselect it")
numSelectedContentPacks = _.size(contentPacks)
@contentLoadTimer.mark("done")
# Edge case: Shouldn't be here if no topics chosen...
if numSelectedContentPacks is 0
return fnEdgeCaseError("No topics chosen - Please choose one or more topics and try again")
# Edge case: corruption in the option
if not (numQuestionsNeeded = Hy.Options.numQuestions.getValue())? or not Hy.Options.numQuestions.isValidValue(numQuestionsNeeded)
fnEdgeCaseError("Invalid \"Number of Questions\" option, resetting to 5 (#{numQuestionsNeeded})")
numQuestionsNeeded = 5
Hy.Options.numQuestions.setValue(numQuestionsNeeded)
# this.getPage().panelNumberOfQuestions.syncCurrentChoiceWithAppOption() # No longer on this page
# Special Case: numQuestions is -1, means "Play as many questions as possible, up to some limit"
if numQuestionsNeeded is -1
# Enforce max number
numQuestionsNeeded = Math.min(totalNumQuestions, Hy.Config.Dynamics.maxNumQuestions)
# Edge case: Shouldn't really be in this situation, either: not enough questions!
# We should be able to set numQuestionsNeeded to a lower value to make it work, since
# we know that the min number of questions in any contest is 5.
if (shortfall = (numQuestionsNeeded - totalNumQuestions)) > 0
for choice in Hy.Options.numQuestions.getChoices().slice(0).reverse()
if choice isnt -1
if (shortfall = (choice-totalNumQuestions)) <= 0
numQuestionsNeeded = choice
Hy.Options.numQuestions.setValue(numQuestionsNeeded)
# this.getPage().panelNumberOfQuestions.syncCurrentChoiceWithAppOption() # No longer on this page
this.getPage().contentPacksLoading("Number of questions reduced to accomodate selected topics...")
break
# Something's wrong: apparently have a contest with fewer than 5 questions
if shortfall > 0
return fnEdgeCaseError("Not enough questions - Please choose more topics and try again (requested=#{numQuestionsNeeded} shortfall=#{shortfall})")
this.getPage().contentPacksLoading("Selecting questions...")
# Edge case: if number of selected content packs > number of requested questions...
numQuestionsPerPack = Math.max(1, Math.floor(numQuestionsNeeded / numSelectedContentPacks))
@contest = new Hy.Contest.Contest()
# This loop should always terminate because we know there are more than enough questions
contentPacks = Hy.Utils.Array.shuffle(contentPacks)
index = -1
numQuestionsFound = 0
while numQuestionsFound < numQuestionsNeeded
if index < (numSelectedContentPacks - 1)
index++
else
index = 0
numQuestionsPerPack = 1 # To fill in the remainder
contentPack = contentPacks[index]
numQuestionsFound += (numQuestionsAdded = @contest.addQuestions(contentPack, numQuestionsPerPack))
if numQuestionsAdded < numQuestionsPerPack
Hy.Trace.debug "ConsoleApp::loadQuestions (NOT ENOUGH QUESTIONS FOUND pack=#{contentPack.getProductID()} #requested=#{numQuestionsPerPack} #found=#{numQuestionsAdded})"
# return false # We should be ok, because we know there are enough questions in total...
for contestQuestion in @contest.getQuestions()
question = contestQuestion.getQuestion()
Hy.Trace.debug "ConsoleApp::contestStart (question ##{question.id} #{question.topic})"
true
# ----------------------------------------------------------------------------------------------------------------
contestPaused: (remotePage)->
@playerNetwork?.sendAll('gamePaused', {page: remotePage})
this
# ----------------------------------------------------------------------------------------------------------------
contestRestart: (completed = true)->
# set this before showing the Start Page
Hy.Network.NetworkService.get().setImmediate()
this.showStartPage()
# this.logContestEnd(completed, @nQuestions, @nAnswered, @contest)
this
# ----------------------------------------------------------------------------------------------------------------
# Player requested that we skip to the final Scoreboard
#
contestForceFinish: ()->
this.contestCompleted()
this
# ----------------------------------------------------------------------------------------------------------------
contestCompleted: ()->
Hy.Trace.debug("ConsoleApp::contestCompleted")
fnNotify = ()=>
if not (Hy.Network.PlayerNetwork.isSingleUserMode() or Hy.Player.Player.isConsolePlayerOnly())
for o in (leaderboard = this.getPage().getLeaderboard())
for player in o.group
Hy.Trace.debug("ConsoleApp::contestCompleted (score: #{o.score} player#: #{player})")
@playerNetwork?.sendAll('contestCompleted', {leaderboard: leaderboard})
null
iQuestion = @iQuestion # By the time the init function below is called, @iQuestion will have been nulled out
Hy.Network.NetworkService.get().setImmediate()
this.showPage(Hy.Pages.PageState.Completed, ((page)=>page.initialize()), [()=>fnNotify()])
Hy.Network.NetworkService.get().setImmediate()
this.logContestEnd(true, @iQuestion, @nAnswered, @contest)
@nQuestions = null
@iQuestion = null
@cq = null
Hy.Utils.MemInfo.log "Contest Completed"
this
# ----------------------------------------------------------------------------------------------------------------
showQuestionChallengePage: (startingDelay)->
someText = @cq.question.question
someText = someText.substr(0, Math.min(30, someText.length))
Hy.Trace.debug "ConsoleApp::showQuestionChallengePage (#=#{@iQuestion} question=#{@cq.question.id}/#{someText})"
@currentPageHadResponses = false #set to true if at least one player responded to current question
@questionChallengeInProgress = true
# we copy these here to avoid possible issues with variable bindings, when the callbacks below are invoked
cq = @cq
iQuestion = @iQuestion
nQuestions = @nQuestions
fnNotify = ()=>@playerNetwork?.sendAll('showQuestion', {questionId: cq.question.id})
nSeconds = Hy.Options.secondsPerQuestion.choices[Hy.Options.secondsPerQuestion.index]
if not nSeconds? or not (nSeconds >= 10 and nSeconds <= 570) # this is brittle. HACK
error = "INVALID nSeconds: #{nSeconds}"
Hy.Trace.debug "ConsoleApp (#{error})"
new Hy.Utils.ErrorMessage("fatal", "Console App Options", error) #will display popup dialog
nSeconds = 10
Hy.Options.secondsPerQuestion.setIndex(0)
# this.getPage().panelSecondsPerQuestion.syncCurrentChoiceWithAppOption() # No longer on this page
controlInfo =
fnPause: (isPaused)=>if isPaused then this.contestPaused("showQuestion") else fnNotify()
fnCompleted: ()=>this.challengeCompleted()
countdownSeconds: nSeconds
startingDelay: startingDelay
questionSpec =
contestQuestion: cq
iQuestion: iQuestion
nQuestions: nQuestions
this.showPage(Hy.Pages.PageState.Question, ((page)=>page.initialize("question", controlInfo, questionSpec)), [()=>fnNotify()])
# ----------------------------------------------------------------------------------------------------------------
challengeCompleted: (finishedEarly=false)->
if @questionChallengeInProgress
Hy.Media.SoundManager.get().playEvent("challengeCompleted")
this.getPage().animateCountdownQuestionCompleted()
this.getPage().stop() #haltCountdown() #adding this here to ensure that countdown stops immediately, avoid overlapping countdowns
@questionChallengeInProgress = false
@cq.setUsed()
@nAnswered++ if @currentPageHadResponses
this.showQuestionAnswerPage()
# ----------------------------------------------------------------------------------------------------------------
showQuestionAnswerPage: ()->
# Hy.Trace.debug "ConsoleApp::showQuestionAnswerPage(#=#{@iQuestion} question=#{@cq.question.id} Responses=#{@currentPageHadResponses} nAnswered=#{@nAnswered})"
responseVector = []
# Tell the remotes if we received their responses in time
for response in Hy.Contest.ContestResponse.selectByQuestionID(@cq.question.id)
responseVector.push {player: response.getPlayer().getIndex(), score: response.getScore()}
fnNotify = ()=>@playerNetwork?.sendAll('revealAnswer', {questionId: @cq.question.id, indexCorrectAnswer: @cq.indexCorrectAnswer, responses:responseVector})
controlInfo =
fnPause: (isPaused)=>if isPaused then this.contestPaused("revealAnswer") else fnNotify()
fnCompleted: ()=>this.questionAnswerCompleted()
countdownSeconds: Hy.Config.Dynamics.revealAnswerTime
startingDelay: 0
this.showPage(Hy.Pages.PageState.Answer, ((page)=>page.initialize("answer", controlInfo)), [()=>fnNotify()])
# ----------------------------------------------------------------------------------------------------------------
questionAnswerCompleted: ()->
Hy.Trace.debug "ConsoleApp::questionAnswerCompleted(#=#{@iQuestion} question=#{@cq.question.id})"
@iQuestion++
if @iQuestion >= @nQuestions
this.contestCompleted()
else
this.showCurrentQuestion()
this
# ----------------------------------------------------------------------------------------------------------------
showCurrentQuestion: ()->
Hy.Trace.debug "ConsoleApp::showCurrentQuestion(#=#{@iQuestion})"
@cq = @contest.contestQuestions[@iQuestion]
if @iQuestion >= @nQuestions
this.contestCompleted()
else
this.showQuestionChallengePage(500)
this
# ----------------------------------------------------------------------------------------------------------------
remotePlayerAdded: (connection, label, majorVersion, minorVersion)->
Hy.Trace.debug "ConsoleApp::remotePlayerAdded (##{connection}/#{label})"
s = "?"
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
player.reactivate()
s = "EXISTING"
else
player = Hy.Player.RemotePlayer.create(connection, label, majorVersion, minorVersion)
@analytics?.logNewPlayer(Hy.Player.Player.count() - 1 ) # Don't count the console player
s = "NEW"
Hy.Media.SoundManager.get().playEvent("remotePlayerJoined")
remotePage = this.remotePlayerMapPage()
currentResponse = null
if @cq?
currentResponse = Hy.Contest.ContestResponse.selectByQuestionIDAndPlayer @cq.question.id, player
Hy.Trace.debug "ConsoleApp::remotePlayerAdded (#{s} #{player.dumpStr()} page=#{remotePage.op} currentAnswerIndex=#{if currentResponse? then currentResponse.answerIndex else -1})"
op = "welcome"
data = {}
data.index = player.index
data.page = remotePage
data.questionId = (if @cq? then @cq.question.id else -1)
data.answerIndex = (if currentResponse? then currentResponse.answerIndex else -1)
data.score = player.score()
data.playerName = player.getName()
@playerNetwork?.sendSingle(player.getConnection(), op, data)
player
# ----------------------------------------------------------------------------------------------------------------
remotePlayerRemoved: (connection)->
Hy.Trace.debug "ConsoleApp::remotePlayerRemoved (#{connection})"
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
Hy.Trace.debug "ConsoleApp::remotePlayerRemoved (#{player.dumpStr()})"
player.destroy()
this
# ----------------------------------------------------------------------------------------------------------------
remotePlayerStatusChanged: (connection, status)->
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
Hy.Trace.debug "ConsoleApp::remotePlayerStatusChanged (status=#{status} #{player.dumpStr()})"
if status
player.reactivate()
else
player.deactivate()
this
# ----------------------------------------------------------------------------------------------------------------
remotePlayerMessage: (connection, op, data)->
player = Hy.Player.RemotePlayer.findByConnection(connection)
if player?
if op is "playerNameChangeRequest"
this.doPlayerNameChangeRequest(player, data)
else
if @pageState.isTransitioning()
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (IGNORING, in Page Transition)"
else
if not this.doGameOp(player, op, data)
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (UNKNOWN OP #{op} #{connection})"
else
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (UNKNOWN PLAYER #{connection})"
this
# ----------------------------------------------------------------------------------------------------------------
doPlayerNameChangeRequest: (player, data)->
result = player.setName(data.name)
if result.errorMessage?
data.errorMessage = result.errorMessage
else
data.givenName = result.givenName
@playerNetwork?.sendSingle(player.getConnection(), "playerNameChangeRequestResponse", data)
true
# ----------------------------------------------------------------------------------------------------------------
doGameOp: (player, op, data)->
handled = true
switch op
when "answer"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (Answered: question=#{data.questionId} answer=#{data.answerIndex} player=#{player.dumpStr()})"
this.playerAnswered(player, data.questionId, data.answerIndex)
when "pauseRequested"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (pauseRequested: player=#{player.dumpStr()})"
if this.getPage()?
switch this.getPage().getState()
when Hy.Pages.PageState.Question, Hy.Pages.PageState.Answer
if not this.getPage().isPaused()
this.getPage().fnPauseClick()
when "continueRequested"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (continueRequested: player=#{player.dumpStr()})"
if this.getPage()?
switch this.getPage().getState()
when Hy.Pages.PageState.Question, Hy.Pages.PageState.Answer
if this.getPage().isPaused()
this.getPage().fnClickContinueGame()
when "newGameRequested"
Hy.Trace.debug "ConsoleApp::messageReceivedFromPlayer (newGameRequested: player=#{player.dumpStr()})"
if this.getPage()?
switch this.getPage().getState()
when Hy.Pages.PageState.Start
this.getPage().fnClickStartGame()
when Hy.Pages.PageState.Completed
this.getPage().fnClickPlayAgain()
when Hy.Pages.PageState.Question, Hy.Pages.PageState.Answer
if this.getPage().isPaused()
this.getPage().fnClickNewGame()
else
handled = false
handled
# ----------------------------------------------------------------------------------------------------------------
remotePlayerMapPage: ()->
page = this.getPage()
remotePage = if page?
switch page.constructor.name
when "SplashPage"
{op: "introPage"}
when "StartPage"
[state, reason] = page.getStartEnabled()
{op: "prepForContest", data: {startEnabled:state, reason: reason}}
when "AboutPage", "ContentOptionsPage", "JoinCodeInfoPage", "GameOptionsPage"
{op: "aboutPage"}
when "QuestionPage"
if page.isPaused()
{op: "gamePaused"}
else
if @questionChallengeInProgress && page.getCountdownValue() > 5
{op: "showQuestion", data: {questionId: (if @cq? then @cq.question.id else -1)}}
else
{op: "waitingForQuestion"}
when "ContestCompletedPage"
{op: "contestCompleted"}
else
{op: "prepForContest"}
else
{op: "prepForContest"}
remotePage
# ----------------------------------------------------------------------------------------------------------------
consolePlayerAnswered: (answerIndex)->
Hy.Player.ConsolePlayer.findConsolePlayer().setHasAnswered(true)
this.playerAnswered(Hy.Player.ConsolePlayer.findConsolePlayer(), @cq.question.id, answerIndex)
this
# ----------------------------------------------------------------------------------------------------------------
playerAnswered: (player, questionId, answerIndex)->
if not this.answeringAllowed(questionId)
return
isConsole = player.isKind(Hy.Player.Player.kKindConsole)
responses = Hy.Contest.ContestResponse.selectByQuestionID(questionId)
if (r = this.playerAlreadyAnswered(player, responses))?
# Hy.Trace.debug "ConsoleApp::playerAnswered(Player already answered! questionId=#{questionId}, answerIndex (last time)=#{r.answerIndex} answerIndex (this time)=#{answerIndex} player => #{player.index})"
return
cq = Hy.Contest.ContestQuestion.findByQuestionID(@contest.contestQuestions, questionId)
isCorrectAnswer = cq.indexCorrectAnswer is answerIndex
# Hy.Trace.debug "ConsoleApp::playerAnswered(#=#{@iQuestion} questionId=#{questionId} answerIndex=#{answerIndex} correct=#{cq.indexCorrectAnswer} #{if isCorrectAnswer then "CORRECT" else "INCORRECT"} player=#{player.index}/#{player.label})"
response = player.buildResponse(cq, answerIndex, this.getPage().getCountdownStartValue(), this.getPage().getCountdownValue())
this.getPage().playerAnswered(response)
@currentPageHadResponses = true
firstCorrectMode = Hy.Options.firstCorrect.getValue() is "yes"
# if all remote players have answered OR if the console player answers, end this challenge
done = if isConsole
true
else
if firstCorrectMode and isCorrectAnswer
true
else
activeRemotePlayers = Hy.Player.Player.getActivePlayersByKind(Hy.Player.Player.kKindRemote)
if (activeRemotePlayers.length is responses.length+1)
true
else
false
if done
this.challengeCompleted(true)
this
# ----------------------------------------------------------------------------------------------------------------
playerAlreadyAnswered: (player, responses)->
return _.detect(responses, (r)=>r.player.index is player.index)
# ----------------------------------------------------------------------------------------------------------------
answeringAllowed: (questionId)->
(@questionChallengeInProgress is true) && (questionId is @cq.question.id)
# ----------------------------------------------------------------------------------------------------------------
logContestEnd: (completed, nQuestions, nAnswered, contest)->
numUserCreatedQuestions = 0
topics = []
for contestQuestion in contest.getQuestions()
if contestQuestion.wasUsed()
# Find the contentPack via the topic, which is really a ProductID
if (contentPack = Hy.Content.ContentPack.findLatestVersion(topic = contestQuestion.getQuestion().topic))?
if contentPack.isThirdParty()
numUserCreatedQuestions++
else
topics.push(topic)
@analytics?.logContestEnd(completed, nQuestions, nAnswered, topics, numUserCreatedQuestions)
this
# ----------------------------------------------------------------------------------------------------------------
userCreatedContentAction: (action, context = null, fn_showPage = null, url = null)->
contentManager = Hy.Content.ContentManager.get()
if fn_showPage?
fn_showPage([(page)=>this.userCreatedContentAction(action, context, null, url)])
else
switch action
when "refresh"
contentManager.userCreatedContentRefreshRequested(context)
when "delete"
contentManager.userCreatedContentDeleteRequested(context)
when "upsell"
contentManager.userCreatedContentUpsell()
when "buy"
contentManager.userCreatedContentBuyFeature()
when "add"
contentManager.userCreatedContentAddRequested(url)
when "samples"
contentManager.userCreatedContentLoadSamples()
when "info"
this.showContentOptionsPage()
this
# ----------------------------------------------------------------------------------------------------------------
showContentOptionsPage: (postFunctions = [])->
@playerNetwork?.sendAll("aboutPage", {})
this.showPage(Hy.Pages.PageState.ContentOptions, ((page)=>page.initialize()), postFunctions)
# ----------------------------------------------------------------------------------------------------------------
restoreAction: ()->
this.showStartPage([(page)=>Hy.Content.ContentManager.get().restore()])
this
# ----------------------------------------------------------------------------------------------------------------
applyInitialCustomization: (options = {page: Hy.Pages.PageState.Start})->
if (c = Hy.Content.ContentManager.getCurrentCustomization())?
Hy.Customize.activate(c, options)
else
this.customizationActivated(null, options)
this
# ----------------------------------------------------------------------------------------------------------------
#
# options.page = page to restart onto
#
# options.fn_completed = function to call when done
# options.page = page to transition to when done
#
customizationActivated: (customization = null, options = null)->
Hy.Trace.debug "ConsoleApp::customizationActivated (ENTER #{customization?})"
#
# Approach:
#
# Transition to black screen
# Clear all existing page instances cached via PageState
# Restart on the ContentOptions Page
#
fn_pageState = ()=>
this.doneWithPageState()
this.initPageState()
null
fn_showPage = ()=>
switch options.page
when Hy.Pages.PageState.Start
this.showStartPage([fn_completed])
when Hy.Pages.PageState.ContentOptions
this.showContentOptionsPage([fn_completed])
null
fn_playerNetwork = ()=>
if Hy.Network.PlayerNetwork.isSingleUserMode()
this.stopPlayerNetwork()
else
this.initPlayerNetwork()
null
fn_completed = ()=>
fn_playerNetwork()
options.fn_completed?()
null
fns = [fn_pageState, fn_showPage]
Hy.Utils.Deferral.create(0, ()=>f?() for f in fns)
this
# ----------------------------------------------------------------------------------------------------------------
#
# We're here because the app was launched, or resumed, because the user is trying to
# open a url of the form:
#
# triviapro://args
#
# where "triviallypro" is specified in info.plist/CFBundleURLSchemes
#
# Let's support this form:
#
# triviapro://contest=url
#
doURLArg: (url)->
if url.match(/^triviapro:\/\/customcontest=/)?
if (i = url.indexOf("=")) isnt -1
contestURL = url.substr(i+1)
this.userCreatedContentAction("add", null, ((actions)=>this.showContentOptionsPage(actions)), contestURL)
this
# ==================================================================================================================
# assign to global namespace:
Hy.ConsoleApp = ConsoleApp
|
[
{
"context": "ast burrito.\",\n \"AIDS.\",\n \"AXE body spray.\",\n \"Aaron Burr.\",\n \"Active listening.\",\n \"Actually getting sho",
"end": 2808,
"score": 0.991296648979187,
"start": 2798,
"tag": "NAME",
"value": "Aaron Burr"
},
{
"context": "\n \"Apologizing.\",\n \"Appre... | src/whitecards.coffee | veronism/hubot-cah | 6 | # White Cards Against Humanity cards to be played against Black cards
#
module.exports = [
"72 virgins.",
"8 oz. of sweet Mexican black-tar heroin.",
"A 55-gallon drum of lube.",
"A Bop It.",
"A Burmese tiger pit.",
"A Christmas stocking full of coleslaw.",
"A Gypsy curse.",
"A Hungry-Man Frozen Christmas Dinner for One.",
"A PowerPoint presentation.",
"A Super Soaker full of cat pee.",
"A bag of magic beans.",
"A balanced breakfast.",
"A beached whale.",
"A big black dick.",
"A big hoopla about nothing.",
"A bigger, blacker dick.",
"A black male in his early 20s, last seen wearing a hoodie.",
"A bleached asshole.",
"A bloody pacifier.",
"A boo-boo.",
"A botched circumcision.",
"A brain tumor.",
"A can of whoop-ass.",
"A cat video so cute that your eyes roll back and your spine slides out of your anus.",
"A clandestine butt scratch.",
"A cooler full of organs.",
"A cop who is also a dog.",
"A crappy little hand.",
"A death ray.",
"A defective condom.",
"A disappointing birthday party.",
"A dollop of sour cream.",
"A drive-by shooting.",
"A falcon with a cap on its head.",
"A fetus.",
"A foul mouth.",
"A gassy antelope.",
"A gentle caress of the inner thigh.",
"A good sniff.",
"A greased-up Matthew McConaughey.",
"A homoerotic volleyball montage.",
"A hot mess.",
"A lamprey swimming up the toilet and latching onto your taint.",
"A lifetime of sadness.",
"A look-see.",
"A low standard of living.",
"A magic hippie love cloud.",
"A man in yoga pants with a ponytail and feather earrings.",
"A mating display.",
"A micropenis.",
"A middle-aged man on roller skates.",
"A mime having a stroke.",
"A monkey smoking a cigar.",
"A mopey zoo lion.",
"A murder most foul.",
"A nuanced critique.",
"A passionate Latino lover.",
"A pile of squirming bodies.",
"A pinata full of scorpions.",
"A really cool hat.",
"A rival dojo",
"A robust mongoloid.",
"A sad fat dragon with no friends.",
"A sad handjob.",
"A salty surprise.",
"A sassy black woman.",
"A sausage festival.",
"A sea of troubles.",
"A slightly shittier parallel universe.",
"A snapping turtle biting the tip of your penis.",
"A soulful rendition of “Ol' Man River.”",
"A spontaneous conga line.",
"A squadron of moles wearing aviator goggles.",
"A stray pube.",
"A surprising amount of hair.",
"A sweaty, panting leather daddy.",
"A sweet spaceship.",
"A thermonuclear detonation.",
"A tiny horse.",
"A toxic family environment.",
"A vagina that leads into another dimension.",
"A visually arresting turtleneck.",
"A web of lies.",
"A windmill full of corpses.",
"A woman scorned.",
"A zesty breakfast burrito.",
"AIDS.",
"AXE body spray.",
"Aaron Burr.",
"Active listening.",
"Actually getting shot, for real.",
"Actually taking candy from a baby.",
"Adderall.",
"African children.",
"Agriculture.",
"Alcoholism.",
"All my friends dying.",
"All of this blood.",
"All-you-can-eat shrimp for $4.99.",
"Altar boys.",
"American Gladiators.",
"Amputees.",
"An M. Night Shyamalan plot twist.",
"An Oedipus complex.",
"An all-midget production of Shakespeare's Richard III.",
"An army of skeletons.",
"An ass disaster.",
"An asymmetric boob job.",
"An erection that lasts more than four hours.",
"An ether-soaked rag.",
"An honest cop with nothing left to lose.",
"An icepick lobotomy.",
"An unhinged ferris wheel rolling toward the sea.",
"An unstoppable wave of fire ants.",
"Anal beads.",
"Another goddamn vampire movie.",
"Another shitty year.",
"Another shot of morphine.",
"Apologizing.",
"Appreciative snapping.",
"Arnold Schwarzenegger.",
"Asians who aren't good at math.",
"Assless chaps.",
"Attitude.",
"Auschwitz.",
"Authentic Mexican cuisine.",
"Autocannibalism.",
"BATMAN!!!",
"Balls.",
"Barack Obama.",
"Basic human decency.",
"Beating your wives.",
"Beefin' over turf.",
"Bees?",
"Being a busy adult with many important things to do.",
"Being a dick to children.",
"Being a dinosaur.",
"Being a motherfucking sorcerer.",
"Being awesome at sex.",
"Being fabulous.",
"Being marginalized.",
"Being on fire.",
"Being rich.",
"Bill Clinton, naked on a bearskin rug with a saxophone.",
"Bill Nye the Science Guy.",
"Bingeing and purging.",
"Bitches.",
"Black people.",
"Bling.",
"Blood farts.",
"Blowing some dudes in an alley.",
"Booby-trapping the house to foil burglars.",
"Boogers.",
"Boris the Soviet Love Hammer.",
"Bosnian chicken farmers.",
"Breaking out into song and dance.",
"Britney Spears at 55.",
"Bullshit.",
"Buying the right pants to be cool.",
"Cards Against Humanity.",
"Carnies.",
"Catapults.",
"Catastrophic Urethral Trauma.",
"Centaurs.",
"Chainsaws for hands.",
"Charisma.",
"Cheating in the Special Olympics.",
"Child abuse.",
"Child beauty pageants.",
"Children on leashes.",
"Chivalry.",
"Christopher Walken.",
"Chugging a lava lamp.",
"Civilian casualties.",
"Clams.",
"Classist Undertones.",
"Clearing a bloody path through Walmart with a scimitar.",
"Coat hanger abortions.",
"Cock.",
"Cockfights.",
"College.",
"Concealing a boner.",
"Consultants.",
"Copping a feel.",
"Coughing into a vagina.",
"Count Chocula.",
"Crippling debt.",
"Crying into the pages of Sylvia Plath.",
"Crystal meth.",
"Cuddling.",
"Customer service representatives.",
"Cybernetic enhancements.",
"Daddy issues.",
"Daddy's belt.",
"Dancing with a broom.",
"Darth Vader.",
"Date rape.",
"Dead babies.",
"Dead parents.",
"Death by Steven Seagal.",
"Deflowering the princess.",
"Demonic possession.",
"Dental dams.",
"Dick Cheney.",
"Dick fingers.",
"Dining with cardboard cutouts of the cast of “Friends.”",
"Disco fever.",
"Doin' it in the butt.",
"Doing the right thing.",
"Domino's Oreo Dessert Pizza.",
"Dorito breath.",
"Double penetration.",
"Drinking alone.",
"Drinking ten 5-hour ENERGYs to get fifty continuous hours of energy.",
"Dropping a chandelier on your enemies and riding the rope up.",
"Dry heaving.",
"Dwarf tossing.",
"Dying alone and in pain.",
"Dying of dysentery.",
"Dying.",
"Eating Tom Selleck's mustache to gain his powers.",
"Eating all of the cookies before the AIDS bake-sale.",
"Eating an albino.",
"Eating an entire snowman.",
"Eating the last known Bison.",
"Edible underpants.",
"Elderly Japanese men.",
"Elf cum.",
"Embryonic stem cells.",
"Emotions.",
"Enormous Scandinavian women.",
"Erectile dysfunction.",
"Estrogen.",
"Ethnic cleansing.",
"Eugenics.",
"Euphoria by Calvin Klein.",
"Exactly what you'd expect.",
"Exchanging pleasantries.",
"Existing.",
"Expecting a burp and vomiting on the floor.",
"Explosions.",
"Fabricating statistics.",
"Famine.",
"Fancy Feast.",
"Farting and walking away.",
"Fear itself.",
"Feeding Rosie O'Donnell.",
"Fetal alcohol syndrome.",
"Fiery poops.",
"Figgy pudding.",
"Filling every orifice with butterscotch pudding.",
"Finding Waldo.",
"Finding a skeleton.",
"Finger painting.",
"Fingering.",
"Firing a rifle into the air while balls deep in a squealing hog.",
"Fisting.",
"Five-Dollar Footlongs.",
"Flash flooding.",
"Flesh-eating bacteria.",
"Flightless birds.",
"Flying robots that kill people.",
"Flying sex snakes.",
"Foreskin.",
"Forgetting the Alamo.",
"Former President George W. Bush.",
"Free samples.",
"Friction.",
"Friendly fire.",
"Friends who eat all the snacks.",
"Friends with benefits.",
"Frolicking.",
"Fuck Mountain.",
"Fucking up “Silent Night” in front of 300 parents.",
"Full frontal nudity.",
"Gandalf.",
"Gay aliens",
"Geese.",
"Genetically engineered super-soldiers.",
"Genghis Khan.",
"Genital piercings.",
"George Clooney's musk.",
"German dungeon porn.",
"Getting abducted by Peter Pan.",
"Getting drunk on mouthwash.",
"Getting hilariously gang-banged by the Blue Man Group.",
"Getting in her pants, politely.",
"Getting naked and watching Nickelodeon.",
"Getting really high.",
"Getting so angry that you pop a boner.",
"Getting your dick stuck in a Chinese finger trap with another dick.",
"Ghandi.",
"Ghosts.",
"Gift-wrapping a live hamster.",
"Girls that always be textin'.",
"Giving 110%.",
"Gladitorial combat.",
"Glenn Beck being harried by a swarm of buzzards.",
"Glenn Beck catching his scrotum on a curtain hook.",
"Glenn Beck convulsively vomiting as a brood of crab spiders hatches in his brain and erupts from his tear ducts.",
"Global warming.",
"Gloryholes.",
"GoGurt.",
"Goats eating cans.",
"Goblins.",
"God.",
"Going around punching people.",
"Golden showers.",
"Good grammar.",
"Grandma.",
"Grandpa's ashes.",
"Graphic violence, adult language and some sexual content.",
"Grave robbing.",
"Guys who don't call.",
"Half-assed foreplay.",
"Harry Potter erotica.",
"Having sex on top of a pizza.",
"Having shotguns for legs.",
"Heartwarming orphans.",
"Her Royal Highness, Queen Elizabeth II.",
"Heteronormativity.",
"Hillary Clinton's death stare.",
"Hipsters.",
"Historical revisionism.",
"Historically black colleges.",
"Home video of Oprah sobbing into a Lean Cuisine.",
"Homeless people.",
"Hope.",
"Hormone injections.",
"Horrifying laser hair removal accidents.",
"Horse meat.",
"Hot Cheese.",
"Hot Pockets.",
"Hot people.",
"Hulk Hogan.",
"Hurricane Katrina.",
"Immaculate conception.",
"Inappropriate yodeling.",
"Incest.",
"Indescribable loneliness.",
"Insatiable bloodlust.",
"Intelligent design.",
"Intimacy problems.",
"Italians.",
"Jafar.",
"Jean-Claude Van Damme.",
"Jeff Goldblum.",
"Jerking off into a pool of children's tears.",
"Jew-fros.",
"Jewish fraternities.",
"Jibber-jabber.",
"John Wilkes Booth.",
"Judge Judy.",
"Jumping out at people.",
"Just the tip.",
"Justin Bieber.",
"Kamikaze pilots.",
"Kanye West.",
"Keanu Reaves.",
"Keg stands.",
"Kids with ass cancer.",
"Kim-Jong-il.",
"Krampus, the Austrian Christmas Monster.",
"Lactation.",
"Lady Gaga.",
"Lance Armstrong's missing testicle.",
"Land mines.",
"Laying an egg.",
"Leaving an awkward voicemail.",
"Leprosy.",
"Letting everyone down.",
"Leveling up.",
"Licking things to claim them as your own.",
"Literally eating shit.",
"Living in a trashcan.",
"Lockjaw.",
"Loki, the trickster god.",
"Loose lips.",
"Lumberjack fantasies.",
"Lunchables.",
"Mad hacky-sack skills.",
"Making a friend.",
"Making a pouty face.",
"Making the penises kiss.",
"Making the penises kiss.",
"Mall Santa.",
"Man meat.",
"Masturbation.",
"Me time.",
"Me.",
"MechaHitler.",
"Media coverage.",
"Medieval Times Dinner & Tournament.",
"Men.",
"Menstruation.",
"Michael Jackson.",
"Michelle Obama's arms.",
"Mild autism.",
"Mooing.",
"Moral ambiguity.",
"Morgan Freeman's voice.",
"Mouth herpes.",
"Mr. Clean, right behind you.",
"Mufasa's death scene.",
"Muhammad (Praise Be Unto Him).",
"Multiple stab wounds.",
"Mutually-assured destruction.",
"My collection of high-tech sex toys.",
"My first kill.",
"My genitals.",
"My hot cousin.",
"My humps.",
"My inner demons.",
"My machete.",
"My manservant, Claude.",
"My relationship status.",
"My sex life.",
"My soul.",
"My vagina.",
"Natalie Portman.",
"Natural male enhancement.",
"Natural selection.",
"Nazis.",
"Necrophilia.",
"Neil Patrick Harris.",
"New Age music.",
"Nickelback.",
"Nicolas Cage.",
"Nipple blades.",
"Nocturnal emissions.",
"Not contributing to society in any meaningful way.",
"Not giving a shit about the Third World.",
"Not having sex.",
"Not reciprocating oral sex.",
"Nothing.",
"Nublile slave boys.",
"Nunchuck moves.",
"Obesity.",
"Object permanence.",
"Old-people smell.",
"Ominous background music.",
"One Ring to rule them all.",
"One thousand Slim Jims.",
"Oompa-Loompas.",
"Opposable thumbs.",
"Overcompensation.",
"Overpowering your father.",
"Oversized lollipops.",
"Pabst Blue Ribbon.",
"Pac-Man uncontrollably guzzling cum.",
"Panda sex.",
"Panty raids.",
"Parting the Red Sea.",
"Party poopers.",
"Passable transvestites.",
"Passing a kidney stone.",
"Passive-aggressive Post-it notes.",
"Pedophiles.",
"Peeing a little bit.",
"Penis envy.",
"Picking up girls at the abortion clinic.",
"Pictures of boobs.",
"Pistol-whipping a hostage.",
"Pixelated bukkake.",
"Police brutality.",
"Pooping back and forth. Forever.",
"Poor life choices.",
"Poor people.",
"Poorly-timed Holocaust jokes.",
"Porn stars.",
"Powerful thighs.",
"Prancing.",
"Praying the gay away.",
"Preteens.",
"Pretending to be happy.",
"Pretending to care.",
"Pretty Pretty Princess Dress-Up Board Game.",
"Pterodactyl eggs.",
"Puberty.",
"Public ridicule.",
"Pulling out",
"Pumping out a baby every nine months.",
"Puppies!",
"Putting an entire peanut butter and jelly sandwich into the VCR.",
"Queefing.",
"Quiche.",
"Quivering jowls.",
"Racially-biased SAT questions.",
"Racism.",
"Raping and pillaging.",
"Re-gifting.",
"Repression.",
"Republicans.",
"Revenge fucking.",
"Reverse cowgirl.",
"Riding off into the sunset.",
"Ripping into a man's chest and pulling out his still-beating heart.",
"Rising from the grave.",
"Road head.",
"Robert Downey, Jr.",
"RoboCop.",
"Roland the Farter, flatulist to the king.",
"Ronald Reagan.",
"Roofies.",
"Running naked through a mall, pissing and shitting everywhere.",
"Ryan Gosling riding in on a white horse.",
"Same-sex ice dancing.",
"Samuel L. Jackson.",
"Santa Claus.",
"Santa's heavy sack.",
"Sarah Palin.",
"Saxophone solos.",
"Scalping.",
"Science.",
"Scientology",
"Screaming like a maniac.",
"Scrotal frostbite.",
"Scrotum tickling.",
"Scrubbing under the folds.",
"Sean Connery.",
"Sean Penn.",
"Seduction.",
"Self-flagellation.",
"Self-loathing.",
"Seppuku.",
"Serfdom.",
"Several intertwining love stories featuring Hugh Grant.",
"Sexting.",
"Sexual humiliation.",
"Sexual tension.",
"Sexy pillow fights.",
"Sexy siamese twins.",
"Shaft.",
"Shapeshifters.",
"Shaquille O'Neal's acting career.",
"Sharing needles.",
"Shutting the fuck up.",
"Skeletor.",
"Slapping a racist old lady.",
"Slow motion.",
"Smallpox blankets.",
"Smegma.",
"Sneezing, farting, and coming at the same time."
"Sniffing glue.",
"Socks.",
"Soiling oneself.",
"Some douche with an acoustic guitar.",
"Some kind of bird-man.",
"Some really fucked-up shit.",
"Soup that is too hot.",
"Space Jam on VHS.",
"Space muffins.",
"Special musical guest, Cher.",
"Spectacular abs.",
"Spending lots of money.",
"Sperm whales.",
"Spontaneous human combustion.",
"Spring break!",
"Statistically validated stereotypes.",
"Stephen Hawking talking dirty.",
"Stifling a giggle at the mention of Hutus and Tutsis.",
"Stranger danger.",
"Subduing a grizzly bear and making her your wife.",
"Sudden Poop Explosion Disease.",
"Suicidal thoughts.",
"Sunshine and rainbows.",
"Surprise sex!",
"Survivor's guilt.",
"Sweet, sweet vengeance.",
"Swiftly achieving orgasm.",
"Switching to Geico.",
"Swooping.",
"Take-backsies.",
"Taking a man's eyes and balls out and putting his eyes where his balls go and then his balls in the eye holes.",
"Taking down Santa with a surface-to-air missiles.",
"Taking off your shirt.",
"Tangled Slinkys.",
"Tasteful sideboob.",
"Teaching a robot to love.",
"Team-building exercises.",
"Teenage pregnancy.",
"Tentacle porn.",
"Testicular torsion.",
"That ass.",
"That thing that electrocutes your abs.",
"The American Dream.",
"The Big Bang.",
"The Blood of Christ.",
"The Care Bear Stare.",
"The Chinese gymnastics team.",
"The Dance of the Sugar Plum Fairy.",
"The Donald Trump Seal of Approval.",
"The Fanta girls.",
"The Force.",
"The Google.",
"The Gulags.",
"The Hamburglar.",
"The Harlem Globetrotters.",
"The Holy Bible.",
"The Hustle.",
"The Jews.",
"The KKK.",
"The Kool-Aid Man.",
"The Land of Chocolate.",
"The Little Engine That Could.",
"The Make-A-Wish foundation.",
"The Pope.",
"The Qeusadilla Explosion Salad from Chili's.",
"The Rapture.",
"The Rev. Dr. Martin Luther King, Jr.",
"The South.",
"The Star Wars Holiday Special.",
"The Tempur-Pedic Swedish Sleep System.",
"The Three-Fifths Compromise.",
"The Trail of Tears.",
"The Ubermensch.",
"The Virginia Tech Massacre.",
"The World of Warcraft.",
"The boners of the elderly.",
"The chronic.",
"The clitoris.",
"The corporations.",
"The day the birds attacked.",
"The economy.",
"The entire Internet.",
"The folly of man.",
"The forbidden fruit.",
"The four arms of Vishnu.",
"The gays.",
"The glass ceiling.",
"The grey nutrient broth that sustains Mitt Romney.",
"The hardworking Mexican.",
"The harsh light of day.",
"The heart of a child.",
"The hiccups.",
"The homosexual agenda.",
"The human body.",
"The inevitable heat death of the universe.",
"The invisible hand.",
"The mere concept of Applebee's.",
"The milk man.",
"The miracle of childbirth.",
"The mixing of the races.",
"The moist, demanding chasm of his mouth.",
"The new Radiohead album.",
"The placenta.",
"The primal, ball-slapping sex your parents are having right now.",
"The profoundly handicapped.",
"The shambling corpse of Larry King.",
"The systematic destruction of an entire people and their way of life.",
"The taint; the grundle; the fleshy fun-bridge.",
"The terrorists.",
"The thin veneer of sitautional causality that underlies porn.",
"The tiny calloused hands of the Chinese children that made this card.",
"The token minority.",
"The true meaning of Christmas.",
"The underground railroad.",
"The violation of our most basic human rights.",
"The way white people is.",
"Third base.",
"Three months in the hole.",
"Tiny nipples.",
"Tom Cruise.",
"Tongue.",
"Toni Morrison's vagina.",
"Too much hair gel.",
"Tripping balls.",
"Tweeting.",
"Two midgets shitting into a bucket.",
"Unfathomable stupidity.",
"Unlimited soup, salad, and breadsticks.",
"Upgrading homeless people to mobile hotspots.",
"Uppercuts.",
"Vehicular manslaughter.",
"Velcro",
"Viagra.",
"Vietnam flashbacks.",
"Vigilante justice.",
"Vigorous jazz hands.",
"Vikings.",
"Vomiting mid-blowjob.",
"Waiting 'til marriage.",
"Waking up half-naked in a Denny's parking lot.",
"Warm, velvety muppet sex"
"Waterboarding.",
"Weapons-grade plutonium.",
"Wearing an octopus for a hat.",
"Wearing underwear inside-out to avoid doing laundry.",
"Whatever Kwanzaa is supposed to be about.",
"When you fart and a little bit comes out.",
"Whining like a little bitch.",
"Whipping a disobedient slave.",
"Whipping it out.",
"White people.",
"White privilege.",
"Wifely duties.",
"William Shatner.",
"Winking at old people.",
"Wiping her butt.",
"Women in yogurt commercials.",
"Women's suffrage.",
"Words, words, words.",
"World peace.",
"YOU MUST CONSTRUCT ADDITIONAL PYLONS.",
"Yeast.",
"Zeus's sexual appetites.",
] | 197039 | # White Cards Against Humanity cards to be played against Black cards
#
module.exports = [
"72 virgins.",
"8 oz. of sweet Mexican black-tar heroin.",
"A 55-gallon drum of lube.",
"A Bop It.",
"A Burmese tiger pit.",
"A Christmas stocking full of coleslaw.",
"A Gypsy curse.",
"A Hungry-Man Frozen Christmas Dinner for One.",
"A PowerPoint presentation.",
"A Super Soaker full of cat pee.",
"A bag of magic beans.",
"A balanced breakfast.",
"A beached whale.",
"A big black dick.",
"A big hoopla about nothing.",
"A bigger, blacker dick.",
"A black male in his early 20s, last seen wearing a hoodie.",
"A bleached asshole.",
"A bloody pacifier.",
"A boo-boo.",
"A botched circumcision.",
"A brain tumor.",
"A can of whoop-ass.",
"A cat video so cute that your eyes roll back and your spine slides out of your anus.",
"A clandestine butt scratch.",
"A cooler full of organs.",
"A cop who is also a dog.",
"A crappy little hand.",
"A death ray.",
"A defective condom.",
"A disappointing birthday party.",
"A dollop of sour cream.",
"A drive-by shooting.",
"A falcon with a cap on its head.",
"A fetus.",
"A foul mouth.",
"A gassy antelope.",
"A gentle caress of the inner thigh.",
"A good sniff.",
"A greased-up Matthew McConaughey.",
"A homoerotic volleyball montage.",
"A hot mess.",
"A lamprey swimming up the toilet and latching onto your taint.",
"A lifetime of sadness.",
"A look-see.",
"A low standard of living.",
"A magic hippie love cloud.",
"A man in yoga pants with a ponytail and feather earrings.",
"A mating display.",
"A micropenis.",
"A middle-aged man on roller skates.",
"A mime having a stroke.",
"A monkey smoking a cigar.",
"A mopey zoo lion.",
"A murder most foul.",
"A nuanced critique.",
"A passionate Latino lover.",
"A pile of squirming bodies.",
"A pinata full of scorpions.",
"A really cool hat.",
"A rival dojo",
"A robust mongoloid.",
"A sad fat dragon with no friends.",
"A sad handjob.",
"A salty surprise.",
"A sassy black woman.",
"A sausage festival.",
"A sea of troubles.",
"A slightly shittier parallel universe.",
"A snapping turtle biting the tip of your penis.",
"A soulful rendition of “Ol' Man River.”",
"A spontaneous conga line.",
"A squadron of moles wearing aviator goggles.",
"A stray pube.",
"A surprising amount of hair.",
"A sweaty, panting leather daddy.",
"A sweet spaceship.",
"A thermonuclear detonation.",
"A tiny horse.",
"A toxic family environment.",
"A vagina that leads into another dimension.",
"A visually arresting turtleneck.",
"A web of lies.",
"A windmill full of corpses.",
"A woman scorned.",
"A zesty breakfast burrito.",
"AIDS.",
"AXE body spray.",
"<NAME>.",
"Active listening.",
"Actually getting shot, for real.",
"Actually taking candy from a baby.",
"Adderall.",
"African children.",
"Agriculture.",
"Alcoholism.",
"All my friends dying.",
"All of this blood.",
"All-you-can-eat shrimp for $4.99.",
"Altar boys.",
"American Gladiators.",
"Amputees.",
"An M. Night Shyamalan plot twist.",
"An Oedipus complex.",
"An all-midget production of Shakespeare's Richard III.",
"An army of skeletons.",
"An ass disaster.",
"An asymmetric boob job.",
"An erection that lasts more than four hours.",
"An ether-soaked rag.",
"An honest cop with nothing left to lose.",
"An icepick lobotomy.",
"An unhinged ferris wheel rolling toward the sea.",
"An unstoppable wave of fire ants.",
"Anal beads.",
"Another goddamn vampire movie.",
"Another shitty year.",
"Another shot of morphine.",
"Apologizing.",
"Appreciative snapping.",
"<NAME>.",
"Asians who aren't good at math.",
"Assless chaps.",
"Attitude.",
"Auschwitz.",
"Authentic Mexican cuisine.",
"Autocannibalism.",
"BATMAN!!!",
"Balls.",
"Bar<NAME>ama.",
"Basic human decency.",
"Beating your wives.",
"Beefin' over turf.",
"Bees?",
"Being a busy adult with many important things to do.",
"Being a dick to children.",
"Being a dinosaur.",
"Being a motherfucking sorcerer.",
"Being awesome at sex.",
"Being fabulous.",
"Being marginalized.",
"Being on fire.",
"Being rich.",
"<NAME>, naked on a bearskin rug with a saxophone.",
"<NAME>ye the Science Guy.",
"Bingeing and purging.",
"Bitches.",
"Black people.",
"Bling.",
"Blood farts.",
"Blowing some dudes in an alley.",
"Booby-trapping the house to foil burglars.",
"Boogers.",
"Boris the Soviet Love Hammer.",
"Bosnian chicken farmers.",
"Breaking out into song and dance.",
"Britney Spears at 55.",
"Bullshit.",
"Buying the right pants to be cool.",
"Cards Against Humanity.",
"Carnies.",
"Catapults.",
"Catastrophic Urethral Trauma.",
"Centaurs.",
"Chainsaws for hands.",
"Charisma.",
"Cheating in the Special Olympics.",
"Child abuse.",
"Child beauty pageants.",
"Children on leashes.",
"Chivalry.",
"<NAME>.",
"Chugging a lava lamp.",
"Civilian casualties.",
"Clams.",
"Classist Undertones.",
"Clearing a bloody path through Walmart with a scimitar.",
"Coat hanger abortions.",
"Cock.",
"Cockfights.",
"College.",
"Concealing a boner.",
"Consultants.",
"Copping a feel.",
"Coughing into a vagina.",
"Count Chocula.",
"Crippling debt.",
"Crying into the pages of Sylvia Plath.",
"Crystal meth.",
"Cuddling.",
"Customer service representatives.",
"Cybernetic enhancements.",
"Daddy issues.",
"Daddy's belt.",
"Dancing with a broom.",
"D<NAME>.",
"Date rape.",
"Dead babies.",
"Dead parents.",
"Death by Steven Seagal.",
"Deflowering the princess.",
"Demonic possession.",
"Dental dams.",
"<NAME>.",
"Dick fingers.",
"Dining with cardboard cutouts of the cast of “Friends.”",
"Disco fever.",
"Doin' it in the butt.",
"Doing the right thing.",
"Domino's Oreo Dessert Pizza.",
"Dorito breath.",
"Double penetration.",
"Drinking alone.",
"Drinking ten 5-hour ENERGYs to get fifty continuous hours of energy.",
"Dropping a chandelier on your enemies and riding the rope up.",
"Dry heaving.",
"Dwarf tossing.",
"Dying alone and in pain.",
"Dying of dysentery.",
"Dying.",
"Eating <NAME>'s mustache to gain his powers.",
"Eating all of the cookies before the AIDS bake-sale.",
"Eating an albino.",
"Eating an entire snowman.",
"Eating the last known Bison.",
"Edible underpants.",
"Elderly Japanese men.",
"Elf cum.",
"Embryonic stem cells.",
"Emotions.",
"Enormous Scandinavian women.",
"Erectile dysfunction.",
"Estrogen.",
"Ethnic cleansing.",
"Eugenics.",
"Euphoria by <NAME>.",
"Exactly what you'd expect.",
"Exchanging pleasantries.",
"Existing.",
"Expecting a burp and vomiting on the floor.",
"Explosions.",
"Fabricating statistics.",
"Famine.",
"Fancy Feast.",
"Farting and walking away.",
"Fear itself.",
"Feeding <NAME>.",
"Fetal alcohol syndrome.",
"Fiery poops.",
"Figgy pudding.",
"Filling every orifice with butterscotch pudding.",
"Finding Waldo.",
"Finding a skeleton.",
"Finger painting.",
"Fingering.",
"Firing a rifle into the air while balls deep in a squealing hog.",
"Fisting.",
"Five-Dollar Footlongs.",
"Flash flooding.",
"Flesh-eating bacteria.",
"Flightless birds.",
"Flying robots that kill people.",
"Flying sex snakes.",
"Foreskin.",
"Forgetting the Alamo.",
"Former President <NAME>.",
"Free samples.",
"Friction.",
"Friendly fire.",
"Friends who eat all the snacks.",
"Friends with benefits.",
"Frolicking.",
"Fuck Mountain.",
"Fucking up “Silent Night” in front of 300 parents.",
"Full frontal nudity.",
"<NAME>.",
"Gay aliens",
"Geese.",
"Genetically engineered super-soldiers.",
"<NAME>.",
"Genital piercings.",
"<NAME>'s musk.",
"German dungeon porn.",
"Getting abducted by <NAME>.",
"Getting drunk on mouthwash.",
"Getting hilariously gang-banged by the Blue Man Group.",
"Getting in her pants, politely.",
"Getting naked and watching Nickelodeon.",
"Getting really high.",
"Getting so angry that you pop a boner.",
"Getting your dick stuck in a Chinese finger trap with another dick.",
"<NAME>i.",
"Ghosts.",
"Gift-wrapping a live hamster.",
"Girls that always be textin'.",
"Giving 110%.",
"Gladitorial combat.",
"<NAME> being harried by a swarm of buzzards.",
"<NAME> catching his scrotum on a curtain hook.",
"<NAME> convulsively vomiting as a brood of crab spiders hatches in his brain and erupts from his tear ducts.",
"Global warming.",
"Gloryholes.",
"GoGurt.",
"Goats eating cans.",
"Goblins.",
"God.",
"Going around punching people.",
"Golden showers.",
"Good grammar.",
"Grandma.",
"Grandpa's ashes.",
"Graphic violence, adult language and some sexual content.",
"Grave robbing.",
"Guys who don't call.",
"Half-assed foreplay.",
"Harry Potter erotica.",
"Having sex on top of a pizza.",
"Having shotguns for legs.",
"Heartwarming orphans.",
"Her Royal Highness, Queen Elizabeth II.",
"Heteronormativity.",
"<NAME>'s death stare.",
"Hipsters.",
"Historical revisionism.",
"Historically black colleges.",
"Home video of Oprah sobbing into a Lean Cuisine.",
"Homeless people.",
"Hope.",
"Hormone injections.",
"Horrifying laser hair removal accidents.",
"Horse meat.",
"Hot Cheese.",
"Hot Pockets.",
"Hot people.",
"<NAME>.",
"Hur<NAME>ane <NAME>at<NAME>ina.",
"Immaculate conception.",
"Inappropriate yodeling.",
"Incest.",
"Indescribable loneliness.",
"Insatiable bloodlust.",
"Intelligent design.",
"Intimacy problems.",
"Italians.",
"Jafar.",
"<NAME>.",
"<NAME>.",
"Jerking off into a pool of children's tears.",
"Jew-fros.",
"Jewish fraternities.",
"Jibber-jabber.",
"<NAME>.",
"<NAME>.",
"Jumping out at people.",
"Just the tip.",
"<NAME>.",
"Kamikaze pilots.",
"Kanye West.",
"Keanu Reaves.",
"Keg stands.",
"Kids with ass cancer.",
"Kim-Jong-il.",
"Krampus, the Austrian Christmas Monster.",
"Lactation.",
"<NAME>.",
"<NAME>'s missing testicle.",
"Land mines.",
"Laying an egg.",
"Leaving an awkward voicemail.",
"Leprosy.",
"Letting everyone down.",
"Leveling up.",
"Licking things to claim them as your own.",
"Literally eating shit.",
"Living in a trashcan.",
"Lockjaw.",
"Loki, the trickster god.",
"Loose lips.",
"Lumberjack fantasies.",
"Lunchables.",
"Mad hacky-sack skills.",
"Making a friend.",
"Making a pouty face.",
"Making the penises kiss.",
"Making the penises kiss.",
"Mall Santa.",
"Man meat.",
"Masturbation.",
"Me time.",
"Me.",
"MechaHitler.",
"Media coverage.",
"Medieval Times Dinner & Tournament.",
"Men.",
"Menstruation.",
"<NAME>.",
"Mic<NAME>le Obama's arms.",
"Mild autism.",
"Mooing.",
"Moral ambiguity.",
"Morgan Freeman's voice.",
"Mouth herpes.",
"Mr. Clean, right behind you.",
"Mufasa's death scene.",
"<NAME> (Praise Be Unto Him).",
"Multiple stab wounds.",
"Mutually-assured destruction.",
"My collection of high-tech sex toys.",
"My first kill.",
"My genitals.",
"My hot cousin.",
"My humps.",
"My inner demons.",
"My machete.",
"My manservant, <NAME>.",
"My relationship status.",
"My sex life.",
"My soul.",
"My vagina.",
"<NAME>.",
"Natural male enhancement.",
"Natural selection.",
"Nazis.",
"Necrophilia.",
"<NAME>.",
"New Age music.",
"Nickelback.",
"<NAME>icolas Cage.",
"Nipple blades.",
"Nocturnal emissions.",
"Not contributing to society in any meaningful way.",
"Not giving a shit about the Third World.",
"Not having sex.",
"Not reciprocating oral sex.",
"Nothing.",
"Nublile slave boys.",
"Nunchuck moves.",
"Obesity.",
"Object permanence.",
"Old-people smell.",
"Ominous background music.",
"One Ring to rule them all.",
"One thousand Slim Jims.",
"Oompa-Loompas.",
"Opposable thumbs.",
"Overcompensation.",
"Overpowering your father.",
"Oversized lollipops.",
"Pabst Blue Ribbon.",
"Pac-Man uncontrollably guzzling cum.",
"Panda sex.",
"Panty raids.",
"Parting the Red Sea.",
"Party poopers.",
"Passable transvestites.",
"Passing a kidney stone.",
"Passive-aggressive Post-it notes.",
"Pedophiles.",
"Peeing a little bit.",
"Penis envy.",
"Picking up girls at the abortion clinic.",
"Pictures of boobs.",
"Pistol-whipping a hostage.",
"Pixelated bukkake.",
"Police brutality.",
"Pooping back and forth. Forever.",
"Poor life choices.",
"Poor people.",
"Poorly-timed Holocaust jokes.",
"Porn stars.",
"Powerful thighs.",
"Prancing.",
"Praying the gay away.",
"Preteens.",
"Pretending to be happy.",
"Pretending to care.",
"Pretty Pretty Princess Dress-Up Board Game.",
"Pterodactyl eggs.",
"Puberty.",
"Public ridicule.",
"Pulling out",
"Pumping out a baby every nine months.",
"Puppies!",
"Putting an entire peanut butter and jelly sandwich into the VCR.",
"Queefing.",
"Quiche.",
"Quivering jowls.",
"Racially-biased SAT questions.",
"Racism.",
"Raping and pillaging.",
"Re-gifting.",
"Repression.",
"Republicans.",
"Revenge fucking.",
"Reverse cowgirl.",
"Riding off into the sunset.",
"Ripping into a man's chest and pulling out his still-beating heart.",
"Rising from the grave.",
"Road head.",
"<NAME>, Jr.",
"RoboCop.",
"<NAME>, flatulist to the king.",
"<NAME>.",
"Roofies.",
"Running naked through a mall, pissing and shitting everywhere.",
"<NAME> riding in on a white horse.",
"Same-sex ice dancing.",
"<NAME>.",
"Santa <NAME>.",
"Santa's heavy sack.",
"<NAME>.",
"Saxophone solos.",
"Scalping.",
"Science.",
"Scientology",
"Screaming like a maniac.",
"Scrotal frostbite.",
"Scrotum tickling.",
"Scrubbing under the folds.",
"<NAME>.",
"<NAME>.",
"Seduction.",
"Self-flagellation.",
"Self-loathing.",
"Seppuku.",
"Serfdom.",
"Several intertwining love stories featuring <NAME>.",
"Sexting.",
"Sexual humiliation.",
"Sexual tension.",
"Sexy pillow fights.",
"Sexy siamese twins.",
"Shaft.",
"Shapeshifters.",
"<NAME>'s acting career.",
"Sharing needles.",
"Shutting the fuck up.",
"Skeletor.",
"Slapping a racist old lady.",
"Slow motion.",
"Smallpox blankets.",
"Smegma.",
"Sneezing, farting, and coming at the same time."
"Sniffing glue.",
"Socks.",
"Soiling oneself.",
"Some douche with an acoustic guitar.",
"Some kind of bird-man.",
"Some really fucked-up shit.",
"Soup that is too hot.",
"Space Jam on VHS.",
"Space muffins.",
"Special musical guest, <NAME>.",
"Spectacular abs.",
"Spending lots of money.",
"Sperm whales.",
"Spontaneous human combustion.",
"Spring break!",
"Statistically validated stereotypes.",
"<NAME>king talking dirty.",
"Stifling a giggle at the mention of Hutus and Tutsis.",
"Stranger danger.",
"Subduing a grizzly bear and making her your wife.",
"Sudden Poop Explosion Disease.",
"Suicidal thoughts.",
"Sunshine and rainbows.",
"Surprise sex!",
"Survivor's guilt.",
"Sweet, sweet vengeance.",
"Swiftly achieving orgasm.",
"Switching to Geico.",
"Swooping.",
"Take-backsies.",
"Taking a man's eyes and balls out and putting his eyes where his balls go and then his balls in the eye holes.",
"Taking down Santa with a surface-to-air missiles.",
"Taking off your shirt.",
"Tangled Slinkys.",
"Tasteful sideboob.",
"Teaching a robot to love.",
"Team-building exercises.",
"Teenage pregnancy.",
"Tentacle porn.",
"Testicular torsion.",
"That ass.",
"That thing that electrocutes your abs.",
"The American Dream.",
"The Big Bang.",
"The Blood of Christ.",
"The Care Bear Stare.",
"The Chinese gymnastics team.",
"The Dance of the Sugar Plum Fairy.",
"The Donald Trump Seal of Approval.",
"The Fanta girls.",
"The Force.",
"The Google.",
"The Gulags.",
"The Hamburglar.",
"The Harlem Globetrotters.",
"The Holy Bible.",
"The Hustle.",
"The Jews.",
"The KKK.",
"The Kool-Aid Man.",
"The Land of Chocolate.",
"The Little Engine That Could.",
"The Make-A-Wish foundation.",
"The Pope.",
"The Qeusadilla Explosion Salad from Chili's.",
"The Rapture.",
"The Rev. Dr. <NAME>, Jr.",
"The South.",
"The Star Wars Holiday Special.",
"The Tempur-Pedic Swedish Sleep System.",
"The Three-Fifths Compromise.",
"The Trail of Tears.",
"The Ubermensch.",
"The Virginia Tech Massacre.",
"The World of Warcraft.",
"The boners of the elderly.",
"The chronic.",
"The clitoris.",
"The corporations.",
"The day the birds attacked.",
"The economy.",
"The entire Internet.",
"The folly of man.",
"The forbidden fruit.",
"The four arms of Vishnu.",
"The gays.",
"The glass ceiling.",
"The grey nutrient broth that sustains <NAME>.",
"The hardworking Mexican.",
"The harsh light of day.",
"The heart of a child.",
"The hiccups.",
"The homosexual agenda.",
"The human body.",
"The inevitable heat death of the universe.",
"The invisible hand.",
"The mere concept of Applebee's.",
"The milk man.",
"The miracle of childbirth.",
"The mixing of the races.",
"The moist, demanding chasm of his mouth.",
"The new Radiohead album.",
"The placenta.",
"The primal, ball-slapping sex your parents are having right now.",
"The profoundly handicapped.",
"The shambling corpse of Larry King.",
"The systematic destruction of an entire people and their way of life.",
"The taint; the grundle; the fleshy fun-bridge.",
"The terrorists.",
"The thin veneer of sitautional causality that underlies porn.",
"The tiny calloused hands of the Chinese children that made this card.",
"The token minority.",
"The true meaning of Christmas.",
"The underground railroad.",
"The violation of our most basic human rights.",
"The way white people is.",
"Third base.",
"Three months in the hole.",
"Tiny nipples.",
"<NAME>.",
"Tongue.",
"<NAME>'s vagina.",
"Too much hair gel.",
"Tripping balls.",
"Tweeting.",
"Two midgets shitting into a bucket.",
"Unfathomable stupidity.",
"Unlimited soup, salad, and breadsticks.",
"Upgrading homeless people to mobile hotspots.",
"Uppercuts.",
"Vehicular manslaughter.",
"Velcro",
"Viagra.",
"Vietnam flashbacks.",
"Vigilante justice.",
"Vigorous jazz hands.",
"Vikings.",
"Vomiting mid-blowjob.",
"Waiting 'til marriage.",
"Waking up half-naked in a Denny's parking lot.",
"Warm, velvety muppet sex"
"Waterboarding.",
"Weapons-grade plutonium.",
"Wearing an octopus for a hat.",
"Wearing underwear inside-out to avoid doing laundry.",
"Whatever Kwanzaa is supposed to be about.",
"When you fart and a little bit comes out.",
"Whining like a little bitch.",
"Whipping a disobedient slave.",
"Whipping it out.",
"White people.",
"White privilege.",
"Wifely duties.",
"<NAME>.",
"Winking at old people.",
"Wiping her butt.",
"Women in yogurt commercials.",
"Women's suffrage.",
"Words, words, words.",
"World peace.",
"YOU MUST CONSTRUCT ADDITIONAL PYLONS.",
"Yeast.",
"Zeus's sexual appetites.",
] | true | # White Cards Against Humanity cards to be played against Black cards
#
module.exports = [
"72 virgins.",
"8 oz. of sweet Mexican black-tar heroin.",
"A 55-gallon drum of lube.",
"A Bop It.",
"A Burmese tiger pit.",
"A Christmas stocking full of coleslaw.",
"A Gypsy curse.",
"A Hungry-Man Frozen Christmas Dinner for One.",
"A PowerPoint presentation.",
"A Super Soaker full of cat pee.",
"A bag of magic beans.",
"A balanced breakfast.",
"A beached whale.",
"A big black dick.",
"A big hoopla about nothing.",
"A bigger, blacker dick.",
"A black male in his early 20s, last seen wearing a hoodie.",
"A bleached asshole.",
"A bloody pacifier.",
"A boo-boo.",
"A botched circumcision.",
"A brain tumor.",
"A can of whoop-ass.",
"A cat video so cute that your eyes roll back and your spine slides out of your anus.",
"A clandestine butt scratch.",
"A cooler full of organs.",
"A cop who is also a dog.",
"A crappy little hand.",
"A death ray.",
"A defective condom.",
"A disappointing birthday party.",
"A dollop of sour cream.",
"A drive-by shooting.",
"A falcon with a cap on its head.",
"A fetus.",
"A foul mouth.",
"A gassy antelope.",
"A gentle caress of the inner thigh.",
"A good sniff.",
"A greased-up Matthew McConaughey.",
"A homoerotic volleyball montage.",
"A hot mess.",
"A lamprey swimming up the toilet and latching onto your taint.",
"A lifetime of sadness.",
"A look-see.",
"A low standard of living.",
"A magic hippie love cloud.",
"A man in yoga pants with a ponytail and feather earrings.",
"A mating display.",
"A micropenis.",
"A middle-aged man on roller skates.",
"A mime having a stroke.",
"A monkey smoking a cigar.",
"A mopey zoo lion.",
"A murder most foul.",
"A nuanced critique.",
"A passionate Latino lover.",
"A pile of squirming bodies.",
"A pinata full of scorpions.",
"A really cool hat.",
"A rival dojo",
"A robust mongoloid.",
"A sad fat dragon with no friends.",
"A sad handjob.",
"A salty surprise.",
"A sassy black woman.",
"A sausage festival.",
"A sea of troubles.",
"A slightly shittier parallel universe.",
"A snapping turtle biting the tip of your penis.",
"A soulful rendition of “Ol' Man River.”",
"A spontaneous conga line.",
"A squadron of moles wearing aviator goggles.",
"A stray pube.",
"A surprising amount of hair.",
"A sweaty, panting leather daddy.",
"A sweet spaceship.",
"A thermonuclear detonation.",
"A tiny horse.",
"A toxic family environment.",
"A vagina that leads into another dimension.",
"A visually arresting turtleneck.",
"A web of lies.",
"A windmill full of corpses.",
"A woman scorned.",
"A zesty breakfast burrito.",
"AIDS.",
"AXE body spray.",
"PI:NAME:<NAME>END_PI.",
"Active listening.",
"Actually getting shot, for real.",
"Actually taking candy from a baby.",
"Adderall.",
"African children.",
"Agriculture.",
"Alcoholism.",
"All my friends dying.",
"All of this blood.",
"All-you-can-eat shrimp for $4.99.",
"Altar boys.",
"American Gladiators.",
"Amputees.",
"An M. Night Shyamalan plot twist.",
"An Oedipus complex.",
"An all-midget production of Shakespeare's Richard III.",
"An army of skeletons.",
"An ass disaster.",
"An asymmetric boob job.",
"An erection that lasts more than four hours.",
"An ether-soaked rag.",
"An honest cop with nothing left to lose.",
"An icepick lobotomy.",
"An unhinged ferris wheel rolling toward the sea.",
"An unstoppable wave of fire ants.",
"Anal beads.",
"Another goddamn vampire movie.",
"Another shitty year.",
"Another shot of morphine.",
"Apologizing.",
"Appreciative snapping.",
"PI:NAME:<NAME>END_PI.",
"Asians who aren't good at math.",
"Assless chaps.",
"Attitude.",
"Auschwitz.",
"Authentic Mexican cuisine.",
"Autocannibalism.",
"BATMAN!!!",
"Balls.",
"BarPI:NAME:<NAME>END_PIama.",
"Basic human decency.",
"Beating your wives.",
"Beefin' over turf.",
"Bees?",
"Being a busy adult with many important things to do.",
"Being a dick to children.",
"Being a dinosaur.",
"Being a motherfucking sorcerer.",
"Being awesome at sex.",
"Being fabulous.",
"Being marginalized.",
"Being on fire.",
"Being rich.",
"PI:NAME:<NAME>END_PI, naked on a bearskin rug with a saxophone.",
"PI:NAME:<NAME>END_PIye the Science Guy.",
"Bingeing and purging.",
"Bitches.",
"Black people.",
"Bling.",
"Blood farts.",
"Blowing some dudes in an alley.",
"Booby-trapping the house to foil burglars.",
"Boogers.",
"Boris the Soviet Love Hammer.",
"Bosnian chicken farmers.",
"Breaking out into song and dance.",
"Britney Spears at 55.",
"Bullshit.",
"Buying the right pants to be cool.",
"Cards Against Humanity.",
"Carnies.",
"Catapults.",
"Catastrophic Urethral Trauma.",
"Centaurs.",
"Chainsaws for hands.",
"Charisma.",
"Cheating in the Special Olympics.",
"Child abuse.",
"Child beauty pageants.",
"Children on leashes.",
"Chivalry.",
"PI:NAME:<NAME>END_PI.",
"Chugging a lava lamp.",
"Civilian casualties.",
"Clams.",
"Classist Undertones.",
"Clearing a bloody path through Walmart with a scimitar.",
"Coat hanger abortions.",
"Cock.",
"Cockfights.",
"College.",
"Concealing a boner.",
"Consultants.",
"Copping a feel.",
"Coughing into a vagina.",
"Count Chocula.",
"Crippling debt.",
"Crying into the pages of Sylvia Plath.",
"Crystal meth.",
"Cuddling.",
"Customer service representatives.",
"Cybernetic enhancements.",
"Daddy issues.",
"Daddy's belt.",
"Dancing with a broom.",
"DPI:NAME:<NAME>END_PI.",
"Date rape.",
"Dead babies.",
"Dead parents.",
"Death by Steven Seagal.",
"Deflowering the princess.",
"Demonic possession.",
"Dental dams.",
"PI:NAME:<NAME>END_PI.",
"Dick fingers.",
"Dining with cardboard cutouts of the cast of “Friends.”",
"Disco fever.",
"Doin' it in the butt.",
"Doing the right thing.",
"Domino's Oreo Dessert Pizza.",
"Dorito breath.",
"Double penetration.",
"Drinking alone.",
"Drinking ten 5-hour ENERGYs to get fifty continuous hours of energy.",
"Dropping a chandelier on your enemies and riding the rope up.",
"Dry heaving.",
"Dwarf tossing.",
"Dying alone and in pain.",
"Dying of dysentery.",
"Dying.",
"Eating PI:NAME:<NAME>END_PI's mustache to gain his powers.",
"Eating all of the cookies before the AIDS bake-sale.",
"Eating an albino.",
"Eating an entire snowman.",
"Eating the last known Bison.",
"Edible underpants.",
"Elderly Japanese men.",
"Elf cum.",
"Embryonic stem cells.",
"Emotions.",
"Enormous Scandinavian women.",
"Erectile dysfunction.",
"Estrogen.",
"Ethnic cleansing.",
"Eugenics.",
"Euphoria by PI:NAME:<NAME>END_PI.",
"Exactly what you'd expect.",
"Exchanging pleasantries.",
"Existing.",
"Expecting a burp and vomiting on the floor.",
"Explosions.",
"Fabricating statistics.",
"Famine.",
"Fancy Feast.",
"Farting and walking away.",
"Fear itself.",
"Feeding PI:NAME:<NAME>END_PI.",
"Fetal alcohol syndrome.",
"Fiery poops.",
"Figgy pudding.",
"Filling every orifice with butterscotch pudding.",
"Finding Waldo.",
"Finding a skeleton.",
"Finger painting.",
"Fingering.",
"Firing a rifle into the air while balls deep in a squealing hog.",
"Fisting.",
"Five-Dollar Footlongs.",
"Flash flooding.",
"Flesh-eating bacteria.",
"Flightless birds.",
"Flying robots that kill people.",
"Flying sex snakes.",
"Foreskin.",
"Forgetting the Alamo.",
"Former President PI:NAME:<NAME>END_PI.",
"Free samples.",
"Friction.",
"Friendly fire.",
"Friends who eat all the snacks.",
"Friends with benefits.",
"Frolicking.",
"Fuck Mountain.",
"Fucking up “Silent Night” in front of 300 parents.",
"Full frontal nudity.",
"PI:NAME:<NAME>END_PI.",
"Gay aliens",
"Geese.",
"Genetically engineered super-soldiers.",
"PI:NAME:<NAME>END_PI.",
"Genital piercings.",
"PI:NAME:<NAME>END_PI's musk.",
"German dungeon porn.",
"Getting abducted by PI:NAME:<NAME>END_PI.",
"Getting drunk on mouthwash.",
"Getting hilariously gang-banged by the Blue Man Group.",
"Getting in her pants, politely.",
"Getting naked and watching Nickelodeon.",
"Getting really high.",
"Getting so angry that you pop a boner.",
"Getting your dick stuck in a Chinese finger trap with another dick.",
"PI:NAME:<NAME>END_PIi.",
"Ghosts.",
"Gift-wrapping a live hamster.",
"Girls that always be textin'.",
"Giving 110%.",
"Gladitorial combat.",
"PI:NAME:<NAME>END_PI being harried by a swarm of buzzards.",
"PI:NAME:<NAME>END_PI catching his scrotum on a curtain hook.",
"PI:NAME:<NAME>END_PI convulsively vomiting as a brood of crab spiders hatches in his brain and erupts from his tear ducts.",
"Global warming.",
"Gloryholes.",
"GoGurt.",
"Goats eating cans.",
"Goblins.",
"God.",
"Going around punching people.",
"Golden showers.",
"Good grammar.",
"Grandma.",
"Grandpa's ashes.",
"Graphic violence, adult language and some sexual content.",
"Grave robbing.",
"Guys who don't call.",
"Half-assed foreplay.",
"Harry Potter erotica.",
"Having sex on top of a pizza.",
"Having shotguns for legs.",
"Heartwarming orphans.",
"Her Royal Highness, Queen Elizabeth II.",
"Heteronormativity.",
"PI:NAME:<NAME>END_PI's death stare.",
"Hipsters.",
"Historical revisionism.",
"Historically black colleges.",
"Home video of Oprah sobbing into a Lean Cuisine.",
"Homeless people.",
"Hope.",
"Hormone injections.",
"Horrifying laser hair removal accidents.",
"Horse meat.",
"Hot Cheese.",
"Hot Pockets.",
"Hot people.",
"PI:NAME:<NAME>END_PI.",
"HurPI:NAME:<NAME>END_PIane PI:NAME:<NAME>END_PIatPI:NAME:<NAME>END_PIina.",
"Immaculate conception.",
"Inappropriate yodeling.",
"Incest.",
"Indescribable loneliness.",
"Insatiable bloodlust.",
"Intelligent design.",
"Intimacy problems.",
"Italians.",
"Jafar.",
"PI:NAME:<NAME>END_PI.",
"PI:NAME:<NAME>END_PI.",
"Jerking off into a pool of children's tears.",
"Jew-fros.",
"Jewish fraternities.",
"Jibber-jabber.",
"PI:NAME:<NAME>END_PI.",
"PI:NAME:<NAME>END_PI.",
"Jumping out at people.",
"Just the tip.",
"PI:NAME:<NAME>END_PI.",
"Kamikaze pilots.",
"Kanye West.",
"Keanu Reaves.",
"Keg stands.",
"Kids with ass cancer.",
"Kim-Jong-il.",
"Krampus, the Austrian Christmas Monster.",
"Lactation.",
"PI:NAME:<NAME>END_PI.",
"PI:NAME:<NAME>END_PI's missing testicle.",
"Land mines.",
"Laying an egg.",
"Leaving an awkward voicemail.",
"Leprosy.",
"Letting everyone down.",
"Leveling up.",
"Licking things to claim them as your own.",
"Literally eating shit.",
"Living in a trashcan.",
"Lockjaw.",
"Loki, the trickster god.",
"Loose lips.",
"Lumberjack fantasies.",
"Lunchables.",
"Mad hacky-sack skills.",
"Making a friend.",
"Making a pouty face.",
"Making the penises kiss.",
"Making the penises kiss.",
"Mall Santa.",
"Man meat.",
"Masturbation.",
"Me time.",
"Me.",
"MechaHitler.",
"Media coverage.",
"Medieval Times Dinner & Tournament.",
"Men.",
"Menstruation.",
"PI:NAME:<NAME>END_PI.",
"MicPI:NAME:<NAME>END_PIle Obama's arms.",
"Mild autism.",
"Mooing.",
"Moral ambiguity.",
"Morgan Freeman's voice.",
"Mouth herpes.",
"Mr. Clean, right behind you.",
"Mufasa's death scene.",
"PI:NAME:<NAME>END_PI (Praise Be Unto Him).",
"Multiple stab wounds.",
"Mutually-assured destruction.",
"My collection of high-tech sex toys.",
"My first kill.",
"My genitals.",
"My hot cousin.",
"My humps.",
"My inner demons.",
"My machete.",
"My manservant, PI:NAME:<NAME>END_PI.",
"My relationship status.",
"My sex life.",
"My soul.",
"My vagina.",
"PI:NAME:<NAME>END_PI.",
"Natural male enhancement.",
"Natural selection.",
"Nazis.",
"Necrophilia.",
"PI:NAME:<NAME>END_PI.",
"New Age music.",
"Nickelback.",
"PI:NAME:<NAME>END_PIicolas Cage.",
"Nipple blades.",
"Nocturnal emissions.",
"Not contributing to society in any meaningful way.",
"Not giving a shit about the Third World.",
"Not having sex.",
"Not reciprocating oral sex.",
"Nothing.",
"Nublile slave boys.",
"Nunchuck moves.",
"Obesity.",
"Object permanence.",
"Old-people smell.",
"Ominous background music.",
"One Ring to rule them all.",
"One thousand Slim Jims.",
"Oompa-Loompas.",
"Opposable thumbs.",
"Overcompensation.",
"Overpowering your father.",
"Oversized lollipops.",
"Pabst Blue Ribbon.",
"Pac-Man uncontrollably guzzling cum.",
"Panda sex.",
"Panty raids.",
"Parting the Red Sea.",
"Party poopers.",
"Passable transvestites.",
"Passing a kidney stone.",
"Passive-aggressive Post-it notes.",
"Pedophiles.",
"Peeing a little bit.",
"Penis envy.",
"Picking up girls at the abortion clinic.",
"Pictures of boobs.",
"Pistol-whipping a hostage.",
"Pixelated bukkake.",
"Police brutality.",
"Pooping back and forth. Forever.",
"Poor life choices.",
"Poor people.",
"Poorly-timed Holocaust jokes.",
"Porn stars.",
"Powerful thighs.",
"Prancing.",
"Praying the gay away.",
"Preteens.",
"Pretending to be happy.",
"Pretending to care.",
"Pretty Pretty Princess Dress-Up Board Game.",
"Pterodactyl eggs.",
"Puberty.",
"Public ridicule.",
"Pulling out",
"Pumping out a baby every nine months.",
"Puppies!",
"Putting an entire peanut butter and jelly sandwich into the VCR.",
"Queefing.",
"Quiche.",
"Quivering jowls.",
"Racially-biased SAT questions.",
"Racism.",
"Raping and pillaging.",
"Re-gifting.",
"Repression.",
"Republicans.",
"Revenge fucking.",
"Reverse cowgirl.",
"Riding off into the sunset.",
"Ripping into a man's chest and pulling out his still-beating heart.",
"Rising from the grave.",
"Road head.",
"PI:NAME:<NAME>END_PI, Jr.",
"RoboCop.",
"PI:NAME:<NAME>END_PI, flatulist to the king.",
"PI:NAME:<NAME>END_PI.",
"Roofies.",
"Running naked through a mall, pissing and shitting everywhere.",
"PI:NAME:<NAME>END_PI riding in on a white horse.",
"Same-sex ice dancing.",
"PI:NAME:<NAME>END_PI.",
"Santa PI:NAME:<NAME>END_PI.",
"Santa's heavy sack.",
"PI:NAME:<NAME>END_PI.",
"Saxophone solos.",
"Scalping.",
"Science.",
"Scientology",
"Screaming like a maniac.",
"Scrotal frostbite.",
"Scrotum tickling.",
"Scrubbing under the folds.",
"PI:NAME:<NAME>END_PI.",
"PI:NAME:<NAME>END_PI.",
"Seduction.",
"Self-flagellation.",
"Self-loathing.",
"Seppuku.",
"Serfdom.",
"Several intertwining love stories featuring PI:NAME:<NAME>END_PI.",
"Sexting.",
"Sexual humiliation.",
"Sexual tension.",
"Sexy pillow fights.",
"Sexy siamese twins.",
"Shaft.",
"Shapeshifters.",
"PI:NAME:<NAME>END_PI's acting career.",
"Sharing needles.",
"Shutting the fuck up.",
"Skeletor.",
"Slapping a racist old lady.",
"Slow motion.",
"Smallpox blankets.",
"Smegma.",
"Sneezing, farting, and coming at the same time."
"Sniffing glue.",
"Socks.",
"Soiling oneself.",
"Some douche with an acoustic guitar.",
"Some kind of bird-man.",
"Some really fucked-up shit.",
"Soup that is too hot.",
"Space Jam on VHS.",
"Space muffins.",
"Special musical guest, PI:NAME:<NAME>END_PI.",
"Spectacular abs.",
"Spending lots of money.",
"Sperm whales.",
"Spontaneous human combustion.",
"Spring break!",
"Statistically validated stereotypes.",
"PI:NAME:<NAME>END_PIking talking dirty.",
"Stifling a giggle at the mention of Hutus and Tutsis.",
"Stranger danger.",
"Subduing a grizzly bear and making her your wife.",
"Sudden Poop Explosion Disease.",
"Suicidal thoughts.",
"Sunshine and rainbows.",
"Surprise sex!",
"Survivor's guilt.",
"Sweet, sweet vengeance.",
"Swiftly achieving orgasm.",
"Switching to Geico.",
"Swooping.",
"Take-backsies.",
"Taking a man's eyes and balls out and putting his eyes where his balls go and then his balls in the eye holes.",
"Taking down Santa with a surface-to-air missiles.",
"Taking off your shirt.",
"Tangled Slinkys.",
"Tasteful sideboob.",
"Teaching a robot to love.",
"Team-building exercises.",
"Teenage pregnancy.",
"Tentacle porn.",
"Testicular torsion.",
"That ass.",
"That thing that electrocutes your abs.",
"The American Dream.",
"The Big Bang.",
"The Blood of Christ.",
"The Care Bear Stare.",
"The Chinese gymnastics team.",
"The Dance of the Sugar Plum Fairy.",
"The Donald Trump Seal of Approval.",
"The Fanta girls.",
"The Force.",
"The Google.",
"The Gulags.",
"The Hamburglar.",
"The Harlem Globetrotters.",
"The Holy Bible.",
"The Hustle.",
"The Jews.",
"The KKK.",
"The Kool-Aid Man.",
"The Land of Chocolate.",
"The Little Engine That Could.",
"The Make-A-Wish foundation.",
"The Pope.",
"The Qeusadilla Explosion Salad from Chili's.",
"The Rapture.",
"The Rev. Dr. PI:NAME:<NAME>END_PI, Jr.",
"The South.",
"The Star Wars Holiday Special.",
"The Tempur-Pedic Swedish Sleep System.",
"The Three-Fifths Compromise.",
"The Trail of Tears.",
"The Ubermensch.",
"The Virginia Tech Massacre.",
"The World of Warcraft.",
"The boners of the elderly.",
"The chronic.",
"The clitoris.",
"The corporations.",
"The day the birds attacked.",
"The economy.",
"The entire Internet.",
"The folly of man.",
"The forbidden fruit.",
"The four arms of Vishnu.",
"The gays.",
"The glass ceiling.",
"The grey nutrient broth that sustains PI:NAME:<NAME>END_PI.",
"The hardworking Mexican.",
"The harsh light of day.",
"The heart of a child.",
"The hiccups.",
"The homosexual agenda.",
"The human body.",
"The inevitable heat death of the universe.",
"The invisible hand.",
"The mere concept of Applebee's.",
"The milk man.",
"The miracle of childbirth.",
"The mixing of the races.",
"The moist, demanding chasm of his mouth.",
"The new Radiohead album.",
"The placenta.",
"The primal, ball-slapping sex your parents are having right now.",
"The profoundly handicapped.",
"The shambling corpse of Larry King.",
"The systematic destruction of an entire people and their way of life.",
"The taint; the grundle; the fleshy fun-bridge.",
"The terrorists.",
"The thin veneer of sitautional causality that underlies porn.",
"The tiny calloused hands of the Chinese children that made this card.",
"The token minority.",
"The true meaning of Christmas.",
"The underground railroad.",
"The violation of our most basic human rights.",
"The way white people is.",
"Third base.",
"Three months in the hole.",
"Tiny nipples.",
"PI:NAME:<NAME>END_PI.",
"Tongue.",
"PI:NAME:<NAME>END_PI's vagina.",
"Too much hair gel.",
"Tripping balls.",
"Tweeting.",
"Two midgets shitting into a bucket.",
"Unfathomable stupidity.",
"Unlimited soup, salad, and breadsticks.",
"Upgrading homeless people to mobile hotspots.",
"Uppercuts.",
"Vehicular manslaughter.",
"Velcro",
"Viagra.",
"Vietnam flashbacks.",
"Vigilante justice.",
"Vigorous jazz hands.",
"Vikings.",
"Vomiting mid-blowjob.",
"Waiting 'til marriage.",
"Waking up half-naked in a Denny's parking lot.",
"Warm, velvety muppet sex"
"Waterboarding.",
"Weapons-grade plutonium.",
"Wearing an octopus for a hat.",
"Wearing underwear inside-out to avoid doing laundry.",
"Whatever Kwanzaa is supposed to be about.",
"When you fart and a little bit comes out.",
"Whining like a little bitch.",
"Whipping a disobedient slave.",
"Whipping it out.",
"White people.",
"White privilege.",
"Wifely duties.",
"PI:NAME:<NAME>END_PI.",
"Winking at old people.",
"Wiping her butt.",
"Women in yogurt commercials.",
"Women's suffrage.",
"Words, words, words.",
"World peace.",
"YOU MUST CONSTRUCT ADDITIONAL PYLONS.",
"Yeast.",
"Zeus's sexual appetites.",
] |
[
{
"context": " @scope.user =\n email: \"test@test.com\"\n name: \"test\"\n pas",
"end": 786,
"score": 0.9999211430549622,
"start": 773,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": " name: \"test\"\n ... | app/components/login/controller-test.coffee | vidatio/web-app | 0 | "use strict"
describe "Login / Register Directive", ->
beforeEach ->
module "app"
inject ($controller, $rootScope, $q, $state, $log) ->
@scope = $rootScope.$new()
@rootScope = $rootScope
@deferred = $q.defer()
@UserFactory =
save: (user) ->
@UserService =
logon: (name, password) ->
spyOn(@UserService, 'logon').and.returnValue(@deferred.promise)
spyOn(@UserFactory, 'save').and.returnValue(@deferred.promise)
LoginCtrl = $controller "LoginCtrl", $scope: @scope, UserService: @UserService, $rootScope: @rootScope, $state: $state, $log: $log, UserFactory: @UserFactory
@scope.user =
email: "test@test.com"
name: "test"
password: "test"
afterEach ->
@UserService.logon.calls.reset()
@UserFactory.save.calls.reset()
describe "on logon", ->
it 'should call logon of the UserService', ->
@scope.logon()
expect(@UserService.logon).toHaveBeenCalled()
expect(@UserService.logon).toHaveBeenCalledWith(@scope.user)
describe "on register", ->
it 'should call save of the UserFactory', ->
@scope.register()
expect(@UserFactory.save).toHaveBeenCalled()
expect(@UserFactory.save.calls.argsFor(0)[0]).toEqual(@scope.user)
| 75161 | "use strict"
describe "Login / Register Directive", ->
beforeEach ->
module "app"
inject ($controller, $rootScope, $q, $state, $log) ->
@scope = $rootScope.$new()
@rootScope = $rootScope
@deferred = $q.defer()
@UserFactory =
save: (user) ->
@UserService =
logon: (name, password) ->
spyOn(@UserService, 'logon').and.returnValue(@deferred.promise)
spyOn(@UserFactory, 'save').and.returnValue(@deferred.promise)
LoginCtrl = $controller "LoginCtrl", $scope: @scope, UserService: @UserService, $rootScope: @rootScope, $state: $state, $log: $log, UserFactory: @UserFactory
@scope.user =
email: "<EMAIL>"
name: "test"
password: "<PASSWORD>"
afterEach ->
@UserService.logon.calls.reset()
@UserFactory.save.calls.reset()
describe "on logon", ->
it 'should call logon of the UserService', ->
@scope.logon()
expect(@UserService.logon).toHaveBeenCalled()
expect(@UserService.logon).toHaveBeenCalledWith(@scope.user)
describe "on register", ->
it 'should call save of the UserFactory', ->
@scope.register()
expect(@UserFactory.save).toHaveBeenCalled()
expect(@UserFactory.save.calls.argsFor(0)[0]).toEqual(@scope.user)
| true | "use strict"
describe "Login / Register Directive", ->
beforeEach ->
module "app"
inject ($controller, $rootScope, $q, $state, $log) ->
@scope = $rootScope.$new()
@rootScope = $rootScope
@deferred = $q.defer()
@UserFactory =
save: (user) ->
@UserService =
logon: (name, password) ->
spyOn(@UserService, 'logon').and.returnValue(@deferred.promise)
spyOn(@UserFactory, 'save').and.returnValue(@deferred.promise)
LoginCtrl = $controller "LoginCtrl", $scope: @scope, UserService: @UserService, $rootScope: @rootScope, $state: $state, $log: $log, UserFactory: @UserFactory
@scope.user =
email: "PI:EMAIL:<EMAIL>END_PI"
name: "test"
password: "PI:PASSWORD:<PASSWORD>END_PI"
afterEach ->
@UserService.logon.calls.reset()
@UserFactory.save.calls.reset()
describe "on logon", ->
it 'should call logon of the UserService', ->
@scope.logon()
expect(@UserService.logon).toHaveBeenCalled()
expect(@UserService.logon).toHaveBeenCalledWith(@scope.user)
describe "on register", ->
it 'should call save of the UserFactory', ->
@scope.register()
expect(@UserFactory.save).toHaveBeenCalled()
expect(@UserFactory.save.calls.argsFor(0)[0]).toEqual(@scope.user)
|
[
{
"context": "mespace COOLSTRAP\n * @class Plugins\n * \n * @author Cristian Ferrari <cristianferrarig@gmail.com> || @energettico\n * @",
"end": 103,
"score": 0.9998801350593567,
"start": 87,
"tag": "NAME",
"value": "Cristian Ferrari"
},
{
"context": "* @class Plugins\n * \n * @autho... | coolstrap-core/app/assets/javascripts/coolstrap/plugins/_Coolstrap.Plugins.coffee | cristianferrarig/coolstrap | 0 | ###
* Coolstrapp Plugins
*
* @namespace COOLSTRAP
* @class Plugins
*
* @author Cristian Ferrari <cristianferrarig@gmail.com> || @energettico
* @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera
*
###
COOLSTRAP.Plugins = ((cool, document) ->
# fn arg can be an object or a function, thanks to handleEvent
# read more about the explanation at: http://www.thecssninja.com/javascript/handleevent
addEvt = (el, evt, fn, bubble) ->
if "addEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.addEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.addEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
), bubble
else
throw e
else if "attachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.attachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
else
el.attachEvent "on" + evt, fn
rmEvt = (el, evt, fn, bubble) ->
if "removeEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.removeEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.removeEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
), bubble
else
throw e
else if "detachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.detachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
else
el.detachEvent "on" + evt, fn
hadTouchEvent = false
###
* Fast Buttons
* fastButton is used to make instant responsive buttons,
* 300ms faster to be exact.
*
* new COOLSTRAP.Plugins.fastButton(document.getElementById('myBtn'), function() { // do something });
*
* Inspired by MBP
* https://github.com/h5bp/mobile-boilerplate/blob/master/js/helper.js
###
fastButton = (element, handler) ->
@handler = handler
if element.length and element.length > 1
for singleElIdx of element
@addClickEvent element[singleElIdx]
else
@addClickEvent element
fastButton::handleEvent = (event) ->
event = event or window.event
switch event.type
when "touchstart"
@onTouchStart event
when "touchmove"
@onTouchMove event
when "touchend"
@onClick event
when "click"
@onClick event
fastButton::onTouchStart = (event) ->
element = event.srcElement
event.stopPropagation()
element.addEventListener "touchend", this, false
document.body.addEventListener "touchmove", this, false
@startX = event.touches[0].clientX
@startY = event.touches[0].clientY
element.style.backgroundColor = "rgba(0,0,0,.7)"
fastButton::onTouchMove = (event) ->
@reset element if Math.abs(event.touches[0].clientX - @startX) > 10 or Math.abs(event.touches[0].clientY - @startY) > 10
fastButton::onClick = (event) ->
event = event or window.event
element = event.srcElement
event.stopPropagation() if event.stopPropagation
@reset event
@handler.apply event.currentTarget, [ event ]
preventGhostClick @startX, @startY if event.type is "touchend"
element.style.backgroundColor = ""
fastButton::reset = (event) ->
element = event.srcElement
rmEvt element, "touchend", this, false
rmEvt document.body, "touchmove", this, false
element.style.backgroundColor = ""
fastButton::addClickEvent = (element) ->
addEvt element, "touchstart", this, false
addEvt element, "click", this, false
preventGhostClick = (x, y) ->
coords.push x, y
window.setTimeout (->
coords.splice 0, 2
), 2500
ghostClickHandler = (event) ->
if not hadTouchEvent and "ontouchstart" of window
###
This is a bit of fun for Android 2.3...
If you change window.location via fastButton, a click event will fire
on the new page, as if the events are continuing from the previous page.
We pick that event up here, but coords is empty, because it's a new page,
so we don't prevent it. Here's we're assuming that click events on touch devices
that occur without a preceding touchStart are to be ignored.
###
event.stopPropagation()
event.preventDefault()
return
i = 0
len = coords.length
while i < len
x = coords[i]
y = coords[i + 1]
if Math.abs(event.clientX - x) < 25 and Math.abs(event.clientY - y) < 25
event.stopPropagation()
event.preventDefault()
i += 2
document.addEventListener "click", ghostClickHandler, true if document.addEventListener
addEvt document.documentElement, "touchstart", (->
hadTouchEvent = true
), false
coords = []
fastButton: fastButton
)(COOLSTRAP, document) | 112682 | ###
* Coolstrapp Plugins
*
* @namespace COOLSTRAP
* @class Plugins
*
* @author <NAME> <<EMAIL>> || @energettico
* @author <NAME> <<EMAIL>> || @abraham_barrera
*
###
COOLSTRAP.Plugins = ((cool, document) ->
# fn arg can be an object or a function, thanks to handleEvent
# read more about the explanation at: http://www.thecssninja.com/javascript/handleevent
addEvt = (el, evt, fn, bubble) ->
if "addEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.addEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.addEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
), bubble
else
throw e
else if "attachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.attachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
else
el.attachEvent "on" + evt, fn
rmEvt = (el, evt, fn, bubble) ->
if "removeEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.removeEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.removeEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
), bubble
else
throw e
else if "detachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.detachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
else
el.detachEvent "on" + evt, fn
hadTouchEvent = false
###
* Fast Buttons
* fastButton is used to make instant responsive buttons,
* 300ms faster to be exact.
*
* new COOLSTRAP.Plugins.fastButton(document.getElementById('myBtn'), function() { // do something });
*
* Inspired by MBP
* https://github.com/h5bp/mobile-boilerplate/blob/master/js/helper.js
###
fastButton = (element, handler) ->
@handler = handler
if element.length and element.length > 1
for singleElIdx of element
@addClickEvent element[singleElIdx]
else
@addClickEvent element
fastButton::handleEvent = (event) ->
event = event or window.event
switch event.type
when "touchstart"
@onTouchStart event
when "touchmove"
@onTouchMove event
when "touchend"
@onClick event
when "click"
@onClick event
fastButton::onTouchStart = (event) ->
element = event.srcElement
event.stopPropagation()
element.addEventListener "touchend", this, false
document.body.addEventListener "touchmove", this, false
@startX = event.touches[0].clientX
@startY = event.touches[0].clientY
element.style.backgroundColor = "rgba(0,0,0,.7)"
fastButton::onTouchMove = (event) ->
@reset element if Math.abs(event.touches[0].clientX - @startX) > 10 or Math.abs(event.touches[0].clientY - @startY) > 10
fastButton::onClick = (event) ->
event = event or window.event
element = event.srcElement
event.stopPropagation() if event.stopPropagation
@reset event
@handler.apply event.currentTarget, [ event ]
preventGhostClick @startX, @startY if event.type is "touchend"
element.style.backgroundColor = ""
fastButton::reset = (event) ->
element = event.srcElement
rmEvt element, "touchend", this, false
rmEvt document.body, "touchmove", this, false
element.style.backgroundColor = ""
fastButton::addClickEvent = (element) ->
addEvt element, "touchstart", this, false
addEvt element, "click", this, false
preventGhostClick = (x, y) ->
coords.push x, y
window.setTimeout (->
coords.splice 0, 2
), 2500
ghostClickHandler = (event) ->
if not hadTouchEvent and "ontouchstart" of window
###
This is a bit of fun for Android 2.3...
If you change window.location via fastButton, a click event will fire
on the new page, as if the events are continuing from the previous page.
We pick that event up here, but coords is empty, because it's a new page,
so we don't prevent it. Here's we're assuming that click events on touch devices
that occur without a preceding touchStart are to be ignored.
###
event.stopPropagation()
event.preventDefault()
return
i = 0
len = coords.length
while i < len
x = coords[i]
y = coords[i + 1]
if Math.abs(event.clientX - x) < 25 and Math.abs(event.clientY - y) < 25
event.stopPropagation()
event.preventDefault()
i += 2
document.addEventListener "click", ghostClickHandler, true if document.addEventListener
addEvt document.documentElement, "touchstart", (->
hadTouchEvent = true
), false
coords = []
fastButton: fastButton
)(COOLSTRAP, document) | true | ###
* Coolstrapp Plugins
*
* @namespace COOLSTRAP
* @class Plugins
*
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @energettico
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @abraham_barrera
*
###
COOLSTRAP.Plugins = ((cool, document) ->
# fn arg can be an object or a function, thanks to handleEvent
# read more about the explanation at: http://www.thecssninja.com/javascript/handleevent
addEvt = (el, evt, fn, bubble) ->
if "addEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.addEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.addEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
), bubble
else
throw e
else if "attachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.attachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
else
el.attachEvent "on" + evt, fn
rmEvt = (el, evt, fn, bubble) ->
if "removeEventListener" of el
# BBOS6 doesn't support handleEvent, catch and polyfill
try
el.removeEventListener evt, fn, bubble
catch e
if typeof fn is "object" and fn.handleEvent
el.removeEventListener evt, ((e) ->
# Bind fn as this and set first arg as event object
fn.handleEvent.call fn, e
), bubble
else
throw e
else if "detachEvent" of el
# check if the callback is an object and contains handleEvent
if typeof fn is "object" and fn.handleEvent
el.detachEvent "on" + evt, ->
# Bind fn as this
fn.handleEvent.call fn
else
el.detachEvent "on" + evt, fn
hadTouchEvent = false
###
* Fast Buttons
* fastButton is used to make instant responsive buttons,
* 300ms faster to be exact.
*
* new COOLSTRAP.Plugins.fastButton(document.getElementById('myBtn'), function() { // do something });
*
* Inspired by MBP
* https://github.com/h5bp/mobile-boilerplate/blob/master/js/helper.js
###
fastButton = (element, handler) ->
@handler = handler
if element.length and element.length > 1
for singleElIdx of element
@addClickEvent element[singleElIdx]
else
@addClickEvent element
fastButton::handleEvent = (event) ->
event = event or window.event
switch event.type
when "touchstart"
@onTouchStart event
when "touchmove"
@onTouchMove event
when "touchend"
@onClick event
when "click"
@onClick event
fastButton::onTouchStart = (event) ->
element = event.srcElement
event.stopPropagation()
element.addEventListener "touchend", this, false
document.body.addEventListener "touchmove", this, false
@startX = event.touches[0].clientX
@startY = event.touches[0].clientY
element.style.backgroundColor = "rgba(0,0,0,.7)"
fastButton::onTouchMove = (event) ->
@reset element if Math.abs(event.touches[0].clientX - @startX) > 10 or Math.abs(event.touches[0].clientY - @startY) > 10
fastButton::onClick = (event) ->
event = event or window.event
element = event.srcElement
event.stopPropagation() if event.stopPropagation
@reset event
@handler.apply event.currentTarget, [ event ]
preventGhostClick @startX, @startY if event.type is "touchend"
element.style.backgroundColor = ""
fastButton::reset = (event) ->
element = event.srcElement
rmEvt element, "touchend", this, false
rmEvt document.body, "touchmove", this, false
element.style.backgroundColor = ""
fastButton::addClickEvent = (element) ->
addEvt element, "touchstart", this, false
addEvt element, "click", this, false
preventGhostClick = (x, y) ->
coords.push x, y
window.setTimeout (->
coords.splice 0, 2
), 2500
ghostClickHandler = (event) ->
if not hadTouchEvent and "ontouchstart" of window
###
This is a bit of fun for Android 2.3...
If you change window.location via fastButton, a click event will fire
on the new page, as if the events are continuing from the previous page.
We pick that event up here, but coords is empty, because it's a new page,
so we don't prevent it. Here's we're assuming that click events on touch devices
that occur without a preceding touchStart are to be ignored.
###
event.stopPropagation()
event.preventDefault()
return
i = 0
len = coords.length
while i < len
x = coords[i]
y = coords[i + 1]
if Math.abs(event.clientX - x) < 25 and Math.abs(event.clientY - y) < 25
event.stopPropagation()
event.preventDefault()
i += 2
document.addEventListener "click", ghostClickHandler, true if document.addEventListener
addEvt document.documentElement, "touchstart", (->
hadTouchEvent = true
), false
coords = []
fastButton: fastButton
)(COOLSTRAP, document) |
[
{
"context": " author:\n aclType: 'none'\n name: 'author'\n plural: 'authors'\n base: 'User'\n ",
"end": 74,
"score": 0.9302845597267151,
"start": 68,
"tag": "NAME",
"value": "author"
}
] | spec/model-definitions.coffee | CureApp/loopback-promised | 10 | module.exports =
author:
aclType: 'none'
name: 'author'
plural: 'authors'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
notebooks:
type: 'hasMany'
model: 'notebook'
foreignKey: ''
acls: []
methods: []
leaf:
aclType: 'none'
name: 'leaf'
plural: 'leaves'
base: 'PersistedModel'
idInjection: true
properties:
content:
type: 'string'
createdAt:
type: 'date'
validations: []
relations: {}
acls: []
methods: []
notebook:
aclType: 'none'
name: 'notebook'
plural: 'notebooks'
base: 'PersistedModel'
idInjection: true
properties:
name:
type: 'string'
required: true
validations: []
relations:
leaves:
type: 'hasMany'
model: 'leaf'
foreignKey: ''
acls: []
methods: []
| 31378 | module.exports =
author:
aclType: 'none'
name: '<NAME>'
plural: 'authors'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
notebooks:
type: 'hasMany'
model: 'notebook'
foreignKey: ''
acls: []
methods: []
leaf:
aclType: 'none'
name: 'leaf'
plural: 'leaves'
base: 'PersistedModel'
idInjection: true
properties:
content:
type: 'string'
createdAt:
type: 'date'
validations: []
relations: {}
acls: []
methods: []
notebook:
aclType: 'none'
name: 'notebook'
plural: 'notebooks'
base: 'PersistedModel'
idInjection: true
properties:
name:
type: 'string'
required: true
validations: []
relations:
leaves:
type: 'hasMany'
model: 'leaf'
foreignKey: ''
acls: []
methods: []
| true | module.exports =
author:
aclType: 'none'
name: 'PI:NAME:<NAME>END_PI'
plural: 'authors'
base: 'User'
idInjection: true
properties: {}
validations: []
relations:
notebooks:
type: 'hasMany'
model: 'notebook'
foreignKey: ''
acls: []
methods: []
leaf:
aclType: 'none'
name: 'leaf'
plural: 'leaves'
base: 'PersistedModel'
idInjection: true
properties:
content:
type: 'string'
createdAt:
type: 'date'
validations: []
relations: {}
acls: []
methods: []
notebook:
aclType: 'none'
name: 'notebook'
plural: 'notebooks'
base: 'PersistedModel'
idInjection: true
properties:
name:
type: 'string'
required: true
validations: []
relations:
leaves:
type: 'hasMany'
model: 'leaf'
foreignKey: ''
acls: []
methods: []
|
[
{
"context": "rematurely\n yes\n\nmodule.exports = {\n name: \"Owo\"\n handler: handler\n}\n",
"end": 634,
"score": 0.9299149513244629,
"start": 631,
"tag": "NAME",
"value": "Owo"
}
] | src/specials/owo.coffee | MindfulMinun/discord-haruka | 2 | #! ========================================
#! Special: owo
handler = (msg, Haruka) ->
# Matches variations of "owo", preceded or followed by whitespace, case insensitive
reg = /^\s*[ou][wmn][ou]\s*$/i
# Break if regex doesn't match.
if (not reg.test(msg.content)) or msg.author.bot then return no
# Do it one out of 3 times so it doesn't get too annoying
if (1 / 3) <= Math.random() then return no
msg.channel?.send [
"What's this?"
"uwu what's this???"
"whats this"
].choose()
# Message doesn't call Haruka, exit prematurely
yes
module.exports = {
name: "Owo"
handler: handler
}
| 124916 | #! ========================================
#! Special: owo
handler = (msg, Haruka) ->
# Matches variations of "owo", preceded or followed by whitespace, case insensitive
reg = /^\s*[ou][wmn][ou]\s*$/i
# Break if regex doesn't match.
if (not reg.test(msg.content)) or msg.author.bot then return no
# Do it one out of 3 times so it doesn't get too annoying
if (1 / 3) <= Math.random() then return no
msg.channel?.send [
"What's this?"
"uwu what's this???"
"whats this"
].choose()
# Message doesn't call Haruka, exit prematurely
yes
module.exports = {
name: "<NAME>"
handler: handler
}
| true | #! ========================================
#! Special: owo
handler = (msg, Haruka) ->
# Matches variations of "owo", preceded or followed by whitespace, case insensitive
reg = /^\s*[ou][wmn][ou]\s*$/i
# Break if regex doesn't match.
if (not reg.test(msg.content)) or msg.author.bot then return no
# Do it one out of 3 times so it doesn't get too annoying
if (1 / 3) <= Math.random() then return no
msg.channel?.send [
"What's this?"
"uwu what's this???"
"whats this"
].choose()
# Message doesn't call Haruka, exit prematurely
yes
module.exports = {
name: "PI:NAME:<NAME>END_PI"
handler: handler
}
|
[
{
"context": "etter__ 'creds', (creds) ->\n # as reported by Charles Schwab customer support\n # search for \"schwab passw",
"end": 406,
"score": 0.9856370687484741,
"start": 392,
"tag": "NAME",
"value": "Charles Schwab"
},
{
"context": "g password to 8 characters\"\n ... | application/chrome/content/wesabe/fi-scripts/com/schwab/bank.coffee | wesabe/ssu | 28 | wesabe.provide 'fi-scripts.com.schwab.bank',
class bank extends wesabe.download.OFXPlayer
fid: 'com.schwab.bank'
org: 'Charles Schwab Bank, N.A.'
fi:
ofxFid: '101'
ofxOrg: 'ISC'
ofxUrl: 'https://ofx.schwab.com/bankcgi_dev/ofx_server'
this::__defineGetter__ 'creds', ->
@_creds
this::__defineSetter__ 'creds', (creds) ->
# as reported by Charles Schwab customer support
# search for "schwab password 8 characters quicken"
logger.info "Truncating password to 8 characters"
creds.password = creds.password.substring(0, 8)
@_creds = creds
| 113138 | wesabe.provide 'fi-scripts.com.schwab.bank',
class bank extends wesabe.download.OFXPlayer
fid: 'com.schwab.bank'
org: 'Charles Schwab Bank, N.A.'
fi:
ofxFid: '101'
ofxOrg: 'ISC'
ofxUrl: 'https://ofx.schwab.com/bankcgi_dev/ofx_server'
this::__defineGetter__ 'creds', ->
@_creds
this::__defineSetter__ 'creds', (creds) ->
# as reported by <NAME> customer support
# search for "schwab password 8 characters quicken"
logger.info "Truncating password to 8 characters"
creds.password = <PASSWORD>(0, 8)
@_creds = creds
| true | wesabe.provide 'fi-scripts.com.schwab.bank',
class bank extends wesabe.download.OFXPlayer
fid: 'com.schwab.bank'
org: 'Charles Schwab Bank, N.A.'
fi:
ofxFid: '101'
ofxOrg: 'ISC'
ofxUrl: 'https://ofx.schwab.com/bankcgi_dev/ofx_server'
this::__defineGetter__ 'creds', ->
@_creds
this::__defineSetter__ 'creds', (creds) ->
# as reported by PI:NAME:<NAME>END_PI customer support
# search for "schwab password 8 characters quicken"
logger.info "Truncating password to 8 characters"
creds.password = PI:PASSWORD:<PASSWORD>END_PI(0, 8)
@_creds = creds
|
[
{
"context": " phoneNumber: phoneNumber\n password: '123456'\n\n util.requestAsync options\n\n .spread (res",
"end": 5000,
"score": 0.9993461966514587,
"start": 4994,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": " phoneNumber: phoneNumber\n passw... | talk-account/test/apis/mobile.coffee | ikingye/talk-os | 3,084 | should = require 'should'
config = require 'config'
jwt = require 'jsonwebtoken'
Promise = require 'bluebird'
limbo = require 'limbo'
util = require '../util'
redis = require '../../server/components/redis'
phoneNumber = '18500000000'
{
MobileModel
UserModel
} = limbo.use 'account'
requestUtil = require '../../server/util/request'
requestUtil.sendSMS = -> Promise.resolve({})
describe 'Mobile', ->
before util.prepare
it 'should send verify code and get random code', (done) ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber
util.request options, (err, res, body) ->
body.should.have.properties 'randomCode'
util.randomCode = body.randomCode
util.verifyCode = body.verifyCode
done err
it 'should create a new user after verifing phone number', (done) ->
options =
method: 'POST'
url: '/mobile/signin'
body:
verifyCode: util.verifyCode
randomCode: util.randomCode
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql phoneNumber
user.wasNew.should.eql true
{_id, login} = jwt.decode user.accountToken
login.should.eql 'mobile'
util.user1 = user
done()
.catch done
it 'should not bind to an exist phone number', (done) ->
$verifyData = redis.delAsync "sentverify:#{phoneNumber}"
.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber
util.requestAsync options
.spread (res, body) -> body
$bind = $verifyData.then (verifyData) ->
options =
method: 'POST'
url: '/mobile/bind'
body:
accountToken: util.user1.accountToken
randomCode: verifyData.randomCode
verifyCode: verifyData.verifyCode
util.requestAsync options
.spread (res, body) -> done new Error('无法绑定已存在的手机号')
.catch (err) ->
err.message.should.eql '绑定账号已存在'
err.should.have.properties 'data'
err.data.should.have.properties 'bindCode', 'showname'
util.bindCode = err.data.bindCode
done()
it 'should bind to the exist phone number by bindCode', (done) ->
options =
method: 'POST'
url: '/mobile/forcebind'
body:
bindCode: util.bindCode
accountToken: util.user1.accountToken
util.request options, (err, res, user) ->
user.should.have.properties 'phoneNumber', 'accountToken', 'login'
user.phoneNumber.should.eql phoneNumber
done err
it 'should unbind the current phone number', (done) ->
options =
method: 'POST'
url: '/mobile/unbind'
body:
accountToken: util.user1.accountToken
phoneNumber: phoneNumber
util.request options, (err, res, user) ->
user.should.not.have.properties 'phoneNumber', 'accountToken', 'login'
done err
it 'should bind to another phone number', (done) ->
phoneNumber2 = '18500000001'
$verifyData = redis.delAsync "sentverify:#{phoneNumber2}"
.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber2
util.requestAsync options
.spread (res, body) -> body
$bind = $verifyData
.then (verifyData) ->
options =
method: 'POST'
url: '/mobile/bind'
body:
accountToken: util.user1.accountToken
randomCode: verifyData.randomCode
verifyCode: verifyData.verifyCode
util.requestAsync options
.spread (res, user) ->
user.should.have.properties 'phoneNumber', 'accountToken'
user.phoneNumber.should.eql phoneNumber2
done()
.catch done
it 'should change the phoneNumber through change api', (done) ->
$verifyData = redis.delAsync "sentverify:#{phoneNumber}"
.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber
util.requestAsync options
.spread (res, body) -> body
$change = $verifyData.then (verifyData) ->
options =
method: 'POST'
url: '/mobile/change'
body:
accountToken: util.user1.accountToken
randomCode: verifyData.randomCode
verifyCode: verifyData.verifyCode
util.requestAsync options
.spread (res, user) ->
user.should.have.properties 'phoneNumber', 'accountToken'
user.phoneNumber.should.eql phoneNumber
done()
.catch done
after util.cleanup
describe 'Mobile#WithPassword', ->
before util.prepare
it 'should send verifycode with password', (done) ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body:
action: 'signup'
phoneNumber: phoneNumber
password: '123456'
util.requestAsync options
.spread (res, body) ->
body.should.have.properties 'randomCode'
util.randomCode = body.randomCode
util.verifyCode = body.verifyCode
.nodeify done
it 'should signup by verifyCode with password', (done) ->
options =
method: 'POST'
url: '/mobile/signup'
body:
phoneNumber: phoneNumber
randomCode: util.randomCode
verifyCode: util.verifyCode
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql phoneNumber
user.wasNew.should.eql true
.nodeify done
it 'should signin by phoneNumber and password', (done) ->
options =
method: 'POST'
url: '/mobile/signin'
body:
phoneNumber: phoneNumber
password: '123456'
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql phoneNumber
user.wasNew.should.eql false
done()
.catch done
after util.cleanup
describe 'Mobile#checkResetPasswordVerifyCode', ->
newPhoneNumber = '15700000000'
before util.prepare
it 'should send verifycode with password', (done) ->
$createMobile = Promise.resolve().then ->
user = new UserModel
mobile = new MobileModel
phoneNumber: newPhoneNumber
user: user
Promise.all [user.$save(), mobile.$save()]
$sendVerifyCode = $createMobile.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body:
action: 'resetpassword'
phoneNumber: newPhoneNumber
util.requestAsync options
.spread (res, body) ->
body.should.have.properties 'randomCode'
util.randomCode = body.randomCode
util.verifyCode = body.verifyCode
done()
.catch done
it 'should check reset password request verify code and auto login', (done) ->
$verify = Promise.resolve().then ->
options =
method: 'POST'
url: '/mobile/signinbyverifycode'
body:
randomCode: util.randomCode
verifyCode: util.verifyCode
action: 'resetpassword'
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.should.not.have.properties 'password'
user.phoneNumber.should.eql newPhoneNumber
user.wasNew.should.eql false
util.user4 = user
done()
.catch done
it 'should changed to the new password', (done) ->
options =
method: 'POST'
url: '/mobile/resetpassword'
body:
newPassword: 'abc123456'
accountToken: util.user4.accountToken
util.requestAsync options
.spread (res, user) ->
user.wasNew.should.eql false
user.should.have.properties 'accountToken'
.nodeify done
it 'should signin by phoneNumber and new password', (done) ->
options =
method: 'POST'
url: '/mobile/signin'
body:
phoneNumber: newPhoneNumber
password: 'abc123456'
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql newPhoneNumber
user.wasNew.should.eql false
done()
.catch done
after util.cleanup
| 20518 | should = require 'should'
config = require 'config'
jwt = require 'jsonwebtoken'
Promise = require 'bluebird'
limbo = require 'limbo'
util = require '../util'
redis = require '../../server/components/redis'
phoneNumber = '18500000000'
{
MobileModel
UserModel
} = limbo.use 'account'
requestUtil = require '../../server/util/request'
requestUtil.sendSMS = -> Promise.resolve({})
describe 'Mobile', ->
before util.prepare
it 'should send verify code and get random code', (done) ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber
util.request options, (err, res, body) ->
body.should.have.properties 'randomCode'
util.randomCode = body.randomCode
util.verifyCode = body.verifyCode
done err
it 'should create a new user after verifing phone number', (done) ->
options =
method: 'POST'
url: '/mobile/signin'
body:
verifyCode: util.verifyCode
randomCode: util.randomCode
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql phoneNumber
user.wasNew.should.eql true
{_id, login} = jwt.decode user.accountToken
login.should.eql 'mobile'
util.user1 = user
done()
.catch done
it 'should not bind to an exist phone number', (done) ->
$verifyData = redis.delAsync "sentverify:#{phoneNumber}"
.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber
util.requestAsync options
.spread (res, body) -> body
$bind = $verifyData.then (verifyData) ->
options =
method: 'POST'
url: '/mobile/bind'
body:
accountToken: util.user1.accountToken
randomCode: verifyData.randomCode
verifyCode: verifyData.verifyCode
util.requestAsync options
.spread (res, body) -> done new Error('无法绑定已存在的手机号')
.catch (err) ->
err.message.should.eql '绑定账号已存在'
err.should.have.properties 'data'
err.data.should.have.properties 'bindCode', 'showname'
util.bindCode = err.data.bindCode
done()
it 'should bind to the exist phone number by bindCode', (done) ->
options =
method: 'POST'
url: '/mobile/forcebind'
body:
bindCode: util.bindCode
accountToken: util.user1.accountToken
util.request options, (err, res, user) ->
user.should.have.properties 'phoneNumber', 'accountToken', 'login'
user.phoneNumber.should.eql phoneNumber
done err
it 'should unbind the current phone number', (done) ->
options =
method: 'POST'
url: '/mobile/unbind'
body:
accountToken: util.user1.accountToken
phoneNumber: phoneNumber
util.request options, (err, res, user) ->
user.should.not.have.properties 'phoneNumber', 'accountToken', 'login'
done err
it 'should bind to another phone number', (done) ->
phoneNumber2 = '18500000001'
$verifyData = redis.delAsync "sentverify:#{phoneNumber2}"
.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber2
util.requestAsync options
.spread (res, body) -> body
$bind = $verifyData
.then (verifyData) ->
options =
method: 'POST'
url: '/mobile/bind'
body:
accountToken: util.user1.accountToken
randomCode: verifyData.randomCode
verifyCode: verifyData.verifyCode
util.requestAsync options
.spread (res, user) ->
user.should.have.properties 'phoneNumber', 'accountToken'
user.phoneNumber.should.eql phoneNumber2
done()
.catch done
it 'should change the phoneNumber through change api', (done) ->
$verifyData = redis.delAsync "sentverify:#{phoneNumber}"
.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber
util.requestAsync options
.spread (res, body) -> body
$change = $verifyData.then (verifyData) ->
options =
method: 'POST'
url: '/mobile/change'
body:
accountToken: util.user1.accountToken
randomCode: verifyData.randomCode
verifyCode: verifyData.verifyCode
util.requestAsync options
.spread (res, user) ->
user.should.have.properties 'phoneNumber', 'accountToken'
user.phoneNumber.should.eql phoneNumber
done()
.catch done
after util.cleanup
describe 'Mobile#WithPassword', ->
before util.prepare
it 'should send verifycode with password', (done) ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body:
action: 'signup'
phoneNumber: phoneNumber
password: '<PASSWORD>'
util.requestAsync options
.spread (res, body) ->
body.should.have.properties 'randomCode'
util.randomCode = body.randomCode
util.verifyCode = body.verifyCode
.nodeify done
it 'should signup by verifyCode with password', (done) ->
options =
method: 'POST'
url: '/mobile/signup'
body:
phoneNumber: phoneNumber
randomCode: util.randomCode
verifyCode: util.verifyCode
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql phoneNumber
user.wasNew.should.eql true
.nodeify done
it 'should signin by phoneNumber and password', (done) ->
options =
method: 'POST'
url: '/mobile/signin'
body:
phoneNumber: phoneNumber
password: '<PASSWORD>'
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql phoneNumber
user.wasNew.should.eql false
done()
.catch done
after util.cleanup
describe 'Mobile#checkResetPasswordVerifyCode', ->
newPhoneNumber = '15700000000'
before util.prepare
it 'should send verifycode with password', (done) ->
$createMobile = Promise.resolve().then ->
user = new UserModel
mobile = new MobileModel
phoneNumber: newPhoneNumber
user: user
Promise.all [user.$save(), mobile.$save()]
$sendVerifyCode = $createMobile.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body:
action: 'resetpassword'
phoneNumber: newPhoneNumber
util.requestAsync options
.spread (res, body) ->
body.should.have.properties 'randomCode'
util.randomCode = body.randomCode
util.verifyCode = body.verifyCode
done()
.catch done
it 'should check reset password request verify code and auto login', (done) ->
$verify = Promise.resolve().then ->
options =
method: 'POST'
url: '/mobile/signinbyverifycode'
body:
randomCode: util.randomCode
verifyCode: util.verifyCode
action: 'resetpassword'
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.should.not.have.properties 'password'
user.phoneNumber.should.eql newPhoneNumber
user.wasNew.should.eql false
util.user4 = user
done()
.catch done
it 'should changed to the new password', (done) ->
options =
method: 'POST'
url: '/mobile/resetpassword'
body:
newPassword: '<PASSWORD>'
accountToken: util.user4.accountToken
util.requestAsync options
.spread (res, user) ->
user.wasNew.should.eql false
user.should.have.properties 'accountToken'
.nodeify done
it 'should signin by phoneNumber and new password', (done) ->
options =
method: 'POST'
url: '/mobile/signin'
body:
phoneNumber: newPhoneNumber
password: '<PASSWORD>'
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql newPhoneNumber
user.wasNew.should.eql false
done()
.catch done
after util.cleanup
| true | should = require 'should'
config = require 'config'
jwt = require 'jsonwebtoken'
Promise = require 'bluebird'
limbo = require 'limbo'
util = require '../util'
redis = require '../../server/components/redis'
phoneNumber = '18500000000'
{
MobileModel
UserModel
} = limbo.use 'account'
requestUtil = require '../../server/util/request'
requestUtil.sendSMS = -> Promise.resolve({})
describe 'Mobile', ->
before util.prepare
it 'should send verify code and get random code', (done) ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber
util.request options, (err, res, body) ->
body.should.have.properties 'randomCode'
util.randomCode = body.randomCode
util.verifyCode = body.verifyCode
done err
it 'should create a new user after verifing phone number', (done) ->
options =
method: 'POST'
url: '/mobile/signin'
body:
verifyCode: util.verifyCode
randomCode: util.randomCode
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql phoneNumber
user.wasNew.should.eql true
{_id, login} = jwt.decode user.accountToken
login.should.eql 'mobile'
util.user1 = user
done()
.catch done
it 'should not bind to an exist phone number', (done) ->
$verifyData = redis.delAsync "sentverify:#{phoneNumber}"
.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber
util.requestAsync options
.spread (res, body) -> body
$bind = $verifyData.then (verifyData) ->
options =
method: 'POST'
url: '/mobile/bind'
body:
accountToken: util.user1.accountToken
randomCode: verifyData.randomCode
verifyCode: verifyData.verifyCode
util.requestAsync options
.spread (res, body) -> done new Error('无法绑定已存在的手机号')
.catch (err) ->
err.message.should.eql '绑定账号已存在'
err.should.have.properties 'data'
err.data.should.have.properties 'bindCode', 'showname'
util.bindCode = err.data.bindCode
done()
it 'should bind to the exist phone number by bindCode', (done) ->
options =
method: 'POST'
url: '/mobile/forcebind'
body:
bindCode: util.bindCode
accountToken: util.user1.accountToken
util.request options, (err, res, user) ->
user.should.have.properties 'phoneNumber', 'accountToken', 'login'
user.phoneNumber.should.eql phoneNumber
done err
it 'should unbind the current phone number', (done) ->
options =
method: 'POST'
url: '/mobile/unbind'
body:
accountToken: util.user1.accountToken
phoneNumber: phoneNumber
util.request options, (err, res, user) ->
user.should.not.have.properties 'phoneNumber', 'accountToken', 'login'
done err
it 'should bind to another phone number', (done) ->
phoneNumber2 = '18500000001'
$verifyData = redis.delAsync "sentverify:#{phoneNumber2}"
.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber2
util.requestAsync options
.spread (res, body) -> body
$bind = $verifyData
.then (verifyData) ->
options =
method: 'POST'
url: '/mobile/bind'
body:
accountToken: util.user1.accountToken
randomCode: verifyData.randomCode
verifyCode: verifyData.verifyCode
util.requestAsync options
.spread (res, user) ->
user.should.have.properties 'phoneNumber', 'accountToken'
user.phoneNumber.should.eql phoneNumber2
done()
.catch done
it 'should change the phoneNumber through change api', (done) ->
$verifyData = redis.delAsync "sentverify:#{phoneNumber}"
.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body: phoneNumber: phoneNumber
util.requestAsync options
.spread (res, body) -> body
$change = $verifyData.then (verifyData) ->
options =
method: 'POST'
url: '/mobile/change'
body:
accountToken: util.user1.accountToken
randomCode: verifyData.randomCode
verifyCode: verifyData.verifyCode
util.requestAsync options
.spread (res, user) ->
user.should.have.properties 'phoneNumber', 'accountToken'
user.phoneNumber.should.eql phoneNumber
done()
.catch done
after util.cleanup
describe 'Mobile#WithPassword', ->
before util.prepare
it 'should send verifycode with password', (done) ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body:
action: 'signup'
phoneNumber: phoneNumber
password: 'PI:PASSWORD:<PASSWORD>END_PI'
util.requestAsync options
.spread (res, body) ->
body.should.have.properties 'randomCode'
util.randomCode = body.randomCode
util.verifyCode = body.verifyCode
.nodeify done
it 'should signup by verifyCode with password', (done) ->
options =
method: 'POST'
url: '/mobile/signup'
body:
phoneNumber: phoneNumber
randomCode: util.randomCode
verifyCode: util.verifyCode
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql phoneNumber
user.wasNew.should.eql true
.nodeify done
it 'should signin by phoneNumber and password', (done) ->
options =
method: 'POST'
url: '/mobile/signin'
body:
phoneNumber: phoneNumber
password: 'PI:PASSWORD:<PASSWORD>END_PI'
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql phoneNumber
user.wasNew.should.eql false
done()
.catch done
after util.cleanup
describe 'Mobile#checkResetPasswordVerifyCode', ->
newPhoneNumber = '15700000000'
before util.prepare
it 'should send verifycode with password', (done) ->
$createMobile = Promise.resolve().then ->
user = new UserModel
mobile = new MobileModel
phoneNumber: newPhoneNumber
user: user
Promise.all [user.$save(), mobile.$save()]
$sendVerifyCode = $createMobile.then ->
options =
method: 'POST'
url: '/mobile/sendverifycode'
body:
action: 'resetpassword'
phoneNumber: newPhoneNumber
util.requestAsync options
.spread (res, body) ->
body.should.have.properties 'randomCode'
util.randomCode = body.randomCode
util.verifyCode = body.verifyCode
done()
.catch done
it 'should check reset password request verify code and auto login', (done) ->
$verify = Promise.resolve().then ->
options =
method: 'POST'
url: '/mobile/signinbyverifycode'
body:
randomCode: util.randomCode
verifyCode: util.verifyCode
action: 'resetpassword'
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.should.not.have.properties 'password'
user.phoneNumber.should.eql newPhoneNumber
user.wasNew.should.eql false
util.user4 = user
done()
.catch done
it 'should changed to the new password', (done) ->
options =
method: 'POST'
url: '/mobile/resetpassword'
body:
newPassword: 'PI:PASSWORD:<PASSWORD>END_PI'
accountToken: util.user4.accountToken
util.requestAsync options
.spread (res, user) ->
user.wasNew.should.eql false
user.should.have.properties 'accountToken'
.nodeify done
it 'should signin by phoneNumber and new password', (done) ->
options =
method: 'POST'
url: '/mobile/signin'
body:
phoneNumber: newPhoneNumber
password: 'PI:PASSWORD:<PASSWORD>END_PI'
util.requestAsync options
.spread (res, user) ->
(res.headers['set-cookie'].some (str) -> str.indexOf('aid') isnt -1 ).should.eql true
user.should.have.properties 'phoneNumber', 'accountToken', 'wasNew'
user.phoneNumber.should.eql newPhoneNumber
user.wasNew.should.eql false
done()
.catch done
after util.cleanup
|
[
{
"context": "tion for Backbone.Marionette\n#\n# Copyright (C)2012 Derick Bailey, Muted Solutions, LLC\n# Distributed Under MIT Lic",
"end": 108,
"score": 0.9998453855514526,
"start": 95,
"tag": "NAME",
"value": "Derick Bailey"
},
{
"context": "nd Full License Available at:\n# http:/... | client/contacts/contactlist.coffee | zhangcheng/bbclonemail-meteor | 1 | # Backbone.BBCloneMail
# A reference application for Backbone.Marionette
#
# Copyright (C)2012 Derick Bailey, Muted Solutions, LLC
# Distributed Under MIT License
#
# Documentation and Full License Available at:
# http://github.com/derickbailey/backbone.bbclonemail
# http://github.com/derickbailey/backbone.marionette
# Contacts List
# -------------
# Manage the display of, and interaction with, the list of contacts.
BBCloneMail.module "ContactsApp.ContactList", (ContactList, BBCloneMail, Backbone, Marionette, $, _) ->
# Contact List Views
# ------------------
# Display an individual contact in the list.
ContactItemView = Marionette.ItemView.extend
tagName: "li"
template: "contact-item"
# Display the list of contacts.
ContactListView = Marionette.CollectionView.extend
tagName: "ul"
className: "contact-list"
itemView: ContactItemView
# Public API
# ----------
# Show the list of contacts.
ContactList.show = (contacts) ->
contactsView = new ContactListView(collection: contacts)
BBCloneMail.layout.main.show contactsView
| 61507 | # Backbone.BBCloneMail
# A reference application for Backbone.Marionette
#
# Copyright (C)2012 <NAME>, Muted Solutions, LLC
# Distributed Under MIT License
#
# Documentation and Full License Available at:
# http://github.com/derickbailey/backbone.bbclonemail
# http://github.com/derickbailey/backbone.marionette
# Contacts List
# -------------
# Manage the display of, and interaction with, the list of contacts.
BBCloneMail.module "ContactsApp.ContactList", (ContactList, BBCloneMail, Backbone, Marionette, $, _) ->
# Contact List Views
# ------------------
# Display an individual contact in the list.
ContactItemView = Marionette.ItemView.extend
tagName: "li"
template: "contact-item"
# Display the list of contacts.
ContactListView = Marionette.CollectionView.extend
tagName: "ul"
className: "contact-list"
itemView: ContactItemView
# Public API
# ----------
# Show the list of contacts.
ContactList.show = (contacts) ->
contactsView = new ContactListView(collection: contacts)
BBCloneMail.layout.main.show contactsView
| true | # Backbone.BBCloneMail
# A reference application for Backbone.Marionette
#
# Copyright (C)2012 PI:NAME:<NAME>END_PI, Muted Solutions, LLC
# Distributed Under MIT License
#
# Documentation and Full License Available at:
# http://github.com/derickbailey/backbone.bbclonemail
# http://github.com/derickbailey/backbone.marionette
# Contacts List
# -------------
# Manage the display of, and interaction with, the list of contacts.
BBCloneMail.module "ContactsApp.ContactList", (ContactList, BBCloneMail, Backbone, Marionette, $, _) ->
# Contact List Views
# ------------------
# Display an individual contact in the list.
ContactItemView = Marionette.ItemView.extend
tagName: "li"
template: "contact-item"
# Display the list of contacts.
ContactListView = Marionette.CollectionView.extend
tagName: "ul"
className: "contact-list"
itemView: ContactItemView
# Public API
# ----------
# Show the list of contacts.
ContactList.show = (contacts) ->
contactsView = new ContactListView(collection: contacts)
BBCloneMail.layout.main.show contactsView
|
[
{
"context": "ittle Mocha Reference ========\nhttps://github.com/visionmedia/should.js\nhttps://github.com/visionmedia/mocha\n##",
"end": 284,
"score": 0.9994957447052002,
"start": 273,
"tag": "USERNAME",
"value": "visionmedia"
},
{
"context": "thub.com/visionmedia/should.js\nhttps:/... | nodejs/flarebyte.net/0.8/node/magma/node_modules/magma-plugin-json-file-reader/test/magma-plugin-json-file-reader_test.coffee | flarebyte/wonderful-bazar | 0 | 'use strict'
init = require("fb-custom-init")
magma_plugin_json_file_reader = require('magma-plugin-json-file-reader')
should = require('should')
CT = require('magma-constant')
_ = require('lodash')
###
======== A Handy Little Mocha Reference ========
https://github.com/visionmedia/should.js
https://github.com/visionmedia/mocha
###
pluginEx=
pluginId: magma_plugin_json_file_reader.PLUGIN_ID
options:
folder: "test/andesite"
input:
param: "p1"
output:
key: "results"
pluginExStore=
pluginId: magma_plugin_json_file_reader.PLUGIN_ID
options:
folder: "test/andesite"
input:
param: "p1"
output:
key: "alpha"
ctxWithPath=
req:
query:
p1: "ctx_u1"
content:
results: []
store: {}
ctxWithStore=
req:
query:
p1: "ctx_u1"
content:
results: []
store: {}
describe 'magma-plugin-json-file-reader', ()->
describe '#validatePlugin()', ()->
it 'validated plugin', (done)->
magma_plugin_json_file_reader.validatePlugin pluginEx, (e, res)->
if e
done(e)
else
res.should.be.ok
done()
describe '#process()', ()->
it 'populates results', (done)->
magma_plugin_json_file_reader.process pluginEx.options,
ctxWithPath, (e, res)->
if e
done(e)
else
expected= "magma:f/gate/773779160"
res.content.results[0].gateId.should.eql expected
done()
it 'populates the store', (done)->
magma_plugin_json_file_reader.process pluginExStore.options,
ctxWithStore, (e, res)->
if e
done(e)
else
expected= "magma:f/gate/773779160"
res.content.store.alpha.gateId.should.eql expected
done()
| 222799 | 'use strict'
init = require("fb-custom-init")
magma_plugin_json_file_reader = require('magma-plugin-json-file-reader')
should = require('should')
CT = require('magma-constant')
_ = require('lodash')
###
======== A Handy Little Mocha Reference ========
https://github.com/visionmedia/should.js
https://github.com/visionmedia/mocha
###
pluginEx=
pluginId: magma_plugin_json_file_reader.PLUGIN_ID
options:
folder: "test/andesite"
input:
param: "p1"
output:
key: "<KEY>"
pluginExStore=
pluginId: magma_plugin_json_file_reader.PLUGIN_ID
options:
folder: "test/andesite"
input:
param: "p1"
output:
key: "<KEY>"
ctxWithPath=
req:
query:
p1: "ctx_u1"
content:
results: []
store: {}
ctxWithStore=
req:
query:
p1: "ctx_u1"
content:
results: []
store: {}
describe 'magma-plugin-json-file-reader', ()->
describe '#validatePlugin()', ()->
it 'validated plugin', (done)->
magma_plugin_json_file_reader.validatePlugin pluginEx, (e, res)->
if e
done(e)
else
res.should.be.ok
done()
describe '#process()', ()->
it 'populates results', (done)->
magma_plugin_json_file_reader.process pluginEx.options,
ctxWithPath, (e, res)->
if e
done(e)
else
expected= "magma:f/gate/773779160"
res.content.results[0].gateId.should.eql expected
done()
it 'populates the store', (done)->
magma_plugin_json_file_reader.process pluginExStore.options,
ctxWithStore, (e, res)->
if e
done(e)
else
expected= "magma:f/gate/773779160"
res.content.store.alpha.gateId.should.eql expected
done()
| true | 'use strict'
init = require("fb-custom-init")
magma_plugin_json_file_reader = require('magma-plugin-json-file-reader')
should = require('should')
CT = require('magma-constant')
_ = require('lodash')
###
======== A Handy Little Mocha Reference ========
https://github.com/visionmedia/should.js
https://github.com/visionmedia/mocha
###
pluginEx=
pluginId: magma_plugin_json_file_reader.PLUGIN_ID
options:
folder: "test/andesite"
input:
param: "p1"
output:
key: "PI:KEY:<KEY>END_PI"
pluginExStore=
pluginId: magma_plugin_json_file_reader.PLUGIN_ID
options:
folder: "test/andesite"
input:
param: "p1"
output:
key: "PI:KEY:<KEY>END_PI"
ctxWithPath=
req:
query:
p1: "ctx_u1"
content:
results: []
store: {}
ctxWithStore=
req:
query:
p1: "ctx_u1"
content:
results: []
store: {}
describe 'magma-plugin-json-file-reader', ()->
describe '#validatePlugin()', ()->
it 'validated plugin', (done)->
magma_plugin_json_file_reader.validatePlugin pluginEx, (e, res)->
if e
done(e)
else
res.should.be.ok
done()
describe '#process()', ()->
it 'populates results', (done)->
magma_plugin_json_file_reader.process pluginEx.options,
ctxWithPath, (e, res)->
if e
done(e)
else
expected= "magma:f/gate/773779160"
res.content.results[0].gateId.should.eql expected
done()
it 'populates the store', (done)->
magma_plugin_json_file_reader.process pluginExStore.options,
ctxWithStore, (e, res)->
if e
done(e)
else
expected= "magma:f/gate/773779160"
res.content.store.alpha.gateId.should.eql expected
done()
|
[
{
"context": "as {{username}}:{{password}}',\n # username: username\n # password: password\n # )\n return",
"end": 578,
"score": 0.9988399147987366,
"start": 570,
"tag": "USERNAME",
"value": "username"
},
{
"context": ",\n # username: username\n # ... | frontend/scripts/session-controller.coffee | rao1219/Vedio | 0 | angular.module 'vsvs'
.controller 'SessionController', [
'$resource'
'Session'
($resource, Session) ->
@login = (username, password) ->
console.log "username: #{username} password: #{password}"
Session.login username, password
.then ->
console.log 'Good'
, ->
console.log 'login error'
# TODO return promise change state
@logout = ->
Session.logout()
# @register = (username, password) ->
# alert gettextCatalog.getString(
# 'register as {{username}}:{{password}}',
# username: username
# password: password
# )
return
]
| 78386 | angular.module 'vsvs'
.controller 'SessionController', [
'$resource'
'Session'
($resource, Session) ->
@login = (username, password) ->
console.log "username: #{username} password: #{password}"
Session.login username, password
.then ->
console.log 'Good'
, ->
console.log 'login error'
# TODO return promise change state
@logout = ->
Session.logout()
# @register = (username, password) ->
# alert gettextCatalog.getString(
# 'register as {{username}}:{{password}}',
# username: username
# password: <PASSWORD>
# )
return
]
| true | angular.module 'vsvs'
.controller 'SessionController', [
'$resource'
'Session'
($resource, Session) ->
@login = (username, password) ->
console.log "username: #{username} password: #{password}"
Session.login username, password
.then ->
console.log 'Good'
, ->
console.log 'login error'
# TODO return promise change state
@logout = ->
Session.logout()
# @register = (username, password) ->
# alert gettextCatalog.getString(
# 'register as {{username}}:{{password}}',
# username: username
# password: PI:PASSWORD:<PASSWORD>END_PI
# )
return
]
|
[
{
"context": "2\n database: \"mydb\" \n user: \"user\"\n password: \"password\"\n staging:\n ",
"end": 456,
"score": 0.7870566844940186,
"start": 452,
"tag": "USERNAME",
"value": "user"
},
{
"context": "\" \n user: \"user\"\n p... | src/test.coffee | assignittous/knodeo_scriptella | 0 | console.log "TEST"
scriptella = require("./index").Scriptella
propertiesTest =
databases:
drivers:
postgresql:
class: "org.postgresql.Driver"
classPath: "{{cwd}}/_workshop/drivers/postgresql-9.3-1103.jdbc4.jar"
baseUrl: "jdbc:postgresql://{{something}}"
mydb:
development:
driver: "postgresql"
host: "localhost"
port: 5432
database: "mydb"
user: "user"
password: "password"
staging:
driver: "postgresql"
host: "localhost"
port: 5432
database: "mydb"
user: "user"
password: "password"
production:
driver: "postgresql"
host: "localhost"
port: 5432
database: "mydb"
user: "user"
password: "password"
scriptella.testMode = true
locals =
cwd: ()->
return process.cwd()
something: "something!!244"
# scriptella.writeProperties "etl.properties", properties, locals
scriptella.execute "e:\\Staging\\test.xml", propertiesTest, locals | 156568 | console.log "TEST"
scriptella = require("./index").Scriptella
propertiesTest =
databases:
drivers:
postgresql:
class: "org.postgresql.Driver"
classPath: "{{cwd}}/_workshop/drivers/postgresql-9.3-1103.jdbc4.jar"
baseUrl: "jdbc:postgresql://{{something}}"
mydb:
development:
driver: "postgresql"
host: "localhost"
port: 5432
database: "mydb"
user: "user"
password: "<PASSWORD>"
staging:
driver: "postgresql"
host: "localhost"
port: 5432
database: "mydb"
user: "user"
password: "<PASSWORD>"
production:
driver: "postgresql"
host: "localhost"
port: 5432
database: "mydb"
user: "user"
password: "<PASSWORD>"
scriptella.testMode = true
locals =
cwd: ()->
return process.cwd()
something: "something!!244"
# scriptella.writeProperties "etl.properties", properties, locals
scriptella.execute "e:\\Staging\\test.xml", propertiesTest, locals | true | console.log "TEST"
scriptella = require("./index").Scriptella
propertiesTest =
databases:
drivers:
postgresql:
class: "org.postgresql.Driver"
classPath: "{{cwd}}/_workshop/drivers/postgresql-9.3-1103.jdbc4.jar"
baseUrl: "jdbc:postgresql://{{something}}"
mydb:
development:
driver: "postgresql"
host: "localhost"
port: 5432
database: "mydb"
user: "user"
password: "PI:PASSWORD:<PASSWORD>END_PI"
staging:
driver: "postgresql"
host: "localhost"
port: 5432
database: "mydb"
user: "user"
password: "PI:PASSWORD:<PASSWORD>END_PI"
production:
driver: "postgresql"
host: "localhost"
port: 5432
database: "mydb"
user: "user"
password: "PI:PASSWORD:<PASSWORD>END_PI"
scriptella.testMode = true
locals =
cwd: ()->
return process.cwd()
something: "something!!244"
# scriptella.writeProperties "etl.properties", properties, locals
scriptella.execute "e:\\Staging\\test.xml", propertiesTest, locals |
[
{
"context": "ngth != 6\n console.log(\"#{@name} #{dir} #{dist} length #{@genericMovement_dict[\"#",
"end": 1137,
"score": 0.48764681816101074,
"start": 1133,
"tag": "USERNAME",
"value": "name"
},
{
"context": "r}\"\n $(\"##{@elem_id} .panel-title\").tex... | src/coffee/hotac_data.coffee | elistevens/xwing-hotac | 1 | exportObj = exports ? this
#EventEmitter2 = require('eventemitter2').EventEmitter2;
clone = (obj) ->
if not obj? or typeof obj isnt 'object' #or obj.isGlobalState
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
class EnemyAi
constructor: () ->
@movement_dict = {}
@movement_dict.ahead = clone @genericMovement_dict.ahead
@movement_dict.behind = clone @genericMovement_dict.behind
for dir in ['ahead', 'flank', 'behind']
for bearing in ['right', 'left']
@movement_dict["#{dir}#{bearing}"] = {}
for dist in ['far', 'near']
if @genericMovement_dict["#{dir}x"][dist].length != 6
console.log("#{@name} #{dir} #{dist} length #{@genericMovement_dict["#{dir}x"][dist].length}")
@movement_dict["#{dir}#{bearing}"][dist] = []
for move_tup, index in @genericMovement_dict["#{dir}x"][dist]
move_tup = clone move_tup
if move_tup[1] == 'x'
move_tup[1] = bearing
if move_tup[1] == 'y'
if bearing == 'left'
move_tup[1] = 'right'
else
move_tup[1] = 'left'
@movement_dict["#{dir}#{bearing}"][dist][index] = move_tup
initDom: (@ship_str) ->
t = @
@elem_id = "ai-#{@ship_str}"
$("##{@elem_id} .panel-title").text("#{@name}")
$("##{@elem_id} .displayship i").removeClass()\
.addClass("xwing-miniatures-ship xwing-miniatures-ship-#{@id}")
$("\#ai-panel \#ai-toggle-#{@ship_str} i").removeClass()\
.addClass("xwing-miniatures-ship xwing-miniatures-ship-#{@id}")
$("\#ai-panel \#ai-toggle-#{@ship_str}").on(
'click',
null,
null,
(event) -> t.onClick_toggle(event))
for dir in ['ahead', 'flank', 'behind']
for bearing in ['', 'right', 'left']
sector = "#{dir}#{bearing}"
if sector != 'flank'
for distance in ['far', 'near']
$("##{@elem_id} .#{sector}.#{distance}").on(
'click',
null,
{'sector': sector, 'distance': distance},
(event) -> t.onClick_move(event))
$("##{@elem_id} .displayship").on(
'click',
null,
null,
(event) -> t.onClick_ship(event))
if @defaultshow
@onClick_toggle()
onClick_move: (event) ->
move_tup = @movement_dict[event.data.sector][event.data.distance][Math.floor(Math.random() * 6)]
move_str = "#{move_tup[0]}#{move_tup[1] or ''}#{move_tup[2]}"
color = @color_dict[move_str] or 'white'
console.log("#{event.data.sector} #{event.data.distance}: #{move_str}")
$("##{@elem_id} .display i").removeClass()
$("##{@elem_id} .display span").removeClass().text('')
$("##{@elem_id} .#{event.data.sector}.#{event.data.distance}.display i")\
.addClass("xwing-miniatures-font xwing-miniatures-font-#{move_tup[0]}#{move_tup[1] or ''} #{color}")
$("##{@elem_id} .#{event.data.sector}.#{event.data.distance}.display span").addClass(color).text(move_tup[2])
onClick_ship: (event) ->
$("##{@elem_id} .display i").removeClass()
$("##{@elem_id} .display span").text('')
onClick_toggle: (event) ->
$("##{@elem_id}").toggleClass('displaynone')
$("\#ai-panel \#ai-toggle-#{@ship_str}").toggleClass('glow')
exportObj.shipAi = {}
class exportObj.shipAi.TieFighter extends EnemyAi
name: 'TIE Fighter'
id: 'tiefighter'
defaultshow: true
color_dict: {kturn3: 'red', kturn4: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 2],
['bank', 'right', 2],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 2],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 4]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 4],
['kturn', null, 4]],
},
behind: {
far: [
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 3],
['turn', 'right', 3],
['straight', null, 5]],
},
}
class exportObj.shipAi.TieInterceptor extends EnemyAi
name: 'TIE Interceptor'
id: 'tieinterceptor'
defaultshow: true
color_dict: {kturn3: 'red', kturn5: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 2],
['bank', 'right', 2],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 5],
['kturn', null, 5]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 2],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 5]],
},
behindx: {
far: [
['kturn', null, 5],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 5],
['kturn', null, 5]],
},
behind: {
far: [
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 5],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 3],
['turn', 'right', 3],
['straight', null, 5]],
},
}
class exportObj.shipAi.TieAdvanced extends EnemyAi
name: 'TIE Advanced'
id: 'tieadvanced'
color_dict: {kturn4: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 1],
['bank', 'right', 1],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 1],
['bank', 'x', 1],
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4]],
},
flankx: {
far: [
['bank', 'x', 1],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
},
behind: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 2],
['turn', 'right', 2]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 3],
['turn', 'right', 3]],
},
}
class exportObj.shipAi.TieBomber extends EnemyAi
name: 'TIE Bomber'
id: 'tiebomber'
color_dict: {kturn5: 'red', turnleft2: 'red', turnright2: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 4],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2]],
near: [
['bank', 'left', 1],
['bank', 'right', 1],
['straight', null, 1],
['straight', null, 1],
['straight', null, 1],
['kturn', null, 5]],
},
aheadx: {
far: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['turn', 'x', 3],
['straight', null, 1],
['bank', 'x', 1],
['bank', 'x', 1],
['bank', 'x', 1],
['kturn', null, 5]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2]],
},
behindx: {
far: [
['kturn', null, 5],
['kturn', null, 5],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 2]],
},
behind: {
far: [
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'left', 2],
['turn', 'right', 2]],
near: [
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'left', 3],
['turn', 'right', 3]],
},
}
class exportObj.shipAi.TieDefender extends EnemyAi
name: 'TIE Defender'
id: 'tiedefender'
color_dict: {turnleft1: 'red', turnright1: 'red', turnleft2: 'red', turnright2: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 1],
['bank', 'right', 1],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 1],
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 1],
['turn', 'x', 1]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
},
behind: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 3],
['turn', 'right', 3]],
},
}
class exportObj.shipAi.TiePhantom extends EnemyAi
name: 'TIE Phantom'
id: 'tiephantom'
color_dict: {kturn3: 'red', kturn4: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 4],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2]],
near: [
['bank', 'left', 2],
['bank', 'right', 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 2],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 1],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['turn', 'x', 2],
['kturn', null, 4]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 4],
['kturn', null, 4]],
},
behind: {
far: [
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 3],
['turn', 'right', 3],
['straight', null, 4]],
},
}
class exportObj.shipAi.LambdaShuttle extends EnemyAi
name: 'Lambda Shuttle'
id: 'lambdaclassshuttle'
color_dict: {stop0: 'red', turnleft2: 'red', turnright2: 'red', bankleft3: 'red', bankright3: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 3],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2],
['straight', null, 2],
['straight', null, 1]],
near: [
['stop', null, 0],
['stop', null, 0],
['stop', null, 0],
['straight', null, 1],
['bank', 'left', 1],
['bank', 'right', 1]],
},
aheadx: {
far: [
['straight', null, 2],
['bank', 'x', 3],
['bank', 'x', 2],
['bank', 'x', 2],
['bank', 'x', 2],
['turn', 'x', 2]],
near: [
['stop', null, 0],
['straight', null, 1],
['bank', 'x', 1],
['bank', 'x', 1],
['bank', 'x', 1],
['turn', 'x', 2]],
},
flankx: {
far: [
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 2],
['bank', 'x', 3]],
near: [
['stop', null, 0],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1],
['bank', 'x', 2]],
},
behindx: {
far: [
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1],
['bank', 'x', 1]],
near: [
['stop', null, 0],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 2],
['bank', 'x', 3]],
},
behind: {
far: [
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'right', 2],
['turn', 'right', 2],
['turn', 'right', 2]],
near: [
['stop', null, 0],
['stop', null, 0],
['turn', 'left', 2],
['turn', 'right', 2],
['bank', 'left', 3],
['bank', 'right', 3]],
},
}
class exportObj.shipAi.Vt49Decimator extends EnemyAi
name: 'VT-49 Decimator'
id: 'vt49decimator'
color_dict: {}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 4],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2]],
near: [
['straight', null, 4],
['straight', null, 4],
['bank', 'left', 3],
['bank', 'right', 3],
['turn', 'left', 3],
['turn', 'right', 3]],
},
aheadx: {
far: [
['straight', null, 4],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 3]],
near: [
['straight', null, 4],
['straight', null, 4],
['bank', 'x', 3],
['bank', 'y', 3],
['bank', 'y', 2],
['turn', 'y', 2]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
near: [
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
},
behindx: {
far: [
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 1]],
near: [
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
},
behind: {
far: [
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'right', 2],
['turn', 'right', 2],
['turn', 'right', 2]],
near: [
['turn', 'left', 3],
['turn', 'left', 2],
['bank', 'left', 1],
['turn', 'right', 3],
['turn', 'right', 2],
['bank', 'right', 1]],
},
}
| 162443 | exportObj = exports ? this
#EventEmitter2 = require('eventemitter2').EventEmitter2;
clone = (obj) ->
if not obj? or typeof obj isnt 'object' #or obj.isGlobalState
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
class EnemyAi
constructor: () ->
@movement_dict = {}
@movement_dict.ahead = clone @genericMovement_dict.ahead
@movement_dict.behind = clone @genericMovement_dict.behind
for dir in ['ahead', 'flank', 'behind']
for bearing in ['right', 'left']
@movement_dict["#{dir}#{bearing}"] = {}
for dist in ['far', 'near']
if @genericMovement_dict["#{dir}x"][dist].length != 6
console.log("#{@name} #{dir} #{dist} length #{@genericMovement_dict["#{dir}x"][dist].length}")
@movement_dict["#{dir}#{bearing}"][dist] = []
for move_tup, index in @genericMovement_dict["#{dir}x"][dist]
move_tup = clone move_tup
if move_tup[1] == 'x'
move_tup[1] = bearing
if move_tup[1] == 'y'
if bearing == 'left'
move_tup[1] = 'right'
else
move_tup[1] = 'left'
@movement_dict["#{dir}#{bearing}"][dist][index] = move_tup
initDom: (@ship_str) ->
t = @
@elem_id = "ai-#{@ship_str}"
$("##{@elem_id} .panel-title").text("#{@name}")
$("##{@elem_id} .displayship i").removeClass()\
.addClass("xwing-miniatures-ship xwing-miniatures-ship-#{@id}")
$("\#ai-panel \#ai-toggle-#{@ship_str} i").removeClass()\
.addClass("xwing-miniatures-ship xwing-miniatures-ship-#{@id}")
$("\#ai-panel \#ai-toggle-#{@ship_str}").on(
'click',
null,
null,
(event) -> t.onClick_toggle(event))
for dir in ['ahead', 'flank', 'behind']
for bearing in ['', 'right', 'left']
sector = "#{dir}#{bearing}"
if sector != 'flank'
for distance in ['far', 'near']
$("##{@elem_id} .#{sector}.#{distance}").on(
'click',
null,
{'sector': sector, 'distance': distance},
(event) -> t.onClick_move(event))
$("##{@elem_id} .displayship").on(
'click',
null,
null,
(event) -> t.onClick_ship(event))
if @defaultshow
@onClick_toggle()
onClick_move: (event) ->
move_tup = @movement_dict[event.data.sector][event.data.distance][Math.floor(Math.random() * 6)]
move_str = "#{move_tup[0]}#{move_tup[1] or ''}#{move_tup[2]}"
color = @color_dict[move_str] or 'white'
console.log("#{event.data.sector} #{event.data.distance}: #{move_str}")
$("##{@elem_id} .display i").removeClass()
$("##{@elem_id} .display span").removeClass().text('')
$("##{@elem_id} .#{event.data.sector}.#{event.data.distance}.display i")\
.addClass("xwing-miniatures-font xwing-miniatures-font-#{move_tup[0]}#{move_tup[1] or ''} #{color}")
$("##{@elem_id} .#{event.data.sector}.#{event.data.distance}.display span").addClass(color).text(move_tup[2])
onClick_ship: (event) ->
$("##{@elem_id} .display i").removeClass()
$("##{@elem_id} .display span").text('')
onClick_toggle: (event) ->
$("##{@elem_id}").toggleClass('displaynone')
$("\#ai-panel \#ai-toggle-#{@ship_str}").toggleClass('glow')
exportObj.shipAi = {}
class exportObj.shipAi.TieFighter extends EnemyAi
name: '<NAME>'
id: 'tiefighter'
defaultshow: true
color_dict: {kturn3: 'red', kturn4: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 2],
['bank', 'right', 2],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 2],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 4]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 4],
['kturn', null, 4]],
},
behind: {
far: [
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 3],
['turn', 'right', 3],
['straight', null, 5]],
},
}
class exportObj.shipAi.TieInterceptor extends EnemyAi
name: '<NAME>'
id: 'tieinterceptor'
defaultshow: true
color_dict: {kturn3: 'red', kturn5: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 2],
['bank', 'right', 2],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 5],
['kturn', null, 5]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 2],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 5]],
},
behindx: {
far: [
['kturn', null, 5],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 5],
['kturn', null, 5]],
},
behind: {
far: [
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 5],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 3],
['turn', 'right', 3],
['straight', null, 5]],
},
}
class exportObj.shipAi.TieAdvanced extends EnemyAi
name: '<NAME>'
id: 'tieadvanced'
color_dict: {kturn4: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 1],
['bank', 'right', 1],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 1],
['bank', 'x', 1],
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4]],
},
flankx: {
far: [
['bank', 'x', 1],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
},
behind: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 2],
['turn', 'right', 2]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 3],
['turn', 'right', 3]],
},
}
class exportObj.shipAi.TieBomber extends EnemyAi
name: '<NAME>'
id: 'tiebomber'
color_dict: {kturn5: 'red', turnleft2: 'red', turnright2: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 4],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2]],
near: [
['bank', 'left', 1],
['bank', 'right', 1],
['straight', null, 1],
['straight', null, 1],
['straight', null, 1],
['kturn', null, 5]],
},
aheadx: {
far: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['turn', 'x', 3],
['straight', null, 1],
['bank', 'x', 1],
['bank', 'x', 1],
['bank', 'x', 1],
['kturn', null, 5]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2]],
},
behindx: {
far: [
['kturn', null, 5],
['kturn', null, 5],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 2]],
},
behind: {
far: [
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'left', 2],
['turn', 'right', 2]],
near: [
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'left', 3],
['turn', 'right', 3]],
},
}
class exportObj.shipAi.TieDefender extends EnemyAi
name: '<NAME>'
id: 'tiedefender'
color_dict: {turnleft1: 'red', turnright1: 'red', turnleft2: 'red', turnright2: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 1],
['bank', 'right', 1],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 1],
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 1],
['turn', 'x', 1]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
},
behind: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 3],
['turn', 'right', 3]],
},
}
class exportObj.shipAi.TiePhantom extends EnemyAi
name: '<NAME>'
id: 'tiephantom'
color_dict: {kturn3: 'red', kturn4: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 4],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2]],
near: [
['bank', 'left', 2],
['bank', 'right', 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 2],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 1],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['turn', 'x', 2],
['kturn', null, 4]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 4],
['kturn', null, 4]],
},
behind: {
far: [
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 3],
['turn', 'right', 3],
['straight', null, 4]],
},
}
class exportObj.shipAi.LambdaShuttle extends EnemyAi
name: '<NAME>'
id: 'lambdaclassshuttle'
color_dict: {stop0: 'red', turnleft2: 'red', turnright2: 'red', bankleft3: 'red', bankright3: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 3],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2],
['straight', null, 2],
['straight', null, 1]],
near: [
['stop', null, 0],
['stop', null, 0],
['stop', null, 0],
['straight', null, 1],
['bank', 'left', 1],
['bank', 'right', 1]],
},
aheadx: {
far: [
['straight', null, 2],
['bank', 'x', 3],
['bank', 'x', 2],
['bank', 'x', 2],
['bank', 'x', 2],
['turn', 'x', 2]],
near: [
['stop', null, 0],
['straight', null, 1],
['bank', 'x', 1],
['bank', 'x', 1],
['bank', 'x', 1],
['turn', 'x', 2]],
},
flankx: {
far: [
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 2],
['bank', 'x', 3]],
near: [
['stop', null, 0],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1],
['bank', 'x', 2]],
},
behindx: {
far: [
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1],
['bank', 'x', 1]],
near: [
['stop', null, 0],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 2],
['bank', 'x', 3]],
},
behind: {
far: [
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'right', 2],
['turn', 'right', 2],
['turn', 'right', 2]],
near: [
['stop', null, 0],
['stop', null, 0],
['turn', 'left', 2],
['turn', 'right', 2],
['bank', 'left', 3],
['bank', 'right', 3]],
},
}
class exportObj.shipAi.Vt49Decimator extends EnemyAi
name: '<NAME>'
id: 'vt49decimator'
color_dict: {}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 4],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2]],
near: [
['straight', null, 4],
['straight', null, 4],
['bank', 'left', 3],
['bank', 'right', 3],
['turn', 'left', 3],
['turn', 'right', 3]],
},
aheadx: {
far: [
['straight', null, 4],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 3]],
near: [
['straight', null, 4],
['straight', null, 4],
['bank', 'x', 3],
['bank', 'y', 3],
['bank', 'y', 2],
['turn', 'y', 2]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
near: [
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
},
behindx: {
far: [
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 1]],
near: [
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
},
behind: {
far: [
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'right', 2],
['turn', 'right', 2],
['turn', 'right', 2]],
near: [
['turn', 'left', 3],
['turn', 'left', 2],
['bank', 'left', 1],
['turn', 'right', 3],
['turn', 'right', 2],
['bank', 'right', 1]],
},
}
| true | exportObj = exports ? this
#EventEmitter2 = require('eventemitter2').EventEmitter2;
clone = (obj) ->
if not obj? or typeof obj isnt 'object' #or obj.isGlobalState
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = clone obj[key]
return newInstance
class EnemyAi
constructor: () ->
@movement_dict = {}
@movement_dict.ahead = clone @genericMovement_dict.ahead
@movement_dict.behind = clone @genericMovement_dict.behind
for dir in ['ahead', 'flank', 'behind']
for bearing in ['right', 'left']
@movement_dict["#{dir}#{bearing}"] = {}
for dist in ['far', 'near']
if @genericMovement_dict["#{dir}x"][dist].length != 6
console.log("#{@name} #{dir} #{dist} length #{@genericMovement_dict["#{dir}x"][dist].length}")
@movement_dict["#{dir}#{bearing}"][dist] = []
for move_tup, index in @genericMovement_dict["#{dir}x"][dist]
move_tup = clone move_tup
if move_tup[1] == 'x'
move_tup[1] = bearing
if move_tup[1] == 'y'
if bearing == 'left'
move_tup[1] = 'right'
else
move_tup[1] = 'left'
@movement_dict["#{dir}#{bearing}"][dist][index] = move_tup
initDom: (@ship_str) ->
t = @
@elem_id = "ai-#{@ship_str}"
$("##{@elem_id} .panel-title").text("#{@name}")
$("##{@elem_id} .displayship i").removeClass()\
.addClass("xwing-miniatures-ship xwing-miniatures-ship-#{@id}")
$("\#ai-panel \#ai-toggle-#{@ship_str} i").removeClass()\
.addClass("xwing-miniatures-ship xwing-miniatures-ship-#{@id}")
$("\#ai-panel \#ai-toggle-#{@ship_str}").on(
'click',
null,
null,
(event) -> t.onClick_toggle(event))
for dir in ['ahead', 'flank', 'behind']
for bearing in ['', 'right', 'left']
sector = "#{dir}#{bearing}"
if sector != 'flank'
for distance in ['far', 'near']
$("##{@elem_id} .#{sector}.#{distance}").on(
'click',
null,
{'sector': sector, 'distance': distance},
(event) -> t.onClick_move(event))
$("##{@elem_id} .displayship").on(
'click',
null,
null,
(event) -> t.onClick_ship(event))
if @defaultshow
@onClick_toggle()
onClick_move: (event) ->
move_tup = @movement_dict[event.data.sector][event.data.distance][Math.floor(Math.random() * 6)]
move_str = "#{move_tup[0]}#{move_tup[1] or ''}#{move_tup[2]}"
color = @color_dict[move_str] or 'white'
console.log("#{event.data.sector} #{event.data.distance}: #{move_str}")
$("##{@elem_id} .display i").removeClass()
$("##{@elem_id} .display span").removeClass().text('')
$("##{@elem_id} .#{event.data.sector}.#{event.data.distance}.display i")\
.addClass("xwing-miniatures-font xwing-miniatures-font-#{move_tup[0]}#{move_tup[1] or ''} #{color}")
$("##{@elem_id} .#{event.data.sector}.#{event.data.distance}.display span").addClass(color).text(move_tup[2])
onClick_ship: (event) ->
$("##{@elem_id} .display i").removeClass()
$("##{@elem_id} .display span").text('')
onClick_toggle: (event) ->
$("##{@elem_id}").toggleClass('displaynone')
$("\#ai-panel \#ai-toggle-#{@ship_str}").toggleClass('glow')
exportObj.shipAi = {}
class exportObj.shipAi.TieFighter extends EnemyAi
name: 'PI:NAME:<NAME>END_PI'
id: 'tiefighter'
defaultshow: true
color_dict: {kturn3: 'red', kturn4: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 2],
['bank', 'right', 2],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 2],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 4]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 4],
['kturn', null, 4]],
},
behind: {
far: [
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 3],
['turn', 'right', 3],
['straight', null, 5]],
},
}
class exportObj.shipAi.TieInterceptor extends EnemyAi
name: 'PI:NAME:<NAME>END_PI'
id: 'tieinterceptor'
defaultshow: true
color_dict: {kturn3: 'red', kturn5: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 2],
['bank', 'right', 2],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 5],
['kturn', null, 5]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 2],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 5]],
},
behindx: {
far: [
['kturn', null, 5],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 5],
['kturn', null, 5]],
},
behind: {
far: [
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 5],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 3],
['turn', 'right', 3],
['straight', null, 5]],
},
}
class exportObj.shipAi.TieAdvanced extends EnemyAi
name: 'PI:NAME:<NAME>END_PI'
id: 'tieadvanced'
color_dict: {kturn4: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 1],
['bank', 'right', 1],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 1],
['bank', 'x', 1],
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4]],
},
flankx: {
far: [
['bank', 'x', 1],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
},
behind: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 2],
['turn', 'right', 2]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 3],
['turn', 'right', 3]],
},
}
class exportObj.shipAi.TieBomber extends EnemyAi
name: 'PI:NAME:<NAME>END_PI'
id: 'tiebomber'
color_dict: {kturn5: 'red', turnleft2: 'red', turnright2: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 4],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2]],
near: [
['bank', 'left', 1],
['bank', 'right', 1],
['straight', null, 1],
['straight', null, 1],
['straight', null, 1],
['kturn', null, 5]],
},
aheadx: {
far: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['turn', 'x', 3],
['straight', null, 1],
['bank', 'x', 1],
['bank', 'x', 1],
['bank', 'x', 1],
['kturn', null, 5]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2]],
},
behindx: {
far: [
['kturn', null, 5],
['kturn', null, 5],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 2]],
},
behind: {
far: [
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'left', 2],
['turn', 'right', 2]],
near: [
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['kturn', null, 5],
['turn', 'left', 3],
['turn', 'right', 3]],
},
}
class exportObj.shipAi.TieDefender extends EnemyAi
name: 'PI:NAME:<NAME>END_PI'
id: 'tiedefender'
color_dict: {turnleft1: 'red', turnright1: 'red', turnleft2: 'red', turnright2: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 5],
['straight', null, 5],
['straight', null, 5],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3]],
near: [
['bank', 'left', 1],
['bank', 'right', 1],
['straight', null, 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 2],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 1],
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 3]],
near: [
['bank', 'x', 1],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 1],
['turn', 'x', 1]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
},
behind: {
far: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'left', 3],
['turn', 'right', 3]],
},
}
class exportObj.shipAi.TiePhantom extends EnemyAi
name: 'PI:NAME:<NAME>END_PI'
id: 'tiephantom'
color_dict: {kturn3: 'red', kturn4: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 4],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2]],
near: [
['bank', 'left', 2],
['bank', 'right', 2],
['straight', null, 2],
['kturn', null, 4],
['kturn', null, 4],
['kturn', null, 4]],
},
aheadx: {
far: [
['straight', null, 3],
['bank', 'x', 2],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3]],
near: [
['straight', null, 2],
['bank', 'x', 2],
['kturn', null, 4],
['kturn', null, 4],
['turn', 'x', 1],
['turn', 'x', 1]],
},
flankx: {
far: [
['bank', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['turn', 'x', 2],
['kturn', null, 4]],
},
behindx: {
far: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 1]],
near: [
['turn', 'x', 1],
['turn', 'x', 1],
['turn', 'x', 2],
['kturn', null, 3],
['kturn', null, 4],
['kturn', null, 4]],
},
behind: {
far: [
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 1],
['turn', 'right', 1]],
near: [
['kturn', null, 4],
['kturn', null, 3],
['kturn', null, 3],
['turn', 'left', 3],
['turn', 'right', 3],
['straight', null, 4]],
},
}
class exportObj.shipAi.LambdaShuttle extends EnemyAi
name: 'PI:NAME:<NAME>END_PI'
id: 'lambdaclassshuttle'
color_dict: {stop0: 'red', turnleft2: 'red', turnright2: 'red', bankleft3: 'red', bankright3: 'red'}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 3],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2],
['straight', null, 2],
['straight', null, 1]],
near: [
['stop', null, 0],
['stop', null, 0],
['stop', null, 0],
['straight', null, 1],
['bank', 'left', 1],
['bank', 'right', 1]],
},
aheadx: {
far: [
['straight', null, 2],
['bank', 'x', 3],
['bank', 'x', 2],
['bank', 'x', 2],
['bank', 'x', 2],
['turn', 'x', 2]],
near: [
['stop', null, 0],
['straight', null, 1],
['bank', 'x', 1],
['bank', 'x', 1],
['bank', 'x', 1],
['turn', 'x', 2]],
},
flankx: {
far: [
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 2],
['bank', 'x', 3]],
near: [
['stop', null, 0],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1],
['bank', 'x', 2]],
},
behindx: {
far: [
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1],
['bank', 'x', 1]],
near: [
['stop', null, 0],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 2],
['bank', 'x', 3]],
},
behind: {
far: [
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'right', 2],
['turn', 'right', 2],
['turn', 'right', 2]],
near: [
['stop', null, 0],
['stop', null, 0],
['turn', 'left', 2],
['turn', 'right', 2],
['bank', 'left', 3],
['bank', 'right', 3]],
},
}
class exportObj.shipAi.Vt49Decimator extends EnemyAi
name: 'PI:NAME:<NAME>END_PI'
id: 'vt49decimator'
color_dict: {}
genericMovement_dict: {
ahead: {
far: [
['straight', null, 4],
['straight', null, 4],
['straight', null, 4],
['straight', null, 3],
['straight', null, 3],
['straight', null, 2]],
near: [
['straight', null, 4],
['straight', null, 4],
['bank', 'left', 3],
['bank', 'right', 3],
['turn', 'left', 3],
['turn', 'right', 3]],
},
aheadx: {
far: [
['straight', null, 4],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 3]],
near: [
['straight', null, 4],
['straight', null, 4],
['bank', 'x', 3],
['bank', 'y', 3],
['bank', 'y', 2],
['turn', 'y', 2]],
},
flankx: {
far: [
['bank', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 3],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
near: [
['bank', 'x', 3],
['bank', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
},
behindx: {
far: [
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 3],
['turn', 'x', 3],
['bank', 'x', 1]],
near: [
['bank', 'x', 3],
['bank', 'x', 3],
['bank', 'x', 2],
['turn', 'x', 2],
['turn', 'x', 2],
['bank', 'x', 1]],
},
behind: {
far: [
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'left', 2],
['turn', 'right', 2],
['turn', 'right', 2],
['turn', 'right', 2]],
near: [
['turn', 'left', 3],
['turn', 'left', 2],
['bank', 'left', 1],
['turn', 'right', 3],
['turn', 'right', 2],
['bank', 'right', 1]],
},
}
|
[
{
"context": " model.populate({ email: \"\", email_confirmation: \"foo@somewhere.com\" });\n expect(! model.isValid()).toBeTruthy()\n ",
"end": 2156,
"score": 0.9999237656593323,
"start": 2139,
"tag": "EMAIL",
"value": "foo@somewhere.com"
},
{
"context": "d confirm blank\", ->\n ... | test/spec_coffee/confirmation_validator_spec.coffee | kirkbowers/mvcoffee | 0 | MVCoffee = require("../lib/mvcoffee")
theUser = class User extends MVCoffee.Model
theUser.validates 'email', test: 'confirmation'
# The 'email_confirmation' property should be implied
describe "confirmation", ->
model = null
beforeEach ->
model = new User
it "fails when undefined", ->
model.validate();
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when null and confirm undefined", ->
model.populate({ email: null });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm undefined", ->
model.populate({ email: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when null and confirm null", ->
model.populate({ email: null, email_confirmation: null });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm null", ->
model.populate({ email: "", email_confirmation: null });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when null and confirm blank", ->
model.populate({ email: null, email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm blank", ->
model.populate({ email: "", email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm something", ->
model.populate({ email: "", email_confirmation: "foo@somewhere.com" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when something and confirm blank", ->
model.populate({ email: "foo@somewhere.com", email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when something and confirm something else", ->
model.populate({ email: "foo@somewhere.com", email_confirmation: "fob@somewhere.com" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "passes when something and confirm matches", ->
model.populate({ email: "foo@somewhere.com", email_confirmation: "foo@somewhere.com" });
expect(model.isValid()).toBeTruthy()
#----------------------------------------------
# Try with allow blank
theUser = class UserAllowBlank extends MVCoffee.Model
theUser.validates 'email', test: 'confirmation', allow_blank: true
describe "confirmation", ->
model = null
beforeEach ->
model = new UserAllowBlank
it "passes when undefined", ->
model.validate();
expect(model.isValid()).toBeTruthy()
it "passes when null and confirm undefined", ->
model.populate({ email: null });
expect(model.isValid()).toBeTruthy()
it "passes when blank and confirm undefined", ->
model.populate({ email: "" });
expect(model.isValid()).toBeTruthy()
it "passes when null and confirm null", ->
model.populate({ email: null, email_confirmation: null });
expect(model.isValid()).toBeTruthy()
it "passes when blank and confirm null", ->
model.populate({ email: "", email_confirmation: null });
expect(model.isValid()).toBeTruthy()
it "passes when null and confirm blank", ->
model.populate({ email: null, email_confirmation: "" });
expect(model.isValid()).toBeTruthy()
it "passes when blank and confirm blank", ->
model.populate({ email: "", email_confirmation: "" });
expect(model.isValid()).toBeTruthy()
it "fails when something and confirm blank", ->
model.populate({ email: "foo@somewhere.com", email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when something and confirm something else", ->
model.populate({ email: "foo@somewhere.com", email_confirmation: "fob@somewhere.com" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "passes when something and confirm matches", ->
model.populate({ email: "foo@somewhere.com", email_confirmation: "foo@somewhere.com" });
expect(model.isValid()).toBeTruthy()
| 90765 | MVCoffee = require("../lib/mvcoffee")
theUser = class User extends MVCoffee.Model
theUser.validates 'email', test: 'confirmation'
# The 'email_confirmation' property should be implied
describe "confirmation", ->
model = null
beforeEach ->
model = new User
it "fails when undefined", ->
model.validate();
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when null and confirm undefined", ->
model.populate({ email: null });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm undefined", ->
model.populate({ email: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when null and confirm null", ->
model.populate({ email: null, email_confirmation: null });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm null", ->
model.populate({ email: "", email_confirmation: null });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when null and confirm blank", ->
model.populate({ email: null, email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm blank", ->
model.populate({ email: "", email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm something", ->
model.populate({ email: "", email_confirmation: "<EMAIL>" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when something and confirm blank", ->
model.populate({ email: "<EMAIL>", email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when something and confirm something else", ->
model.populate({ email: "<EMAIL>", email_confirmation: "<EMAIL>" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "passes when something and confirm matches", ->
model.populate({ email: "<EMAIL>", email_confirmation: "<EMAIL>" });
expect(model.isValid()).toBeTruthy()
#----------------------------------------------
# Try with allow blank
theUser = class UserAllowBlank extends MVCoffee.Model
theUser.validates 'email', test: 'confirmation', allow_blank: true
describe "confirmation", ->
model = null
beforeEach ->
model = new UserAllowBlank
it "passes when undefined", ->
model.validate();
expect(model.isValid()).toBeTruthy()
it "passes when null and confirm undefined", ->
model.populate({ email: null });
expect(model.isValid()).toBeTruthy()
it "passes when blank and confirm undefined", ->
model.populate({ email: "" });
expect(model.isValid()).toBeTruthy()
it "passes when null and confirm null", ->
model.populate({ email: null, email_confirmation: null });
expect(model.isValid()).toBeTruthy()
it "passes when blank and confirm null", ->
model.populate({ email: "", email_confirmation: null });
expect(model.isValid()).toBeTruthy()
it "passes when null and confirm blank", ->
model.populate({ email: null, email_confirmation: "" });
expect(model.isValid()).toBeTruthy()
it "passes when blank and confirm blank", ->
model.populate({ email: "", email_confirmation: "" });
expect(model.isValid()).toBeTruthy()
it "fails when something and confirm blank", ->
model.populate({ email: "<EMAIL>", email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when something and confirm something else", ->
model.populate({ email: "<EMAIL>", email_confirmation: "<EMAIL>" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "passes when something and confirm matches", ->
model.populate({ email: "<EMAIL>", email_confirmation: "<EMAIL>" });
expect(model.isValid()).toBeTruthy()
| true | MVCoffee = require("../lib/mvcoffee")
theUser = class User extends MVCoffee.Model
theUser.validates 'email', test: 'confirmation'
# The 'email_confirmation' property should be implied
describe "confirmation", ->
model = null
beforeEach ->
model = new User
it "fails when undefined", ->
model.validate();
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when null and confirm undefined", ->
model.populate({ email: null });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm undefined", ->
model.populate({ email: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when null and confirm null", ->
model.populate({ email: null, email_confirmation: null });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm null", ->
model.populate({ email: "", email_confirmation: null });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when null and confirm blank", ->
model.populate({ email: null, email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm blank", ->
model.populate({ email: "", email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when blank and confirm something", ->
model.populate({ email: "", email_confirmation: "PI:EMAIL:<EMAIL>END_PI" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when something and confirm blank", ->
model.populate({ email: "PI:EMAIL:<EMAIL>END_PI", email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when something and confirm something else", ->
model.populate({ email: "PI:EMAIL:<EMAIL>END_PI", email_confirmation: "PI:EMAIL:<EMAIL>END_PI" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "passes when something and confirm matches", ->
model.populate({ email: "PI:EMAIL:<EMAIL>END_PI", email_confirmation: "PI:EMAIL:<EMAIL>END_PI" });
expect(model.isValid()).toBeTruthy()
#----------------------------------------------
# Try with allow blank
theUser = class UserAllowBlank extends MVCoffee.Model
theUser.validates 'email', test: 'confirmation', allow_blank: true
describe "confirmation", ->
model = null
beforeEach ->
model = new UserAllowBlank
it "passes when undefined", ->
model.validate();
expect(model.isValid()).toBeTruthy()
it "passes when null and confirm undefined", ->
model.populate({ email: null });
expect(model.isValid()).toBeTruthy()
it "passes when blank and confirm undefined", ->
model.populate({ email: "" });
expect(model.isValid()).toBeTruthy()
it "passes when null and confirm null", ->
model.populate({ email: null, email_confirmation: null });
expect(model.isValid()).toBeTruthy()
it "passes when blank and confirm null", ->
model.populate({ email: "", email_confirmation: null });
expect(model.isValid()).toBeTruthy()
it "passes when null and confirm blank", ->
model.populate({ email: null, email_confirmation: "" });
expect(model.isValid()).toBeTruthy()
it "passes when blank and confirm blank", ->
model.populate({ email: "", email_confirmation: "" });
expect(model.isValid()).toBeTruthy()
it "fails when something and confirm blank", ->
model.populate({ email: "PI:EMAIL:<EMAIL>END_PI", email_confirmation: "" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "fails when something and confirm something else", ->
model.populate({ email: "PI:EMAIL:<EMAIL>END_PI", email_confirmation: "PI:EMAIL:<EMAIL>END_PI" });
expect(! model.isValid()).toBeTruthy()
expect(model.errors.length).toEqual(1)
expect(model.errors[0]).toEqual("Email doesn't match confirmation")
it "passes when something and confirm matches", ->
model.populate({ email: "PI:EMAIL:<EMAIL>END_PI", email_confirmation: "PI:EMAIL:<EMAIL>END_PI" });
expect(model.isValid()).toBeTruthy()
|
[
{
"context": " This guild base is located in Frigri.\n *\n * @name Frigri\n * @category Bases\n * @package Guild\n * @cos",
"end": 95,
"score": 0.7531615495681763,
"start": 94,
"tag": "NAME",
"value": "F"
},
{
"context": "his guild base is located in Frigri.\n *\n * @name Frigri\n * ... | src/map/guild-bases/Frigri.coffee | jawsome/IdleLands | 3 | GuildBase = require "../GuildBase"
`/**
* This guild base is located in Frigri.
*
* @name Frigri
* @category Bases
* @package Guild
* @cost {move-in} 150000
* @cost {build-sm} 70000
* @cost {build-md} 120000
* @cost {build-lg} 150000
* @buildings {sm} 2
* @buildings {md} 4
* @buildings {lg} 3
*/`
class FrigriGuildHall extends GuildBase
constructor: (game, guild) ->
super "Frigri", game, guild
@costs = FrigriGuildHall::costs =
moveIn: 150000
build:
sm: 70000
md: 120000
lg: 150000
baseTile: 7
startLoc: [1, 11]
buildings:
## Small buildings
sm: [
{
startCoords: [6, 6]
signpostLoc: [5, 5]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
{
startCoords: [26, 26]
signpostLoc: [29, 29]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
]
## Medium Buildings
md: [
{
startCoords: [15, 5]
signpostLoc: [20, 4]
tiles: [
3, 0, 0, 3, 3
0, 0, 0, 0, 3,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
3, 0, 0, 0, 3
]
}
{
startCoords: [5, 15]
signpostLoc: [4, 20]
tiles: [
3, 0, 0, 0, 3
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
3, 0, 0, 0, 0,
3, 3, 0, 0, 3
]
}
{
startCoords: [25, 15]
signpostLoc: [24, 14]
tiles: [
3, 3, 0, 0, 3
3, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
3, 0, 0, 0, 3
]
}
{
startCoords: [15, 25]
signpostLoc: [20, 30]
tiles: [
3, 0, 0, 0, 3
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 3,
3, 0, 0, 3, 3
]
}
]
## Large Buildings
lg: [
{
startCoords: [24, 4]
signpostLoc: [23, 3]
tiles: [
3, 0, 0, 0, 0, 3, 3,
0, 0, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0,
3, 3, 0, 0, 0, 0, 3
]
}
{
startCoords: [14, 14]
signpostLoc: [21, 13]
tiles: [
3, 3, 0, 0, 0, 3, 3,
3, 0, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 3,
3, 3, 0, 0, 0, 3, 3
]
}
{
startCoords: [4, 24]
signpostLoc: [3, 23]
tiles: [
3, 0, 0, 0, 0, 3, 3,
0, 0, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0,
3, 3, 0, 0, 0, 0, 3
]
}
]
module.exports = exports = FrigriGuildHall | 102150 | GuildBase = require "../GuildBase"
`/**
* This guild base is located in Frigri.
*
* @name <NAME>rigri
* @category Bases
* @package Guild
* @cost {move-in} 150000
* @cost {build-sm} 70000
* @cost {build-md} 120000
* @cost {build-lg} 150000
* @buildings {sm} 2
* @buildings {md} 4
* @buildings {lg} 3
*/`
class FrigriGuildHall extends GuildBase
constructor: (game, guild) ->
super "Frigri", game, guild
@costs = FrigriGuildHall::costs =
moveIn: 150000
build:
sm: 70000
md: 120000
lg: 150000
baseTile: 7
startLoc: [1, 11]
buildings:
## Small buildings
sm: [
{
startCoords: [6, 6]
signpostLoc: [5, 5]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
{
startCoords: [26, 26]
signpostLoc: [29, 29]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
]
## Medium Buildings
md: [
{
startCoords: [15, 5]
signpostLoc: [20, 4]
tiles: [
3, 0, 0, 3, 3
0, 0, 0, 0, 3,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
3, 0, 0, 0, 3
]
}
{
startCoords: [5, 15]
signpostLoc: [4, 20]
tiles: [
3, 0, 0, 0, 3
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
3, 0, 0, 0, 0,
3, 3, 0, 0, 3
]
}
{
startCoords: [25, 15]
signpostLoc: [24, 14]
tiles: [
3, 3, 0, 0, 3
3, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
3, 0, 0, 0, 3
]
}
{
startCoords: [15, 25]
signpostLoc: [20, 30]
tiles: [
3, 0, 0, 0, 3
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 3,
3, 0, 0, 3, 3
]
}
]
## Large Buildings
lg: [
{
startCoords: [24, 4]
signpostLoc: [23, 3]
tiles: [
3, 0, 0, 0, 0, 3, 3,
0, 0, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0,
3, 3, 0, 0, 0, 0, 3
]
}
{
startCoords: [14, 14]
signpostLoc: [21, 13]
tiles: [
3, 3, 0, 0, 0, 3, 3,
3, 0, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 3,
3, 3, 0, 0, 0, 3, 3
]
}
{
startCoords: [4, 24]
signpostLoc: [3, 23]
tiles: [
3, 0, 0, 0, 0, 3, 3,
0, 0, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0,
3, 3, 0, 0, 0, 0, 3
]
}
]
module.exports = exports = FrigriGuildHall | true | GuildBase = require "../GuildBase"
`/**
* This guild base is located in Frigri.
*
* @name PI:NAME:<NAME>END_PIrigri
* @category Bases
* @package Guild
* @cost {move-in} 150000
* @cost {build-sm} 70000
* @cost {build-md} 120000
* @cost {build-lg} 150000
* @buildings {sm} 2
* @buildings {md} 4
* @buildings {lg} 3
*/`
class FrigriGuildHall extends GuildBase
constructor: (game, guild) ->
super "Frigri", game, guild
@costs = FrigriGuildHall::costs =
moveIn: 150000
build:
sm: 70000
md: 120000
lg: 150000
baseTile: 7
startLoc: [1, 11]
buildings:
## Small buildings
sm: [
{
startCoords: [6, 6]
signpostLoc: [5, 5]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
{
startCoords: [26, 26]
signpostLoc: [29, 29]
tiles: [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
}
]
## Medium Buildings
md: [
{
startCoords: [15, 5]
signpostLoc: [20, 4]
tiles: [
3, 0, 0, 3, 3
0, 0, 0, 0, 3,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
3, 0, 0, 0, 3
]
}
{
startCoords: [5, 15]
signpostLoc: [4, 20]
tiles: [
3, 0, 0, 0, 3
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
3, 0, 0, 0, 0,
3, 3, 0, 0, 3
]
}
{
startCoords: [25, 15]
signpostLoc: [24, 14]
tiles: [
3, 3, 0, 0, 3
3, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
3, 0, 0, 0, 3
]
}
{
startCoords: [15, 25]
signpostLoc: [20, 30]
tiles: [
3, 0, 0, 0, 3
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 3,
3, 0, 0, 3, 3
]
}
]
## Large Buildings
lg: [
{
startCoords: [24, 4]
signpostLoc: [23, 3]
tiles: [
3, 0, 0, 0, 0, 3, 3,
0, 0, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0,
3, 3, 0, 0, 0, 0, 3
]
}
{
startCoords: [14, 14]
signpostLoc: [21, 13]
tiles: [
3, 3, 0, 0, 0, 3, 3,
3, 0, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 3,
3, 3, 0, 0, 0, 3, 3
]
}
{
startCoords: [4, 24]
signpostLoc: [3, 23]
tiles: [
3, 0, 0, 0, 0, 3, 3,
0, 0, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0,
3, 3, 0, 0, 0, 0, 3
]
}
]
module.exports = exports = FrigriGuildHall |
[
{
"context": "ree ]\n\n it 'should sort by value', ->\n key = \"name\"\n arr = @arr.sort( (a,b) -> b[key] - a[key] )\n",
"end": 454,
"score": 0.9915022850036621,
"start": 450,
"tag": "KEY",
"value": "name"
},
{
"context": "@arr.sort( (a,b) -> b[key] - a[key] )\n\n key = \"n... | src/spec/sorting-spec.coffee | creativeprogramming/mozart | 1 | describe 'Mozart.parseSort', ->
beforeEach ->
@one = Mozart.MztObject.create({name:'one', value:"1"})
@two = Mozart.MztObject.create({name:'two', value:"2"})
@three = Mozart.MztObject.create({name:'three', value:"3"})
@four = Mozart.MztObject.create({name:'four', value:"4"})
@five = Mozart.MztObject.create({name:'five', value:"5"})
@arr = [ @two, @four, @five, @one, @three ]
it 'should sort by value', ->
key = "name"
arr = @arr.sort( (a,b) -> b[key] - a[key] )
key = "name"
arr2 = @arr.sort( (a,b) -> a[key] - b[key] )
describe 'argument parsing', ->
it 'should parse a single value', ->
x = Mozart.parseSort('one')
expect(x).toEqual(['one'])
it 'should parse multiple values', ->
x = Mozart.parseSort('one,two')
expect(x).toEqual(['one','two'])
it 'should parse nested values', ->
x = Mozart.parseSort('one,two,[three,four]')
expect(x).toEqual(['one','two',['three','four']])
it 'should parse multiple nested values', ->
x = Mozart.parseSort('one,two,[three,four],[five,six]')
expect(x).toEqual(['one','two',['three','four'],['five','six']])
it 'should throw on invalid input ', ->
x = -> Mozart.parseSort('one,two[three,four]')
expect(x).toThrow('parseSort: Unexpected Character [ at 8')
| 63362 | describe 'Mozart.parseSort', ->
beforeEach ->
@one = Mozart.MztObject.create({name:'one', value:"1"})
@two = Mozart.MztObject.create({name:'two', value:"2"})
@three = Mozart.MztObject.create({name:'three', value:"3"})
@four = Mozart.MztObject.create({name:'four', value:"4"})
@five = Mozart.MztObject.create({name:'five', value:"5"})
@arr = [ @two, @four, @five, @one, @three ]
it 'should sort by value', ->
key = "<KEY>"
arr = @arr.sort( (a,b) -> b[key] - a[key] )
key = "<KEY>"
arr2 = @arr.sort( (a,b) -> a[key] - b[key] )
describe 'argument parsing', ->
it 'should parse a single value', ->
x = Mozart.parseSort('one')
expect(x).toEqual(['one'])
it 'should parse multiple values', ->
x = Mozart.parseSort('one,two')
expect(x).toEqual(['one','two'])
it 'should parse nested values', ->
x = Mozart.parseSort('one,two,[three,four]')
expect(x).toEqual(['one','two',['three','four']])
it 'should parse multiple nested values', ->
x = Mozart.parseSort('one,two,[three,four],[five,six]')
expect(x).toEqual(['one','two',['three','four'],['five','six']])
it 'should throw on invalid input ', ->
x = -> Mozart.parseSort('one,two[three,four]')
expect(x).toThrow('parseSort: Unexpected Character [ at 8')
| true | describe 'Mozart.parseSort', ->
beforeEach ->
@one = Mozart.MztObject.create({name:'one', value:"1"})
@two = Mozart.MztObject.create({name:'two', value:"2"})
@three = Mozart.MztObject.create({name:'three', value:"3"})
@four = Mozart.MztObject.create({name:'four', value:"4"})
@five = Mozart.MztObject.create({name:'five', value:"5"})
@arr = [ @two, @four, @five, @one, @three ]
it 'should sort by value', ->
key = "PI:KEY:<KEY>END_PI"
arr = @arr.sort( (a,b) -> b[key] - a[key] )
key = "PI:KEY:<KEY>END_PI"
arr2 = @arr.sort( (a,b) -> a[key] - b[key] )
describe 'argument parsing', ->
it 'should parse a single value', ->
x = Mozart.parseSort('one')
expect(x).toEqual(['one'])
it 'should parse multiple values', ->
x = Mozart.parseSort('one,two')
expect(x).toEqual(['one','two'])
it 'should parse nested values', ->
x = Mozart.parseSort('one,two,[three,four]')
expect(x).toEqual(['one','two',['three','four']])
it 'should parse multiple nested values', ->
x = Mozart.parseSort('one,two,[three,four],[five,six]')
expect(x).toEqual(['one','two',['three','four'],['five','six']])
it 'should throw on invalid input ', ->
x = -> Mozart.parseSort('one,two[three,four]')
expect(x).toThrow('parseSort: Unexpected Character [ at 8')
|
[
{
"context": "quest.setRequestHeader(\"X-Authentication-Token\", 'xzBA8HXinAO2zprPr')\n error: (jqXHR, textStatus, errorThrown) -",
"end": 443,
"score": 0.945411205291748,
"start": 426,
"tag": "KEY",
"value": "xzBA8HXinAO2zprPr"
}
] | app/assets/javascripts/questions.js.coffee | unepwcmc/ORS-API | 2 | window.Questions = class Questions
constructor: (@$container_el, @questionnaire_id) ->
@get_questions()
get_questions: ->
$.ajax(
url: "http://demo-ors-api.ort-staging.linode.unep-wcmc.org/api/v1/questionnaires/#{@questionnaire_id}/questions"
type: 'GET'
dataType: 'json'
contentType: 'text/plain'
beforeSend: (request) ->
request.setRequestHeader("X-Authentication-Token", 'xzBA8HXinAO2zprPr')
error: (jqXHR, textStatus, errorThrown) ->
@$container_el.append "AJAX Error: {textStatus}"
success: (data, textStatus, jqXHR) =>
@append_questions_details(data.questions)
new Question(@$container_el, @questionnaire_id)
)
append_questions_details: (questions) ->
sections = {
sections: _.groupBy(questions, (q) ->
q.question.path[0]
)
}
@$container_el.append(HandlebarsTemplates['questionnaire/questions'](sections))
| 209948 | window.Questions = class Questions
constructor: (@$container_el, @questionnaire_id) ->
@get_questions()
get_questions: ->
$.ajax(
url: "http://demo-ors-api.ort-staging.linode.unep-wcmc.org/api/v1/questionnaires/#{@questionnaire_id}/questions"
type: 'GET'
dataType: 'json'
contentType: 'text/plain'
beforeSend: (request) ->
request.setRequestHeader("X-Authentication-Token", '<KEY>')
error: (jqXHR, textStatus, errorThrown) ->
@$container_el.append "AJAX Error: {textStatus}"
success: (data, textStatus, jqXHR) =>
@append_questions_details(data.questions)
new Question(@$container_el, @questionnaire_id)
)
append_questions_details: (questions) ->
sections = {
sections: _.groupBy(questions, (q) ->
q.question.path[0]
)
}
@$container_el.append(HandlebarsTemplates['questionnaire/questions'](sections))
| true | window.Questions = class Questions
constructor: (@$container_el, @questionnaire_id) ->
@get_questions()
get_questions: ->
$.ajax(
url: "http://demo-ors-api.ort-staging.linode.unep-wcmc.org/api/v1/questionnaires/#{@questionnaire_id}/questions"
type: 'GET'
dataType: 'json'
contentType: 'text/plain'
beforeSend: (request) ->
request.setRequestHeader("X-Authentication-Token", 'PI:KEY:<KEY>END_PI')
error: (jqXHR, textStatus, errorThrown) ->
@$container_el.append "AJAX Error: {textStatus}"
success: (data, textStatus, jqXHR) =>
@append_questions_details(data.questions)
new Question(@$container_el, @questionnaire_id)
)
append_questions_details: (questions) ->
sections = {
sections: _.groupBy(questions, (q) ->
q.question.path[0]
)
}
@$container_el.append(HandlebarsTemplates['questionnaire/questions'](sections))
|
[
{
"context": "ce in aid of Amnesty International and St.\n Vincent de Paul'''\n",
"end": 1289,
"score": 0.9602702856063843,
"start": 1274,
"tag": "NAME",
"value": "Vincent de Paul"
}
] | static/src/scripts/app/AppRouter.coffee | Specialkbyte/single-page-static-test | 0 | define [
'backbone',
'collections/TeamsCollection'
'models/FiltersModel'
'views/IndexView'
'views/teams/ListPageView'
], (Backbone, Teams, Filters, IndexView, TeamsListPageView) ->
class Router extends Backbone.Router
routes:
'': 'index'
'teams(/)': 'teams'
initialize: ->
@bodyContainer = $('#body-container')
index: ->
require ['async!//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false'], (data) ->
# do nothing just start loading its
indexView = new IndexView
@_showView indexView, ''
teams: ->
filters = new Filters
teams = new Teams [],
filters: filters
limit: 20
teams.fetch()
teamsView = new TeamsListPageView
collection: teams
filters: filters
@_showView teamsView, 'Teams List'
_showView: (view, title) ->
if @currentView?.close
@currentView.close()
@currentView = view
@bodyContainer.html view.render().$el
@_updateTitle(title)
_updateTitle: (title) ->
if title
sep = ' | '
else
sep = ''
document.title = title + sep + '''JailbreakHQ 2015 a global
charity race in aid of Amnesty International and St.
Vincent de Paul'''
| 134034 | define [
'backbone',
'collections/TeamsCollection'
'models/FiltersModel'
'views/IndexView'
'views/teams/ListPageView'
], (Backbone, Teams, Filters, IndexView, TeamsListPageView) ->
class Router extends Backbone.Router
routes:
'': 'index'
'teams(/)': 'teams'
initialize: ->
@bodyContainer = $('#body-container')
index: ->
require ['async!//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false'], (data) ->
# do nothing just start loading its
indexView = new IndexView
@_showView indexView, ''
teams: ->
filters = new Filters
teams = new Teams [],
filters: filters
limit: 20
teams.fetch()
teamsView = new TeamsListPageView
collection: teams
filters: filters
@_showView teamsView, 'Teams List'
_showView: (view, title) ->
if @currentView?.close
@currentView.close()
@currentView = view
@bodyContainer.html view.render().$el
@_updateTitle(title)
_updateTitle: (title) ->
if title
sep = ' | '
else
sep = ''
document.title = title + sep + '''JailbreakHQ 2015 a global
charity race in aid of Amnesty International and St.
<NAME>'''
| true | define [
'backbone',
'collections/TeamsCollection'
'models/FiltersModel'
'views/IndexView'
'views/teams/ListPageView'
], (Backbone, Teams, Filters, IndexView, TeamsListPageView) ->
class Router extends Backbone.Router
routes:
'': 'index'
'teams(/)': 'teams'
initialize: ->
@bodyContainer = $('#body-container')
index: ->
require ['async!//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false'], (data) ->
# do nothing just start loading its
indexView = new IndexView
@_showView indexView, ''
teams: ->
filters = new Filters
teams = new Teams [],
filters: filters
limit: 20
teams.fetch()
teamsView = new TeamsListPageView
collection: teams
filters: filters
@_showView teamsView, 'Teams List'
_showView: (view, title) ->
if @currentView?.close
@currentView.close()
@currentView = view
@bodyContainer.html view.render().$el
@_updateTitle(title)
_updateTitle: (title) ->
if title
sep = ' | '
else
sep = ''
document.title = title + sep + '''JailbreakHQ 2015 a global
charity race in aid of Amnesty International and St.
PI:NAME:<NAME>END_PI'''
|
[
{
"context": "setCardSetId(CardSet.Coreshatter)\n\t\t\tcard.name = \"Grand Strategos\"\n\t\t\tcard.setDescription(\"Trial: Summon 12 minions",
"end": 3652,
"score": 0.8863011002540588,
"start": 3637,
"tag": "NAME",
"value": "Grand Strategos"
},
{
"context": "bject()\n\t\t\temblemModi... | app/sdk/cards/factory/coreshatter/faction1.coffee | willroberts/duelyst | 5 | # do not add this file to a package
# it is specifically parsed by the package generation script
_ = require 'underscore'
moment = require 'moment'
Logger = require 'app/common/logger'
CONFIG = require('app/common/config')
RSX = require('app/data/resources')
Card = require 'app/sdk/cards/card'
Cards = require 'app/sdk/cards/cardsLookupComplete'
CardType = require 'app/sdk/cards/cardType'
Factions = require 'app/sdk/cards/factionsLookup'
FactionFactory = require 'app/sdk/cards/factionFactory'
Races = require 'app/sdk/cards/racesLookup'
Rarity = require 'app/sdk/cards/rarityLookup'
Unit = require 'app/sdk/entities/unit'
CardSet = require 'app/sdk/cards/cardSetLookup'
Artifact = require 'app/sdk/artifacts/artifact'
SpellFilterType = require 'app/sdk/spells/spellFilterType'
SpellIntensifyIncreasingDominance = require 'app/sdk/spells/spellIntensifyIncreasingDominance'
SpellBuffAttributeByOtherAttribute = require 'app/sdk/spells/spellBuffAttributeByOtherAttribute'
SpellResilience = require 'app/sdk/spells/spellResilience'
SpellRally = require 'app/sdk/spells/spellRally'
SpellChargeIntoBattle = require 'app/sdk/spells/spellChargeIntoBattle'
SpellOnceMoreWithProvoke = require 'app/sdk/spells/spellOnceMoreWithProvoke'
Modifier = require 'app/sdk/modifiers/modifier'
ModifierBandingFlying = require 'app/sdk/modifiers/modifierBandingFlying'
ModifierProvoke = require 'app/sdk/modifiers/modifierProvoke'
ModifierIntensifyOneManArmy = require 'app/sdk/modifiers/modifierIntensifyOneManArmy'
ModifierFriendsguard = require 'app/sdk/modifiers/modifierFriendsguard'
ModifierMyGeneralAttackWatchSpawnRandomEntityFromDeck = require 'app/sdk/modifiers/modifierMyGeneralAttackWatchSpawnRandomEntityFromDeck'
ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand'
ModifierTranscendance = require 'app/sdk/modifiers/modifierTranscendance'
ModifierInvulnerable = require 'app/sdk/modifiers/modifierInvulnerable'
ModifierCardControlledPlayerModifiers = require 'app/sdk/modifiers/modifierCardControlledPlayerModifiers'
ModifierBanding = require 'app/sdk/modifiers/modifierBanding'
ModifierStartTurnWatchImmolateDamagedMinions = require 'app/sdk/modifiers/modifierStartTurnWatchImmolateDamagedMinions'
ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems'
ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator'
ModifierFateLyonarSmallMinionQuest = require 'app/sdk/modifiers/modifierFateLyonarSmallMinionQuest'
ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced'
ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify'
ModifierFlying = require 'app/sdk/modifiers/modifierFlying'
ModifierOpeningGambit = require 'app/sdk/modifiers/modifierOpeningGambit'
ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify'
ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand'
PlayerModifierEmblemEndTurnWatchLyonarSmallMinionQuest = require 'app/sdk/playerModifiers/playerModifierEmblemEndTurnWatchLyonarSmallMinionQuest'
i18next = require 'i18next'
if i18next.t() is undefined
i18next.t = (text) ->
return text
class CardFactory_CoreshatterSet_Faction1
###*
* Returns a card that matches the identifier.
* @param {Number|String} identifier
* @param {GameSession} gameSession
* @returns {Card}
###
@cardForIdentifier: (identifier,gameSession) ->
card = null
if (identifier == Cards.Faction1.RightfulHeir)
card = new Unit(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.name = "Grand Strategos"
card.setDescription("Trial: Summon 12 minions with 1 or less Attack.\nDestiny: Promote other friendly minions at the end of your turn.")
card.atk = 5
card.maxHP = 5
card.manaCost = 5
card.rarityId = Rarity.Mythron
emblemModifier = PlayerModifierEmblemEndTurnWatchLyonarSmallMinionQuest.createContextObject()
emblemModifier.appliedName = "Grand Stratagem"
emblemModifier.appliedDescription = "At the end of your turn, transform friendly minions other than Grand Strategos into faction minions that cost 1 more."
card.setInherentModifiersContextObjects([
ModifierStartsInHand.createContextObject(),
ModifierCannotBeReplaced.createContextObject(),
ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemModifier], true, false),
ModifierFateLyonarSmallMinionQuest.createContextObject(12),
ModifierCannotBeRemovedFromHand.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.TwilightMage"])
card.setBoundingBoxWidth(50)
card.setBoundingBoxHeight(75)
card.setBaseSoundResource(
apply : RSX.sfx_ui_booster_packexplode.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_f2_jadeogre_attack_swing.audio
receiveDamage : RSX.sfx_f3_dunecaster_hit.audio
attackDamage : RSX.sfx_f3_dunecaster_impact.audio
death : RSX.sfx_f3_dunecaster_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1RightfulHeirBreathing.name
idle : RSX.f1RightfulHeirIdle.name
walk : RSX.f1RightfulHeirRun.name
attack : RSX.f1RightfulHeirAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.3
damage : RSX.f1RightfulHeirHit.name
death : RSX.f1RightfulHeirDeath.name
)
if (identifier == Cards.Spell.IncreasingDominance)
card = new SpellIntensifyIncreasingDominance(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.IncreasingDominance
card.name = "Bolster"
card.setDescription("Intensify: Give friendly minions +2 Health.")
card.manaCost = 2
card.rarityId = Rarity.Common
card.modifierAppliedName = "Bolstered"
card.spellFilterType = SpellFilterType.None
card.addKeywordClassToInclude(ModifierIntensify)
card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()])
card.setFXResource(["FX.Cards.Spell.Bolster"])
card.setBaseAnimResource(
idle: RSX.iconIncreasingDominanceIdle.name
active: RSX.iconIncreasingDominanceActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_kineticequilibrium.audio
)
if (identifier == Cards.Faction1.OneManArmy)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "Legion"
card.setDescription("Intensify: Put 1 Crestfallen into your action bar. Shuffle a copy of this minion into your deck.")
card.atk = 3
card.maxHP = 2
card.manaCost = 3
card.rarityId = Rarity.Common
card.setInherentModifiersContextObjects([
ModifierIntensifyOneManArmy.createContextObject(),
ModifierCounterIntensify.createContextObject()
])
card.addKeywordClassToInclude(ModifierTokenCreator)
card.setFXResource(["FX.Cards.Faction1.SilverguardSquire"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_immolation_b.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_f1silverguardsquire_attack_swing.audio
receiveDamage : RSX.sfx_f1silverguardsquire_hit.audio
attackDamage : RSX.sfx_f1silverguardsquire_attack_impact.audio
death : RSX.sfx_f1silverguardsquire_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1KaiserGladiatorBreathing.name
idle : RSX.f1KaiserGladiatorIdle.name
walk : RSX.f1KaiserGladiatorRun.name
attack : RSX.f1KaiserGladiatorAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.6
damage : RSX.f1KaiserGladiatorHit.name
death : RSX.f1KaiserGladiatorDeath.name
)
if (identifier == Cards.Faction1.CatapultGryphon)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "Gryphon Fledgling"
card.setDescription("Zeal: Flying")
card.atk = 5
card.maxHP = 3
card.manaCost = 3
card.rarityId = Rarity.Rare
card.setInherentModifiersContextObjects([
ModifierBandingFlying.createContextObject()
])
card.addKeywordClassToInclude(ModifierFlying)
card.setFXResource(["FX.Cards.Neutral.WingsOfParadise"])
card.setBaseSoundResource(
apply : RSX.sfx_neutral_ubo_attack_swing.audio
walk : RSX.sfx_neutral_ubo_attack_swing.audio
attack : RSX.sfx_neutral_wingsofparadise_attack_swing.audio
receiveDamage : RSX.sfx_neutral_wingsofparadise_hit.audio
attackDamage : RSX.sfx_neutral_wingsofparadise_attack_impact.audio
death : RSX.sfx_neutral_wingsofparadise_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1GryphinoxBreathing.name
idle : RSX.f1GryphinoxIdle.name
walk : RSX.f1GryphinoxRun.name
attack : RSX.f1GryphinoxAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f1GryphinoxHit.name
death : RSX.f1GryphinoxDeath.name
)
if (identifier == Cards.Spell.DivinestBonderest)
card = new SpellBuffAttributeByOtherAttribute(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.DivinestBonderest
card.name = "Divine Liturgy"
card.setDescription("Give all friendly minions +Attack equal to their Health.")
card.manaCost = 6
card.rarityId = Rarity.Rare
card.spellFilterType = SpellFilterType.AllyIndirect
card.radius = CONFIG.WHOLE_BOARD_RADIUS
card.attributeTarget = "atk"
card.attributeSource = "hp"
card.appliedName = "Strength of Will"
card.appliedDescription = "Gained +Attack equal to Health"
card.setFXResource(["FX.Cards.Spell.DivineLiturgy"])
card.setBaseSoundResource(
apply : RSX.sfx_f6_voiceofthewind_attack_impact.audio
)
card.setBaseAnimResource(
idle : RSX.iconDivinestBondIdle.name
active : RSX.iconDivinestBondActive.name
)
if (identifier == Cards.Spell.Resilience)
card = new SpellResilience(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.Resilience
card.name = "Lifestream"
card.setDescription("Fully heal a friendly minion, then draw a copy of it from your deck.")
card.manaCost = 1
card.rarityId = Rarity.Common
card.spellFilterType = SpellFilterType.AllyDirect
card.canTargetGeneral = false
card.setFXResource(["FX.Cards.Spell.Lifestream"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_fountainofyouth.audio
)
card.setBaseAnimResource(
idle : RSX.iconLifestreamIdle.name
active : RSX.iconLifestreamActive.name
)
if (identifier == Cards.Faction1.Friendsguard)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "Windcliffe Protector"
card.setDescription("Provoke\nWhen a friendly Windcliffe Alarmist dies, transform this minion into a Windcliffe Alarmist.")
card.atk = 5
card.maxHP = 5
card.manaCost = 5
card.rarityId = Rarity.Epic
card.setInherentModifiersContextObjects([
ModifierProvoke.createContextObject(),
ModifierFriendsguard.createContextObject({id: Cards.Faction1.FriendFighter})
])
card.setFXResource(["FX.Cards.Neutral.GoldenJusticar"])
card.setBoundingBoxWidth(105)
card.setBoundingBoxHeight(100)
card.setBaseSoundResource(
apply : RSX.sfx_unit_deploy_3.audio
walk : RSX.sfx_neutral_earthwalker_death.audio
attack : RSX.sfx_f5_vindicator_attack_impact.audio
receiveDamage : RSX.sfx_neutral_grimrock_hit.audio
attackDamage : RSX.sfx_neutral_grimrock_attack_impact.audio
death : RSX.sfx_neutral_grimrock_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1FriendsGuardBreathing.name
idle : RSX.f1FriendsGuardIdle.name
walk : RSX.f1FriendsGuardRun.name
attack : RSX.f1FriendsGuardAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.8
damage : RSX.f1FriendsGuardHit.name
death : RSX.f1FriendsGuardDeath.name
)
if (identifier == Cards.Faction1.FriendFighter)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "Windcliffe Alarmist"
card.setDescription("Opening Gambit: Summon a 5/5 Windcliffe Protector with Provoke from your deck.")
card.atk = 2
card.maxHP = 2
card.manaCost = 4
card.rarityId = Rarity.Common
card.setFollowups([
{
id: Cards.Spell.FollowupSpawnEntityFromDeck
}
])
card.addKeywordClassToInclude(ModifierOpeningGambit)
card.addKeywordClassToInclude(ModifierProvoke)
card.setFXResource(["FX.Cards.Faction1.RadiantDragoon"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_immolation_b.audio
walk : RSX.sfx_neutral_arcanelimiter_attack_impact.audio
attack : RSX.sfx_neutral_rook_attack_swing.audio
receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio
attackDamage : RSX.sfx_neutral_rook_attack_impact.audio
death : RSX.sfx_neutral_windstopper_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1BaastChampionBreathing.name
idle : RSX.f1BaastChampionIdle.name
walk : RSX.f1BaastChampionRun.name
attack : RSX.f1BaastChampionAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f1BaastChampionHit.name
death : RSX.f1BaastChampionDeath.name
)
if (identifier == Cards.Spell.Rally)
card = new SpellRally(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.Rally
card.name = "Marching Orders"
card.setDescription("Give friendly minions directly in front of and behind your General +2/+2. If they have Zeal, they cannot be targeted by enemy spells.")
card.manaCost = 2
card.rarityId = Rarity.Rare
card.buffName = "Marching Command"
card.spellFilterType = SpellFilterType.None
card.canTargetGeneral = false
card.addKeywordClassToInclude(ModifierBanding)
card.setFXResource(["FX.Cards.Spell.MarchingOrders"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_forcebarrier.audio
)
card.setBaseAnimResource(
idle : RSX.iconRallyIdle.name
active : RSX.iconRallyActive.name
)
if (identifier == Cards.Artifact.TwoHander)
card = new Artifact(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.id = Cards.Artifact.TwoHander
card.name = "Radiant Standard"
card.setDescription("Your General has +3 Attack.\nWhen your General attacks, summon a minion that costs 3 from your deck nearby.")
card.manaCost = 6
card.rarityId = Rarity.Epic
card.durability = 3
card.setTargetModifiersContextObjects([
Modifier.createContextObjectWithAttributeBuffs(3,undefined),
ModifierMyGeneralAttackWatchSpawnRandomEntityFromDeck.createContextObject(3,true,1)
])
card.setFXResource(["FX.Cards.Artifact.SunstoneBracers"])
card.setBaseAnimResource(
idle: RSX.iconIronBannerIdle.name
active: RSX.iconIronBannerActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_victory_crest.audio
)
if (identifier == Cards.Spell.ChargeIntoBattle)
card = new SpellChargeIntoBattle(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.ChargeIntoBattle
card.name = "Lionize"
card.setDescription("Give Celerity to a friendly minion directly behind your General.")
card.manaCost = 5
card.rarityId = Rarity.Epic
card.spellFilterType = SpellFilterType.AllyDirect
card.canTargetGeneral = false
celerityObject = ModifierTranscendance.createContextObject()
card.setTargetModifiersContextObjects([
celerityObject
])
card.addKeywordClassToInclude(ModifierTranscendance)
card.setFXResource(["FX.Cards.Spell.Lionize"])
card.setBaseSoundResource(
apply : RSX.sfx_neutral_arakiheadhunter_attack_swing.audio
)
card.setBaseAnimResource(
idle : RSX.iconChargeIntoBattleIdle.name
active : RSX.iconChargeIntoBattleActive.name
)
if (identifier == Cards.Faction1.Invincibuddy)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "Indominus"
card.setDescription("Your General is Invulnerable BUT cannot move or attack.")
card.atk = 7
card.maxHP = 9
card.manaCost = 7
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierInvulnerable.createContextObject()])
])
card.addKeywordClassToInclude(ModifierInvulnerable)
card.setBoundingBoxWidth(100)
card.setBoundingBoxHeight(60)
card.setFXResource(["FX.Cards.Neutral.BlisteringSkorn"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_icepillar_melt.audio
walk : RSX.sfx_neutral_primordialgazer_death.audio
attack : RSX.sfx_neutral_pandora_attack_impact.audio
receiveDamage : RSX.sfx_neutral_makantorwarbeast_hit.audio
attackDamage : RSX.sfx_neutral_makantorwarbeast_attack_impact.audio
death : RSX.sfx_neutral_makantorwarbeast_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1InvincibuddyBreathing.name
idle : RSX.f1InvincibuddyIdle.name
walk : RSX.f1InvincibuddyRun.name
attack : RSX.f1InvincibuddyAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f1InvincibuddyHit.name
death : RSX.f1InvincibuddyDeath.name
)
if (identifier == Cards.Faction1.SuntideExpert)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "War Exorcist"
card.setDescription("Provoke\nAt the start of your turn, Holy Immolation your damaged minions.")
card.atk = 3
card.maxHP = 8
card.manaCost = 5
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierProvoke.createContextObject(),
ModifierStartTurnWatchImmolateDamagedMinions.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.Grailmaster"])
card.setBoundingBoxWidth(100)
card.setBoundingBoxHeight(105)
card.setBaseSoundResource(
apply : RSX.sfx_spell_diretidefrenzy.audio
walk : RSX.sfx_neutral_sai_attack_impact.audio
attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio
receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio
attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio
death : RSX.sfx_neutral_spiritscribe_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1LeovoyantBreathing.name
idle : RSX.f1LeovoyantIdle.name
walk : RSX.f1LeovoyantRun.name
attack : RSX.f1LeovoyantAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.9
damage : RSX.f1LeovoyantHit.name
death : RSX.f1LeovoyantDeath.name
)
if (identifier == Cards.Spell.OnceMoreWithProvoke)
card = new SpellOnceMoreWithProvoke(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.OnceMoreWithProvoke
card.name = "Amaranthine Vow"
card.setDescription("Summon around your General all friendly minions with Provoke that died this game.")
card.manaCost = 9
card.rarityId = Rarity.Legendary
card.addKeywordClassToInclude(ModifierProvoke)
card.setFXResource(["FX.Cards.Spell.AmaranthineVow"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_sunbloom.audio
)
card.setBaseAnimResource(
idle : RSX.iconOnceMoreIdle.name
active : RSX.iconOnceMoreActive.name
)
return card
module.exports = CardFactory_CoreshatterSet_Faction1
| 84366 | # do not add this file to a package
# it is specifically parsed by the package generation script
_ = require 'underscore'
moment = require 'moment'
Logger = require 'app/common/logger'
CONFIG = require('app/common/config')
RSX = require('app/data/resources')
Card = require 'app/sdk/cards/card'
Cards = require 'app/sdk/cards/cardsLookupComplete'
CardType = require 'app/sdk/cards/cardType'
Factions = require 'app/sdk/cards/factionsLookup'
FactionFactory = require 'app/sdk/cards/factionFactory'
Races = require 'app/sdk/cards/racesLookup'
Rarity = require 'app/sdk/cards/rarityLookup'
Unit = require 'app/sdk/entities/unit'
CardSet = require 'app/sdk/cards/cardSetLookup'
Artifact = require 'app/sdk/artifacts/artifact'
SpellFilterType = require 'app/sdk/spells/spellFilterType'
SpellIntensifyIncreasingDominance = require 'app/sdk/spells/spellIntensifyIncreasingDominance'
SpellBuffAttributeByOtherAttribute = require 'app/sdk/spells/spellBuffAttributeByOtherAttribute'
SpellResilience = require 'app/sdk/spells/spellResilience'
SpellRally = require 'app/sdk/spells/spellRally'
SpellChargeIntoBattle = require 'app/sdk/spells/spellChargeIntoBattle'
SpellOnceMoreWithProvoke = require 'app/sdk/spells/spellOnceMoreWithProvoke'
Modifier = require 'app/sdk/modifiers/modifier'
ModifierBandingFlying = require 'app/sdk/modifiers/modifierBandingFlying'
ModifierProvoke = require 'app/sdk/modifiers/modifierProvoke'
ModifierIntensifyOneManArmy = require 'app/sdk/modifiers/modifierIntensifyOneManArmy'
ModifierFriendsguard = require 'app/sdk/modifiers/modifierFriendsguard'
ModifierMyGeneralAttackWatchSpawnRandomEntityFromDeck = require 'app/sdk/modifiers/modifierMyGeneralAttackWatchSpawnRandomEntityFromDeck'
ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand'
ModifierTranscendance = require 'app/sdk/modifiers/modifierTranscendance'
ModifierInvulnerable = require 'app/sdk/modifiers/modifierInvulnerable'
ModifierCardControlledPlayerModifiers = require 'app/sdk/modifiers/modifierCardControlledPlayerModifiers'
ModifierBanding = require 'app/sdk/modifiers/modifierBanding'
ModifierStartTurnWatchImmolateDamagedMinions = require 'app/sdk/modifiers/modifierStartTurnWatchImmolateDamagedMinions'
ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems'
ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator'
ModifierFateLyonarSmallMinionQuest = require 'app/sdk/modifiers/modifierFateLyonarSmallMinionQuest'
ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced'
ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify'
ModifierFlying = require 'app/sdk/modifiers/modifierFlying'
ModifierOpeningGambit = require 'app/sdk/modifiers/modifierOpeningGambit'
ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify'
ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand'
PlayerModifierEmblemEndTurnWatchLyonarSmallMinionQuest = require 'app/sdk/playerModifiers/playerModifierEmblemEndTurnWatchLyonarSmallMinionQuest'
i18next = require 'i18next'
if i18next.t() is undefined
i18next.t = (text) ->
return text
class CardFactory_CoreshatterSet_Faction1
###*
* Returns a card that matches the identifier.
* @param {Number|String} identifier
* @param {GameSession} gameSession
* @returns {Card}
###
@cardForIdentifier: (identifier,gameSession) ->
card = null
if (identifier == Cards.Faction1.RightfulHeir)
card = new Unit(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.name = "<NAME>"
card.setDescription("Trial: Summon 12 minions with 1 or less Attack.\nDestiny: Promote other friendly minions at the end of your turn.")
card.atk = 5
card.maxHP = 5
card.manaCost = 5
card.rarityId = Rarity.Mythron
emblemModifier = PlayerModifierEmblemEndTurnWatchLyonarSmallMinionQuest.createContextObject()
emblemModifier.appliedName = "Grand Str<NAME>"
emblemModifier.appliedDescription = "At the end of your turn, transform friendly minions other than Grand Strategos into faction minions that cost 1 more."
card.setInherentModifiersContextObjects([
ModifierStartsInHand.createContextObject(),
ModifierCannotBeReplaced.createContextObject(),
ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemModifier], true, false),
ModifierFateLyonarSmallMinionQuest.createContextObject(12),
ModifierCannotBeRemovedFromHand.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.TwilightMage"])
card.setBoundingBoxWidth(50)
card.setBoundingBoxHeight(75)
card.setBaseSoundResource(
apply : RSX.sfx_ui_booster_packexplode.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_f2_jadeogre_attack_swing.audio
receiveDamage : RSX.sfx_f3_dunecaster_hit.audio
attackDamage : RSX.sfx_f3_dunecaster_impact.audio
death : RSX.sfx_f3_dunecaster_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1RightfulHeirBreathing.name
idle : RSX.f1RightfulHeirIdle.name
walk : RSX.f1RightfulHeirRun.name
attack : RSX.f1RightfulHeirAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.3
damage : RSX.f1RightfulHeirHit.name
death : RSX.f1RightfulHeirDeath.name
)
if (identifier == Cards.Spell.IncreasingDominance)
card = new SpellIntensifyIncreasingDominance(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.IncreasingDominance
card.name = "<NAME>"
card.setDescription("Intensify: Give friendly minions +2 Health.")
card.manaCost = 2
card.rarityId = Rarity.Common
card.modifierAppliedName = "Bolstered"
card.spellFilterType = SpellFilterType.None
card.addKeywordClassToInclude(ModifierIntensify)
card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()])
card.setFXResource(["FX.Cards.Spell.Bolster"])
card.setBaseAnimResource(
idle: RSX.iconIncreasingDominanceIdle.name
active: RSX.iconIncreasingDominanceActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_kineticequilibrium.audio
)
if (identifier == Cards.Faction1.OneManArmy)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "<NAME>"
card.setDescription("Intensify: Put 1 Crestfallen into your action bar. Shuffle a copy of this minion into your deck.")
card.atk = 3
card.maxHP = 2
card.manaCost = 3
card.rarityId = Rarity.Common
card.setInherentModifiersContextObjects([
ModifierIntensifyOneManArmy.createContextObject(),
ModifierCounterIntensify.createContextObject()
])
card.addKeywordClassToInclude(ModifierTokenCreator)
card.setFXResource(["FX.Cards.Faction1.SilverguardSquire"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_immolation_b.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_f1silverguardsquire_attack_swing.audio
receiveDamage : RSX.sfx_f1silverguardsquire_hit.audio
attackDamage : RSX.sfx_f1silverguardsquire_attack_impact.audio
death : RSX.sfx_f1silverguardsquire_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1KaiserGladiatorBreathing.name
idle : RSX.f1KaiserGladiatorIdle.name
walk : RSX.f1KaiserGladiatorRun.name
attack : RSX.f1KaiserGladiatorAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.6
damage : RSX.f1KaiserGladiatorHit.name
death : RSX.f1KaiserGladiatorDeath.name
)
if (identifier == Cards.Faction1.CatapultGryphon)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "<NAME>"
card.setDescription("Zeal: Flying")
card.atk = 5
card.maxHP = 3
card.manaCost = 3
card.rarityId = Rarity.Rare
card.setInherentModifiersContextObjects([
ModifierBandingFlying.createContextObject()
])
card.addKeywordClassToInclude(ModifierFlying)
card.setFXResource(["FX.Cards.Neutral.WingsOfParadise"])
card.setBaseSoundResource(
apply : RSX.sfx_neutral_ubo_attack_swing.audio
walk : RSX.sfx_neutral_ubo_attack_swing.audio
attack : RSX.sfx_neutral_wingsofparadise_attack_swing.audio
receiveDamage : RSX.sfx_neutral_wingsofparadise_hit.audio
attackDamage : RSX.sfx_neutral_wingsofparadise_attack_impact.audio
death : RSX.sfx_neutral_wingsofparadise_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1GryphinoxBreathing.name
idle : RSX.f1GryphinoxIdle.name
walk : RSX.f1GryphinoxRun.name
attack : RSX.f1GryphinoxAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f1GryphinoxHit.name
death : RSX.f1GryphinoxDeath.name
)
if (identifier == Cards.Spell.DivinestBonderest)
card = new SpellBuffAttributeByOtherAttribute(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.DivinestBonderest
card.name = "<NAME>"
card.setDescription("Give all friendly minions +Attack equal to their Health.")
card.manaCost = 6
card.rarityId = Rarity.Rare
card.spellFilterType = SpellFilterType.AllyIndirect
card.radius = CONFIG.WHOLE_BOARD_RADIUS
card.attributeTarget = "atk"
card.attributeSource = "hp"
card.appliedName = "Strength of Will"
card.appliedDescription = "Gained +Attack equal to Health"
card.setFXResource(["FX.Cards.Spell.DivineLiturgy"])
card.setBaseSoundResource(
apply : RSX.sfx_f6_voiceofthewind_attack_impact.audio
)
card.setBaseAnimResource(
idle : RSX.iconDivinestBondIdle.name
active : RSX.iconDivinestBondActive.name
)
if (identifier == Cards.Spell.Resilience)
card = new SpellResilience(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.Resilience
card.name = "Lifestream"
card.setDescription("Fully heal a friendly minion, then draw a copy of it from your deck.")
card.manaCost = 1
card.rarityId = Rarity.Common
card.spellFilterType = SpellFilterType.AllyDirect
card.canTargetGeneral = false
card.setFXResource(["FX.Cards.Spell.Lifestream"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_fountainofyouth.audio
)
card.setBaseAnimResource(
idle : RSX.iconLifestreamIdle.name
active : RSX.iconLifestreamActive.name
)
if (identifier == Cards.Faction1.Friendsguard)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "<NAME> Prot<NAME>"
card.setDescription("Provoke\nWhen a friendly Windcliffe Alarmist dies, transform this minion into a Windcliffe Alarmist.")
card.atk = 5
card.maxHP = 5
card.manaCost = 5
card.rarityId = Rarity.Epic
card.setInherentModifiersContextObjects([
ModifierProvoke.createContextObject(),
ModifierFriendsguard.createContextObject({id: Cards.Faction1.FriendFighter})
])
card.setFXResource(["FX.Cards.Neutral.GoldenJusticar"])
card.setBoundingBoxWidth(105)
card.setBoundingBoxHeight(100)
card.setBaseSoundResource(
apply : RSX.sfx_unit_deploy_3.audio
walk : RSX.sfx_neutral_earthwalker_death.audio
attack : RSX.sfx_f5_vindicator_attack_impact.audio
receiveDamage : RSX.sfx_neutral_grimrock_hit.audio
attackDamage : RSX.sfx_neutral_grimrock_attack_impact.audio
death : RSX.sfx_neutral_grimrock_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1FriendsGuardBreathing.name
idle : RSX.f1FriendsGuardIdle.name
walk : RSX.f1FriendsGuardRun.name
attack : RSX.f1FriendsGuardAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.8
damage : RSX.f1FriendsGuardHit.name
death : RSX.f1FriendsGuardDeath.name
)
if (identifier == Cards.Faction1.FriendFighter)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "<NAME>fe Alarmist"
card.setDescription("Opening Gambit: Summon a 5/5 Windcliffe Protector with Provoke from your deck.")
card.atk = 2
card.maxHP = 2
card.manaCost = 4
card.rarityId = Rarity.Common
card.setFollowups([
{
id: Cards.Spell.FollowupSpawnEntityFromDeck
}
])
card.addKeywordClassToInclude(ModifierOpeningGambit)
card.addKeywordClassToInclude(ModifierProvoke)
card.setFXResource(["FX.Cards.Faction1.RadiantDragoon"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_immolation_b.audio
walk : RSX.sfx_neutral_arcanelimiter_attack_impact.audio
attack : RSX.sfx_neutral_rook_attack_swing.audio
receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio
attackDamage : RSX.sfx_neutral_rook_attack_impact.audio
death : RSX.sfx_neutral_windstopper_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1BaastChampionBreathing.name
idle : RSX.f1BaastChampionIdle.name
walk : RSX.f1BaastChampionRun.name
attack : RSX.f1BaastChampionAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f1BaastChampionHit.name
death : RSX.f1BaastChampionDeath.name
)
if (identifier == Cards.Spell.Rally)
card = new SpellRally(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.Rally
card.name = "<NAME>"
card.setDescription("Give friendly minions directly in front of and behind your General +2/+2. If they have Zeal, they cannot be targeted by enemy spells.")
card.manaCost = 2
card.rarityId = Rarity.Rare
card.buffName = "Marching Command"
card.spellFilterType = SpellFilterType.None
card.canTargetGeneral = false
card.addKeywordClassToInclude(ModifierBanding)
card.setFXResource(["FX.Cards.Spell.MarchingOrders"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_forcebarrier.audio
)
card.setBaseAnimResource(
idle : RSX.iconRallyIdle.name
active : RSX.iconRallyActive.name
)
if (identifier == Cards.Artifact.TwoHander)
card = new Artifact(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.id = Cards.Artifact.TwoHander
card.name = "<NAME>"
card.setDescription("Your General has +3 Attack.\nWhen your General attacks, summon a minion that costs 3 from your deck nearby.")
card.manaCost = 6
card.rarityId = Rarity.Epic
card.durability = 3
card.setTargetModifiersContextObjects([
Modifier.createContextObjectWithAttributeBuffs(3,undefined),
ModifierMyGeneralAttackWatchSpawnRandomEntityFromDeck.createContextObject(3,true,1)
])
card.setFXResource(["FX.Cards.Artifact.SunstoneBracers"])
card.setBaseAnimResource(
idle: RSX.iconIronBannerIdle.name
active: RSX.iconIronBannerActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_victory_crest.audio
)
if (identifier == Cards.Spell.ChargeIntoBattle)
card = new SpellChargeIntoBattle(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.ChargeIntoBattle
card.name = "<NAME>"
card.setDescription("Give Celerity to a friendly minion directly behind your General.")
card.manaCost = 5
card.rarityId = Rarity.Epic
card.spellFilterType = SpellFilterType.AllyDirect
card.canTargetGeneral = false
celerityObject = ModifierTranscendance.createContextObject()
card.setTargetModifiersContextObjects([
celerityObject
])
card.addKeywordClassToInclude(ModifierTranscendance)
card.setFXResource(["FX.Cards.Spell.Lionize"])
card.setBaseSoundResource(
apply : RSX.sfx_neutral_arakiheadhunter_attack_swing.audio
)
card.setBaseAnimResource(
idle : RSX.iconChargeIntoBattleIdle.name
active : RSX.iconChargeIntoBattleActive.name
)
if (identifier == Cards.Faction1.Invincibuddy)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "<NAME>inus"
card.setDescription("Your General is Invulnerable BUT cannot move or attack.")
card.atk = 7
card.maxHP = 9
card.manaCost = 7
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierInvulnerable.createContextObject()])
])
card.addKeywordClassToInclude(ModifierInvulnerable)
card.setBoundingBoxWidth(100)
card.setBoundingBoxHeight(60)
card.setFXResource(["FX.Cards.Neutral.BlisteringSkorn"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_icepillar_melt.audio
walk : RSX.sfx_neutral_primordialgazer_death.audio
attack : RSX.sfx_neutral_pandora_attack_impact.audio
receiveDamage : RSX.sfx_neutral_makantorwarbeast_hit.audio
attackDamage : RSX.sfx_neutral_makantorwarbeast_attack_impact.audio
death : RSX.sfx_neutral_makantorwarbeast_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1InvincibuddyBreathing.name
idle : RSX.f1InvincibuddyIdle.name
walk : RSX.f1InvincibuddyRun.name
attack : RSX.f1InvincibuddyAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f1InvincibuddyHit.name
death : RSX.f1InvincibuddyDeath.name
)
if (identifier == Cards.Faction1.SuntideExpert)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "War Exorcist"
card.setDescription("Provoke\nAt the start of your turn, Holy Immolation your damaged minions.")
card.atk = 3
card.maxHP = 8
card.manaCost = 5
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierProvoke.createContextObject(),
ModifierStartTurnWatchImmolateDamagedMinions.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.Grailmaster"])
card.setBoundingBoxWidth(100)
card.setBoundingBoxHeight(105)
card.setBaseSoundResource(
apply : RSX.sfx_spell_diretidefrenzy.audio
walk : RSX.sfx_neutral_sai_attack_impact.audio
attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio
receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio
attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio
death : RSX.sfx_neutral_spiritscribe_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1LeovoyantBreathing.name
idle : RSX.f1LeovoyantIdle.name
walk : RSX.f1LeovoyantRun.name
attack : RSX.f1LeovoyantAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.9
damage : RSX.f1LeovoyantHit.name
death : RSX.f1LeovoyantDeath.name
)
if (identifier == Cards.Spell.OnceMoreWithProvoke)
card = new SpellOnceMoreWithProvoke(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.OnceMoreWithProvoke
card.name = "<NAME>"
card.setDescription("Summon around your General all friendly minions with Provoke that died this game.")
card.manaCost = 9
card.rarityId = Rarity.Legendary
card.addKeywordClassToInclude(ModifierProvoke)
card.setFXResource(["FX.Cards.Spell.AmaranthineVow"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_sunbloom.audio
)
card.setBaseAnimResource(
idle : RSX.iconOnceMoreIdle.name
active : RSX.iconOnceMoreActive.name
)
return card
module.exports = CardFactory_CoreshatterSet_Faction1
| true | # do not add this file to a package
# it is specifically parsed by the package generation script
_ = require 'underscore'
moment = require 'moment'
Logger = require 'app/common/logger'
CONFIG = require('app/common/config')
RSX = require('app/data/resources')
Card = require 'app/sdk/cards/card'
Cards = require 'app/sdk/cards/cardsLookupComplete'
CardType = require 'app/sdk/cards/cardType'
Factions = require 'app/sdk/cards/factionsLookup'
FactionFactory = require 'app/sdk/cards/factionFactory'
Races = require 'app/sdk/cards/racesLookup'
Rarity = require 'app/sdk/cards/rarityLookup'
Unit = require 'app/sdk/entities/unit'
CardSet = require 'app/sdk/cards/cardSetLookup'
Artifact = require 'app/sdk/artifacts/artifact'
SpellFilterType = require 'app/sdk/spells/spellFilterType'
SpellIntensifyIncreasingDominance = require 'app/sdk/spells/spellIntensifyIncreasingDominance'
SpellBuffAttributeByOtherAttribute = require 'app/sdk/spells/spellBuffAttributeByOtherAttribute'
SpellResilience = require 'app/sdk/spells/spellResilience'
SpellRally = require 'app/sdk/spells/spellRally'
SpellChargeIntoBattle = require 'app/sdk/spells/spellChargeIntoBattle'
SpellOnceMoreWithProvoke = require 'app/sdk/spells/spellOnceMoreWithProvoke'
Modifier = require 'app/sdk/modifiers/modifier'
ModifierBandingFlying = require 'app/sdk/modifiers/modifierBandingFlying'
ModifierProvoke = require 'app/sdk/modifiers/modifierProvoke'
ModifierIntensifyOneManArmy = require 'app/sdk/modifiers/modifierIntensifyOneManArmy'
ModifierFriendsguard = require 'app/sdk/modifiers/modifierFriendsguard'
ModifierMyGeneralAttackWatchSpawnRandomEntityFromDeck = require 'app/sdk/modifiers/modifierMyGeneralAttackWatchSpawnRandomEntityFromDeck'
ModifierStartsInHand = require 'app/sdk/modifiers/modifierStartsInHand'
ModifierTranscendance = require 'app/sdk/modifiers/modifierTranscendance'
ModifierInvulnerable = require 'app/sdk/modifiers/modifierInvulnerable'
ModifierCardControlledPlayerModifiers = require 'app/sdk/modifiers/modifierCardControlledPlayerModifiers'
ModifierBanding = require 'app/sdk/modifiers/modifierBanding'
ModifierStartTurnWatchImmolateDamagedMinions = require 'app/sdk/modifiers/modifierStartTurnWatchImmolateDamagedMinions'
ModifierOnSummonFromHandApplyEmblems = require 'app/sdk/modifiers/modifierOnSummonFromHandApplyEmblems'
ModifierTokenCreator = require 'app/sdk/modifiers/modifierTokenCreator'
ModifierFateLyonarSmallMinionQuest = require 'app/sdk/modifiers/modifierFateLyonarSmallMinionQuest'
ModifierCannotBeReplaced = require 'app/sdk/modifiers/modifierCannotBeReplaced'
ModifierIntensify = require 'app/sdk/modifiers/modifierIntensify'
ModifierFlying = require 'app/sdk/modifiers/modifierFlying'
ModifierOpeningGambit = require 'app/sdk/modifiers/modifierOpeningGambit'
ModifierCounterIntensify = require 'app/sdk/modifiers/modifierCounterIntensify'
ModifierCannotBeRemovedFromHand = require 'app/sdk/modifiers/modifierCannotBeRemovedFromHand'
PlayerModifierEmblemEndTurnWatchLyonarSmallMinionQuest = require 'app/sdk/playerModifiers/playerModifierEmblemEndTurnWatchLyonarSmallMinionQuest'
i18next = require 'i18next'
if i18next.t() is undefined
i18next.t = (text) ->
return text
class CardFactory_CoreshatterSet_Faction1
###*
* Returns a card that matches the identifier.
* @param {Number|String} identifier
* @param {GameSession} gameSession
* @returns {Card}
###
@cardForIdentifier: (identifier,gameSession) ->
card = null
if (identifier == Cards.Faction1.RightfulHeir)
card = new Unit(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Trial: Summon 12 minions with 1 or less Attack.\nDestiny: Promote other friendly minions at the end of your turn.")
card.atk = 5
card.maxHP = 5
card.manaCost = 5
card.rarityId = Rarity.Mythron
emblemModifier = PlayerModifierEmblemEndTurnWatchLyonarSmallMinionQuest.createContextObject()
emblemModifier.appliedName = "Grand StrPI:NAME:<NAME>END_PI"
emblemModifier.appliedDescription = "At the end of your turn, transform friendly minions other than Grand Strategos into faction minions that cost 1 more."
card.setInherentModifiersContextObjects([
ModifierStartsInHand.createContextObject(),
ModifierCannotBeReplaced.createContextObject(),
ModifierOnSummonFromHandApplyEmblems.createContextObject([emblemModifier], true, false),
ModifierFateLyonarSmallMinionQuest.createContextObject(12),
ModifierCannotBeRemovedFromHand.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.TwilightMage"])
card.setBoundingBoxWidth(50)
card.setBoundingBoxHeight(75)
card.setBaseSoundResource(
apply : RSX.sfx_ui_booster_packexplode.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_f2_jadeogre_attack_swing.audio
receiveDamage : RSX.sfx_f3_dunecaster_hit.audio
attackDamage : RSX.sfx_f3_dunecaster_impact.audio
death : RSX.sfx_f3_dunecaster_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1RightfulHeirBreathing.name
idle : RSX.f1RightfulHeirIdle.name
walk : RSX.f1RightfulHeirRun.name
attack : RSX.f1RightfulHeirAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.3
damage : RSX.f1RightfulHeirHit.name
death : RSX.f1RightfulHeirDeath.name
)
if (identifier == Cards.Spell.IncreasingDominance)
card = new SpellIntensifyIncreasingDominance(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.IncreasingDominance
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Intensify: Give friendly minions +2 Health.")
card.manaCost = 2
card.rarityId = Rarity.Common
card.modifierAppliedName = "Bolstered"
card.spellFilterType = SpellFilterType.None
card.addKeywordClassToInclude(ModifierIntensify)
card.setInherentModifiersContextObjects([ModifierCounterIntensify.createContextObject()])
card.setFXResource(["FX.Cards.Spell.Bolster"])
card.setBaseAnimResource(
idle: RSX.iconIncreasingDominanceIdle.name
active: RSX.iconIncreasingDominanceActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_spell_kineticequilibrium.audio
)
if (identifier == Cards.Faction1.OneManArmy)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Intensify: Put 1 Crestfallen into your action bar. Shuffle a copy of this minion into your deck.")
card.atk = 3
card.maxHP = 2
card.manaCost = 3
card.rarityId = Rarity.Common
card.setInherentModifiersContextObjects([
ModifierIntensifyOneManArmy.createContextObject(),
ModifierCounterIntensify.createContextObject()
])
card.addKeywordClassToInclude(ModifierTokenCreator)
card.setFXResource(["FX.Cards.Faction1.SilverguardSquire"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_immolation_b.audio
walk : RSX.sfx_singe2.audio
attack : RSX.sfx_f1silverguardsquire_attack_swing.audio
receiveDamage : RSX.sfx_f1silverguardsquire_hit.audio
attackDamage : RSX.sfx_f1silverguardsquire_attack_impact.audio
death : RSX.sfx_f1silverguardsquire_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1KaiserGladiatorBreathing.name
idle : RSX.f1KaiserGladiatorIdle.name
walk : RSX.f1KaiserGladiatorRun.name
attack : RSX.f1KaiserGladiatorAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.6
damage : RSX.f1KaiserGladiatorHit.name
death : RSX.f1KaiserGladiatorDeath.name
)
if (identifier == Cards.Faction1.CatapultGryphon)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Zeal: Flying")
card.atk = 5
card.maxHP = 3
card.manaCost = 3
card.rarityId = Rarity.Rare
card.setInherentModifiersContextObjects([
ModifierBandingFlying.createContextObject()
])
card.addKeywordClassToInclude(ModifierFlying)
card.setFXResource(["FX.Cards.Neutral.WingsOfParadise"])
card.setBaseSoundResource(
apply : RSX.sfx_neutral_ubo_attack_swing.audio
walk : RSX.sfx_neutral_ubo_attack_swing.audio
attack : RSX.sfx_neutral_wingsofparadise_attack_swing.audio
receiveDamage : RSX.sfx_neutral_wingsofparadise_hit.audio
attackDamage : RSX.sfx_neutral_wingsofparadise_attack_impact.audio
death : RSX.sfx_neutral_wingsofparadise_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1GryphinoxBreathing.name
idle : RSX.f1GryphinoxIdle.name
walk : RSX.f1GryphinoxRun.name
attack : RSX.f1GryphinoxAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f1GryphinoxHit.name
death : RSX.f1GryphinoxDeath.name
)
if (identifier == Cards.Spell.DivinestBonderest)
card = new SpellBuffAttributeByOtherAttribute(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.DivinestBonderest
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Give all friendly minions +Attack equal to their Health.")
card.manaCost = 6
card.rarityId = Rarity.Rare
card.spellFilterType = SpellFilterType.AllyIndirect
card.radius = CONFIG.WHOLE_BOARD_RADIUS
card.attributeTarget = "atk"
card.attributeSource = "hp"
card.appliedName = "Strength of Will"
card.appliedDescription = "Gained +Attack equal to Health"
card.setFXResource(["FX.Cards.Spell.DivineLiturgy"])
card.setBaseSoundResource(
apply : RSX.sfx_f6_voiceofthewind_attack_impact.audio
)
card.setBaseAnimResource(
idle : RSX.iconDivinestBondIdle.name
active : RSX.iconDivinestBondActive.name
)
if (identifier == Cards.Spell.Resilience)
card = new SpellResilience(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.Resilience
card.name = "Lifestream"
card.setDescription("Fully heal a friendly minion, then draw a copy of it from your deck.")
card.manaCost = 1
card.rarityId = Rarity.Common
card.spellFilterType = SpellFilterType.AllyDirect
card.canTargetGeneral = false
card.setFXResource(["FX.Cards.Spell.Lifestream"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_fountainofyouth.audio
)
card.setBaseAnimResource(
idle : RSX.iconLifestreamIdle.name
active : RSX.iconLifestreamActive.name
)
if (identifier == Cards.Faction1.Friendsguard)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "PI:NAME:<NAME>END_PI ProtPI:NAME:<NAME>END_PI"
card.setDescription("Provoke\nWhen a friendly Windcliffe Alarmist dies, transform this minion into a Windcliffe Alarmist.")
card.atk = 5
card.maxHP = 5
card.manaCost = 5
card.rarityId = Rarity.Epic
card.setInherentModifiersContextObjects([
ModifierProvoke.createContextObject(),
ModifierFriendsguard.createContextObject({id: Cards.Faction1.FriendFighter})
])
card.setFXResource(["FX.Cards.Neutral.GoldenJusticar"])
card.setBoundingBoxWidth(105)
card.setBoundingBoxHeight(100)
card.setBaseSoundResource(
apply : RSX.sfx_unit_deploy_3.audio
walk : RSX.sfx_neutral_earthwalker_death.audio
attack : RSX.sfx_f5_vindicator_attack_impact.audio
receiveDamage : RSX.sfx_neutral_grimrock_hit.audio
attackDamage : RSX.sfx_neutral_grimrock_attack_impact.audio
death : RSX.sfx_neutral_grimrock_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1FriendsGuardBreathing.name
idle : RSX.f1FriendsGuardIdle.name
walk : RSX.f1FriendsGuardRun.name
attack : RSX.f1FriendsGuardAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.8
damage : RSX.f1FriendsGuardHit.name
death : RSX.f1FriendsGuardDeath.name
)
if (identifier == Cards.Faction1.FriendFighter)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "PI:NAME:<NAME>END_PIfe Alarmist"
card.setDescription("Opening Gambit: Summon a 5/5 Windcliffe Protector with Provoke from your deck.")
card.atk = 2
card.maxHP = 2
card.manaCost = 4
card.rarityId = Rarity.Common
card.setFollowups([
{
id: Cards.Spell.FollowupSpawnEntityFromDeck
}
])
card.addKeywordClassToInclude(ModifierOpeningGambit)
card.addKeywordClassToInclude(ModifierProvoke)
card.setFXResource(["FX.Cards.Faction1.RadiantDragoon"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_immolation_b.audio
walk : RSX.sfx_neutral_arcanelimiter_attack_impact.audio
attack : RSX.sfx_neutral_rook_attack_swing.audio
receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio
attackDamage : RSX.sfx_neutral_rook_attack_impact.audio
death : RSX.sfx_neutral_windstopper_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1BaastChampionBreathing.name
idle : RSX.f1BaastChampionIdle.name
walk : RSX.f1BaastChampionRun.name
attack : RSX.f1BaastChampionAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f1BaastChampionHit.name
death : RSX.f1BaastChampionDeath.name
)
if (identifier == Cards.Spell.Rally)
card = new SpellRally(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.Rally
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Give friendly minions directly in front of and behind your General +2/+2. If they have Zeal, they cannot be targeted by enemy spells.")
card.manaCost = 2
card.rarityId = Rarity.Rare
card.buffName = "Marching Command"
card.spellFilterType = SpellFilterType.None
card.canTargetGeneral = false
card.addKeywordClassToInclude(ModifierBanding)
card.setFXResource(["FX.Cards.Spell.MarchingOrders"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_forcebarrier.audio
)
card.setBaseAnimResource(
idle : RSX.iconRallyIdle.name
active : RSX.iconRallyActive.name
)
if (identifier == Cards.Artifact.TwoHander)
card = new Artifact(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.id = Cards.Artifact.TwoHander
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Your General has +3 Attack.\nWhen your General attacks, summon a minion that costs 3 from your deck nearby.")
card.manaCost = 6
card.rarityId = Rarity.Epic
card.durability = 3
card.setTargetModifiersContextObjects([
Modifier.createContextObjectWithAttributeBuffs(3,undefined),
ModifierMyGeneralAttackWatchSpawnRandomEntityFromDeck.createContextObject(3,true,1)
])
card.setFXResource(["FX.Cards.Artifact.SunstoneBracers"])
card.setBaseAnimResource(
idle: RSX.iconIronBannerIdle.name
active: RSX.iconIronBannerActive.name
)
card.setBaseSoundResource(
apply : RSX.sfx_victory_crest.audio
)
if (identifier == Cards.Spell.ChargeIntoBattle)
card = new SpellChargeIntoBattle(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.ChargeIntoBattle
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Give Celerity to a friendly minion directly behind your General.")
card.manaCost = 5
card.rarityId = Rarity.Epic
card.spellFilterType = SpellFilterType.AllyDirect
card.canTargetGeneral = false
celerityObject = ModifierTranscendance.createContextObject()
card.setTargetModifiersContextObjects([
celerityObject
])
card.addKeywordClassToInclude(ModifierTranscendance)
card.setFXResource(["FX.Cards.Spell.Lionize"])
card.setBaseSoundResource(
apply : RSX.sfx_neutral_arakiheadhunter_attack_swing.audio
)
card.setBaseAnimResource(
idle : RSX.iconChargeIntoBattleIdle.name
active : RSX.iconChargeIntoBattleActive.name
)
if (identifier == Cards.Faction1.Invincibuddy)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "PI:NAME:<NAME>END_PIinus"
card.setDescription("Your General is Invulnerable BUT cannot move or attack.")
card.atk = 7
card.maxHP = 9
card.manaCost = 7
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierInvulnerable.createContextObject()])
])
card.addKeywordClassToInclude(ModifierInvulnerable)
card.setBoundingBoxWidth(100)
card.setBoundingBoxHeight(60)
card.setFXResource(["FX.Cards.Neutral.BlisteringSkorn"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_icepillar_melt.audio
walk : RSX.sfx_neutral_primordialgazer_death.audio
attack : RSX.sfx_neutral_pandora_attack_impact.audio
receiveDamage : RSX.sfx_neutral_makantorwarbeast_hit.audio
attackDamage : RSX.sfx_neutral_makantorwarbeast_attack_impact.audio
death : RSX.sfx_neutral_makantorwarbeast_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1InvincibuddyBreathing.name
idle : RSX.f1InvincibuddyIdle.name
walk : RSX.f1InvincibuddyRun.name
attack : RSX.f1InvincibuddyAttack.name
attackReleaseDelay: 0.0
attackDelay: 1.2
damage : RSX.f1InvincibuddyHit.name
death : RSX.f1InvincibuddyDeath.name
)
if (identifier == Cards.Faction1.SuntideExpert)
card = new Unit(gameSession)
card.setCardSetId(CardSet.Coreshatter)
card.factionId = Factions.Faction1
card.name = "War Exorcist"
card.setDescription("Provoke\nAt the start of your turn, Holy Immolation your damaged minions.")
card.atk = 3
card.maxHP = 8
card.manaCost = 5
card.rarityId = Rarity.Legendary
card.setInherentModifiersContextObjects([
ModifierProvoke.createContextObject(),
ModifierStartTurnWatchImmolateDamagedMinions.createContextObject()
])
card.setFXResource(["FX.Cards.Neutral.Grailmaster"])
card.setBoundingBoxWidth(100)
card.setBoundingBoxHeight(105)
card.setBaseSoundResource(
apply : RSX.sfx_spell_diretidefrenzy.audio
walk : RSX.sfx_neutral_sai_attack_impact.audio
attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio
receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio
attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio
death : RSX.sfx_neutral_spiritscribe_death.audio
)
card.setBaseAnimResource(
breathing : RSX.f1LeovoyantBreathing.name
idle : RSX.f1LeovoyantIdle.name
walk : RSX.f1LeovoyantRun.name
attack : RSX.f1LeovoyantAttack.name
attackReleaseDelay: 0.0
attackDelay: 0.9
damage : RSX.f1LeovoyantHit.name
death : RSX.f1LeovoyantDeath.name
)
if (identifier == Cards.Spell.OnceMoreWithProvoke)
card = new SpellOnceMoreWithProvoke(gameSession)
card.factionId = Factions.Faction1
card.setCardSetId(CardSet.Coreshatter)
card.id = Cards.Spell.OnceMoreWithProvoke
card.name = "PI:NAME:<NAME>END_PI"
card.setDescription("Summon around your General all friendly minions with Provoke that died this game.")
card.manaCost = 9
card.rarityId = Rarity.Legendary
card.addKeywordClassToInclude(ModifierProvoke)
card.setFXResource(["FX.Cards.Spell.AmaranthineVow"])
card.setBaseSoundResource(
apply : RSX.sfx_spell_sunbloom.audio
)
card.setBaseAnimResource(
idle : RSX.iconOnceMoreIdle.name
active : RSX.iconOnceMoreActive.name
)
return card
module.exports = CardFactory_CoreshatterSet_Faction1
|
[
{
"context": "eck empty newline between class members\n# @author 薛定谔的猫<hh_2013@foxmail.com>\n###\n'use strict'\n\nastUtils =",
"end": 86,
"score": 0.9997463822364807,
"start": 81,
"tag": "NAME",
"value": "薛定谔的猫"
},
{
"context": "pty newline between class members\n# @author 薛定谔的猫<hh_2... | src/rules/lines-between-class-members.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to check empty newline between class members
# @author 薛定谔的猫<hh_2013@foxmail.com>
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'require or disallow an empty line between class members'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/lines-between-class-members'
# fixable: 'whitespace'
schema: [
enum: ['always', 'never']
,
type: 'object'
properties:
exceptAfterSingleLine:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
options = []
options[0] = context.options[0] or 'always'
options[1] = context.options[1] or
exceptAfterSingleLine: no
ALWAYS_MESSAGE = 'Expected blank line between class members.'
NEVER_MESSAGE = 'Unexpected blank line between class members.'
sourceCode = context.getSourceCode()
###*
# Checks if there is padding between two tokens
# @param {Token} first The first token
# @param {Token} second The second token
# @returns {boolean} True if there is at least a line between the tokens
###
isPaddingBetweenTokens = (first, second) ->
comments = sourceCode.getCommentsBefore second
len = comments.length
# If there is no comments
if len is 0
linesBetweenFstAndSnd = second.loc.start.line - first.loc.end.line - 1
return linesBetweenFstAndSnd >= 1
# If there are comments
sumOfCommentLines = 0 # the numbers of lines of comments
prevCommentLineNum = -1 # line number of the end of the previous comment
i = 0
while i < len
commentLinesOfThisComment =
comments[i].loc.end.line - comments[i].loc.start.line + 1
sumOfCommentLines += commentLinesOfThisComment
###
# If this comment and the previous comment are in the same line,
# the count of comment lines is duplicated. So decrement sumOfCommentLines.
###
if prevCommentLineNum is comments[i].loc.start.line
sumOfCommentLines -= 1
prevCommentLineNum = comments[i].loc.end.line
i++
###
# If the first block and the first comment are in the same line,
# the count of comment lines is duplicated. So decrement sumOfCommentLines.
###
if first.loc.end.line is comments[0].loc.start.line
sumOfCommentLines -= 1
###
# If the last comment and the second block are in the same line,
# the count of comment lines is duplicated. So decrement sumOfCommentLines.
###
if comments[len - 1].loc.end.line is second.loc.start.line
sumOfCommentLines -= 1
linesBetweenFstAndSnd = second.loc.start.line - first.loc.end.line - 1
linesBetweenFstAndSnd - sumOfCommentLines >= 1
ClassBody: (node) ->
{body} = node
return unless body.length
for i in [0...(body.length - 1)]
curFirst = sourceCode.getFirstToken body[i]
curLast = sourceCode.getLastToken body[i]
nextFirst = sourceCode.getFirstToken body[i + 1]
isPadded = isPaddingBetweenTokens curLast, nextFirst
isMulti = not astUtils.isTokenOnSameLine curFirst, curLast
skip = not isMulti and options[1].exceptAfterSingleLine
if (
(options[0] is 'always' and not skip and not isPadded) or
(options[0] is 'never' and isPadded)
)
context.report
node: body[i + 1]
message: if isPadded then NEVER_MESSAGE else ALWAYS_MESSAGE
# fix: (fixer) ->
# if isPadded
# fixer.replaceTextRange(
# [curLast.range[1], nextFirst.range[0]]
# '\n'
# )
# else
# fixer.insertTextAfter curLast, '\n'
| 128328 | ###*
# @fileoverview Rule to check empty newline between class members
# @author <NAME><<EMAIL>>
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'require or disallow an empty line between class members'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/lines-between-class-members'
# fixable: 'whitespace'
schema: [
enum: ['always', 'never']
,
type: 'object'
properties:
exceptAfterSingleLine:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
options = []
options[0] = context.options[0] or 'always'
options[1] = context.options[1] or
exceptAfterSingleLine: no
ALWAYS_MESSAGE = 'Expected blank line between class members.'
NEVER_MESSAGE = 'Unexpected blank line between class members.'
sourceCode = context.getSourceCode()
###*
# Checks if there is padding between two tokens
# @param {Token} first The first token
# @param {Token} second The second token
# @returns {boolean} True if there is at least a line between the tokens
###
isPaddingBetweenTokens = (first, second) ->
comments = sourceCode.getCommentsBefore second
len = comments.length
# If there is no comments
if len is 0
linesBetweenFstAndSnd = second.loc.start.line - first.loc.end.line - 1
return linesBetweenFstAndSnd >= 1
# If there are comments
sumOfCommentLines = 0 # the numbers of lines of comments
prevCommentLineNum = -1 # line number of the end of the previous comment
i = 0
while i < len
commentLinesOfThisComment =
comments[i].loc.end.line - comments[i].loc.start.line + 1
sumOfCommentLines += commentLinesOfThisComment
###
# If this comment and the previous comment are in the same line,
# the count of comment lines is duplicated. So decrement sumOfCommentLines.
###
if prevCommentLineNum is comments[i].loc.start.line
sumOfCommentLines -= 1
prevCommentLineNum = comments[i].loc.end.line
i++
###
# If the first block and the first comment are in the same line,
# the count of comment lines is duplicated. So decrement sumOfCommentLines.
###
if first.loc.end.line is comments[0].loc.start.line
sumOfCommentLines -= 1
###
# If the last comment and the second block are in the same line,
# the count of comment lines is duplicated. So decrement sumOfCommentLines.
###
if comments[len - 1].loc.end.line is second.loc.start.line
sumOfCommentLines -= 1
linesBetweenFstAndSnd = second.loc.start.line - first.loc.end.line - 1
linesBetweenFstAndSnd - sumOfCommentLines >= 1
ClassBody: (node) ->
{body} = node
return unless body.length
for i in [0...(body.length - 1)]
curFirst = sourceCode.getFirstToken body[i]
curLast = sourceCode.getLastToken body[i]
nextFirst = sourceCode.getFirstToken body[i + 1]
isPadded = isPaddingBetweenTokens curLast, nextFirst
isMulti = not astUtils.isTokenOnSameLine curFirst, curLast
skip = not isMulti and options[1].exceptAfterSingleLine
if (
(options[0] is 'always' and not skip and not isPadded) or
(options[0] is 'never' and isPadded)
)
context.report
node: body[i + 1]
message: if isPadded then NEVER_MESSAGE else ALWAYS_MESSAGE
# fix: (fixer) ->
# if isPadded
# fixer.replaceTextRange(
# [curLast.range[1], nextFirst.range[0]]
# '\n'
# )
# else
# fixer.insertTextAfter curLast, '\n'
| true | ###*
# @fileoverview Rule to check empty newline between class members
# @author PI:NAME:<NAME>END_PI<PI:EMAIL:<EMAIL>END_PI>
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'require or disallow an empty line between class members'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/lines-between-class-members'
# fixable: 'whitespace'
schema: [
enum: ['always', 'never']
,
type: 'object'
properties:
exceptAfterSingleLine:
type: 'boolean'
additionalProperties: no
]
create: (context) ->
options = []
options[0] = context.options[0] or 'always'
options[1] = context.options[1] or
exceptAfterSingleLine: no
ALWAYS_MESSAGE = 'Expected blank line between class members.'
NEVER_MESSAGE = 'Unexpected blank line between class members.'
sourceCode = context.getSourceCode()
###*
# Checks if there is padding between two tokens
# @param {Token} first The first token
# @param {Token} second The second token
# @returns {boolean} True if there is at least a line between the tokens
###
isPaddingBetweenTokens = (first, second) ->
comments = sourceCode.getCommentsBefore second
len = comments.length
# If there is no comments
if len is 0
linesBetweenFstAndSnd = second.loc.start.line - first.loc.end.line - 1
return linesBetweenFstAndSnd >= 1
# If there are comments
sumOfCommentLines = 0 # the numbers of lines of comments
prevCommentLineNum = -1 # line number of the end of the previous comment
i = 0
while i < len
commentLinesOfThisComment =
comments[i].loc.end.line - comments[i].loc.start.line + 1
sumOfCommentLines += commentLinesOfThisComment
###
# If this comment and the previous comment are in the same line,
# the count of comment lines is duplicated. So decrement sumOfCommentLines.
###
if prevCommentLineNum is comments[i].loc.start.line
sumOfCommentLines -= 1
prevCommentLineNum = comments[i].loc.end.line
i++
###
# If the first block and the first comment are in the same line,
# the count of comment lines is duplicated. So decrement sumOfCommentLines.
###
if first.loc.end.line is comments[0].loc.start.line
sumOfCommentLines -= 1
###
# If the last comment and the second block are in the same line,
# the count of comment lines is duplicated. So decrement sumOfCommentLines.
###
if comments[len - 1].loc.end.line is second.loc.start.line
sumOfCommentLines -= 1
linesBetweenFstAndSnd = second.loc.start.line - first.loc.end.line - 1
linesBetweenFstAndSnd - sumOfCommentLines >= 1
ClassBody: (node) ->
{body} = node
return unless body.length
for i in [0...(body.length - 1)]
curFirst = sourceCode.getFirstToken body[i]
curLast = sourceCode.getLastToken body[i]
nextFirst = sourceCode.getFirstToken body[i + 1]
isPadded = isPaddingBetweenTokens curLast, nextFirst
isMulti = not astUtils.isTokenOnSameLine curFirst, curLast
skip = not isMulti and options[1].exceptAfterSingleLine
if (
(options[0] is 'always' and not skip and not isPadded) or
(options[0] is 'never' and isPadded)
)
context.report
node: body[i + 1]
message: if isPadded then NEVER_MESSAGE else ALWAYS_MESSAGE
# fix: (fixer) ->
# if isPadded
# fixer.replaceTextRange(
# [curLast.range[1], nextFirst.range[0]]
# '\n'
# )
# else
# fixer.insertTextAfter curLast, '\n'
|
[
{
"context": "meteor.com/img/hackifilogo.png'\n companyName: 'Hackifi'\n companyUrl: 'http://hackifi.com'\n company",
"end": 430,
"score": 0.9892280101776123,
"start": 423,
"tag": "NAME",
"value": "Hackifi"
},
{
"context": "elephone: '+(233) 248-060-588'\n companyEmail: '... | lib/_config/emails.coffee | ijayoa/hackifi | 0 | if Meteor.isServer
options =
siteName: Config.name
if Config.socialMedia
_.each Config.socialMedia, (v,k) ->
options[k] = v.url
if Config.legal
options.companyAddress = Config.legal.address
options.companyName = Config.legal.name
options.companyUrl = Config.legal.url
PrettyEmail.options =
from: 'Hackifi'
logo: 'http://hackifi.meteor.com/img/hackifilogo.png'
companyName: 'Hackifi'
companyUrl: 'http://hackifi.com'
companyAddress: '20 Aluguntuguntu Street Ambassadorial Enclave East Legon, Greater Accra, Ghana.'
companyTelephone: '+(233) 248-060-588'
companyEmail: 'support@hackifi.com'
siteName: 'Hackifi'
showFooter: true
| 126984 | if Meteor.isServer
options =
siteName: Config.name
if Config.socialMedia
_.each Config.socialMedia, (v,k) ->
options[k] = v.url
if Config.legal
options.companyAddress = Config.legal.address
options.companyName = Config.legal.name
options.companyUrl = Config.legal.url
PrettyEmail.options =
from: 'Hackifi'
logo: 'http://hackifi.meteor.com/img/hackifilogo.png'
companyName: '<NAME>'
companyUrl: 'http://hackifi.com'
companyAddress: '20 Aluguntuguntu Street Ambassadorial Enclave East Legon, Greater Accra, Ghana.'
companyTelephone: '+(233) 248-060-588'
companyEmail: '<EMAIL>'
siteName: '<NAME>'
showFooter: true
| true | if Meteor.isServer
options =
siteName: Config.name
if Config.socialMedia
_.each Config.socialMedia, (v,k) ->
options[k] = v.url
if Config.legal
options.companyAddress = Config.legal.address
options.companyName = Config.legal.name
options.companyUrl = Config.legal.url
PrettyEmail.options =
from: 'Hackifi'
logo: 'http://hackifi.meteor.com/img/hackifilogo.png'
companyName: 'PI:NAME:<NAME>END_PI'
companyUrl: 'http://hackifi.com'
companyAddress: '20 Aluguntuguntu Street Ambassadorial Enclave East Legon, Greater Accra, Ghana.'
companyTelephone: '+(233) 248-060-588'
companyEmail: 'PI:EMAIL:<EMAIL>END_PI'
siteName: 'PI:NAME:<NAME>END_PI'
showFooter: true
|
[
{
"context": "ken\", \"system\",\n get: ->\n password: @get(\"password\")\n email: @get(\"email\")\n token: @get(\"t",
"end": 517,
"score": 0.5727882385253906,
"start": 509,
"tag": "PASSWORD",
"value": "password"
}
] | addon/utils/errors.coffee | simwms/simwms-shared | 0 | `import Ember from 'ember'`
`import {simplifyError} from './apiv3-error-tools'`
{computed, A} = Ember
{notEmpty: notEmpty, or: ifAny} = computed
Errors = Ember.Object.extend
hasErrors: ifAny "hasEmailErrors", "hasTokenErrors", "hasPasswordErrors", "hasSystemErrors"
hasTokenErrors: notEmpty "token"
hasPasswordErrors: notEmpty "password"
hasEmailErrors: notEmpty "email"
hasSystemErrors: notEmpty "system"
core: computed "password", "email", "token", "system",
get: ->
password: @get("password")
email: @get("email")
token: @get("token")
system: @get("system")
init: ->
@_super arguments...
@clear()
clear: ->
@set "password", A()
@set "email", A()
@set "token", A()
@set "system", A()
addError: ({key, msg}) ->
switch key
when "email", "password", "token", "system"
@get(key).pushObject msg
else
@addError "system", msg
addErrors: ({errors}) ->
A errors
.map simplifyError
.forEach @addError, @
`export default Errors` | 95569 | `import Ember from 'ember'`
`import {simplifyError} from './apiv3-error-tools'`
{computed, A} = Ember
{notEmpty: notEmpty, or: ifAny} = computed
Errors = Ember.Object.extend
hasErrors: ifAny "hasEmailErrors", "hasTokenErrors", "hasPasswordErrors", "hasSystemErrors"
hasTokenErrors: notEmpty "token"
hasPasswordErrors: notEmpty "password"
hasEmailErrors: notEmpty "email"
hasSystemErrors: notEmpty "system"
core: computed "password", "email", "token", "system",
get: ->
password: @get("<PASSWORD>")
email: @get("email")
token: @get("token")
system: @get("system")
init: ->
@_super arguments...
@clear()
clear: ->
@set "password", A()
@set "email", A()
@set "token", A()
@set "system", A()
addError: ({key, msg}) ->
switch key
when "email", "password", "token", "system"
@get(key).pushObject msg
else
@addError "system", msg
addErrors: ({errors}) ->
A errors
.map simplifyError
.forEach @addError, @
`export default Errors` | true | `import Ember from 'ember'`
`import {simplifyError} from './apiv3-error-tools'`
{computed, A} = Ember
{notEmpty: notEmpty, or: ifAny} = computed
Errors = Ember.Object.extend
hasErrors: ifAny "hasEmailErrors", "hasTokenErrors", "hasPasswordErrors", "hasSystemErrors"
hasTokenErrors: notEmpty "token"
hasPasswordErrors: notEmpty "password"
hasEmailErrors: notEmpty "email"
hasSystemErrors: notEmpty "system"
core: computed "password", "email", "token", "system",
get: ->
password: @get("PI:PASSWORD:<PASSWORD>END_PI")
email: @get("email")
token: @get("token")
system: @get("system")
init: ->
@_super arguments...
@clear()
clear: ->
@set "password", A()
@set "email", A()
@set "token", A()
@set "system", A()
addError: ({key, msg}) ->
switch key
when "email", "password", "token", "system"
@get(key).pushObject msg
else
@addError "system", msg
addErrors: ({errors}) ->
A errors
.map simplifyError
.forEach @addError, @
`export default Errors` |
[
{
"context": "cryption.encrypt {\n credentialsDeviceToken: 'cred-token2'\n credentials:\n secret: 'resour",
"end": 754,
"score": 0.7905679941177368,
"start": 743,
"tag": "PASSWORD",
"value": "cred-token2"
},
{
"context": "fresh token'\n }\n @resourceOwner... | test/integration/auth-spec.coffee | octoblu/endo-lib | 0 | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
fs = require 'fs'
Encryption = require 'meshblu-encryption'
request = require 'request'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
MockStrategy = require '../mock-strategy'
Server = require '../..'
describe 'Auth Spec', ->
beforeEach (done) ->
@privateKey = fs.readFileSync "#{__dirname}/../data/private-key.pem", 'utf8'
encryption = Encryption.fromPem @privateKey
@publicKey = encryption.key.exportKey 'public'
@encryptedSecrets = encryption.encrypt {
credentialsDeviceToken: 'cred-token2'
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@resourceOwnerSignature = 'Ula5075pW5J6pbIzhez3Be78UsyVApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
decryptClientSecret = (req, res, next) =>
return next() unless req.body?.$set?['endo']?['encrypted']?
req.body.$set['endo']['encrypted'] = encryption.decrypt req.body.$set['endo']['encrypted']
next()
@meshblu = shmock 0xd00d, [decryptClientSecret]
@meshblu
.get '/publickey'
.reply 200, {@publicKey}
enableDestroy @meshblu
@apiStub = sinon.stub().yields(new Error('Unauthorized'))
@apiStrategy = new MockStrategy name: 'api', @apiStub
@octobluStub = sinon.stub().yields(new Error('Unauthorized'))
@octobluStrategy = new MockStrategy name: 'octoblu', @octobluStub
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic cGV0ZXI6aS1jb3VsZC1lYXQ="
.reply 200, {
options:
imageUrl: "http://this-is-an-image.exe"
}
serverOptions =
logFn: -> console.log arguments...
messageHandler: {}
deviceType: 'endo-app'
apiStrategy: @apiStrategy
octobluStrategy: @octobluStrategy
disableLogging: true
meshbluConfig:
hostname: 'localhost'
protocol: 'http'
port: 0xd00d
uuid: 'peter'
token: 'i-could-eat'
privateKey: @privateKey
port: undefined,
serviceUrl: "http://the-endo-url"
userDeviceManagerUrl: 'http://manage-my.endo'
appOctobluHost: 'http://app.octoblu.biz/'
meshbluPublicKeyUri: 'http://localhost:53261/publickey'
healthcheckService: healthcheck: =>
@server = new Server serverOptions
@server.run (error) =>
return done error if error?
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.destroy done
describe 'When inauthenticated', ->
describe 'On GET /', ->
beforeEach (done) ->
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
request.get '/', options, (error, @response, @body) =>
done error
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302, @body
it 'should redirect to /auth/octoblu', ->
expect(@response.headers.location).to.equal '/auth/octoblu'
describe 'On GET /auth/octoblu', ->
beforeEach (done) ->
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
request.get '/auth/octoblu', options, (error, @response, @body) =>
done error
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302, @body
describe 'On GET /auth/octoblu/callback with a valid code', ->
beforeEach (done) ->
@octobluStub.yields null, {
uuid: 'u'
bearerToken: 'grizzly'
}
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Bearer grizzly"
.reply 200, {}
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
qs:
code: new Buffer('client-id:u:t1').toString 'base64'
request.get '/auth/octoblu/callback', options, (error, @response, @body) =>
done error
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302
it 'should redirect to /auth/api', ->
expect(@response.headers.location).to.equal '/auth/api'
it 'should set the meshblu auth cookies', ->
expect(@response.headers['set-cookie']).to.contain 'meshblu_auth_bearer=grizzly; Path=/'
describe 'On GET /auth/api', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
@authDevice = @meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
options =
uri: '/auth/api'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: 'some-token'
request.get options, (error, @response, @body) =>
done error
it 'should auth the octoblu device', ->
@authDevice.done()
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302
describe 'On GET /auth/api/callback', ->
describe 'when the credentials device does not exist', ->
beforeEach ->
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send
'endo.idKey': 'Ula5075pW5J6pbIzhez3Be78UsyVApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
.reply 200, []
@createCredentialsDevice = @meshblu
.post '/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send
meshblu:
version: '2.0.0'
whitelists:
discover:
view: [{uuid: 'peter'}]
as: [{uuid: 'peter'}]
configure:
update: [{uuid: 'peter'}]
message:
received: [{uuid: 'peter'}]
.reply 200, uuid: 'cred-uuid', token: 'cred-token'
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "cred-token2"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: 'pG7eYd4TYZOX2R5S73jo9aexPzldiNo4pw1wViDpYrAAGRMT6dY0jlbXbfHMz9y+El6AcXMZJEOxaeO1lITsYg=='
idKey: 'Ula5075pW5J6pbIzhez3Be78UsyVApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentialsDeviceToken: 'cred-token2'
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
endoSignature: 'i7OF2Kc6ReZ2EKpDRLgyt/VlyxilV7nes+36ib6zsqe6i90RkZ2IF9JRFhEcwWbt4/JYUpZcfr1YhODtGH769g=='
.reply 204
@createMessageReceivedSubscription = @meshblu
.post '/v2/devices/peter/subscriptions/cred-uuid/message.received'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201
describe 'when called without an accept header', ->
beforeEach (done) ->
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: 'some-token'
request.get options, (error, @response, @body) =>
done error
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301, @body
it 'should create a credentials device', ->
@createCredentialsDevice.done()
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it "should subscribe the service to the credential's received messages", ->
@createMessageReceivedSubscription.done()
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
UNEXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal UNEXPECTED
describe 'when called with a JSON accept header', ->
beforeEach (done) ->
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
json: true
headers:
Accept: 'application/json'
auth:
username: 'some-uuid'
password: 'some-token'
request.get options, (error, @response, @body) =>
done error
it 'should return a 201', ->
expect(@response.statusCode).to.equal 201, @body
it 'should create a credentials device', ->
@createCredentialsDevice.done()
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it "should subscribe the service to the credential's received messages", ->
@createMessageReceivedSubscription.done()
it 'should return the credentials device uuid', ->
expect(@body).to.deep.equal uuid: 'cred-uuid'
describe 'when the credentials device does exist', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send 'endo.idKey': 'Ula5075pW5J6pbIzhez3Be78UsyVApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
.reply 200, [{
uuid: 'cred-uuid'
token: 'cred-token'
endoSignature: 'chpYIsrXkwFXGJ+n/tPkS0UwIQlMr7F6xjP2QdFJP/sBwkDKokLyUgYW8ZYFbQn/RLriSv8Do7CmTBkoKofX5g=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "cred-token2"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: 'pG7eYd4TYZOX2R5S73jo9aexPzldiNo4pw1wViDpYrAAGRMT6dY0jlbXbfHMz9y+El6AcXMZJEOxaeO1lITsYg=='
idKey: 'Ula5075pW5J6pbIzhez3Be78UsyVApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
credentialsDeviceToken: 'cred-token2'
endoSignature: "i7OF2Kc6ReZ2EKpDRLgyt/VlyxilV7nes+36ib6zsqe6i90RkZ2IF9JRFhEcwWbt4/JYUpZcfr1YhODtGH769g=="
.reply 204
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: 'some-token'
qs:
oauth_token: 'oauth_token'
oauth_verifier: 'oauth_verifier'
request.get options, (error, @response, @body) =>
done error
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
EXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal EXPECTED
describe 'when two credentials devices exist, but only one has an valid endoSignature', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send 'endo.idKey': 'Ula5075pW5J6pbIzhez3Be78UsyVApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
.reply 200, [{
uuid: 'bad-cred-uuid'
token: 'bad-cred-token'
endoSignature: 'whatever'
endo:
credentialsDeviceUuid: 'bad-cred-uuid'
encrypted: @encryptedSecrets
}, {
uuid: 'cred-uuid'
token: 'cred-token'
endoSignature: 'chpYIsrXkwFXGJ+n/tPkS0UwIQlMr7F6xjP2QdFJP/sBwkDKokLyUgYW8ZYFbQn/RLriSv8Do7CmTBkoKofX5g=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "cred-token2"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: 'pG7eYd4TYZOX2R5S73jo9aexPzldiNo4pw1wViDpYrAAGRMT6dY0jlbXbfHMz9y+El6AcXMZJEOxaeO1lITsYg=='
idKey: 'Ula5075pW5J6pbIzhez3Be78UsyVApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentialsDeviceToken: 'cred-token2'
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
endoSignature: "i7OF2Kc6ReZ2EKpDRLgyt/VlyxilV7nes+36ib6zsqe6i90RkZ2IF9JRFhEcwWbt4/JYUpZcfr1YhODtGH769g=="
.reply 204
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: 'some-token'
qs:
oauth_token: 'oauth_token'
oauth_verifier: 'oauth_verifier'
request.get options, (error, @response, @body) =>
done error
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
EXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal EXPECTED
describe 'when two credentials devices exist with valid endoSignature, but one has a bad credentialsDeviceUrl', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send 'endo.idKey': 'Ula5075pW5J6pbIzhez3Be78UsyVApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
.reply 200, [{
uuid: 'bad-cred-uuid'
endoSignature: 'chpYIsrXkwFXGJ+n/tPkS0UwIQlMr7F6xjP2QdFJP/sBwkDKokLyUgYW8ZYFbQn/RLriSv8Do7CmTBkoKofX5g=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}, {
uuid: 'cred-uuid'
endoSignature: 'chpYIsrXkwFXGJ+n/tPkS0UwIQlMr7F6xjP2QdFJP/sBwkDKokLyUgYW8ZYFbQn/RLriSv8Do7CmTBkoKofX5g=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "cred-token2"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: 'pG7eYd4TYZOX2R5S73jo9aexPzldiNo4pw1wViDpYrAAGRMT6dY0jlbXbfHMz9y+El6AcXMZJEOxaeO1lITsYg=='
idKey: 'Ula5075pW5J6pbIzhez3Be78UsyVApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
credentialsDeviceToken: "cred-token2"
endoSignature: "i7OF2Kc6ReZ2EKpDRLgyt/VlyxilV7nes+36ib6zsqe6i90RkZ2IF9JRFhEcwWbt4/JYUpZcfr1YhODtGH769g=="
.reply 204
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: 'some-token'
qs:
oauth_token: 'oauth_token'
oauth_verifier: 'oauth_verifier'
request.get options, (error, @response, @body) =>
done error
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301, JSON.stringify(@body)
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
EXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal EXPECTED
| 133615 | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
fs = require 'fs'
Encryption = require 'meshblu-encryption'
request = require 'request'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
MockStrategy = require '../mock-strategy'
Server = require '../..'
describe 'Auth Spec', ->
beforeEach (done) ->
@privateKey = fs.readFileSync "#{__dirname}/../data/private-key.pem", 'utf8'
encryption = Encryption.fromPem @privateKey
@publicKey = encryption.key.exportKey 'public'
@encryptedSecrets = encryption.encrypt {
credentialsDeviceToken: '<PASSWORD>'
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@resourceOwnerSignature = '<KEY>
decryptClientSecret = (req, res, next) =>
return next() unless req.body?.$set?['endo']?['encrypted']?
req.body.$set['endo']['encrypted'] = encryption.decrypt req.body.$set['endo']['encrypted']
next()
@meshblu = shmock 0xd00d, [decryptClientSecret]
@meshblu
.get '/publickey'
.reply 200, {@publicKey}
enableDestroy @meshblu
@apiStub = sinon.stub().yields(new Error('Unauthorized'))
@apiStrategy = new MockStrategy name: 'api', @apiStub
@octobluStub = sinon.stub().yields(new Error('Unauthorized'))
@octobluStrategy = new MockStrategy name: 'octoblu', @octobluStub
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic cGV0ZXI6aS1jb3VsZC1lYXQ="
.reply 200, {
options:
imageUrl: "http://this-is-an-image.exe"
}
serverOptions =
logFn: -> console.log arguments...
messageHandler: {}
deviceType: 'endo-app'
apiStrategy: @apiStrategy
octobluStrategy: @octobluStrategy
disableLogging: true
meshbluConfig:
hostname: 'localhost'
protocol: 'http'
port: 0xd00d
uuid: 'peter'
token: '<PASSWORD>'
privateKey: @privateKey
port: undefined,
serviceUrl: "http://the-endo-url"
userDeviceManagerUrl: 'http://manage-my.endo'
appOctobluHost: 'http://app.octoblu.biz/'
meshbluPublicKeyUri: 'http://localhost:53261/publickey'
healthcheckService: healthcheck: =>
@server = new Server serverOptions
@server.run (error) =>
return done error if error?
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.destroy done
describe 'When inauthenticated', ->
describe 'On GET /', ->
beforeEach (done) ->
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
request.get '/', options, (error, @response, @body) =>
done error
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302, @body
it 'should redirect to /auth/octoblu', ->
expect(@response.headers.location).to.equal '/auth/octoblu'
describe 'On GET /auth/octoblu', ->
beforeEach (done) ->
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
request.get '/auth/octoblu', options, (error, @response, @body) =>
done error
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302, @body
describe 'On GET /auth/octoblu/callback with a valid code', ->
beforeEach (done) ->
@octobluStub.yields null, {
uuid: 'u'
bearerToken: '<PASSWORD>'
}
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Bearer <PASSWORD>"
.reply 200, {}
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
qs:
code: new Buffer('client-id:u:t1').toString 'base64'
request.get '/auth/octoblu/callback', options, (error, @response, @body) =>
done error
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302
it 'should redirect to /auth/api', ->
expect(@response.headers.location).to.equal '/auth/api'
it 'should set the meshblu auth cookies', ->
expect(@response.headers['set-cookie']).to.contain 'meshblu_auth_bearer=grizzly; Path=/'
describe 'On GET /auth/api', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
@authDevice = @meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
options =
uri: '/auth/api'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: '<PASSWORD>'
request.get options, (error, @response, @body) =>
done error
it 'should auth the octoblu device', ->
@authDevice.done()
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302
describe 'On GET /auth/api/callback', ->
describe 'when the credentials device does not exist', ->
beforeEach ->
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send
'endo.idKey': '<KEY>
.reply 200, []
@createCredentialsDevice = @meshblu
.post '/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send
meshblu:
version: '2.0.0'
whitelists:
discover:
view: [{uuid: '<NAME>ter'}]
as: [{uuid: '<NAME>ter'}]
configure:
update: [{uuid: '<NAME>ter'}]
message:
received: [{uuid: '<NAME>ter'}]
.reply 200, uuid: 'cred-uuid', token: 'cred-token'
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "<PASSWORD>"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: '<KEY>
idKey: '<KEY>ApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentialsDeviceToken: '<PASSWORD>'
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
endoSignature: 'i7OF2Kc6ReZ2EKpDRLgyt/VlyxilV7nes+36ib6zsqe6i90RkZ2IF9JRFhEcwWbt4/JYUpZcfr1YhODtGH769g=='
.reply 204
@createMessageReceivedSubscription = @meshblu
.post '/v2/devices/peter/subscriptions/cred-uuid/message.received'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201
describe 'when called without an accept header', ->
beforeEach (done) ->
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: '<PASSWORD>'
request.get options, (error, @response, @body) =>
done error
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301, @body
it 'should create a credentials device', ->
@createCredentialsDevice.done()
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it "should subscribe the service to the credential's received messages", ->
@createMessageReceivedSubscription.done()
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
UNEXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal UNEXPECTED
describe 'when called with a JSON accept header', ->
beforeEach (done) ->
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
json: true
headers:
Accept: 'application/json'
auth:
username: 'some-uuid'
password: '<PASSWORD>'
request.get options, (error, @response, @body) =>
done error
it 'should return a 201', ->
expect(@response.statusCode).to.equal 201, @body
it 'should create a credentials device', ->
@createCredentialsDevice.done()
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it "should subscribe the service to the credential's received messages", ->
@createMessageReceivedSubscription.done()
it 'should return the credentials device uuid', ->
expect(@body).to.deep.equal uuid: 'cred-uuid'
describe 'when the credentials device does exist', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send 'endo.idKey': '<KEY>
.reply 200, [{
uuid: 'cred-uuid'
token: 'cred-token'
endoSignature: 'chpYIsrXkwFXGJ+n/tPkS0UwIQlMr7F6xjP2QdFJP/sBwkDKokLyUgYW8ZYFbQn/RLriSv8Do7CmTBkoKofX5g=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "<PASSWORD>"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: '<KEY>
idKey: '<KEY>
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
credentialsDeviceToken: '<PASSWORD>'
endoSignature: "i7OF2Kc6ReZ2EKpDRLgyt/VlyxilV7nes+36ib6zsqe6i90RkZ2IF9JRFhEcwWbt4/JYUpZcfr1YhODtGH769g=="
.reply 204
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: '<PASSWORD>'
qs:
oauth_token: 'oauth_token'
oauth_verifier: 'oauth_verifier'
request.get options, (error, @response, @body) =>
done error
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
EXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal EXPECTED
describe 'when two credentials devices exist, but only one has an valid endoSignature', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send 'endo.idKey': 'U<KEY>
.reply 200, [{
uuid: 'bad-cred-uuid'
token: 'bad-cred-token'
endoSignature: 'whatever'
endo:
credentialsDeviceUuid: 'bad-cred-uuid'
encrypted: @encryptedSecrets
}, {
uuid: 'cred-uuid'
token: '<PASSWORD>-token'
endoSignature: 'chpYIsrXkwFXGJ+n/tPkS0UwIQlMr7F6xjP2QdFJP/sBwkDKokLyUgYW8ZYFbQn/RLriSv8Do7CmTBkoKofX5g=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "<PASSWORD>"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: '<KEY>
idKey: '<KEY>
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentialsDeviceToken: 'cred-token2'
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
endoSignature: "i7OF2Kc6ReZ2EKpDRLgyt/VlyxilV7nes+36ib6zsqe6i90RkZ2IF9JRFhEcwWbt4/JYUpZcfr1YhODtGH769g=="
.reply 204
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: '<PASSWORD>'
qs:
oauth_token: '<PASSWORD>'
oauth_verifier: 'oauth_verifier'
request.get options, (error, @response, @body) =>
done error
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
EXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal EXPECTED
describe 'when two credentials devices exist with valid endoSignature, but one has a bad credentialsDeviceUrl', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send 'endo.idKey': '<KEY>
.reply 200, [{
uuid: 'bad-cred-uuid'
endoSignature: 'chpYIsrXkwFXGJ+n/tPkS0UwIQlMr7F6xjP2Qd<KEY>JP/<KEY>wkDK<KEY>LyUgYW<KEY>/RL<KEY>Sv<KEY>g=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}, {
uuid: 'cred-uuid'
endoSignature: 'ch<KEY>kwFXGJ+<KEY>/<KEY>Pk<KEY>0UwIQ<KEY>7<KEY>xj<KEY>=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "<PASSWORD>"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: '<KEY>
idKey: '<KEY>
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
credentialsDeviceToken: "cred-token2"
endoSignature: "<KEY>
.reply 204
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: '<PASSWORD>'
qs:
oauth_token: 'oauth_token'
oauth_verifier: 'oauth_verifier'
request.get options, (error, @response, @body) =>
done error
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301, JSON.stringify(@body)
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
EXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal EXPECTED
| true | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
sinon = require 'sinon'
fs = require 'fs'
Encryption = require 'meshblu-encryption'
request = require 'request'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
MockStrategy = require '../mock-strategy'
Server = require '../..'
describe 'Auth Spec', ->
beforeEach (done) ->
@privateKey = fs.readFileSync "#{__dirname}/../data/private-key.pem", 'utf8'
encryption = Encryption.fromPem @privateKey
@publicKey = encryption.key.exportKey 'public'
@encryptedSecrets = encryption.encrypt {
credentialsDeviceToken: 'PI:PASSWORD:<PASSWORD>END_PI'
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@resourceOwnerSignature = 'PI:KEY:<KEY>END_PI
decryptClientSecret = (req, res, next) =>
return next() unless req.body?.$set?['endo']?['encrypted']?
req.body.$set['endo']['encrypted'] = encryption.decrypt req.body.$set['endo']['encrypted']
next()
@meshblu = shmock 0xd00d, [decryptClientSecret]
@meshblu
.get '/publickey'
.reply 200, {@publicKey}
enableDestroy @meshblu
@apiStub = sinon.stub().yields(new Error('Unauthorized'))
@apiStrategy = new MockStrategy name: 'api', @apiStub
@octobluStub = sinon.stub().yields(new Error('Unauthorized'))
@octobluStrategy = new MockStrategy name: 'octoblu', @octobluStub
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic cGV0ZXI6aS1jb3VsZC1lYXQ="
.reply 200, {
options:
imageUrl: "http://this-is-an-image.exe"
}
serverOptions =
logFn: -> console.log arguments...
messageHandler: {}
deviceType: 'endo-app'
apiStrategy: @apiStrategy
octobluStrategy: @octobluStrategy
disableLogging: true
meshbluConfig:
hostname: 'localhost'
protocol: 'http'
port: 0xd00d
uuid: 'peter'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
privateKey: @privateKey
port: undefined,
serviceUrl: "http://the-endo-url"
userDeviceManagerUrl: 'http://manage-my.endo'
appOctobluHost: 'http://app.octoblu.biz/'
meshbluPublicKeyUri: 'http://localhost:53261/publickey'
healthcheckService: healthcheck: =>
@server = new Server serverOptions
@server.run (error) =>
return done error if error?
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.destroy done
describe 'When inauthenticated', ->
describe 'On GET /', ->
beforeEach (done) ->
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
request.get '/', options, (error, @response, @body) =>
done error
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302, @body
it 'should redirect to /auth/octoblu', ->
expect(@response.headers.location).to.equal '/auth/octoblu'
describe 'On GET /auth/octoblu', ->
beforeEach (done) ->
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
request.get '/auth/octoblu', options, (error, @response, @body) =>
done error
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302, @body
describe 'On GET /auth/octoblu/callback with a valid code', ->
beforeEach (done) ->
@octobluStub.yields null, {
uuid: 'u'
bearerToken: 'PI:PASSWORD:<PASSWORD>END_PI'
}
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Bearer PI:PASSWORD:<PASSWORD>END_PI"
.reply 200, {}
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
qs:
code: new Buffer('client-id:u:t1').toString 'base64'
request.get '/auth/octoblu/callback', options, (error, @response, @body) =>
done error
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302
it 'should redirect to /auth/api', ->
expect(@response.headers.location).to.equal '/auth/api'
it 'should set the meshblu auth cookies', ->
expect(@response.headers['set-cookie']).to.contain 'meshblu_auth_bearer=grizzly; Path=/'
describe 'On GET /auth/api', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
@authDevice = @meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
options =
uri: '/auth/api'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
request.get options, (error, @response, @body) =>
done error
it 'should auth the octoblu device', ->
@authDevice.done()
it 'should return a 302', ->
expect(@response.statusCode).to.equal 302
describe 'On GET /auth/api/callback', ->
describe 'when the credentials device does not exist', ->
beforeEach ->
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send
'endo.idKey': 'PI:KEY:<KEY>END_PI
.reply 200, []
@createCredentialsDevice = @meshblu
.post '/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send
meshblu:
version: '2.0.0'
whitelists:
discover:
view: [{uuid: 'PI:NAME:<NAME>END_PIter'}]
as: [{uuid: 'PI:NAME:<NAME>END_PIter'}]
configure:
update: [{uuid: 'PI:NAME:<NAME>END_PIter'}]
message:
received: [{uuid: 'PI:NAME:<NAME>END_PIter'}]
.reply 200, uuid: 'cred-uuid', token: 'cred-token'
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "PI:PASSWORD:<PASSWORD>END_PI"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: 'PI:KEY:<KEY>END_PI
idKey: 'PI:KEY:<KEY>END_PIApbXMXEPXmMwBAtVdtxdHoXNx+fI9nLV/pHZzlOI0RjhJmO+qQ3zAnKviw=='
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentialsDeviceToken: 'PI:KEY:<PASSWORD>END_PI'
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
endoSignature: 'i7OF2Kc6ReZ2EKpDRLgyt/VlyxilV7nes+36ib6zsqe6i90RkZ2IF9JRFhEcwWbt4/JYUpZcfr1YhODtGH769g=='
.reply 204
@createMessageReceivedSubscription = @meshblu
.post '/v2/devices/peter/subscriptions/cred-uuid/message.received'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201
describe 'when called without an accept header', ->
beforeEach (done) ->
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
request.get options, (error, @response, @body) =>
done error
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301, @body
it 'should create a credentials device', ->
@createCredentialsDevice.done()
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it "should subscribe the service to the credential's received messages", ->
@createMessageReceivedSubscription.done()
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
UNEXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal UNEXPECTED
describe 'when called with a JSON accept header', ->
beforeEach (done) ->
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
json: true
headers:
Accept: 'application/json'
auth:
username: 'some-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
request.get options, (error, @response, @body) =>
done error
it 'should return a 201', ->
expect(@response.statusCode).to.equal 201, @body
it 'should create a credentials device', ->
@createCredentialsDevice.done()
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it "should subscribe the service to the credential's received messages", ->
@createMessageReceivedSubscription.done()
it 'should return the credentials device uuid', ->
expect(@body).to.deep.equal uuid: 'cred-uuid'
describe 'when the credentials device does exist', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send 'endo.idKey': 'PI:KEY:<KEY>END_PI
.reply 200, [{
uuid: 'cred-uuid'
token: 'cred-token'
endoSignature: 'chpYIsrXkwFXGJ+n/tPkS0UwIQlMr7F6xjP2QdFJP/sBwkDKokLyUgYW8ZYFbQn/RLriSv8Do7CmTBkoKofX5g=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "PI:PASSWORD:<PASSWORD>END_PI"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: 'PI:KEY:<KEY>END_PI
idKey: 'PI:KEY:<KEY>END_PI
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
credentialsDeviceToken: 'PI:PASSWORD:<PASSWORD>END_PI'
endoSignature: "i7OF2Kc6ReZ2EKpDRLgyt/VlyxilV7nes+36ib6zsqe6i90RkZ2IF9JRFhEcwWbt4/JYUpZcfr1YhODtGH769g=="
.reply 204
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
qs:
oauth_token: 'oauth_token'
oauth_verifier: 'oauth_verifier'
request.get options, (error, @response, @body) =>
done error
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
EXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal EXPECTED
describe 'when two credentials devices exist, but only one has an valid endoSignature', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send 'endo.idKey': 'UPI:KEY:<KEY>END_PI
.reply 200, [{
uuid: 'bad-cred-uuid'
token: 'bad-cred-token'
endoSignature: 'whatever'
endo:
credentialsDeviceUuid: 'bad-cred-uuid'
encrypted: @encryptedSecrets
}, {
uuid: 'cred-uuid'
token: 'PI:PASSWORD:<PASSWORD>END_PI-token'
endoSignature: 'chpYIsrXkwFXGJ+n/tPkS0UwIQlMr7F6xjP2QdFJP/sBwkDKokLyUgYW8ZYFbQn/RLriSv8Do7CmTBkoKofX5g=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "PI:PASSWORD:<PASSWORD>END_PI"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: 'PI:KEY:<KEY>END_PI
idKey: 'PI:KEY:<KEY>END_PI
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentialsDeviceToken: 'cred-token2'
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
endoSignature: "i7OF2Kc6ReZ2EKpDRLgyt/VlyxilV7nes+36ib6zsqe6i90RkZ2IF9JRFhEcwWbt4/JYUpZcfr1YhODtGH769g=="
.reply 204
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
qs:
oauth_token: 'PI:PASSWORD:<PASSWORD>END_PI'
oauth_verifier: 'oauth_verifier'
request.get options, (error, @response, @body) =>
done error
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
EXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal EXPECTED
describe 'when two credentials devices exist with valid endoSignature, but one has a bad credentialsDeviceUrl', ->
beforeEach (done) ->
userAuth = new Buffer('some-uuid:some-token').toString 'base64'
serviceAuth = new Buffer('peter:i-could-eat').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@apiStub.yields null, {
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
}
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.set 'Authorization', "Basic #{serviceAuth}"
.send 'endo.idKey': 'PI:KEY:<KEY>END_PI
.reply 200, [{
uuid: 'bad-cred-uuid'
endoSignature: 'chpYIsrXkwFXGJ+n/tPkS0UwIQlMr7F6xjP2QdPI:KEY:<KEY>END_PIJP/PI:KEY:<KEY>END_PIwkDKPI:KEY:<KEY>END_PILyUgYWPI:KEY:<KEY>END_PI/RLPI:KEY:<KEY>END_PISvPI:KEY:<KEY>END_PIg=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}, {
uuid: 'cred-uuid'
endoSignature: 'chPI:KEY:<KEY>END_PIkwFXGJ+PI:KEY:<KEY>END_PI/PI:KEY:<KEY>END_PIPkPI:KEY:<KEY>END_PI0UwIQPI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PIxjPI:KEY:<KEY>END_PI=='
endo:
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encryptedSecrets
}]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 201, '{"uuid": "cred-uuid", "token": "PI:PASSWORD:<PASSWORD>END_PI"}'
@updateCredentialsDevice = @meshblu
.put '/v2/devices/cred-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.send
$set:
endo:
authorizedKey: 'PI:KEY:<KEY>END_PI
idKey: 'PI:KEY:<KEY>END_PI
credentialsDeviceUuid: 'cred-uuid'
version: '1.0.0'
encrypted:
id: 'resource owner id'
username: 'resource owner username'
secrets:
credentials:
secret: 'resource owner secret'
refreshToken: 'resource owner refresh token'
credentialsDeviceToken: "cred-token2"
endoSignature: "PI:KEY:<KEY>END_PI
.reply 204
options =
uri: '/auth/api/callback'
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
auth:
username: 'some-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
qs:
oauth_token: 'oauth_token'
oauth_verifier: 'oauth_verifier'
request.get options, (error, @response, @body) =>
done error
it 'should return a 301', ->
expect(@response.statusCode).to.equal 301, JSON.stringify(@body)
it 'should update the credentials device with the new resourceOwnerSecret and authorizedUuid', ->
@updateCredentialsDevice.done()
it 'should redirect to the userDeviceManagerUrl with the bearerToken and credentialsDeviceUrl', ->
EXPECTED = 'http://manage-my.endo/?meshbluAuthBearer=c29tZS11dWlkOnNvbWUtdG9rZW4%3D&credentialsDeviceUrl=http%3A%2F%2Fthe-endo-url%2Fcredentials%2Fcred-uuid&appOctobluHost=http%3A%2F%2Fapp.octoblu.biz%2F'
expect(@response.headers.location).to.equal EXPECTED
|
[
{
"context": "\n _array1 = [\n {\n vorname: \"Albert\"\n nachname: \"Einstain\"\n }\n ",
"end": 340,
"score": 0.9995070695877075,
"start": 334,
"tag": "NAME",
"value": "Albert"
},
{
"context": " vorname: \"Albert\"\n nach... | frontend/common/services/helper/helper.spec.coffee | Contactis/translation-manager | 0 | describe "Unit testing: translation.services.helper Module >", () ->
describe "for HelperService >", () ->
HelperService = null
_array1 = null
_array2 = null
# load required modules
beforeEach () ->
module 'translation.services.helper'
_array1 = [
{
vorname: "Albert"
nachname: "Einstain"
}
{
vorname: "Thomas"
nachname: "Edison"
}
{
vorname: "Leonardo"
nachname: "Da Vinci"
}
]
_array2 = [
{
vorname: "Pablo"
nachname: "Picasso"
}
{
vorname: "Leonardo"
nachname: "Da Vinci"
}
]
# Injecting required services
beforeEach inject ( $injector ) ->
#load services
HelperService = $injector.get 'HelperService'
return
afterEach () ->
_array1 = null
_array2 = null
return
# Public tests
describe "checking existing of:", () ->
it "method `diffArrayObjects` should be defined", () ->
expect(typeof HelperService.diffArrayObjects).toBe 'function'
describe '`diffArrayObjects()` function:', () ->
it 'should pass if both array1 and array2 are Array Objects', () ->
array1 = []
array2 = []
foo = () ->
HelperService.diffArrayObjects(array1, array2)
expect(foo).not.toThrow()
it 'should throw error if array2 is String', () ->
array1 = []
array2 = ""
foo = () ->
HelperService.diffArrayObjects(array1, array2)
expect(foo).toThrow()
describe '`partitionArrayByParameter()` function:', () ->
it 'should not throw error if arguments of method are correct', () ->
array1 = []
array2 = []
foo = ->
HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo).not.toThrow()
it 'should throw error if arguments of method are incorrect', () ->
array1 = []
array2 = ""
foo = ->
HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo).toThrow()
it 'should throw error if last argument (equalKey) of method are missing', () ->
array1 = []
array2 = []
foo = ->
HelperService.partitionArrayByParameter(array1, array2)
expect(foo).toThrow()
it 'should return 1 common and 2 diff Objects', () ->
array1 = _array1
array2 = _array2
foo = HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo[0].length).toEqual(1)
expect(foo[1].length).toEqual(2)
it 'should returns 1 common and 1 diff Objects', () ->
array1 = _array2
array2 = _array1
foo = HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo[0].length).toEqual(1)
expect(foo[1].length).toEqual(1)
describe '`partitionGreaterArrayByParameter()` function:', () ->
it 'should not throw error if arguments of method are correct', () ->
array1 = _array1
array2 = _array2
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2, 'vorname')
expect(foo).not.toThrow()
it 'should throw error if arguments of method are incorrect', () ->
array1 = _array1
array2 = ""
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2, 'vorname')
expect(foo).toThrow()
it 'should throw error if last argument (equalKey) of method are missing', () ->
array1 = []
array2 = []
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2)
expect(foo).toThrow()
it 'should take bigger array if they are switched', () ->
array1 = _array2
array2 = _array1
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2, 'vorname')
expect(foo()[0].length).toEqual(1)
expect(foo()[1].length).toEqual(2)
it 'should pass on more complex arrays of objects', () ->
array1 = [
{
"id": 1,
"realm": null,
"username": "Sir Admin",
"credentials": null,
"challenges": null,
"email": "admin@admin.com",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "Sir Super",
"lastName": "Admin",
"role": "admin",
"interfaceLanguage": "en-us"
},
{
"id": 2,
"realm": null,
"username": "Sir Manager",
"credentials": null,
"challenges": null,
"email": "manager@manager.com",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "Sir Super",
"lastName": "Manager",
"role": "user",
"interfaceLanguage": "en-us"
},
{
"id": 3,
"realm": null,
"username": "Sir Translator",
"credentials": null,
"challenges": null,
"email": "translator@translator.com",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "Sir Super",
"lastName": "Translator",
"role": "user",
"interfaceLanguage": "en-us"
},
{
"id": 4,
"realm": null,
"username": "Sir Programmer",
"credentials": null,
"challenges": null,
"email": "programmer@programmer.com",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "Sir Super",
"lastName": "Programmer",
"role": "user",
"interfaceLanguage": "en-us"
}
]
array2 = [
{
"id": 1,
"realm": null,
"username": "Sir Admin",
"credentials": null,
"challenges": null,
"email": "admin@admin.com",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "Sir Super",
"lastName": "Admin",
"role": "admin",
"interfaceLanguage": "en-us"
},
{
"id": 2,
"realm": null,
"username": "Sir Manager",
"credentials": null,
"challenges": null,
"email": "manager@manager.com",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "Sir Super",
"lastName": "Manager",
"role": "user",
"interfaceLanguage": "en-us"
}
]
foo = HelperService.partitionGreaterArrayByParameter(array1, array2, 'id')
expect(foo[0].length).toEqual(2)
expect(foo[1].length).toEqual(2)
| 40872 | describe "Unit testing: translation.services.helper Module >", () ->
describe "for HelperService >", () ->
HelperService = null
_array1 = null
_array2 = null
# load required modules
beforeEach () ->
module 'translation.services.helper'
_array1 = [
{
vorname: "<NAME>"
nachname: "<NAME>"
}
{
vorname: "<NAME>"
nachname: "<NAME>"
}
{
vorname: "<NAME>"
nachname: "<NAME>"
}
]
_array2 = [
{
vorname: "<NAME>"
nachname: "<NAME>"
}
{
vorname: "<NAME>"
nachname: "<NAME>"
}
]
# Injecting required services
beforeEach inject ( $injector ) ->
#load services
HelperService = $injector.get 'HelperService'
return
afterEach () ->
_array1 = null
_array2 = null
return
# Public tests
describe "checking existing of:", () ->
it "method `diffArrayObjects` should be defined", () ->
expect(typeof HelperService.diffArrayObjects).toBe 'function'
describe '`diffArrayObjects()` function:', () ->
it 'should pass if both array1 and array2 are Array Objects', () ->
array1 = []
array2 = []
foo = () ->
HelperService.diffArrayObjects(array1, array2)
expect(foo).not.toThrow()
it 'should throw error if array2 is String', () ->
array1 = []
array2 = ""
foo = () ->
HelperService.diffArrayObjects(array1, array2)
expect(foo).toThrow()
describe '`partitionArrayByParameter()` function:', () ->
it 'should not throw error if arguments of method are correct', () ->
array1 = []
array2 = []
foo = ->
HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo).not.toThrow()
it 'should throw error if arguments of method are incorrect', () ->
array1 = []
array2 = ""
foo = ->
HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo).toThrow()
it 'should throw error if last argument (equalKey) of method are missing', () ->
array1 = []
array2 = []
foo = ->
HelperService.partitionArrayByParameter(array1, array2)
expect(foo).toThrow()
it 'should return 1 common and 2 diff Objects', () ->
array1 = _array1
array2 = _array2
foo = HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo[0].length).toEqual(1)
expect(foo[1].length).toEqual(2)
it 'should returns 1 common and 1 diff Objects', () ->
array1 = _array2
array2 = _array1
foo = HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo[0].length).toEqual(1)
expect(foo[1].length).toEqual(1)
describe '`partitionGreaterArrayByParameter()` function:', () ->
it 'should not throw error if arguments of method are correct', () ->
array1 = _array1
array2 = _array2
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2, 'vorname')
expect(foo).not.toThrow()
it 'should throw error if arguments of method are incorrect', () ->
array1 = _array1
array2 = ""
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2, 'vorname')
expect(foo).toThrow()
it 'should throw error if last argument (equalKey) of method are missing', () ->
array1 = []
array2 = []
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2)
expect(foo).toThrow()
it 'should take bigger array if they are switched', () ->
array1 = _array2
array2 = _array1
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2, 'vorname')
expect(foo()[0].length).toEqual(1)
expect(foo()[1].length).toEqual(2)
it 'should pass on more complex arrays of objects', () ->
array1 = [
{
"id": 1,
"realm": null,
"username": "Sir Admin",
"credentials": null,
"challenges": null,
"email": "<EMAIL>",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "<NAME>",
"lastName": "<NAME>",
"role": "admin",
"interfaceLanguage": "en-us"
},
{
"id": 2,
"realm": null,
"username": "Sir Manager",
"credentials": null,
"challenges": null,
"email": "<EMAIL>",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "<NAME>",
"lastName": "<NAME>",
"role": "user",
"interfaceLanguage": "en-us"
},
{
"id": 3,
"realm": null,
"username": "Sir Translator",
"credentials": null,
"challenges": null,
"email": "<EMAIL>",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "<NAME>",
"lastName": "<NAME>",
"role": "user",
"interfaceLanguage": "en-us"
},
{
"id": 4,
"realm": null,
"username": "<NAME>",
"credentials": null,
"challenges": null,
"email": "<EMAIL>",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "<NAME>",
"lastName": "<NAME>",
"role": "user",
"interfaceLanguage": "en-us"
}
]
array2 = [
{
"id": 1,
"realm": null,
"username": "Sir Admin",
"credentials": null,
"challenges": null,
"email": "<EMAIL>",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "<NAME>",
"lastName": "<NAME>",
"role": "admin",
"interfaceLanguage": "en-us"
},
{
"id": 2,
"realm": null,
"username": "Sir Manager",
"credentials": null,
"challenges": null,
"email": "<EMAIL>",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "<NAME>",
"lastName": "<NAME>",
"role": "user",
"interfaceLanguage": "en-us"
}
]
foo = HelperService.partitionGreaterArrayByParameter(array1, array2, 'id')
expect(foo[0].length).toEqual(2)
expect(foo[1].length).toEqual(2)
| true | describe "Unit testing: translation.services.helper Module >", () ->
describe "for HelperService >", () ->
HelperService = null
_array1 = null
_array2 = null
# load required modules
beforeEach () ->
module 'translation.services.helper'
_array1 = [
{
vorname: "PI:NAME:<NAME>END_PI"
nachname: "PI:NAME:<NAME>END_PI"
}
{
vorname: "PI:NAME:<NAME>END_PI"
nachname: "PI:NAME:<NAME>END_PI"
}
{
vorname: "PI:NAME:<NAME>END_PI"
nachname: "PI:NAME:<NAME>END_PI"
}
]
_array2 = [
{
vorname: "PI:NAME:<NAME>END_PI"
nachname: "PI:NAME:<NAME>END_PI"
}
{
vorname: "PI:NAME:<NAME>END_PI"
nachname: "PI:NAME:<NAME>END_PI"
}
]
# Injecting required services
beforeEach inject ( $injector ) ->
#load services
HelperService = $injector.get 'HelperService'
return
afterEach () ->
_array1 = null
_array2 = null
return
# Public tests
describe "checking existing of:", () ->
it "method `diffArrayObjects` should be defined", () ->
expect(typeof HelperService.diffArrayObjects).toBe 'function'
describe '`diffArrayObjects()` function:', () ->
it 'should pass if both array1 and array2 are Array Objects', () ->
array1 = []
array2 = []
foo = () ->
HelperService.diffArrayObjects(array1, array2)
expect(foo).not.toThrow()
it 'should throw error if array2 is String', () ->
array1 = []
array2 = ""
foo = () ->
HelperService.diffArrayObjects(array1, array2)
expect(foo).toThrow()
describe '`partitionArrayByParameter()` function:', () ->
it 'should not throw error if arguments of method are correct', () ->
array1 = []
array2 = []
foo = ->
HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo).not.toThrow()
it 'should throw error if arguments of method are incorrect', () ->
array1 = []
array2 = ""
foo = ->
HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo).toThrow()
it 'should throw error if last argument (equalKey) of method are missing', () ->
array1 = []
array2 = []
foo = ->
HelperService.partitionArrayByParameter(array1, array2)
expect(foo).toThrow()
it 'should return 1 common and 2 diff Objects', () ->
array1 = _array1
array2 = _array2
foo = HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo[0].length).toEqual(1)
expect(foo[1].length).toEqual(2)
it 'should returns 1 common and 1 diff Objects', () ->
array1 = _array2
array2 = _array1
foo = HelperService.partitionArrayByParameter(array1, array2, 'vorname')
expect(foo[0].length).toEqual(1)
expect(foo[1].length).toEqual(1)
describe '`partitionGreaterArrayByParameter()` function:', () ->
it 'should not throw error if arguments of method are correct', () ->
array1 = _array1
array2 = _array2
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2, 'vorname')
expect(foo).not.toThrow()
it 'should throw error if arguments of method are incorrect', () ->
array1 = _array1
array2 = ""
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2, 'vorname')
expect(foo).toThrow()
it 'should throw error if last argument (equalKey) of method are missing', () ->
array1 = []
array2 = []
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2)
expect(foo).toThrow()
it 'should take bigger array if they are switched', () ->
array1 = _array2
array2 = _array1
foo = ->
HelperService.partitionGreaterArrayByParameter(array1, array2, 'vorname')
expect(foo()[0].length).toEqual(1)
expect(foo()[1].length).toEqual(2)
it 'should pass on more complex arrays of objects', () ->
array1 = [
{
"id": 1,
"realm": null,
"username": "Sir Admin",
"credentials": null,
"challenges": null,
"email": "PI:EMAIL:<EMAIL>END_PI",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "PI:NAME:<NAME>END_PI",
"lastName": "PI:NAME:<NAME>END_PI",
"role": "admin",
"interfaceLanguage": "en-us"
},
{
"id": 2,
"realm": null,
"username": "Sir Manager",
"credentials": null,
"challenges": null,
"email": "PI:EMAIL:<EMAIL>END_PI",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "PI:NAME:<NAME>END_PI",
"lastName": "PI:NAME:<NAME>END_PI",
"role": "user",
"interfaceLanguage": "en-us"
},
{
"id": 3,
"realm": null,
"username": "Sir Translator",
"credentials": null,
"challenges": null,
"email": "PI:EMAIL:<EMAIL>END_PI",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "PI:NAME:<NAME>END_PI",
"lastName": "PI:NAME:<NAME>END_PI",
"role": "user",
"interfaceLanguage": "en-us"
},
{
"id": 4,
"realm": null,
"username": "PI:NAME:<NAME>END_PI",
"credentials": null,
"challenges": null,
"email": "PI:EMAIL:<EMAIL>END_PI",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "PI:NAME:<NAME>END_PI",
"lastName": "PI:NAME:<NAME>END_PI",
"role": "user",
"interfaceLanguage": "en-us"
}
]
array2 = [
{
"id": 1,
"realm": null,
"username": "Sir Admin",
"credentials": null,
"challenges": null,
"email": "PI:EMAIL:<EMAIL>END_PI",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "PI:NAME:<NAME>END_PI",
"lastName": "PI:NAME:<NAME>END_PI",
"role": "admin",
"interfaceLanguage": "en-us"
},
{
"id": 2,
"realm": null,
"username": "Sir Manager",
"credentials": null,
"challenges": null,
"email": "PI:EMAIL:<EMAIL>END_PI",
"emailVerified": true,
"verificationToken": null,
"status": null,
"created": "1970-01-01T00:00:00.000Z",
"lastUpdated": "2015-11-23T20:24:32.000Z",
"firstName": "PI:NAME:<NAME>END_PI",
"lastName": "PI:NAME:<NAME>END_PI",
"role": "user",
"interfaceLanguage": "en-us"
}
]
foo = HelperService.partitionGreaterArrayByParameter(array1, array2, 'id')
expect(foo[0].length).toEqual(2)
expect(foo[1].length).toEqual(2)
|
[
{
"context": "'use strict'\n\n\n# Key\n#\n# @copyright Andrew Lawson 2012\n# @see http://github.com/adlawson/key\n# @see",
"end": 49,
"score": 0.9998739361763,
"start": 36,
"tag": "NAME",
"value": "Andrew Lawson"
},
{
"context": "right Andrew Lawson 2012\n# @see http://github.com/adl... | src/code/brand.coffee | adlawson/coffee-key | 1 | 'use strict'
# Key
#
# @copyright Andrew Lawson 2012
# @see http://github.com/adlawson/key
# @see http://npmjs.org/package/key
# @see http://opensource.org/licenses/mit-license.php MIT License
# Dependencies
{ref} = require '../ref'
# Definitions
brand = {
apple: ref 'Apple ⌘', 224
windows: {
start: ref 'Windows start', [91, 92]
menu: ref 'Windows menu', 93
}
}
# Exports
module.exports = brand
| 71550 | 'use strict'
# Key
#
# @copyright <NAME> 2012
# @see http://github.com/adlawson/key
# @see http://npmjs.org/package/key
# @see http://opensource.org/licenses/mit-license.php MIT License
# Dependencies
{ref} = require '../ref'
# Definitions
brand = {
apple: ref 'Apple ⌘', 224
windows: {
start: ref 'Windows start', [91, 92]
menu: ref 'Windows menu', 93
}
}
# Exports
module.exports = brand
| true | 'use strict'
# Key
#
# @copyright PI:NAME:<NAME>END_PI 2012
# @see http://github.com/adlawson/key
# @see http://npmjs.org/package/key
# @see http://opensource.org/licenses/mit-license.php MIT License
# Dependencies
{ref} = require '../ref'
# Definitions
brand = {
apple: ref 'Apple ⌘', 224
windows: {
start: ref 'Windows start', [91, 92]
menu: ref 'Windows menu', 93
}
}
# Exports
module.exports = brand
|
[
{
"context": " body: '{\\n \"type\": \"bulldozer\",\\n \"name\": \"willy\"}\\n'\n headers:\n 'Content-Type",
"end": 4238,
"score": 0.9894127249717712,
"start": 4233,
"tag": "NAME",
"value": "willy"
},
{
"context": " body: '{\\n \"type\": \"bulldozer\",\... | test/unit/transaction-runner-test.coffee | HBOCodeLabs/dredd | 0 | require 'coffee-errors'
{EventEmitter} = require 'events'
{assert} = require 'chai'
nock = require 'nock'
proxyquire = require 'proxyquire'
sinon = require 'sinon'
htmlStub = require 'html'
advisableStub = require 'advisable'
addHooksStub = sinon.spy require '../../src/add-hooks'
loggerStub = require '../../src/logger'
httpStub = require 'http'
httpsStub = require 'https'
Runner = proxyquire '../../src/transaction-runner', {
'html': htmlStub,
'advisable': advisableStub,
'./add-hooks': addHooksStub
'./logger': loggerStub
'http': httpStub
'https': httpsStub
}
CliReporter = require '../../src/reporters/cli-reporter'
describe 'TransactionRunner', ()->
server = {}
configuration =
server: 'http://localhost:3000'
emitter: new EventEmitter()
options:
'dry-run': false
method: []
header: []
reporter: []
transaction = {}
runner = {}
before () ->
loggerStub.transports.console.silent = true
after () ->
loggerStub.transports.console.silent = false
describe 'constructor', () ->
beforeEach () ->
sinon.spy advisableStub.async, 'call'
runner = new Runner(configuration)
afterEach () ->
sinon.spy advisableStub.async.call.restore()
it 'should copy configuration', () ->
assert.ok runner.configuration.server
it 'should add advice', () ->
assert.ok advisableStub.async.call.called
it 'should add hooks', () ->
assert.ok addHooksStub.called
describe 'configureTransaction(transaction, callback)', () ->
beforeEach () ->
transaction =
request:
body: "{\n \"type\": \"bulldozer\",\n \"name\": \"willy\"}\n"
headers:
"Content-Type":
value: "application/json"
uri: "/machines",
method: "POST"
response:
body: "{\n \"type\": \"bulldozer\",\n \"name\": \"willy\",\n \"id\": \"5229c6e8e4b0bd7dbb07e29c\"\n}\n"
headers:
"content-type":
value: "application/json"
status: "202"
origin:
resourceGroupName: "Group Machine"
resourceName: "Machine"
actionName: "Delete Message"
exampleName: "Bogus example name"
runner = new Runner(configuration)
describe 'when request does not have User-Agent', () ->
it 'should add the Dredd User-Agent', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.ok configuredTransaction.request.headers['User-Agent']
done()
describe 'when no Content-Length is present', () ->
it 'should add a Content-Length header', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.ok configuredTransaction.request.headers['Content-Length']
done()
describe 'when Content-Length header is present', () ->
beforeEach () ->
transaction.headers =
"Content-Length":
value: 44
it 'should not add a Content-Length header', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.equal configuredTransaction.request.headers['Content-Length'], 44
done()
describe 'when configuring a transaction', () ->
it 'should callback with a properly configured transaction', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.equal configuredTransaction.name, 'Group Machine > Machine > Delete Message > Bogus example name'
assert.equal configuredTransaction.id, 'POST /machines'
assert.ok configuredTransaction.host
assert.ok configuredTransaction.request
assert.ok configuredTransaction.expected
assert.strictEqual transaction.origin, configuredTransaction.origin
done()
describe 'executeTransaction(transaction, callback)', () ->
beforeEach () ->
transaction =
name: 'Group Machine > Machine > Delete Message > Bogus example name'
id: 'POST /machines'
host: 'localhost'
port: '3000'
request:
body: '{\n "type": "bulldozer",\n "name": "willy"}\n'
headers:
'Content-Type': 'application/json'
'User-Agent': 'Dredd/0.2.1 (Darwin 13.0.0; x64)'
'Content-Length': 44
uri: '/machines'
method: 'POST'
expected:
headers: 'content-type': 'application/json'
body: '{\n "type": "bulldozer",\n "name": "willy",\n "id": "5229c6e8e4b0bd7dbb07e29c"\n}\n'
status: '202'
origin:
resourceGroupName: 'Group Machine'
resourceName: 'Machine'
actionName: 'Delete Message'
exampleName: 'Bogus example name'
fullPath: '/machines'
protocol: 'http:'
describe 'when printing the names', () ->
beforeEach () ->
sinon.spy loggerStub, 'info'
configuration.options['names'] = true
runner = new Runner(configuration)
afterEach () ->
loggerStub.info.restore()
configuration.options['names'] = false
it 'should print the names and return', (done) ->
runner.executeTransaction transaction, () ->
assert.ok loggerStub.info.called
done()
describe 'when a dry run', () ->
beforeEach () ->
configuration.options['dry-run'] = true
runner = new Runner(configuration)
sinon.stub httpStub, 'request'
afterEach () ->
configuration.options['dry-run'] = false
httpStub.request.restore()
it 'should skip the tests', (done) ->
runner.executeTransaction transaction, () ->
assert.ok httpStub.request.notCalled
done()
describe 'when only certain methods are allowed by the configuration', () ->
beforeEach () ->
configuration.options['method'] = ['GET']
sinon.stub configuration.emitter, 'emit'
runner = new Runner(configuration)
afterEach () ->
configuration.emitter.emit.restore()
configuration.options['method'] = []
it 'should only perform those requests', (done) ->
runner.executeTransaction transaction, () ->
assert.ok configuration.emitter.emit.calledWith 'test skip'
done()
describe 'when a test has been manually set to skip in a hook', () ->
beforeEach () ->
sinon.stub configuration.emitter, 'emit'
runner = new Runner(configuration)
afterEach () ->
configuration.emitter.emit.restore()
it 'should skip the test', (done) ->
transaction.skip = true
runner.executeTransaction transaction, () ->
assert.ok configuration.emitter.emit.calledWith 'test skip'
done()
describe 'when server uses https', () ->
beforeEach () ->
server = nock('https://localhost:3000').
post('/machines', {"type":"bulldozer","name":"willy"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
configuration.server = 'https://localhost:3000'
transaction.protocol = 'https:'
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should make the request with https', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
describe 'when server uses http', () ->
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"willy"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
configuration.server = 'http://localhost:3000'
transaction.protocol = 'http:'
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should make the request with http', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
describe 'when backend responds as it should', () ->
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"willy"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should perform the request', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
it 'should not return an error', (done) ->
runner.executeTransaction transaction, (error) ->
assert.notOk error
done()
describe 'when backend responds with invalid response', () ->
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"willy"}).
reply 400,
'Foo bar',
{'Content-Type': 'text/plain'}
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should perform the request', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
| 104033 | require 'coffee-errors'
{EventEmitter} = require 'events'
{assert} = require 'chai'
nock = require 'nock'
proxyquire = require 'proxyquire'
sinon = require 'sinon'
htmlStub = require 'html'
advisableStub = require 'advisable'
addHooksStub = sinon.spy require '../../src/add-hooks'
loggerStub = require '../../src/logger'
httpStub = require 'http'
httpsStub = require 'https'
Runner = proxyquire '../../src/transaction-runner', {
'html': htmlStub,
'advisable': advisableStub,
'./add-hooks': addHooksStub
'./logger': loggerStub
'http': httpStub
'https': httpsStub
}
CliReporter = require '../../src/reporters/cli-reporter'
describe 'TransactionRunner', ()->
server = {}
configuration =
server: 'http://localhost:3000'
emitter: new EventEmitter()
options:
'dry-run': false
method: []
header: []
reporter: []
transaction = {}
runner = {}
before () ->
loggerStub.transports.console.silent = true
after () ->
loggerStub.transports.console.silent = false
describe 'constructor', () ->
beforeEach () ->
sinon.spy advisableStub.async, 'call'
runner = new Runner(configuration)
afterEach () ->
sinon.spy advisableStub.async.call.restore()
it 'should copy configuration', () ->
assert.ok runner.configuration.server
it 'should add advice', () ->
assert.ok advisableStub.async.call.called
it 'should add hooks', () ->
assert.ok addHooksStub.called
describe 'configureTransaction(transaction, callback)', () ->
beforeEach () ->
transaction =
request:
body: "{\n \"type\": \"bulldozer\",\n \"name\": \"willy\"}\n"
headers:
"Content-Type":
value: "application/json"
uri: "/machines",
method: "POST"
response:
body: "{\n \"type\": \"bulldozer\",\n \"name\": \"willy\",\n \"id\": \"5229c6e8e4b0bd7dbb07e29c\"\n}\n"
headers:
"content-type":
value: "application/json"
status: "202"
origin:
resourceGroupName: "Group Machine"
resourceName: "Machine"
actionName: "Delete Message"
exampleName: "Bogus example name"
runner = new Runner(configuration)
describe 'when request does not have User-Agent', () ->
it 'should add the Dredd User-Agent', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.ok configuredTransaction.request.headers['User-Agent']
done()
describe 'when no Content-Length is present', () ->
it 'should add a Content-Length header', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.ok configuredTransaction.request.headers['Content-Length']
done()
describe 'when Content-Length header is present', () ->
beforeEach () ->
transaction.headers =
"Content-Length":
value: 44
it 'should not add a Content-Length header', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.equal configuredTransaction.request.headers['Content-Length'], 44
done()
describe 'when configuring a transaction', () ->
it 'should callback with a properly configured transaction', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.equal configuredTransaction.name, 'Group Machine > Machine > Delete Message > Bogus example name'
assert.equal configuredTransaction.id, 'POST /machines'
assert.ok configuredTransaction.host
assert.ok configuredTransaction.request
assert.ok configuredTransaction.expected
assert.strictEqual transaction.origin, configuredTransaction.origin
done()
describe 'executeTransaction(transaction, callback)', () ->
beforeEach () ->
transaction =
name: 'Group Machine > Machine > Delete Message > Bogus example name'
id: 'POST /machines'
host: 'localhost'
port: '3000'
request:
body: '{\n "type": "bulldozer",\n "name": "<NAME>"}\n'
headers:
'Content-Type': 'application/json'
'User-Agent': 'Dredd/0.2.1 (Darwin 13.0.0; x64)'
'Content-Length': 44
uri: '/machines'
method: 'POST'
expected:
headers: 'content-type': 'application/json'
body: '{\n "type": "bulldozer",\n "name": "<NAME>",\n "id": "5229c6e8e4b0bd7dbb07e29c"\n}\n'
status: '202'
origin:
resourceGroupName: 'Group Machine'
resourceName: 'Machine'
actionName: 'Delete Message'
exampleName: 'Bogus example name'
fullPath: '/machines'
protocol: 'http:'
describe 'when printing the names', () ->
beforeEach () ->
sinon.spy loggerStub, 'info'
configuration.options['names'] = true
runner = new Runner(configuration)
afterEach () ->
loggerStub.info.restore()
configuration.options['names'] = false
it 'should print the names and return', (done) ->
runner.executeTransaction transaction, () ->
assert.ok loggerStub.info.called
done()
describe 'when a dry run', () ->
beforeEach () ->
configuration.options['dry-run'] = true
runner = new Runner(configuration)
sinon.stub httpStub, 'request'
afterEach () ->
configuration.options['dry-run'] = false
httpStub.request.restore()
it 'should skip the tests', (done) ->
runner.executeTransaction transaction, () ->
assert.ok httpStub.request.notCalled
done()
describe 'when only certain methods are allowed by the configuration', () ->
beforeEach () ->
configuration.options['method'] = ['GET']
sinon.stub configuration.emitter, 'emit'
runner = new Runner(configuration)
afterEach () ->
configuration.emitter.emit.restore()
configuration.options['method'] = []
it 'should only perform those requests', (done) ->
runner.executeTransaction transaction, () ->
assert.ok configuration.emitter.emit.calledWith 'test skip'
done()
describe 'when a test has been manually set to skip in a hook', () ->
beforeEach () ->
sinon.stub configuration.emitter, 'emit'
runner = new Runner(configuration)
afterEach () ->
configuration.emitter.emit.restore()
it 'should skip the test', (done) ->
transaction.skip = true
runner.executeTransaction transaction, () ->
assert.ok configuration.emitter.emit.calledWith 'test skip'
done()
describe 'when server uses https', () ->
beforeEach () ->
server = nock('https://localhost:3000').
post('/machines', {"type":"bulldozer","name":"<NAME>"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
configuration.server = 'https://localhost:3000'
transaction.protocol = 'https:'
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should make the request with https', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
describe 'when server uses http', () ->
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"<NAME>"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
configuration.server = 'http://localhost:3000'
transaction.protocol = 'http:'
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should make the request with http', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
describe 'when backend responds as it should', () ->
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"<NAME>"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should perform the request', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
it 'should not return an error', (done) ->
runner.executeTransaction transaction, (error) ->
assert.notOk error
done()
describe 'when backend responds with invalid response', () ->
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"<NAME>"}).
reply 400,
'Foo bar',
{'Content-Type': 'text/plain'}
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should perform the request', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
| true | require 'coffee-errors'
{EventEmitter} = require 'events'
{assert} = require 'chai'
nock = require 'nock'
proxyquire = require 'proxyquire'
sinon = require 'sinon'
htmlStub = require 'html'
advisableStub = require 'advisable'
addHooksStub = sinon.spy require '../../src/add-hooks'
loggerStub = require '../../src/logger'
httpStub = require 'http'
httpsStub = require 'https'
Runner = proxyquire '../../src/transaction-runner', {
'html': htmlStub,
'advisable': advisableStub,
'./add-hooks': addHooksStub
'./logger': loggerStub
'http': httpStub
'https': httpsStub
}
CliReporter = require '../../src/reporters/cli-reporter'
describe 'TransactionRunner', ()->
server = {}
configuration =
server: 'http://localhost:3000'
emitter: new EventEmitter()
options:
'dry-run': false
method: []
header: []
reporter: []
transaction = {}
runner = {}
before () ->
loggerStub.transports.console.silent = true
after () ->
loggerStub.transports.console.silent = false
describe 'constructor', () ->
beforeEach () ->
sinon.spy advisableStub.async, 'call'
runner = new Runner(configuration)
afterEach () ->
sinon.spy advisableStub.async.call.restore()
it 'should copy configuration', () ->
assert.ok runner.configuration.server
it 'should add advice', () ->
assert.ok advisableStub.async.call.called
it 'should add hooks', () ->
assert.ok addHooksStub.called
describe 'configureTransaction(transaction, callback)', () ->
beforeEach () ->
transaction =
request:
body: "{\n \"type\": \"bulldozer\",\n \"name\": \"willy\"}\n"
headers:
"Content-Type":
value: "application/json"
uri: "/machines",
method: "POST"
response:
body: "{\n \"type\": \"bulldozer\",\n \"name\": \"willy\",\n \"id\": \"5229c6e8e4b0bd7dbb07e29c\"\n}\n"
headers:
"content-type":
value: "application/json"
status: "202"
origin:
resourceGroupName: "Group Machine"
resourceName: "Machine"
actionName: "Delete Message"
exampleName: "Bogus example name"
runner = new Runner(configuration)
describe 'when request does not have User-Agent', () ->
it 'should add the Dredd User-Agent', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.ok configuredTransaction.request.headers['User-Agent']
done()
describe 'when no Content-Length is present', () ->
it 'should add a Content-Length header', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.ok configuredTransaction.request.headers['Content-Length']
done()
describe 'when Content-Length header is present', () ->
beforeEach () ->
transaction.headers =
"Content-Length":
value: 44
it 'should not add a Content-Length header', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.equal configuredTransaction.request.headers['Content-Length'], 44
done()
describe 'when configuring a transaction', () ->
it 'should callback with a properly configured transaction', (done) ->
runner.configureTransaction transaction, (err, configuredTransaction) ->
assert.equal configuredTransaction.name, 'Group Machine > Machine > Delete Message > Bogus example name'
assert.equal configuredTransaction.id, 'POST /machines'
assert.ok configuredTransaction.host
assert.ok configuredTransaction.request
assert.ok configuredTransaction.expected
assert.strictEqual transaction.origin, configuredTransaction.origin
done()
describe 'executeTransaction(transaction, callback)', () ->
beforeEach () ->
transaction =
name: 'Group Machine > Machine > Delete Message > Bogus example name'
id: 'POST /machines'
host: 'localhost'
port: '3000'
request:
body: '{\n "type": "bulldozer",\n "name": "PI:NAME:<NAME>END_PI"}\n'
headers:
'Content-Type': 'application/json'
'User-Agent': 'Dredd/0.2.1 (Darwin 13.0.0; x64)'
'Content-Length': 44
uri: '/machines'
method: 'POST'
expected:
headers: 'content-type': 'application/json'
body: '{\n "type": "bulldozer",\n "name": "PI:NAME:<NAME>END_PI",\n "id": "5229c6e8e4b0bd7dbb07e29c"\n}\n'
status: '202'
origin:
resourceGroupName: 'Group Machine'
resourceName: 'Machine'
actionName: 'Delete Message'
exampleName: 'Bogus example name'
fullPath: '/machines'
protocol: 'http:'
describe 'when printing the names', () ->
beforeEach () ->
sinon.spy loggerStub, 'info'
configuration.options['names'] = true
runner = new Runner(configuration)
afterEach () ->
loggerStub.info.restore()
configuration.options['names'] = false
it 'should print the names and return', (done) ->
runner.executeTransaction transaction, () ->
assert.ok loggerStub.info.called
done()
describe 'when a dry run', () ->
beforeEach () ->
configuration.options['dry-run'] = true
runner = new Runner(configuration)
sinon.stub httpStub, 'request'
afterEach () ->
configuration.options['dry-run'] = false
httpStub.request.restore()
it 'should skip the tests', (done) ->
runner.executeTransaction transaction, () ->
assert.ok httpStub.request.notCalled
done()
describe 'when only certain methods are allowed by the configuration', () ->
beforeEach () ->
configuration.options['method'] = ['GET']
sinon.stub configuration.emitter, 'emit'
runner = new Runner(configuration)
afterEach () ->
configuration.emitter.emit.restore()
configuration.options['method'] = []
it 'should only perform those requests', (done) ->
runner.executeTransaction transaction, () ->
assert.ok configuration.emitter.emit.calledWith 'test skip'
done()
describe 'when a test has been manually set to skip in a hook', () ->
beforeEach () ->
sinon.stub configuration.emitter, 'emit'
runner = new Runner(configuration)
afterEach () ->
configuration.emitter.emit.restore()
it 'should skip the test', (done) ->
transaction.skip = true
runner.executeTransaction transaction, () ->
assert.ok configuration.emitter.emit.calledWith 'test skip'
done()
describe 'when server uses https', () ->
beforeEach () ->
server = nock('https://localhost:3000').
post('/machines', {"type":"bulldozer","name":"PI:NAME:<NAME>END_PI"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
configuration.server = 'https://localhost:3000'
transaction.protocol = 'https:'
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should make the request with https', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
describe 'when server uses http', () ->
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"PI:NAME:<NAME>END_PI"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
configuration.server = 'http://localhost:3000'
transaction.protocol = 'http:'
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should make the request with http', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
describe 'when backend responds as it should', () ->
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"PI:NAME:<NAME>END_PI"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should perform the request', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
it 'should not return an error', (done) ->
runner.executeTransaction transaction, (error) ->
assert.notOk error
done()
describe 'when backend responds with invalid response', () ->
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"PI:NAME:<NAME>END_PI"}).
reply 400,
'Foo bar',
{'Content-Type': 'text/plain'}
runner = new Runner(configuration)
afterEach () ->
nock.cleanAll()
it 'should perform the request', (done) ->
runner.executeTransaction transaction, () ->
assert.ok server.isDone()
done()
|
[
{
"context": "{ 'Content-Type': 'application/json' }, '{\"name\":\"Batman\"}' ]\n\ndescribe 'set respond with', ->\n beforeEac",
"end": 1811,
"score": 0.9998002052307129,
"start": 1805,
"tag": "NAME",
"value": "Batman"
}
] | tests/specs/set-respond-with.spec.coffee | appirio-tech/swagger-fake-server | 0 | 'use strict'
api =
host : 'api.uber.com'
basePath: '/v1'
schemes : ['https', 'http']
paths:
'/player':
get:
responses:
'200':
schema:
type: 'object',
items:
'$ref' : '#/definitions/Player'
'/players':
get:
responses:
'200':
schema:
type: 'array',
items:
'$ref' : '#/definitions/Player'
post:
responses:
'200':
schema:
type: 'object',
items:
'$ref' : '#/definitions/Player'
'/players/{id}':
put:
responses:
'204':
schema: null
'/players/{player_id}/comments/{comment_id}':
get:
responses:
'200':
schema:
type: 'array',
items:
'$ref' : '#/definitions/Player'
definitions:
Player:
properties:
name:
type: 'string'
sample: 'Batman'
setSwaggerResponse = AutoConfigFakeServerPrivates.setSwaggerResponse
fakeServer = null
httpPutRegex = new RegExp('http://api.uber.com/v1/players/' + '([a-zA-Z0-9_\\-\\.]+)' + '(\\?(.)*)?$')
httpUrlRegex = new RegExp('http://api.uber.com/v1/players' + '(\\?(.)*)?$')
httpsUrlRegex = new RegExp('https://api.uber.com/v1/players' + '(\\?(.)*)?$')
inpathUrlRegex = new RegExp('https://api.uber.com/v1/players/' + '([a-zA-Z0-9_\\-\\.]+)' + '/comments/' + '([a-zA-Z0-9_\\-\\.]+)' + '(\\?(.)*)?$')
response = [ 200, { 'Content-Type': 'application/json' }, '[{"name":"Batman"},{"name":"Batman"},{"name":"Batman"},{"name":"Batman"},{"name":"Batman"},{"name":"Batman"}]' ]
postResponse = [ 200, { 'Content-Type': 'application/json' }, '{"name":"Batman"}' ]
describe 'set respond with', ->
beforeEach ->
fakeServer =
respondWith: sinon.spy()
setSwaggerResponse fakeServer, api
it 'should call respondWith 6 times', ->
expect(fakeServer.respondWith.callCount).to.be.equal 10
it 'should match http get arguments', ->
calledWith = fakeServer.respondWith.calledWith 'get', httpUrlRegex, response
expect(calledWith).to.be.ok
it 'should match https get arguments', ->
calledWith = fakeServer.respondWith.calledWith 'get', httpsUrlRegex, response
expect(calledWith).to.be.ok
it 'should match http post arguments', ->
calledWith = fakeServer.respondWith.calledWith 'post', httpUrlRegex, postResponse
expect(calledWith).to.be.ok
it 'should match in path arguments', ->
calledWith = fakeServer.respondWith.calledWith 'get', inpathUrlRegex, response
expect(calledWith).to.be.ok
it 'should match http put 204 arguments', ->
calledWith = fakeServer.respondWith.calledWith 'put', httpPutRegex, ''
expect(calledWith).to.be.ok
| 202063 | 'use strict'
api =
host : 'api.uber.com'
basePath: '/v1'
schemes : ['https', 'http']
paths:
'/player':
get:
responses:
'200':
schema:
type: 'object',
items:
'$ref' : '#/definitions/Player'
'/players':
get:
responses:
'200':
schema:
type: 'array',
items:
'$ref' : '#/definitions/Player'
post:
responses:
'200':
schema:
type: 'object',
items:
'$ref' : '#/definitions/Player'
'/players/{id}':
put:
responses:
'204':
schema: null
'/players/{player_id}/comments/{comment_id}':
get:
responses:
'200':
schema:
type: 'array',
items:
'$ref' : '#/definitions/Player'
definitions:
Player:
properties:
name:
type: 'string'
sample: 'Batman'
setSwaggerResponse = AutoConfigFakeServerPrivates.setSwaggerResponse
fakeServer = null
httpPutRegex = new RegExp('http://api.uber.com/v1/players/' + '([a-zA-Z0-9_\\-\\.]+)' + '(\\?(.)*)?$')
httpUrlRegex = new RegExp('http://api.uber.com/v1/players' + '(\\?(.)*)?$')
httpsUrlRegex = new RegExp('https://api.uber.com/v1/players' + '(\\?(.)*)?$')
inpathUrlRegex = new RegExp('https://api.uber.com/v1/players/' + '([a-zA-Z0-9_\\-\\.]+)' + '/comments/' + '([a-zA-Z0-9_\\-\\.]+)' + '(\\?(.)*)?$')
response = [ 200, { 'Content-Type': 'application/json' }, '[{"name":"Batman"},{"name":"Batman"},{"name":"Batman"},{"name":"Batman"},{"name":"Batman"},{"name":"Batman"}]' ]
postResponse = [ 200, { 'Content-Type': 'application/json' }, '{"name":"<NAME>"}' ]
describe 'set respond with', ->
beforeEach ->
fakeServer =
respondWith: sinon.spy()
setSwaggerResponse fakeServer, api
it 'should call respondWith 6 times', ->
expect(fakeServer.respondWith.callCount).to.be.equal 10
it 'should match http get arguments', ->
calledWith = fakeServer.respondWith.calledWith 'get', httpUrlRegex, response
expect(calledWith).to.be.ok
it 'should match https get arguments', ->
calledWith = fakeServer.respondWith.calledWith 'get', httpsUrlRegex, response
expect(calledWith).to.be.ok
it 'should match http post arguments', ->
calledWith = fakeServer.respondWith.calledWith 'post', httpUrlRegex, postResponse
expect(calledWith).to.be.ok
it 'should match in path arguments', ->
calledWith = fakeServer.respondWith.calledWith 'get', inpathUrlRegex, response
expect(calledWith).to.be.ok
it 'should match http put 204 arguments', ->
calledWith = fakeServer.respondWith.calledWith 'put', httpPutRegex, ''
expect(calledWith).to.be.ok
| true | 'use strict'
api =
host : 'api.uber.com'
basePath: '/v1'
schemes : ['https', 'http']
paths:
'/player':
get:
responses:
'200':
schema:
type: 'object',
items:
'$ref' : '#/definitions/Player'
'/players':
get:
responses:
'200':
schema:
type: 'array',
items:
'$ref' : '#/definitions/Player'
post:
responses:
'200':
schema:
type: 'object',
items:
'$ref' : '#/definitions/Player'
'/players/{id}':
put:
responses:
'204':
schema: null
'/players/{player_id}/comments/{comment_id}':
get:
responses:
'200':
schema:
type: 'array',
items:
'$ref' : '#/definitions/Player'
definitions:
Player:
properties:
name:
type: 'string'
sample: 'Batman'
setSwaggerResponse = AutoConfigFakeServerPrivates.setSwaggerResponse
fakeServer = null
httpPutRegex = new RegExp('http://api.uber.com/v1/players/' + '([a-zA-Z0-9_\\-\\.]+)' + '(\\?(.)*)?$')
httpUrlRegex = new RegExp('http://api.uber.com/v1/players' + '(\\?(.)*)?$')
httpsUrlRegex = new RegExp('https://api.uber.com/v1/players' + '(\\?(.)*)?$')
inpathUrlRegex = new RegExp('https://api.uber.com/v1/players/' + '([a-zA-Z0-9_\\-\\.]+)' + '/comments/' + '([a-zA-Z0-9_\\-\\.]+)' + '(\\?(.)*)?$')
response = [ 200, { 'Content-Type': 'application/json' }, '[{"name":"Batman"},{"name":"Batman"},{"name":"Batman"},{"name":"Batman"},{"name":"Batman"},{"name":"Batman"}]' ]
postResponse = [ 200, { 'Content-Type': 'application/json' }, '{"name":"PI:NAME:<NAME>END_PI"}' ]
describe 'set respond with', ->
beforeEach ->
fakeServer =
respondWith: sinon.spy()
setSwaggerResponse fakeServer, api
it 'should call respondWith 6 times', ->
expect(fakeServer.respondWith.callCount).to.be.equal 10
it 'should match http get arguments', ->
calledWith = fakeServer.respondWith.calledWith 'get', httpUrlRegex, response
expect(calledWith).to.be.ok
it 'should match https get arguments', ->
calledWith = fakeServer.respondWith.calledWith 'get', httpsUrlRegex, response
expect(calledWith).to.be.ok
it 'should match http post arguments', ->
calledWith = fakeServer.respondWith.calledWith 'post', httpUrlRegex, postResponse
expect(calledWith).to.be.ok
it 'should match in path arguments', ->
calledWith = fakeServer.respondWith.calledWith 'get', inpathUrlRegex, response
expect(calledWith).to.be.ok
it 'should match http put 204 arguments', ->
calledWith = fakeServer.respondWith.calledWith 'put', httpPutRegex, ''
expect(calledWith).to.be.ok
|
[
{
"context": "must be at least 3 characters'\n password: 'must be present'\n\n assert.calledWith(form.username.$setValid",
"end": 642,
"score": 0.99920654296875,
"start": 627,
"tag": "PASSWORD",
"value": "must be present"
},
{
"context": "must be at least 3 characters'\n ... | tests/js/util-test.coffee | Treora/h | 0 | assert = chai.assert
sinon.assert.expose(assert, prefix: '')
describe 'h.helpers.formHelpers', ->
formHelpers = null
beforeEach module('h.helpers')
beforeEach inject (_formHelpers_) ->
formHelpers = _formHelpers_
describe '.applyValidationErrors', ->
form = null
beforeEach ->
form =
$setValidity: sinon.spy()
username: {$setValidity: sinon.spy()}
password: {$setValidity: sinon.spy()}
it 'sets the "response" error key for each field with errors', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: 'must be present'
assert.calledWith(form.username.$setValidity, 'response', false)
assert.calledWith(form.password.$setValidity, 'response', false)
it 'adds an error message to each input controller', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: 'must be present'
assert.equal(form.username.responseErrorMessage, 'must be at least 3 characters')
assert.equal(form.password.responseErrorMessage, 'must be present')
it 'sets the "response" error key if the form has a failure reason', ->
formHelpers.applyValidationErrors form, null, 'fail'
assert.calledWith(form.$setValidity, 'response', false)
it 'adds an reason message as the response error', ->
formHelpers.applyValidationErrors form, null, 'fail'
assert.equal(form.responseErrorMessage, 'fail')
| 49861 | assert = chai.assert
sinon.assert.expose(assert, prefix: '')
describe 'h.helpers.formHelpers', ->
formHelpers = null
beforeEach module('h.helpers')
beforeEach inject (_formHelpers_) ->
formHelpers = _formHelpers_
describe '.applyValidationErrors', ->
form = null
beforeEach ->
form =
$setValidity: sinon.spy()
username: {$setValidity: sinon.spy()}
password: {$setValidity: sinon.spy()}
it 'sets the "response" error key for each field with errors', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: '<PASSWORD>'
assert.calledWith(form.username.$setValidity, 'response', false)
assert.calledWith(form.password.$setValidity, 'response', false)
it 'adds an error message to each input controller', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: '<PASSWORD>'
assert.equal(form.username.responseErrorMessage, 'must be at least 3 characters')
assert.equal(form.password.responseErrorMessage, 'must be present')
it 'sets the "response" error key if the form has a failure reason', ->
formHelpers.applyValidationErrors form, null, 'fail'
assert.calledWith(form.$setValidity, 'response', false)
it 'adds an reason message as the response error', ->
formHelpers.applyValidationErrors form, null, 'fail'
assert.equal(form.responseErrorMessage, 'fail')
| true | assert = chai.assert
sinon.assert.expose(assert, prefix: '')
describe 'h.helpers.formHelpers', ->
formHelpers = null
beforeEach module('h.helpers')
beforeEach inject (_formHelpers_) ->
formHelpers = _formHelpers_
describe '.applyValidationErrors', ->
form = null
beforeEach ->
form =
$setValidity: sinon.spy()
username: {$setValidity: sinon.spy()}
password: {$setValidity: sinon.spy()}
it 'sets the "response" error key for each field with errors', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
assert.calledWith(form.username.$setValidity, 'response', false)
assert.calledWith(form.password.$setValidity, 'response', false)
it 'adds an error message to each input controller', ->
formHelpers.applyValidationErrors form,
username: 'must be at least 3 characters'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
assert.equal(form.username.responseErrorMessage, 'must be at least 3 characters')
assert.equal(form.password.responseErrorMessage, 'must be present')
it 'sets the "response" error key if the form has a failure reason', ->
formHelpers.applyValidationErrors form, null, 'fail'
assert.calledWith(form.$setValidity, 'response', false)
it 'adds an reason message as the response error', ->
formHelpers.applyValidationErrors form, null, 'fail'
assert.equal(form.responseErrorMessage, 'fail')
|
[
{
"context": "(涉及帖子操作时,为帖子Owner)'\n },\n {\n key:'userName',\n title:'用户昵称'\n },\n {\n k",
"end": 2100,
"score": 0.9261019229888916,
"start": 2092,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " title: '操作类型'\n },\n {\... | hotShareWeb/server/4_router_server.coffee | Ritesh1991/mobile_app_server | 0 | subs = new SubsManager({
#maximum number of cache subscriptions
cacheLimit: 999,
# any subscription will be expire after 30 days, if it's not subscribed again
expireIn: 60*24*30
});
if Meteor.isServer
request = Meteor.npmRequire('request')
Fiber = Meteor.npmRequire('fibers')
QRImage = Meteor.npmRequire('qr-image')
###
Router.route '/posts/:_id', {
waitOn: ->
[subs.subscribe("publicPosts",this.params._id),
subs.subscribe "pcomments"]
fastRender: true
}
###
injectSignData = (req,res)->
try
console.log(req.url)
if req.url
signature=generateSignature('http://'+server_domain_name+req.url)
if signature
console.log(signature)
InjectData.pushData(res, "wechatsign", signature);
catch error
return null
# 获取对应时区的时间
getLocalTimeByOffset = (i)->
if typeof i isnt 'number'
return
d = new Date()
len = d.getTime()
offset = d.getTimezoneOffset() * 60000
utcTime = len + offset
return new Date(utcTime + 3600000 * i)
Router.configure {
waitOn: ()->
if this and this.path
path=this.path
if path.indexOf('/posts/') is 0
if path.indexOf('?') > 0
path = path.split('?')[0]
params=path.replace('/posts/','')
params=params.split('/')
if params.length > 0
return [subs.subscribe("publicPosts",params[0]),
subs.subscribe("postsAuthor",params[0]),
subs.subscribe "pcomments"]
fastRender: true
}
Router.route('/download-reporter-logs', (req, res, next)->
data = reporterLogs.find({},{sort:{createdAt:-1}}).fetch()
fields = [
{
key:'postId',
title:'帖子Id',
},
{
key:'postTitle',
title:'帖子标题',
},
{
key:'postCreatedAt',
title:'帖子创建时间',
transform: (val, doc)->
d = new Date(val)
return d.toLocaleString()
},
{
key: 'userId',
title: '用户Id(涉及帖子操作时,为帖子Owner)'
},
{
key:'userName',
title:'用户昵称'
},
{
key:'userEmails',
title:'用户Email',
transform: (val, doc)->
emails = ''
if val and val isnt null
val.forEach (item)->
emails += item.address + '\r\n'
return emails;
},
{
key:'eventType',
title: '操作类型'
},
{
key:'loginUser',
title: '操作人员',
transform: (val, doc)->
user = Meteor.users.findOne({_id: val})
userInfo = '_id: '+val+'\r\n username: '+user.username
return userInfo
},
{
key: 'createdAt',
title: '操作时间',
transform: (val, doc)->
d = new Date(val)
return d.toLocaleString()
},
]
title = 'hotShareReporterLogs-'+ (new Date()).toLocaleDateString()
file = Excel.export(title, fields, data)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end(file, 'binary')
, { where: 'server' })
# Router.route('/apple-app-site-association', (req, res, next)->
# #name = 'apple-app-site-association'
# #name = 'import-server'
# fs = Npm.require("fs")
# path = Npm.require('path')
# base = path.resolve('.');
# filepath = path.resolve('.') + '/app/lib/apple-app-site-association';
# #filepath = path.join(__dirname,'../server/import-server.js')
# file = fs.readFileSync(filepath, 'binary');
# headers = {
# 'Content-type': 'application/vnd.openxmlformats',
# 'Content-Disposition': 'attachment; apple-app-site-association'
# }
# this.response.writeHead(200, headers)
# this.response.end(file, 'binary')
# , { where: 'server' })
if Meteor.isServer
workaiId = 'Lh4JcxG7CnmgR3YXe'
workaiName = 'Actiontec'
fomat_greeting_text = (time,time_offset)->
DateTimezone = (d, time_offset)->
if (time_offset == undefined)
if (d.getTimezoneOffset() == 420)
time_offset = -7
else
time_offset = 8
# 取得 UTC time
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
local_now = new Date(utc + (3600000*time_offset))
today_now = new Date(local_now.getFullYear(), local_now.getMonth(), local_now.getDate(),
local_now.getHours(), local_now.getMinutes());
return today_now;
self = time;
now = new Date();
result = '';
self = DateTimezone(time, time_offset);
# DayDiff = now.getDate() - self.getDate();
Minutes = self.getHours() * 60 + self.getMinutes();
# if (DayDiff === 0) {
# result += '今天 '
# } else if (DayDiff === 1) {
# result += '昨天 '
# } else {
# result += self.parseDate('YYYY-MM-DD') + ' ';
# }
if (Minutes >= 0 && Minutes < 360)
result += '凌晨 ';
if (Minutes >= 360 && Minutes < 660)
result += '上午 ';
if (Minutes >= 660 && Minutes < 780)
result += '中午 ';
if (Minutes >= 780 && Minutes < 960)
result += '下午 ';
if (Minutes >= 960 && Minutes < 1080)
result += '傍晚 ';
if (Minutes >= 1080 && Minutes < 1440)
result += '晚上 ';
result += self.parseDate('h:mm');
result = '您的上班时间是 ' + result;
return result;
@send_greeting_msg = (data)->
console.log 'try send_greeting_msg~ with data:'+JSON.stringify(data)
if !data || !data.images ||data.images.img_type isnt 'face'
#console.log 'invalid params'
return
if !data.in_out
device = Devices.findOne({uuid:data.people_uuid})
if !device || !device.in_out
#console.log ' not found device or in_device'
return
data.in_out = device.in_out
person = Person.findOne({group_id:data.group_id,'faces.id':data.images.id},{sort: {createAt: 1}})
if !person
console.log 'not find person with faceid is:'+data.images.id
return
relation = WorkAIUserRelations.findOne({'ai_persons.id':person._id})
create_time = new Date(data.create_time);
if !relation
#console.log 'not find workai user relations'
WorkAIUserRelations.insert({
group_id:data.group_id,
person_name:person.name,
in_uuid:data.people_uuid,
ai_in_time:create_time.getTime(),
ai_lastest_in_time:create_time.getTime(),
ai_in_image:data.images.url,
ai_lastest_in_image:data.images.url,
ai_persons: [
{
id : person._id
}
]
});
return
if data.in_out is 'out'
WorkAIUserRelations.update({_id:relation._id},{$set:{ai_out_time:create_time.getTime(), ai_out_image: data.images.url}});
return
WorkAIUserRelations.update({_id:relation._id},{$set:{ai_lastest_in_time:create_time.getTime(),ai_lastest_in_image:data.images.url}});#平板最新拍到的时间
#再次拍到进门需要把下班的提示移除
if relation.app_user_id
endlog = UserCheckoutEndLog.findOne({userId:relation.app_user_id});
if endlog
outtime = endlog.params.person_info.ts;
if outtime and PERSON.checkIsToday(outtime,data.group_id) and outtime < create_time.getTime()
UserCheckoutEndLog.remove({_id:endlog._id});
if relation.ai_in_time and PERSON.checkIsToday(relation.ai_in_time,data.group_id)
# ai_in_time = new Date(relation.ai_in_time);
# today = new Date(create_time.getFullYear(), create_time.getMonth(), create_time.getDate()).getTime(); #凌晨
# if ai_in_time.getTime() > today
console.log 'today greeting_msg had send'
#WorkAIUserRelations.update({_id:relation._id},{$set:{ai_in_time:create_time.getTime()}});
return
WorkAIUserRelations.update({_id:relation._id},{$set:{ai_in_time:create_time.getTime(), ai_in_image: data.images.url}});
if !relation.app_user_id
return
deviceUser = Meteor.users.findOne({username: data.people_uuid});
time_offset = 8;
group = SimpleChat.Groups.findOne({_id: data.group_id});
if (group && group.offsetTimeZone)
time_offset = group.offsetTimeZone;
sendMqttMessage('/msg/u/'+ relation.app_user_id, {
_id: new Mongo.ObjectID()._str
# form: {
# id: "fTnmgpdDN4hF9re8F",
# name: "workAI",
# icon: "http://data.tiegushi.com/fTnmgpdDN4hF9re8F_1493176458747.jpg"
# }
form:{
id: deviceUser._id,
name: deviceUser.profile.fullname,
icon: deviceUser.profile.icon
}
to: {
id: relation.app_user_id
name: relation.app_user_name
icon: ''
}
images: [data.images]
to_type: "user"
type: "text"
text: fomat_greeting_text(create_time,time_offset)
create_time: new Date()
checkin_time:create_time
is_agent_check:true
offsetTimeZone:time_offset
group_id:data.group_id
people_uuid: data.people_uuid
is_read: false
checkin_out:'in'
})
# 对data 进行处理, data 必须是数组
insertFaces = (face)->
device = Devices.findOne({uuid: face.uuid})
if device and device.name
face.device_name = device.name
face.createdAt = new Date()
Faces.insert(face)
insert_msg2 = (id, url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts,tracker_id,p_ids)->
#people = People.findOne({id: id, uuid: uuid})
name = null
#device = PERSON.upsetDevice(uuid, null)
create_time = new Date()
console.log("insert_msg2: img_ts="+img_ts+", current_ts="+current_ts+", create_time="+create_time)
###
if img_ts and current_ts
img_ts = Number(img_ts)
current_ts = Number(current_ts)
time_diff = img_ts + (create_time.getTime() - current_ts)
create_time = new Date(time_diff)
###
create_time = new Date()
if img_ts and current_ts
img_ts = Number(img_ts)
current_ts = Number(current_ts)
time_diff = img_ts + getTimeZoneDiffByMs(create_time.getTime(), current_ts)
create_time = new Date(time_diff)
#if !people
# people = {_id: new Mongo.ObjectID()._str, id: id, uuid: uuid,name: name,embed: null,local_url: null,aliyun_url: url}
# People.insert(people)
#else
# People.update({_id: people._id}, {$set: {aliyun_url: url}})
device = Devices.findOne({uuid: uuid})
PeopleHis.insert {id: id,uuid: uuid,name: name, people_id: id, embed: null,local_url: null,aliyun_url: url}, (err, _id)->
if err or !_id
return
user = Meteor.users.findOne({username: uuid})
unless user
return
userGroups = SimpleChat.GroupUsers.find({user_id: user._id})
unless userGroups
return
userGroups.forEach((userGroup)->
group = SimpleChat.Groups.findOne({_id:userGroup.group_id});
if group.template and group.template._id
if group.template.img_type != img_type
return
name = null
name = PERSON.getName(null, userGroup.group_id,id)
p_ids_name = [];
#存在可能性最大的三个人的id
# if p_ids and p_ids.length > 0
# for pid in p_ids
# person = Person.findOne({group_id:userGroup.group_id,'faces.id':pid},{sort:{createAt:1}});
# if person
# p_person = {
# name:person.name,
# id:pid,
# url:person.url,
# p_id:person._id
# }
# if(_.pluck(p_ids_name, 'p_id').indexOf(person._id) is -1)
# p_ids_name.push(p_person)
#没有准确度的人一定是没有识别出来的
name = if accuracy then name else null
#没有识别的人的准确度清0
Accuracy = if name then accuracy else false
Fuzziness = fuzziness
if true #name and checkIfSendRecoMsg(userGroup.group_id, uuid, id)
console.log('--------send reco msg to --------', uuid, '----', id, '----', name)
sendMqttMessage('/msg/g/'+ userGroup.group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
icon: user.profile.icon
}
to: {
id: userGroup.group_id
name: userGroup.group_name
icon: userGroup.group_icon
}
images: [
{_id: new Mongo.ObjectID()._str, id: id, people_his_id: _id, url: url, label: name, img_type: img_type, accuracy: Accuracy, fuzziness: Fuzziness, sqlid: sqlid, style: style,p_ids:p_ids_name} # 暂一次只能发一张图
]
to_type: "group"
type: "text"
text: if !name then 'Work AI发现有人在活动' else 'AI观察到 ' + name + ':'
create_time: create_time
people_id: id
people_uuid: uuid
people_his_id: _id
wait_lable: !name
is_people: true
is_read: false
tid:tracker_id
})
# update to DeviceTimeLine
timeObj = {
person_id: id,
person_name: name,
img_url: url,
sqlid: sqlid,
style: style,
accuracy: Accuracy, # 准确度(分数)
fuzziness: Fuzziness, # 模糊度
ts:create_time.getTime()
}
PERSON.updateToDeviceTimeline(uuid,userGroup.group_id,timeObj)
#识别准确度在0.85以上才自动打卡
#if name and accuracy >= withDefaultAccuracy
#if tablet recognizes this person, update it to mainpage.
if name
msg_data = {
group_id:userGroup.group_id,
create_time:create_time,
people_uuid:uuid,
in_out:userGroup.in_out,
images:{
id: id,
people_his_id: _id,
url: url,
label: name,
img_type: img_type,
accuracy: Accuracy,
fuzziness: Fuzziness,
sqlid: sqlid,
style: style
}
}
person = Person.findOne({group_id: userGroup.group_id, name: name}, {sort: {createAt: 1}});
person_info = null
if img_type == 'face' && person && person.faceId
#console.log('post person info to aixd.raidcdn')
person_info = {
'id': person._id,
'uuid': uuid,
'name': name,
'group_id': userGroup.group_id,
'img_url': url,
'type': img_type,
'ts': create_time.getTime(),
'accuracy': accuracy,
'fuzziness': fuzziness
}
relation = WorkAIUserRelations.findOne({'ai_persons.id': person._id})
if (device.in_out is 'in' and relation and relation.app_user_id)
wsts = WorkStatus.findOne({group_id: userGroup.group_id, app_user_id: relation.app_user_id}, {sort: {date: -1}})
if (wsts and !wsts.whats_up)
CreateSatsUpTipTask(relation.app_user_id, userGroup.group_id, device.uuid)
if (device.in_out is 'out' and relation and relation.app_user_id)
checkout_msg = {
userId: relation.app_user_id,
userName: relation.app_user_name,
createAt: new Date(),
params: {
msg_data: msg_data,
person: person,
person_info: person_info
}
}
# UserCheckoutEndLog.remove({userId: relation.app_user_id})
# UserCheckoutEndLog.insert(checkout_msg)
# sendUserCheckoutEvent(uuid, relation.app_user_id)
# return
# 到下班时间后,不终止后续处理
group_outtime = '18:00'
time_offset = 8
if (group and group.group_outtime)
group_outtime = group.group_outtime
if group and group.offsetTimeZone
time_offset = group.offsetTimeZone
group_outtime_H = parseInt(group_outtime.split(":")[0])
group_outtime_M = parseInt(group_outtime.split(":")[1])
group_out_minutes = group_outtime_H * 60 + group_outtime_M
out_time_H = parseInt(create_time.getUTCHours() + time_offset)
out_time_M = create_time.getMinutes()
out_time_minutes = out_time_H * 60 + out_time_M
# 到下班时间后,不自动 checkout(这里先取消, 目前:统一采用自动checkout的方式,但保留手动checkout)
# if (out_time_minutes < group_out_minutes)
# return
send_greeting_msg(msg_data);
PERSON.updateWorkStatus(person._id)
if person_info
PERSON.sendPersonInfoToWeb(person_info)
console.log("device.in_out", device, relation)
if ((device.name.includes('inout') or device.in_out is 'inout' or device.uuid is '28D6R17505001070') and relation)
Devices.update({_id: device._id}, {$set: {in_out:'inout'}});
console.log("activity_update_time")
activity_update_time(person._id, create_time, url)
)
@insert_msg2forTest = (id, url, uuid, accuracy, fuzziness)->
insert_msg2(id, url, uuid, 'face', accuracy, fuzziness, 0, 0)
# 平板 发现 某张图片为 错误识别(不涉及标记), 需要移除 或 修正 相应数据
padCallRemove = (id, url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts,tracker_id,p_ids)->
console.log("padCallRemove: id="+id+", url="+url+", uuid="+uuid+", img_type="+img_type+", accuracy="+accuracy+", fuzziness="+fuzziness+", sqlid="+sqlid+", style="+style+", img_ts="+img_ts+", current_ts="+current_ts+", tracker_id="+tracker_id+", p_ids="+p_ids)
create_time = new Date()
if img_ts and current_ts
img_ts = Number(img_ts)
current_ts = Number(current_ts)
time_diff = img_ts + getTimeZoneDiffByMs(create_time.getTime(), current_ts)
create_time = new Date(time_diff)
hour = new Date(create_time.getTime())
hour.setMinutes(0)
hour.setSeconds(0)
hour.setMilliseconds(0)
console.log("hour="+hour)
minutes = new Date(create_time.getTime())
minutes = minutes.getMinutes()
console.log("minutes="+minutes)
# Step 1. 修正出现记录, WorkAIUserRelations或workStatus
fixWorkStatus = (work_status,in_out)->
today = new Date(create_time.getTime())
today.setHours(0,0,0,0)
console.log('hour='+hour+', today='+today+', uuid='+uuid)
timeline = DeviceTimeLine.findOne({hour:{$lte: hour, $gt: today},uuid: uuid},{sort: {hour: -1}});
if timeline and timeline.perMin # 通过历史记录中的 数据 fix WorkStatus
time = null
imgUrl = null
timelineArray = for mins of timeline.perMin
timeline.perMin[mins]
for obj in timelineArray
if obj.img_url is url
time = Number(obj.ts)
imgUrl = obj.img_url
break
if in_out is 'in'
setObj = {
in_time: time,
in_image: imgUrl,
in_status: 'normal'
}
if !work_status.out_time
setObj.status = 'in'
else if time < work_status.out_time
setObj.status = 'out'
else if time >= work_status.out_time
setObj.status = 'in'
if in_out is 'out'
setObj = {
out_time: time,
out_image: imgUrl,
out_status: 'normal'
}
if !work_status.in_time
setObj.status = 'out'
setObj.out_status = 'warning'
else if time <= work_status.in_time
setObj.status = 'in'
else if time > work_status.in_time
setObj.status = 'out'
else
if in_out is 'in'
setObj = {
status: 'out',
in_uuid: null,
in_time: null,
in_image: null,
in_status: 'unknown'
}
if in_out is 'out'
setObj = {
status: 'in',
out_uuid: null,
out_time: null,
out_image: null,
out_status: 'unknown'
}
if !work_status.in_time
setObj.status = 'out'
WorkStatus.update({_id: work_status._id},$set: setObj)
work_status_in = WorkStatus.findOne({in_image: url})
# 匹配到进的出现
if work_status_in
console.log('padCallRemove Fix WorkStatus, 需要修正进的出现')
#fixWorkStatus(work_status_in,'in')
work_status_out = WorkStatus.findOne({out_image: url})
# 匹配到出的出现
if work_status_out
console.log('padCallRemove Fix WorkStatus, 需要修正出的出现')
#fixWorkStatus(work_status_out,'out')
# 删除出现
WorkStatus.remove({$or:[{in_image: url},{out_image: url}]});
# Step 2. 从设备时间轴中移除
selector = {
hour: hour,
uuid: uuid
}
selector["perMin."+minutes+".img_url"] = url;
###
console.log('selector='+JSON.stringify(selector))
timeline = DeviceTimeLine.findOne(selector)
console.log("timeline._id="+JSON.stringify(timeline._id))
if timeline
minuteArray = timeline.perMin[""+minutes]
console.log("minuteArray="+JSON.stringify(minuteArray))
minuteArray.splice(_.pluck(minuteArray, 'img_url').indexOf(url), 1)
console.log("2, minuteArray="+JSON.stringify(minuteArray))
modifier = {
$set:{}
}
modifier.$set["perMin."+minutes] = minuteArray
DeviceTimeLine.update({_id: timeline._id}, modifier, (err,res)->
if err
console.log('padCallRemove DeviceTimeLine, update Err:'+err)
else
console.log('padCallRemove DeviceTimeLine, update Success')
)
###
console.log('selector='+JSON.stringify(selector))
modifier = {$set:{}}
modifier.$set["perMin."+minutes+".$.person_name"] = null
modifier.$set["perMin."+minutes+".$.accuracy"] = false
DeviceTimeLine.update(selector, modifier, (err,res)->
if err
console.log('padCallRemove DeviceTimeLine, update Err:'+err)
else
console.log('padCallRemove DeviceTimeLine, update Success')
)
# Step 3. 如果 person 表中 有此图片记录, 需要移除
person = Person.findOne({'faces.id': id})
if person
faces = person.faces
faces.splice(_.pluck(faces, 'id').indexOf(obj.face_id), 1)
Person.update({_id: person._id},{$set: {faces: faces}})
# Step 4. 向Group 发送一条 mqtt 消息, 告知需要移除 错误识别 的照片
device = Devices.findOne({uuid: uuid});
if device and device.groupId
group_id = device.groupId
group = SimpleChat.Groups.findOne({_id: group_id})
to = {
id: group._id,
name: group.name,
icon: group.icon
}
device_user = Meteor.users.findOne({username: uuid})
form = {}
if device_user
form = {
id: device_user._id,
name: if (device_user.profile and device_user.profile.fullname) then device_user.profile.fullname else device_user.username,
icon: device_user.profile.icon
}
msg = {
_id: new Mongo.ObjectID()._str,
form: form,
to: to,
to_type: 'group',
type: 'remove_error_img',
id: id,
url: url,
uuid: uuid,
img_type: img_type,
img_ts: img_ts,
current_ts: current_ts,
tid: tracker_id,
pids: p_ids
}
try
sendMqttGroupMessage(group_id,msg)
catch error
console.log('try sendMqttGroupMessage Err:',error)
update_group_dataset = (group_id,dataset_url,uuid)->
unless group_id and dataset_url and uuid
return
group = SimpleChat.Groups.findOne({_id:group_id})
user = Meteor.users.findOne({username: uuid})
if group and user
announcement = group.announcement;
unless announcement
announcement = []
i = 0
isExit = false
while i < announcement.length
if announcement[i].uuid is uuid
announcement[i].dataset_url = dataset_url
isExit = true
break;
i++
unless isExit
announcementObj = {
uuid:uuid,
device_name:user.profile.fullname,
dataset_url:dataset_url
};
announcement.push(announcementObj);
SimpleChat.Groups.update({_id:group_id},{$set:{announcement:announcement}})
# test
# Meteor.startup ()->
# insert_msg2(
# '7YRBBDB72200271715027668215821893',
# 'http://workaiossqn.tiegushi.com/8acb7f90-92e1-11e7-8070-d065caa7da61',
# '28DDU17602003551',
# 'face',
# '0.9',
# '100',
# '0',
# 'front',
# 1506588441021,
# 1506588441021,
# ''
# )
# Faces API
# [{
# 'id': id,
# 'uuid': uuid,
# 'group_id': current_groupid,
# 'img_url': url,
# 'position': position,
# 'type': img_type,
# 'current_ts': int(time.time()*1000),
# 'accuracy': accuracy,
# 'fuzziness': fuzziness,
# 'sqlid': sqlId,
# 'style': style,
# 'tid': tid,
# 'img_ts': img_ts,
# 'p_ids': p_ids,
# }]
Router.route('/restapi/workai/faces', {where: 'server'}).post(()->
data = this.request.body
if (typeof data is 'object' and data.constructor is Array)
data.forEach((face)->
insertFaces(face)
)
this.response.end('{"result": "ok"}\n')
else
this.response.end('{"result": "ok", "reason": "params must be an Array"}\n')
)
Router.route('/restapi/list_device', {where: 'server'}).get(()->
uuid = this.params.query.uuid
console.log(groups)
device = Devices.findOne({"uuid" : uuid})
ret_str = ''
if device
user = {'_id': device._id, 'username': device.name, 'profile': {'icon': '/device_icon_192.png'}}
ret_str += 'Device['+uuid+'] in Devices deleted \n'
if device.groupId
group_id = device.groupId
#SimpleChat.GroupUsers.remove({group_id:group_id,user_id:user._id});
groups = SimpleChat.GroupUsers.find({group_id:group_id,user_name:uuid}).fetch();
console.log(groups)
ret_str += groups.toString()
user = Meteor.users.findOne({username: uuid})
if user
users = Meteor.users.find({username: uuid}).fetch()
console.log(users)
ret_str += users.toString()
if ret_str is ''
return this.response.end('nothing in db')
this.response.end(ret_str)
#userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
#unless userGroup or userGroup.group_id
# return this.response.end('{"result": "failed", "cause": "group not found"}\n')
)
Router.route('/restapi/get_name_by_faceid', {where: 'server'}).get(()->
face_id = this.params.query.face_id
group_id = this.params.query.group_id
if not face_id or not group_id
return this.response.end(JSON.stringify({result: 'invalid parameters'}))
person = Person.findOne({group_id: group_id, faceId: face_id})
if not person
return this.response.end(JSON.stringify({result: 'no such item'}))
return this.response.end(JSON.stringify({result: 'success', name: person.name}))
)
Router.route('/restapi/clean_device', {where: 'server'}).get(()->
uuid = this.params.query.uuid
device = Devices.findOne({"uuid" : uuid})
ret_str = ''
if device
Devices.remove({uuid : uuid})
Devices.remove({_id:device._id});
ret_str += 'Device['+uuid+'] in Devices deleted \n'
if device.groupId
group_id = device.groupId
#SimpleChat.GroupUsers.remove({group_id:group_id,user_id:user._id});
SimpleChat.GroupUsers.remove({group_id:group_id,user_name:uuid});
ret_str += 'Device in userGroup in SimpleChat.GroupUsers deleted \n'
user = Meteor.users.findOne({username: uuid})
if user
Meteor.users.remove({username: uuid})
ret_str += 'Device['+uuid+'] in Meteor.users deleted \n'
if ret_str is ''
return this.response.end('nothing to delete')
this.response.end(ret_str)
#userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
#unless userGroup or userGroup.group_id
# return this.response.end('{"result": "failed", "cause": "group not found"}\n')
)
###
payload = {'groupid': groupid, 'uuid': uuid,'fuzziness_from':fuzziness_from, 'fuzziness_to':fuzziness_to,
'blury_threshold': blury_threshold, 'score_threshold_main': score_threshold_main, 'score_threshold_2nd': score_threshold_2nd}
###
Router.route('/restapi/workai/model_param_update', {where: 'server'}).post(()->
group_id = this.request.body.groupid
uuid = this.request.body.uuid
if group_id and uuid
ModelParam.upsert({groupid: group_id, uuid: uuid}, {$set: this.request.body})
this.response.end('{"result": "ok"}\n')
else
this.response.end('{"result": "ok", "reason": "invalid params"}\n')
)
Router.route('/restapi/workai/model_param', {where: 'server'}).post(()->
group_id = this.request.body.groupid
uuid = this.request.body.uuid
if group_id and uuid
params = ModelParam.findOne({groupid: group_id, uuid: uuid})
this.response.end(JSON.stringify(params) + '\n')
else
this.response.end('{"result": "ok", "reason": "invalid params"}\n')
)
Router.route('/restapi/workai', {where: 'server'}).get(()->
id = this.params.query.id
img_url = this.params.query.img_url
uuid = this.params.query.uuid
img_type = this.params.query.type
tracker_id = this.params.query.tid
console.log '/restapi/workai get request, id:' + id + ', img_url:' + img_url + ',uuid:' + uuid
unless id or img_url or uuid
return this.response.end('{"result": "failed", "cause": "invalid params,check id,uuid,img_url"}\n')
accuracy = this.params.query.accuracy
sqlid = this.params.query.sqlid
style = this.params.query.style
fuzziness = this.params.query.fuzziness
img_ts = this.params.query.img_ts
current_ts = this.params.query.current_ts
if this.params.query.opt and this.params.query.opt is 'remove'
padCallRemove(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style, img_ts, current_ts, tracker_id)
else
insert_msg2(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts,tracker_id)
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('id')
id = this.request.body.id
if this.request.body.hasOwnProperty('img_url')
img_url = this.request.body.img_url
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('type')
img_type = this.request.body.type
if this.request.body.hasOwnProperty('sqlid')
sqlid = this.request.body.sqlid
else
sqlid = 0
if this.request.body.hasOwnProperty('style')
style = this.request.body.style
else
style = 0
if this.request.body.hasOwnProperty('img_ts')
img_ts = this.request.body.img_ts
if this.request.body.hasOwnProperty('current_ts')
current_ts = this.request.body.current_ts
if this.request.body.hasOwnProperty('tid')
tracker_id = this.request.body.tid
if this.request.body.hasOwnProperty('p_ids') #可能性最大的三个人的id
p_ids = this.request.body.p_ids
console.log '/restapi/workai post request, id:' + id + ', img_url:' + img_url + ',uuid:' + uuid + ' img_type=' + img_type + ' sqlid=' + sqlid + ' style=' + style + 'img_ts=' + img_ts
unless id or img_url or uuid
return this.response.end('{"result": "failed", "cause": "invalid params,check id,uuid,img_url"}\n')
accuracy = this.params.query.accuracy
fuzziness = this.params.query.fuzziness
if this.params.query.opt and this.params.query.opt is 'remove'
padCallRemove(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style, img_ts, current_ts, tracker_id)
else
insert_msg2(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts, tracker_id,p_ids)
this.response.end('{"result": "ok"}\n')
)
Router.route('restapi/workai_unknown', {where: 'server'}).get(()->
).post(()->
person_id = ''
persons = []
person_name = null
active_time = null
if this.request.body.hasOwnProperty('person_id')
person_id = this.request.body.person_id
if this.request.body.hasOwnProperty('persons')
persons = this.request.body.persons
console.log("restapi/workai_unknown post: person_id="+person_id+", persons="+JSON.stringify(persons))
if (!(persons instanceof Array) or persons.length < 1)
console.log("restapi/workai_unknown: this.request.body is not array.")
return this.response.end('{"result": "failed!", "cause": "this.request.body is not array."}\n')
console.log("restapi/workai_unknown: uuid = "+persons[0].uuid)
user = Meteor.users.findOne({username: persons[0].uuid})
unless user
console.log("restapi/workai_unknown: user is null")
return this.response.end('{"result": "failed!", "cause": "user is null."}\n')
userGroups = SimpleChat.GroupUsers.find({user_id: user._id})
unless userGroups
console.log("restapi/workai_unknown: userGroups is null")
return this.response.end('{"result": "failed!", "cause":"userGroups is null."}\n')
stranger_id = if person_id != '' then person_id else new Mongo.ObjectID()._str
#name = PERSON.getName(null, userGroup.group_id, person_id)
userGroups.forEach((userGroup)->
console.log("restapi/workai_unknown: userGroup.group_id="+userGroup.group_id)
stranger_name = if person_id != '' then PERSON.getName(null, userGroup.group_id, person_id) else new Mongo.ObjectID()._str
console.log("stranger_name="+stranger_name)
for person in persons
console.log("person="+JSON.stringify(person))
unless active_time
active_time = utilFormatTime(Number(person.img_ts))
if !person_name && person_id != ''
person_name = PERSON.getName(null, userGroup.group_id, person_id)
console.log("person_name="+person_name)
# update to DeviceTimeLine
create_time = new Date()
console.log("create_time.toString()="+create_time.toString())
if person.img_ts and person.current_ts
img_ts = Number(person.img_ts)
current_ts = Number(person.current_ts)
time_diff = img_ts + getTimeZoneDiffByMs(create_time.getTime(), current_ts)
console.log("time_diff="+time_diff)
create_time = new Date(time_diff)
timeObj = {
stranger_id: stranger_id,
stranger_name: stranger_name,
person_id: person.id,
person_name: person.name,
img_url: person.img_url,
sqlid: person.sqlid,
style: person.style,
accuracy: person.accuracy, # 准确度(分数)
fuzziness: person.fuzziness#, # 模糊度
ts:create_time.getTime()
}
uuid = person.uuid
PERSON.updateValueToDeviceTimeline(uuid,userGroup.group_id,timeObj)
if person_name
console.log("restapi/workai_unknown: person_name="+person_name)
#Get Configuration from DB
people_config = WorkAIUserRelations.find({'group_id':userGroup.group_id}, {fields:{'person_name':1, 'hide_it':1}}).fetch()
isShow = people_config.some((elem) => elem.person_name == person_name && !elem.hide_it)
console.log("people_config="+JSON.stringify(people_config))
if isShow and checkIfSendKnownUnknownPushNotification(userGroup.group_id,person_id)
group = SimpleChat.Groups.findOne({_id: userGroup.group_id})
group_name = '监控组'
if group && group.name
group_name = group.name
console.log("group_id="+userGroup.group_id)
console.log("Will notify one known people")
ai_person = Person.findOne({group_id:userGroup.group_id ,'faces.id': person_id});
ai_person_id = if ai_person then ai_person._id else null
sharpai_pushnotification("notify_knownPeople", {active_time:active_time, group_id:userGroup.group_id, group_name:group_name, person_name:person_name}, null, ai_person_id)
else
group = SimpleChat.Groups.findOne({_id: userGroup.group_id})
group_name = '监控组'
is_notify_stranger = true
if group && group.settings && group.settings.notify_stranger == false
is_notify_stranger = false
if group && group.name
group_name = group.name
console.log("group_id="+userGroup.group_id+", is_notify_stranger="+is_notify_stranger)
if is_notify_stranger and checkIfSendKnownUnknownPushNotification(userGroup.group_id,'0')
console.log("Will notify stranger")
sharpai_pushnotification("notify_stranger", {active_time:active_time, group_id:userGroup.group_id, group_name:group_name}, null, null)
)
this.response.end('{"result": "ok"}\n')
)
Router.route('restapi/workai_multiple_people', {where: 'server'}).get(()->
).post(()->
person_id = ''
persons = []
active_time = null
if this.request.body.hasOwnProperty('person_id')
person_id = this.request.body.person_id
if this.request.body.hasOwnProperty('persons')
persons = this.request.body.persons
console.log("restapi/workai_multiple_people post: person_id="+person_id+", persons="+JSON.stringify(persons))
if (!(persons instanceof Array) or persons.length < 1)
console.log("restapi/workai_multiple_people: this.request.body is not array.")
return this.response.end('{"result": "failed!", "cause": "this.request.body is not array."}\n')
console.log("restapi/workai_multiple_people: uuid = "+persons[0].uuid)
user = Meteor.users.findOne({username: persons[0].uuid})
unless user
console.log("restapi/workai_multiple_people: user is null")
return this.response.end('{"result": "failed!", "cause": "user is null."}\n')
userGroups = SimpleChat.GroupUsers.find({user_id: user._id})
unless userGroups
console.log("restapi/workai_multiple_people: userGroups is null")
return this.response.end('{"result": "failed!", "cause":"userGroups is null."}\n')
for person in persons
console.log("person="+JSON.stringify(person))
unless active_time
active_time = utilFormatTime(Number(person.img_ts))
userGroups.forEach((userGroup)->
console.log("restapi/workai_multiple_people: userGroup.group_id="+userGroup.group_id)
#Get Configuration from DB
people_config = WorkAIUserRelations.find({'group_id':userGroup.group_id}, {fields:{'person_name':1, 'hide_it':1}}).fetch()
console.log("people_config="+JSON.stringify(people_config))
multiple_persons = []
for person in persons
if person.accuracy == 0
continue
person_name = PERSON.getName(null, userGroup.group_id, person.id)
console.log("restapi/workai_multiple_people: person_name="+person_name)
isShow = people_config.some((elem) => elem.person_name == person_name && !elem.hide_it)
if isShow
if !multiple_persons.some((elem) => elem == person_name)
multiple_persons.push(person_name)
if multiple_persons.length == 0
console.log("restapi/workai_multiple_people: No people in the request body.")
return
group = SimpleChat.Groups.findOne({_id: userGroup.group_id})
group_name = '监控组'
is_notify_stranger = true
if group && group.settings && group.settings.notify_stranger == false
is_notify_stranger = false
if group && group.name
group_name = group.name
console.log("group_id="+userGroup.group_id)
console.log("Will notify known multiple people")
sharpai_pushnotification("notify_knownPeople", {active_time:active_time, group_id:userGroup.group_id, group_name:group_name, person_name:multiple_persons.join(', ')}, null)
)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-group-qrcode', {where: 'server'}).get(()->
group_id = this.params.query.group_id
console.log '/restapi/workai-group-qrcode get request, group_id: ', group_id
try
img = QRImage.image('http://' + server_domain_name + '/simple-chat/to/group?id=' + group_id, {size: 10})
this.response.writeHead(200, {'Content-Type': 'image/png'})
img.pipe(this.response)
catch
this.response.writeHead(414, {'Content-Type': 'text/html'})
this.response.end('<h1>414 Request-URI Too Large</h1>')
)
device_join_group = (uuid,group_id,name,in_out)->
device = PERSON.upsetDevice(uuid, group_id,name,in_out)
user = Meteor.users.findOne({username: uuid})
if !user
userId = Accounts.createUser({username: uuid, password: '123456', profile: {fullname: device.name, icon: '/device_icon_192.png'},is_device:true})
user = Meteor.users.findOne({_id: userId})
else
Meteor.users.update({_id:user._id},{$set:{'profile.fullname':device.name, 'profile.icon':'/device_icon_192.png', is_device:true }});
group = SimpleChat.Groups.findOne({_id: group_id})
#一个设备只允许加入一个群
groupUsers = SimpleChat.GroupUsers.find({user_id: user._id})
hasBeenJoined = false
if groupUsers.count() > 0
groupUsers.forEach((groupUser)->
if groupUser.group_id is group_id
SimpleChat.GroupUsers.update({_id:groupUser._id},{$set:{is_device:true,in_out:in_out,user_name:device.name}});
hasBeenJoined = true
else
_group = SimpleChat.Groups.findOne({_id: groupUser.group_id})
SimpleChat.GroupUsers.remove(groupUser._id)
sendMqttMessage('/msg/g/'+ _group._id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
icon: user.profile.icon
}
to: {
id: _group._id
name: _group.name
icon: _group.icon
}
images: []
to_type: "group"
type: "text"
text: if user.profile and user.profile.fullname then user.profile.fullname + '[' +user.username + '] 已退出该群!' else '设备 ['+user.username+'] 已退出该群!'
create_time: new Date()
is_read: false
})
)
if hasBeenJoined is false
SimpleChat.GroupUsers.insert({
group_id: group_id
group_name: group.name
group_icon: group.icon
user_id: user._id
user_name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
user_icon: if user.profile and user.profile.icon then user.profile.icon else '/device_icon_192.png'
create_time: new Date()
is_device:true
in_out:in_out
});
sendMqttMessage('/msg/g/'+ group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
icon: user.profile.icon
}
to: {
id: group_id
name: group.name
icon: group.icon
}
images: []
to_type: "group"
type: "text"
text: if user.profile and user.profile.fullname then user.profile.fullname + '[' +user.username + '] 已加入!' else '设备 ['+user.username+'] 已加入!'
create_time: new Date()
is_read: false
})
Meteor.call 'ai-system-register-devices',group_id,uuid, (err, result)->
if err or result isnt 'succ'
return console.log('register devices to AI-system failed ! err=' + err);
if result == 'succ'
return console.log('register devices to AI-system succ');
console.log('user:', user)
console.log('device:', device)
Meteor.methods {
"join-group":(uuid,group_id,name,in_out)->
console.log("uuid = "+uuid+" group id= "+group_id+" name= "+name+" inout = "+in_out)
device_join_group(uuid,group_id,name,'inout')
sendMqttMessage('/msg/d/'+uuid, {text:'groupchanged'});
return "ok"
}
Router.route('/restapi/workai-join-group', {where: 'server'}).get(()->
uuid = this.params.query.uuid
group_id = this.params.query.group_id
console.log '/restapi/workai-join-group get request, uuid:' + uuid + ', group_id:' + group_id
name = this.params.query.name
in_out = this.params.query.in_out
unless uuid or group_id or in_out or name
console.log '/restapi/workai-join-group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
device_join_group(uuid,group_id,name,'inout')
sendMqttMessage('/msg/d/'+uuid, {text:'groupchanged'});
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('name')
name = this.request.body.name
if this.request.body.hasOwnProperty('in_out')
in_out = this.request.body.in_out
console.log '/restapi/workai-join-group post request, uuid:' + uuid + ', group_id:' + group_id
unless uuid or group_id or in_out or name
console.log '/restapi/workai-join-group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
device_join_group(uuid,group_id,name,in_out)
sendMqttMessage('/msg/d/'+uuid, {text:'groupchanged'});
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-group-dataset', {where: 'server'}).get(()->
group_id = this.params.query.group_id
value = this.params.query.value
uuid = this.params.query.uuid
console.log '/restapi/workai-group-dataset get request, group_id:' + group_id + ', value:' + value + ', uuid:' + uuid
unless value and group_id and uuid
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
# insert_msg2(id, img_url, uuid)
update_group_dataset(group_id,value,uuid)
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.id
if this.request.body.hasOwnProperty('value')
value = this.request.body.img_url
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
console.log '/restapi/workai-group-dataset get request, group_id:' + group_id + ', value:' + value + ', uuid:' + uuid
unless value and group_id and uuid
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
#insert_msg2(id, img_url, uuid)
update_group_dataset(group_id,value,uuid)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-getgroupid', {where: 'server'}).get(()->
uuid = this.params.query.uuid
#console.log '/restapi/workai-getgroupid get request, uuid:' + uuid
unless uuid
console.log '/restapi/workai-getgroupid get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
user = Meteor.users.findOne({username: uuid})
device_group = ''
if user
groupUser = SimpleChat.GroupUsers.find({user_id: user._id})
groupUser.forEach((device)->
if device.group_id
device_group += device.group_id
device_group += ','
)
this.response.end(device_group)
)
Router.route('/restapi/workai-send2group', {where: 'server'}).get(()->
uuid = this.params.query.uuid
group_id = this.params.query.group_id
msg_type = this.params.query.type
msg_text = this.params.query.text
is_device_traing = this.params.query.is_device_traing
unless uuid or group_id
console.log '/restapi/workai-send2group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
if (msg_type == 'text' and msg_text)
user = null
userGroup = null
device = Devices.findOne({"uuid" : uuid})
if device and device.groupId
user = {'_id': device._id, 'username': device.name, 'profile': {'icon': '/device_icon_192.png'}}
userGroup = SimpleChat.GroupUsers.findOne({group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
else
user = Meteor.users.findOne({username: uuid})
unless user
return this.response.end('{"result": "failed", "cause": "device not registered"}\n')
userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
sendMqttMessage('/msg/g/'+ userGroup.group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname + '['+user.username+']' else user.username
icon: user.profile.icon
}
to: {
id: userGroup.group_id
name: userGroup.group_name
icon: userGroup.group_icon
}
images: []
to_type: "group"
type: "text"
text: msg_text
create_time: new Date()
is_read: false
is_device_traing: is_device_traing
})
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('type')
msg_type = this.request.body.type
if this.request.body.hasOwnProperty('text')
msg_text = this.request.body.text
if this.request.body.hasOwnProperty('is_device_traing')
is_device_traing = this.request.body.is_device_traing
unless uuid or group_id
console.log '/restapi/workai-send2group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
if (msg_type == 'text' and msg_text)
user = null
userGroup = null
device = Devices.findOne({"uuid" : uuid})
if device and device.groupId
user = {'_id': device._id, 'username': device.name, 'profile': {'icon': '/device_icon_192.png'}}
userGroup = SimpleChat.GroupUsers.findOne({group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
else
user = Meteor.users.findOne({username: uuid})
unless user
return this.response.end('{"result": "failed", "cause": "device not registered"}\n')
userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
sendMqttMessage('/msg/g/'+ userGroup.group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname + '['+user.username+']' else user.username
icon: user.profile.icon
}
to: {
id: userGroup.group_id
name: userGroup.group_name
icon: userGroup.group_icon
}
images: []
to_type: "group"
type: "text"
text: msg_text
create_time: new Date()
is_read: false
is_device_traing: is_device_traing
})
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-group-template', {where: 'server'}).get(()->
result = {
group_templates:[
{
"_id" : new Mongo.ObjectID()._str,
"name": "Work AI工作效能模版",
"icon": rest_api_url + "/workAIGroupTemplate/efficiency.jpg",
"img_type": "face"
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "家庭安全模版",
"icon": rest_api_url + "/workAIGroupTemplate/safety.jpg",
"img_type": "object"
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "NLP情绪分析模版",
"icon": rest_api_url + "/workAIGroupTemplate/sentiment.jpg"
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "NLP通用文本分类模版",
"icon": rest_api_url + "/workAIGroupTemplate/classification.jpg",
"type":'nlp_classify'
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "ChatBot训练模版",
"icon": rest_api_url + "/workAIGroupTemplate/chatBot.jpg"
}
]}
this.response.end(JSON.stringify(result))
)
onNewHotSharePost = (postData)->
console.log 'onNewHotSharePost:' , postData
nlp_group = SimpleChat.Groups.findOne({_id:'92bf785ddbe299bac9d1ca82'});
nlp_user = Meteor.users.findOne({_id: 'xWA3KLXDprNe8Lczw'});
#nlp_classname = NLP_CLASSIFY.getName()
nlp_classname = postData.classname
if nlp_classname
NLP_CLASSIFY.setName(nlp_group._id,nlp_classname)
sendMqttMessage('/msg/g/'+ nlp_group._id, {
_id: new Mongo.ObjectID()._str
form: {
id: nlp_user._id
name: if nlp_user.profile and nlp_user.profile.fullname then nlp_user.profile.fullname + '['+nlp_user.username+']' else nlp_user.username
icon: nlp_user.profile.icon
}
to: {
id: nlp_group._id
name: nlp_group.name
icon: nlp_group.icon
}
to_type: "group"
type: "url"
text: if !nlp_classname then '1 个链接需要标注' else nlp_className + ':'
urls:[{
_id:new Mongo.ObjectID()._str,
label: nlp_classname,
#class_id:postData.classid,
url:postData.posturl,
title:postData.posttitle,
thumbData:postData.mainimage,
description:if postData.description then postData.description else postData.posturl
}]
create_time: new Date()
class_name: nlp_classname
wait_lable: !nlp_classname
is_read: false
})
Router.route('/restapi/workai-hotshare-newpost', {where: 'server'}).get(()->
classname = this.params.query.classname
#username = this.params.query.username
posttitle = this.params.query.posttitle
posturl = this.params.query.posturl
mainimage = this.params.query.mainimage
description = this.params.query.description
postData = { classname: classname, posttitle: posttitle, posturl: posturl ,mainimage:mainimage, description:description}
onNewHotSharePost(postData)
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('classname')
classname = this.request.body.classname
if this.request.body.hasOwnProperty('posttitle')
posttitle = this.request.body.posttitle
if this.request.body.hasOwnProperty('posturl')
posturl = this.request.body.posturl
if this.request.body.hasOwnProperty('mainimage')
mainimage = this.request.body.mainimage
if this.request.body.hasOwnProperty('description')
description = this.request.body.description
postData = { classname: classname, posttitle: posttitle, posturl: posturl, mainimage:mainimage, description:description}
onNewHotSharePost(postData)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-motion-imgs/:id', {where: 'server'}).get(()->
id = this.params.id
post = Posts.findOne({_id: id})
html = Assets.getText('workai-motion-imgs.html');
imgs = ''
post.docSource.imgs.forEach (img)->
imgs += '<li><img src="'+img+'" /></li>'
html = html.replace('{{imgs}}', imgs)
this.response.end(html)
)
Router.route('/restapi/workai-motion', {where: 'server'}).post(()->
payload = this.request.body || {}
deviceUser = Meteor.users.findOne({username: payload.uuid})|| {}
groupUser = SimpleChat.GroupUsers.findOne({user_id: deviceUser._id}) || {} # 一个平板只对应一个聊天群
group = SimpleChat.Groups.findOne({_id: groupUser.group_id})
if (!group)
return this.response.end('{"result": "error"}\n')
if (payload.motion_gif)
imgs = [payload.motion_gif]
# if (payload.imgs)
# imgs = payload.imgs
if (!imgs or imgs.length <= 0)
return this.response.end('{"result": "error"}\n')
if (imgs.length > 10)
imgs = imgs.slice(0, 9)
deferSetImmediate ()->
# update follow
SimpleChat.GroupUsers.find({group_id: group._id}).forEach (item)->
if (Follower.find({userId: item.user_id, followerId: deviceUser._id}).count() <= 0)
console.log('insert follower:', item.user_id)
Follower.insert({
userId: item.user_id
followerId: deviceUser._id
createAt: new Date()
})
#一个设备一天的动作只放在一个帖子里
devicePost = Posts.findOne({owner:deviceUser._id})
isTodayPost = false;
if(devicePost)
today = new Date().toDateString()
isTodayPost = if devicePost.createdAt.toDateString() is today then true else false;
console.log 'isTodayPost:'+isTodayPost
name = PERSON.getName(payload.uuid, group._id, payload.id)
postId = if isTodayPost then devicePost._id else new Mongo.ObjectID()._str
deviceName = if deviceUser.profile and deviceUser.profile.fullname then deviceUser.profile.fullname else deviceUser.username
title = if name then "摄像头看到#{name} 在#{deviceName}" else (if payload.type is 'face' then "摄像头看到有人在#{deviceName}" else "摄像头看到#{deviceName}有动静")
time = '时间:' + new Date().toString()
post = {
pub: if isTodayPost then devicePost.pub else []
title: title
addontitle: time
browse: 0
heart: []
retweet: []
comment: []
commentsCount: 0
mainImage: if payload.motion_gif then payload.motion_gif else payload.img_url
publish: true
owner: deviceUser._id
ownerName: deviceName
ownerIcon: if deviceUser.profile and deviceUser.profile.icon then deviceUser.profile.icon else '/userPicture.png'
createdAt: new Date # new Date(payload.ts)
isReview: true
insertHook: true
import_status: 'done'
fromUrl: ''
docType: 'motion'
docSource: payload
}
newPub = []
# newPub.push({
# _id: new Mongo.ObjectID()._str
# type: 'text'
# isImage: false
# owner: deviceUser._id
# text: "类 型:#{if payload.type is 'face' then '人' else '对像'}\n准确度:#{payload.accuracy}\n模糊度:#{payload.fuzziness}\n设 备:#{deviceName}\n动 作:#{payload.mid}\n"
# style: ''
# data_row: 1
# data_col: 1
# data_sizex: 6
# data_sizey: 1
# data_wait_init: true
# })
# newPub.push({
# _id: new Mongo.ObjectID()._str
# type: 'text'
# isImage: false
# owner: deviceUser._id
# text: '以下为设备的截图:'
# style: ''
# data_row: 2
# data_col: 1
# data_sizex: 6
# data_sizey: 1
# data_wait_init: true
# })
data_row = 3
imgs.forEach (img)->
newPub.push({
_id: new Mongo.ObjectID()._str
type: 'image'
isImage: true
# inIframe: true
owner: deviceUser._id
# text: '您当前程序不支持视频观看',
# iframe: '<iframe height="100%" width="100%" src="'+rest_api_url+'/restapi/workai-motion-imgs/'+postId+'" frameborder="0" allowfullscreen></iframe>'
imgUrl: img,
data_row: data_row
data_col: 1
data_sizex: 6
data_sizey: 5
data_wait_init: true
})
data_row += 5
newPub.push({
_id: new Mongo.ObjectID()._str
type: 'text'
isImage: false
owner: deviceUser._id
text: time
style: ''
data_row: 1
data_col: 1
data_sizex: 6
data_sizey: 1
data_wait_init: true
isTime:true
})
newPub.push({
_id: new Mongo.ObjectID()._str
type: 'text'
isImage: false
owner: deviceUser._id
text: title
style: ''
data_row: 1
data_col: 1
data_sizex: 6
data_sizey: 1
data_wait_init: true
})
Array.prototype.push.apply(newPub, post.pub)
post.pub = newPub
# formatPostPub(post.pub)
if isTodayPost
console.log('update motion post:', postId)
Posts.update({_id:postId},{$set:post})
globalPostsUpdateHookDeferHandle(post.owner, postId,null,{$set:post})
return;
post._id = postId
globalPostsInsertHookDeferHandle(post.owner, post._id)
Posts.insert(post)
console.log('insert motion post:', post._id)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/date', (req, res, next)->
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
this.response.end(Date.now().toString())
, {where: 'server'})
Router.route('/restapi/allgroupsid/:token/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token
limit = this.params.limit
skip = this.params.skip
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/allgroupsid get request, token:' + token + ' limit:' + limit + ' skip:' + skip
allgroups = []
groups = SimpleChat.Groups.find({}, {fields:{"_id": 1, "name": 1}, limit: parseInt(limit), skip: parseInt(skip)})
unless groups
return this.response.end('[]\n')
groups.forEach((group)->
allgroups.push({'id':group._id, 'name': group.name})
)
this.response.end(JSON.stringify(allgroups))
)
Router.route('/restapi/groupusers/:token/:groupid/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token
limit = this.params.limit
skip = this.params.skip
groupid = this.params.groupid
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/groupusers get request, token:' + token + ' limit:' + limit + ' skip:' + skip + ' groupid:' + groupid
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
#groupDevices = Devices.find({'groupId': groupid}).fetch()
#console.log 'no group found:' + groupDevices
allUsers = []
userGroups = SimpleChat.GroupUsers.find({group_id: groupid}, {fields:{"user_id": 1, "user_name": 1}, limit: parseInt(limit), skip: parseInt(skip)})
unless userGroups
return this.response.end('[]\n')
userGroups.forEach((userGroup)->
#if _.pluck(groupDevices, 'uuid').indexOf(userGroup.user_id) is -1
allUsers.push({'user_id':userGroup.user_id, 'user_name': userGroup.user_name})
)
this.response.end(JSON.stringify(allUsers))
)
Router.route('/restapi/activity/:token/:direction/:groupid/:ts/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token
groupid = this.params.groupid
limit = this.params.limit
skip = this.params.skip
direction = this.params.direction
starttime = this.params.ts
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/user get request, token:' + token + ' limit:' + limit + ' skip:' + skip + ' groupid:' + groupid + ' Direction:' + direction + ' starttime:' + starttime
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
allActivity = []
#Activity.id is id of person name
groupActivity = Activity.find(
{'group_id': groupid, 'ts': {$gt: parseInt(starttime)}, 'in_out': direction}
{fields:{'id': 1, 'name': 1, 'ts': 1, 'in_out': 1, 'img_url':1}, limit: parseInt(limit), skip: parseInt(skip)}
)
unless groupActivity
return this.response.end('[]\n')
groupActivity.forEach((activity)->
allActivity.push({'user_id': activity.id, 'user_name': activity.name, 'in_out': activity.in_out, 'img_url': activity.img_url})
)
this.response.end(JSON.stringify(allActivity))
)
Router.route('/restapi/active/:active/:token/:direction/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token #
limit = this.params.limit #
skip = this.params.skip #
direction = this.params.direction #'in'/'out'
active = this.params.active #'active'/'notactive'
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/:active get request, token:' + token + ' limit:' + limit + ' skip:' + skip + ' Direction:' + direction + ' active:' + active
allnotActivity = []
daytime = new Date()
daytime.setSeconds(0)
daytime.setMinutes(0)
daytime.setHours(0)
daytime = new Date(daytime).getTime()
notActivity = WorkAIUserRelations.find({}, {limit: parseInt(limit), skip: parseInt(skip)})
unless notActivity
return this.response.end('[]\n')
notActivity.forEach((item)->
#console.log(item)
if !item.checkin_time
item.checkin_time = 0
if !item.ai_in_time
item.ai_in_time= 0
if !item.checkout_time
item.checkout_time = 0
if !item.ai_out_time
item.ai_out_time = 0
if active is 'notactive'
if direction is 'in' and item.checkin_time < daytime and item.ai_in_time < daytime
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.in_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
else if direction is 'out' and item.checkout_time < daytime and item.ai_out_time < daytime
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.out_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
else if active is 'active'
if direction is 'in' and (item.checkin_time > daytime or item.ai_in_time > daytime)
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.in_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
else if direction is 'out' and (item.checkout_time > daytime or item.ai_out_time > daytime)
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.out_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
)
this.response.end(JSON.stringify(allnotActivity))
)
Router.route('/restapi/resetworkstatus/:token', {where: 'server'}).get(()->
token = this.params.token #
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/resetworkstatus get request'
date = Date.now();
mod = 24*60*60*1000;
date = date - (date % mod)
nextday = date + mod
relations = WorkAIUserRelations.find({})
relations.forEach((fields)->
if fields && fields.group_id
# 按 group 所在时区初始化 workStatus 数据
timeOffset = 8
shouldInitWorkStatus = false
group = SimpleChat.Groups.findOne({_id: fields.group_id})
if (group and group.offsetTimeZone)
timeOffset = parseInt(group.offsetTimeZone)
# 根据时区 获取 group 对应时区时间
group_local_time = getLocalTimeByOffset(timeOffset)
group_local_time_hour = group_local_time.getHours()
if group_local_time_hour is 0
shouldInitWorkStatus = true
console.log('now should init the offsetTimeZone: ', timeOffset)
#console.log('>>> ' + JSON.stringify(fields))
workstatus = WorkStatus.findOne({'group_id': fields.group_id, 'date': nextday, 'person_name': fields.person_name})
if !workstatus and shouldInitWorkStatus
newWorkStatus = {
"app_user_id" : fields.app_user_id
"group_id" : fields.group_id
"date" : nextday
"person_id" : fields.ai_persons
"person_name" : fields.person_name
"status" : "out"
"in_status" : "unknown"
"out_status" : "unknown"
"in_uuid" : fields.in_uuid
"out_uuid" : fields.out_uuid
"whats_up" : ""
"in_time" : 0
"out_time" : 0
"hide_it" : if fields.hide_it then fields.hide_it else false
}
#console.log('>>> new a WorkStatus ' + JSON.stringify(newWorkStatus))
WorkStatus.insert(newWorkStatus)
)
# 计算没有确认下班的数据
docs = UserCheckoutEndLog.find({}).fetch()
docs.map (doc)->
# remove
UserCheckoutEndLog.remove({_id: doc._id})
# 状态
startUTC = Date.UTC(doc.params.msg_data.create_time.getUTCFullYear(), doc.params.msg_data.create_time.getUTCMonth(), doc.params.msg_data.create_time.getUTCDate(), 0, 0, 0, 0)
endUTC = Date.UTC(doc.params.msg_data.create_time.getUTCFullYear(), doc.params.msg_data.create_time.getUTCMonth(), doc.params.msg_data.create_time.getUTCDate(), 23, 59, 59, 0)
workstatus = WorkStatus.findOne({'group_id': doc.params.msg_data.group_id, 'date': {$gte: startUTC, $lte: endUTC}})
# local date
now = new Date()
group = SimpleChat.Groups.findOne({_id: doc.params.msg_data.group_id})
if (group and group.offsetTimeZone)
now = new Date((now.getTime()+(now.getTimezoneOffset()*60000)) + (3600000*group.offsetTimeZone))
else
now = new Date((now.getTime()+(now.getTimezoneOffset()*60000)) + (3600000*8))
# console.log('===1==', workstatus.status)
unless (workstatus and workstatus.status is 'out')
# console.log('===2==', doc.userName, doc.params.msg_data.create_time.getUTCDate(), now.getUTCDate())
# 当天数据
if (doc.params.msg_data.create_time.getUTCDate() is now.getUTCDate())
# console.log('===3==', doc.userName)
send_greeting_msg(doc.params.msg_data);
PERSON.updateWorkStatus(doc.params.person._id)
if (doc.params.person_info)
PERSON.sendPersonInfoToWeb(doc.params.person_info)
else
# TODO:
this.response.end(JSON.stringify({result: 'ok'}))
)
# params = {
# uuid: 设备UUID,
# person_id: id,
# video_post: 视频封面图地址,
# video_src: 视频播放地址
# ts: 时间戳
# ts_offset: 时区 (eg : 东八区 是 -8);
# }
Router.route('/restapi/timeline/video/', {where: 'server'}).post(()->
payload = this.request.body || {}
console.log('/restapi/timeline/video/ request body = ',JSON.stringify(payload))
if (!payload.uuid or !payload.person_id or !payload.video_post or !payload.video_src or !payload.ts or !payload.ts_offset)
return this.response.end('{"result": "error", "reson":"参数不全或格式错误!"}\n')
# step 1. get group_id by uuid
device = Devices.findOne({uuid: payload.uuid})
if device and device.groupId
group_id = device.groupId
# step 2. get person_name by person_id
person_name = PERSON.getName(payload.uuid, group_id, payload.person_id)
if (!person_name)
person_name = ""
PERSON.updateToDeviceTimeline(payload.uuid,group_id,{
is_video: true,
person_id: payload.person_id,
person_name: person_name,
video_post: payload.video_post,
video_src: payload.video_src,
ts: Number(payload.ts),
ts_offset: Number(payload.ts_offset)
})
return this.response.end('{"result": "success"}\n')
)
Router.route('/restapi/clustering', {where: 'server'}).get(()->
group_id = this.params.query.group_id
faceId = this.params.query.faceId
totalFaces = this.params.query.totalFaces
url = this.params.query.url
rawfilepath = this.params.query.rawfilepath
isOneSelf = this.params.query.isOneSelf
if isOneSelf == 'true'
isOneSelf = true
else
isOneSelf = false
console.log '/restapi/clustering get request, group_id:' + group_id + ', faceId:' + faceId + ',totalFaces:' + totalFaces + ',url' + url + ',rawfilepath' + rawfilepath + ',isOneSelf' + isOneSelf
unless group_id and isOneSelf
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
#取回这个组某个人所有正确/不正确的图片
if group_id and faceId
dataset={'group_id': group_id, 'faceId': faceId, 'dataset': []}
allClustering = Clustering.find({'group_id': group_id, 'faceId': faceId, 'isOneSelf': isOneSelf}).fetch()
allClustering.forEach((fields)->
dataset.dataset.push({url:fields.url, rawfilepath: fields.rawfilepath})
)
else
dataset={'group_id': group_id, 'dataset': []}
#取回这个组某个人所有不正确的图片
#返回标注过的数据集
this.response.end(JSON.stringify(dataset))
).post(()->
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('faceId')
faceId = this.request.body.faceId
if this.request.body.hasOwnProperty('totalFaces')
totalFaces = this.request.body.totalFaces
if this.request.body.hasOwnProperty('url')
url = this.request.body.url
if this.request.body.hasOwnProperty('rawfilepath')
rawfilepath = this.request.body.rawfilepath
if this.request.body.hasOwnProperty('isOneSelf')
isOneSelf = this.request.body.isOneSelf
if isOneSelf == "true"
isOneSelf = true
console.log '/restapi/clustering post request, group_id:' + group_id + ', faceId:' + faceId + ',totalFaces:' + totalFaces + ',url' + url + ',rawfilepath' + rawfilepath + ',isOneSelf' + isOneSelf
unless group_id and faceId and url
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
#插入数据库
person = Person.findOne({group_id: group_id, 'faceId': faceId},{sort: {createAt: 1}})
if !person
person = {
_id: new Mongo.ObjectID()._str,
id: 1,
group_id: group_id,
faceId: faceId,
url: url,
name: faceId,
faces: [],
deviceId: 'clustering',
DeviceName: 'clustering',
createAt: new Date(),
updateAt: new Date()
};
Person.insert(person)
console.log('>>> new people' + faceId)
clusteringObj = {
group_id: group_id,
faceId: faceId,
totalFaces: totalFaces,
url: url,
rawfilepath: rawfilepath,
isOneSelf: isOneSelf
}
Clustering.insert(clusteringObj)
#console.log('>>> ' + JSON.stringify(clusteringObj))
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/get-group-users', {where: 'server'}).get(()->
group_id = this.params.query.group_id
resObj = []
gUsers = Person.find({group_id: group_id})
if gUsers
gUsers.forEach((user)->
resObj.push(user)
)
this.response.end(JSON.stringify(resObj))
).post(()->
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
resObj = []
gUsers = Person.find({group_id: group_id})
if gUsers
gUsers.forEach((user)->
resObj.push(user)
)
this.response.end(JSON.stringify(resObj))
)
Router.route('/restapi/datasync/:token/:groupid', {where: 'server'}).get(()->
token = this.params.token
groupid = this.params.groupid
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/datasync get request, token:' + token + ' groupid:' + groupid
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
syncDateSet=[]
#取出群相册里面所有已经标注的数据
persons = Person.find({group_id: groupid},{fields:{name: 1, faceId:1}}).fetch()
persons.forEach((item)->
urls=[]
if item and item.name
dataset = LableDadaSet.find({group_id: groupid ,name: item.name}, {fields:{url: 1,style:1,sqlid:1}}).fetch()
dataset.forEach((item2)->
if item2 and item2.url
urls.push({
url:item2.url,
style: item2.style || 'front',
sqlid: item2.sqlid || null
})
)
if item and item.faceId
syncDateSet.push({faceId: item.faceId, urls: urls})
)
this.response.end(JSON.stringify(syncDateSet))
)
Router.route('/restapi/groupdatasync/:token/:groupid', {where: 'server'}).get(()->
token = this.params.token
groupid = this.params.groupid
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/datasync get request, token:' + token + ' groupid:' + groupid
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
syncDateSet=[]
#取出群相册里面所有已经标注的数据
person = GroupPerson.find({group_id: groupid},{fields:{name: 1, faceId:1}}).fetch()
person.forEach((item)->
urls=[]
if item and item.name
dataset = GroupLableDadaSet.find({group_id: groupid ,name: item.name}, {fields:{url: 1,style:1,sqlid:1}}).fetch()
dataset.forEach((item2)->
if item2 and item2.url
urls.push({
url:item2.url,
style: item2.style || 'front',
sqlid: item2.sqlid || null
})
)
if item and item.faceId
syncDateSet.push({faceId: item.faceId, urls: urls})
)
this.response.end(JSON.stringify(syncDateSet))
)
getInComTimeLen = (workstatus) ->
group_id = workstatus.group_id;
diff = 0;
out_time = workstatus.out_time;
today_end = workstatus.out_time;
time_offset = 8
group = SimpleChat.Groups.findOne({_id: group_id});
if (group && group.offsetTimeZone)
time_offset = group.offsetTimeZone;
DateTimezone = (d, time_offset) ->
if (time_offset == undefined)
if (d.getTimezoneOffset() == 420)
time_offset = -7
else
time_offset = 8
#取得 UTC time
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
local_now = new Date(utc + (3600000*time_offset))
today_now = new Date(local_now.getFullYear(), local_now.getMonth(), local_now.getDate(),
local_now.getHours(), local_now.getMinutes());
return today_now;
#计算out_time
if(workstatus.in_time)
date = new Date(workstatus.in_time);
fomatDate = date.shortTime(time_offset);
isToday = PERSON.checkIsToday(workstatus.in_time,group_id)
#不是今天的时间没有out_time的或者是不是今天时间,最后一次拍到的是进门的状态的都计算到当天结束
if((!out_time and !isToday) or (workstatus.status is 'in' and !isToday))
date = DateTimezone(date,time_offset);
day_end = new Date(date).setHours(23,59,59);
#day_end = new Date(this.in_time).setUTCHours(0,0,0,0) + (24 - time_offset)*60*60*1000 - 1;
out_time = day_end;
workstatus.in_time = date.getTime();
#今天的时间(没有离开过监控组)
else if(!out_time and isToday)
now_time = Date.now();
out_time = now_time;
#今天的时间(离开监控组又回到监控组)
else if(out_time and workstatus.status is 'in' and isToday)
now_time = Date.now();
out_time = now_time;
if(workstatus.in_time and out_time)
diff = out_time - workstatus.in_time;
if(diff > 24*60*60*1000)
diff = 24*60*60*1000;
else if(diff < 0)
diff = 0;
min = diff / 1000 / 60 ;
hour = Math.floor(min/60)+' h '+Math.floor(min%60) + ' min';
if(min < 60)
hour = Math.floor(min%60) + ' min';
if(diff == 0)
hour = '0 min';
return hour;
getShortTime = (ts,group_id)->
time_offset = 8
group = SimpleChat.Groups.findOne({_id: group_id});
if (group && group.offsetTimeZone)
time_offset = group.offsetTimeZone;
time = new Date(ts);
return time.shortTime(time_offset,true);
sendEmailToGroupUsers = (group_id)->
if !group_id
return
group = SimpleChat.Groups.findOne({_id:group_id});
if !group
return
date = Date.now();
mod = 24*60*60*1000;
date = date - (date % mod)
yesterday = date - mod
console.log 'date:'+ yesterday
workstatus_content = ''
WorkStatus.find({'group_id': group_id, 'date': yesterday}).forEach((target)->
unless target.hide_it
text = Assets.getText('email/work-status-content.html');
text = text.replace('{{person_name}}', target.person_name);
# app_user_status_color = 'gray'
# app_notifaction_status = ''
# if target.app_user_id
# app_user_status_color = 'green'
# if target.app_notifaction_status is 'on'
# app_notifaction_status = '<i class="fa fa-bell app-user-status" style="color:green;"></i>'
# app_user_status = '<i class="fa fa-user app-user-status" style="color:green;"></i>'+app_notifaction_status
# text = text.replace('{{app_user_status_color}}',app_user_status_color);
# text = text.replace('{{app_notifaction_status}}',app_notifaction_status);
isStatusIN_color = if target.status is 'in' then 'green' else 'gray'
# if target.in_time > 0
# if PERSON.checkIsToday(target.in_time,group_id)
# isStatusIN_color = 'gray'
# text = text.replace('{{isStatusIN_color}}',isStatusIN_color);
InComTimeLen = getInComTimeLen(target)
text = text.replace('{{InComTimeLen}}',InComTimeLen);
isInStatusNotUnknownStyle = if target.in_status is 'unknown' then 'display:none;' else 'display:table-cell;'
text = text.replace('{{isInStatusNotUnknownStyle}}',isInStatusNotUnknownStyle);
isInStatusUnknownStyle = if target.in_status is 'unknown' then 'display:table-cell;' else 'display:none;'
text = text.replace('{{isInStatusUnknownStyle}}',isInStatusUnknownStyle);
if target.in_status isnt 'unknown'
text = text.replace('{{in_image}}',target.in_image);
text = text.replace('{{in_time}}',getShortTime(target.in_time,group_id))
in_time_Color = 'green'
if target.in_status is 'warning'
in_time_Color = 'orange'
else if target.in_status is 'error'
in_time_Color = 'red'
text = text.replace('{{in_time_Color}}',in_time_Color);
historyUnknownOutStyle = 'display:none;'
if isStatusIN_color is 'green'
historyUnknownOutStyle = 'display:table-cell;color:red;'
else
if target.out_status is 'unknown'
historyUnknownOutStyle = 'display:table-cell;'
text = text.replace('{{historyUnknownOutStyle}}',historyUnknownOutStyle);
isOutStatusNotUnknownStyle = if historyUnknownOutStyle is 'display:none;' then 'display:table-cell;' else 'display:none;'
text = text.replace('{{isOutStatusNotUnknownStyle}}',isOutStatusNotUnknownStyle);
if historyUnknownOutStyle is 'display:none;'
text = text.replace('{{out_image}}',target.out_image);
text = text.replace('{{out_time}}',getShortTime(target.out_time,group_id));
out_time_Color = 'green'
if target.out_status is 'warning'
out_time_Color = 'orange'
else if target.out_status is 'error'
out_time_Color = 'red'
text = text.replace('{{out_time_Color}}',out_time_Color);
whats_up = ''
if target.whats_up
whatsUpLists = [];
if typeof(target.whats_up) is 'string'
whatsUpLists.push({
person_name:target.person_name,
content:target.whats_up,
ts:target.in_time
})
# ...
else
whatsUpLists = target.whats_up
for item in whatsUpLists
whats_up = whats_up + '<p style="white-space: pre-wrap;"><strong>'+item.person_name+'</strong>['+getShortTime(item.ts,group_id)+']'+item.content
else
whats_up = '今天还没有工作安排...'
text = text.replace('{{whats_up}}',whats_up);
workstatus_content = workstatus_content + text
)
if workstatus_content.length > 0
text = Assets.getText('email/work-status-report.html');
text = text.replace('{{group.name}}', group.name);
y_date = new Date(yesterday)
year = y_date.getFullYear();
month = y_date.getMonth() + 1;
y_date_title = '(' + year + '-' + month + '-' +y_date.getDate() + ')';
text = text.replace('{{date.fomatStr}}',y_date_title)
text = text.replace('{{workStatus.content}}', workstatus_content);
subject = group.name + ' 每日出勤报告'+y_date_title
else
return
#console.log 'html:'+ JSON.stringify(text)
SimpleChat.GroupUsers.find({group_id:group_id}).forEach(
(fields)->
if fields and fields.user_id
user_id = fields.user_id
#user_id = 'GriTByu7MhRGhQdPD'
user = Meteor.users.findOne({_id:user_id});
if user and user.emails and user.emails.length > 0
email_address = user.emails[0].address
#email_address = 'dsun@actionteca.com'
isUnavailable = UnavailableEmails.findOne({address:email_address});
unless isUnavailable
#email_address = user.emails[0].address
console.log 'groupuser : ' + user.profile.fullname + ' email address is :' + user.emails[0].address
try
Email.send({
to:email_address,
from:'点圈<notify@mail.tiegushi.com>',
subject:subject,
html : text,
envelope:{
from:'点圈<notify@mail.tiegushi.com>',
to:email_address + '<' + email_address + '>'
}
})
console.log 'try send mail to:'+email_address
catch e
console.log 'exception:send mail error = %s, userEmail = %s',e,email_address
###
unavailableEmail = UnavailableEmails.findOne({address:email_address})
if unavailableEmail
UnavailableEmails.update({reason:e});
else
UnavailableEmails.insert({address:email_address,reason:e,createAt:new Date()});
###
)
Router.route('/restapi/sendReportByEmail/:token',{where:'server'}).get(()->
token = this.params.token #
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/sendReportByEmail get request'
#sendEmailToGroupUsers('ae64c98bdff9b674fb5dad4b')
groups = SimpleChat.Groups.find({})
groups.forEach((fields)->
if fields
sendEmailToGroupUsers(fields._id)
)
this.response.end(JSON.stringify({result: 'ok'}))
)
# 定义相应的mailgun webhook, dropped,hardbounces,unsubscribe 下次不再向相应的邮件地址发信
# docs: https://documentation.mailgun.com/en/latest/user_manual.html#webhooks
@mailGunSendHooks = (address, type, reason)->
if !address and !reason
return console.log('need email address and webhook reason')
console.log('Email send Hooks, send to '+address + ' failed , reason: '+ reason)
unavailableEmail = UnavailableEmails.findOne({address: address})
if unavailableEmail
UnavailableEmails.update({_id: unavailableEmail._id},{$set:{
reason:reason
}})
else
UnavailableEmails.insert({
address: address,
reason: reason
createAt: new Date()
})
# 发信失败跟踪 (Dropped Messages)
Router.route('/hooks/emails/dropped', {where: 'server'}).post(()->
data = this.request.body
mailGunSendHooks(emails,'dropped')
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
# 硬/软 退信跟踪 (Hard Bounces)
Router.route('/hooks/emails/bounced', {where: 'server'}).post(()->
data = this.request.body
type = data.event || 'bounced'
mailGunSendHooks(data.recipient,type)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
# 垃圾邮件跟踪 (Spam Complaints)
Router.route('/hooks/emails/complained', {where: 'server'}).post(()->
data = this.request.body
type = data.event || 'complained'
mailGunSendHooks(data.recipient,type)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
# 取消订阅跟踪 (Unsubscribes)
Router.route('/hooks/emails/unsubscribe', {where: 'server'}).post(()->
data = this.request.body
type = data.event || 'unsubscribe'
mailGunSendHooks(data.recipient,type)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
#陌生人图片信息
Router.route('/restapi/updateStrangers', {where: 'server'}).post(()->
if this.request.body.hasOwnProperty('imgs')
imgs = this.request.body.imgs
if this.request.body.hasOwnProperty('img_gif')
img_gif = this.request.body.img_gif
if this.request.body.hasOwnProperty('isStrange')
isStrange = this.request.body.isStrange
if this.request.body.hasOwnProperty('createTime')
createTime = this.request.body.createTime
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('camera_id')
cid = this.request.body.camera_id
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('tid')
trackerId = this.request.body.tid
unless imgs and img_gif and group_id and uuid
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
Strangers.insert({
imgs: imgs,
img_gif: img_gif,
group_id: group_id,
camera_id: cid,
uuid: uuid,
trackerId: trackerId,
isStrange: isStrange,
createTime: new Date(),
avatar: imgs[0].url
})
#console.log(Strangers.find({}).fetch())
this.response.end('{"result": "ok"}\n')
)
| 112008 | subs = new SubsManager({
#maximum number of cache subscriptions
cacheLimit: 999,
# any subscription will be expire after 30 days, if it's not subscribed again
expireIn: 60*24*30
});
if Meteor.isServer
request = Meteor.npmRequire('request')
Fiber = Meteor.npmRequire('fibers')
QRImage = Meteor.npmRequire('qr-image')
###
Router.route '/posts/:_id', {
waitOn: ->
[subs.subscribe("publicPosts",this.params._id),
subs.subscribe "pcomments"]
fastRender: true
}
###
injectSignData = (req,res)->
try
console.log(req.url)
if req.url
signature=generateSignature('http://'+server_domain_name+req.url)
if signature
console.log(signature)
InjectData.pushData(res, "wechatsign", signature);
catch error
return null
# 获取对应时区的时间
getLocalTimeByOffset = (i)->
if typeof i isnt 'number'
return
d = new Date()
len = d.getTime()
offset = d.getTimezoneOffset() * 60000
utcTime = len + offset
return new Date(utcTime + 3600000 * i)
Router.configure {
waitOn: ()->
if this and this.path
path=this.path
if path.indexOf('/posts/') is 0
if path.indexOf('?') > 0
path = path.split('?')[0]
params=path.replace('/posts/','')
params=params.split('/')
if params.length > 0
return [subs.subscribe("publicPosts",params[0]),
subs.subscribe("postsAuthor",params[0]),
subs.subscribe "pcomments"]
fastRender: true
}
Router.route('/download-reporter-logs', (req, res, next)->
data = reporterLogs.find({},{sort:{createdAt:-1}}).fetch()
fields = [
{
key:'postId',
title:'帖子Id',
},
{
key:'postTitle',
title:'帖子标题',
},
{
key:'postCreatedAt',
title:'帖子创建时间',
transform: (val, doc)->
d = new Date(val)
return d.toLocaleString()
},
{
key: 'userId',
title: '用户Id(涉及帖子操作时,为帖子Owner)'
},
{
key:'userName',
title:'用户昵称'
},
{
key:'userEmails',
title:'用户Email',
transform: (val, doc)->
emails = ''
if val and val isnt null
val.forEach (item)->
emails += item.address + '\r\n'
return emails;
},
{
key:'eventType',
title: '操作类型'
},
{
key:'loginUser',
title: '操作人员',
transform: (val, doc)->
user = Meteor.users.findOne({_id: val})
userInfo = '_id: '+val+'\r\n username: '+user.username
return userInfo
},
{
key: 'createdAt',
title: '操作时间',
transform: (val, doc)->
d = new Date(val)
return d.toLocaleString()
},
]
title = 'hotShareReporterLogs-'+ (new Date()).toLocaleDateString()
file = Excel.export(title, fields, data)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end(file, 'binary')
, { where: 'server' })
# Router.route('/apple-app-site-association', (req, res, next)->
# #name = 'apple-app-site-association'
# #name = 'import-server'
# fs = Npm.require("fs")
# path = Npm.require('path')
# base = path.resolve('.');
# filepath = path.resolve('.') + '/app/lib/apple-app-site-association';
# #filepath = path.join(__dirname,'../server/import-server.js')
# file = fs.readFileSync(filepath, 'binary');
# headers = {
# 'Content-type': 'application/vnd.openxmlformats',
# 'Content-Disposition': 'attachment; apple-app-site-association'
# }
# this.response.writeHead(200, headers)
# this.response.end(file, 'binary')
# , { where: 'server' })
if Meteor.isServer
workaiId = 'Lh4JcxG7CnmgR3YXe'
workaiName = 'Actiontec'
fomat_greeting_text = (time,time_offset)->
DateTimezone = (d, time_offset)->
if (time_offset == undefined)
if (d.getTimezoneOffset() == 420)
time_offset = -7
else
time_offset = 8
# 取得 UTC time
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
local_now = new Date(utc + (3600000*time_offset))
today_now = new Date(local_now.getFullYear(), local_now.getMonth(), local_now.getDate(),
local_now.getHours(), local_now.getMinutes());
return today_now;
self = time;
now = new Date();
result = '';
self = DateTimezone(time, time_offset);
# DayDiff = now.getDate() - self.getDate();
Minutes = self.getHours() * 60 + self.getMinutes();
# if (DayDiff === 0) {
# result += '今天 '
# } else if (DayDiff === 1) {
# result += '昨天 '
# } else {
# result += self.parseDate('YYYY-MM-DD') + ' ';
# }
if (Minutes >= 0 && Minutes < 360)
result += '凌晨 ';
if (Minutes >= 360 && Minutes < 660)
result += '上午 ';
if (Minutes >= 660 && Minutes < 780)
result += '中午 ';
if (Minutes >= 780 && Minutes < 960)
result += '下午 ';
if (Minutes >= 960 && Minutes < 1080)
result += '傍晚 ';
if (Minutes >= 1080 && Minutes < 1440)
result += '晚上 ';
result += self.parseDate('h:mm');
result = '您的上班时间是 ' + result;
return result;
@send_greeting_msg = (data)->
console.log 'try send_greeting_msg~ with data:'+JSON.stringify(data)
if !data || !data.images ||data.images.img_type isnt 'face'
#console.log 'invalid params'
return
if !data.in_out
device = Devices.findOne({uuid:data.people_uuid})
if !device || !device.in_out
#console.log ' not found device or in_device'
return
data.in_out = device.in_out
person = Person.findOne({group_id:data.group_id,'faces.id':data.images.id},{sort: {createAt: 1}})
if !person
console.log 'not find person with faceid is:'+data.images.id
return
relation = WorkAIUserRelations.findOne({'ai_persons.id':person._id})
create_time = new Date(data.create_time);
if !relation
#console.log 'not find workai user relations'
WorkAIUserRelations.insert({
group_id:data.group_id,
person_name:person.name,
in_uuid:data.people_uuid,
ai_in_time:create_time.getTime(),
ai_lastest_in_time:create_time.getTime(),
ai_in_image:data.images.url,
ai_lastest_in_image:data.images.url,
ai_persons: [
{
id : person._id
}
]
});
return
if data.in_out is 'out'
WorkAIUserRelations.update({_id:relation._id},{$set:{ai_out_time:create_time.getTime(), ai_out_image: data.images.url}});
return
WorkAIUserRelations.update({_id:relation._id},{$set:{ai_lastest_in_time:create_time.getTime(),ai_lastest_in_image:data.images.url}});#平板最新拍到的时间
#再次拍到进门需要把下班的提示移除
if relation.app_user_id
endlog = UserCheckoutEndLog.findOne({userId:relation.app_user_id});
if endlog
outtime = endlog.params.person_info.ts;
if outtime and PERSON.checkIsToday(outtime,data.group_id) and outtime < create_time.getTime()
UserCheckoutEndLog.remove({_id:endlog._id});
if relation.ai_in_time and PERSON.checkIsToday(relation.ai_in_time,data.group_id)
# ai_in_time = new Date(relation.ai_in_time);
# today = new Date(create_time.getFullYear(), create_time.getMonth(), create_time.getDate()).getTime(); #凌晨
# if ai_in_time.getTime() > today
console.log 'today greeting_msg had send'
#WorkAIUserRelations.update({_id:relation._id},{$set:{ai_in_time:create_time.getTime()}});
return
WorkAIUserRelations.update({_id:relation._id},{$set:{ai_in_time:create_time.getTime(), ai_in_image: data.images.url}});
if !relation.app_user_id
return
deviceUser = Meteor.users.findOne({username: data.people_uuid});
time_offset = 8;
group = SimpleChat.Groups.findOne({_id: data.group_id});
if (group && group.offsetTimeZone)
time_offset = group.offsetTimeZone;
sendMqttMessage('/msg/u/'+ relation.app_user_id, {
_id: new Mongo.ObjectID()._str
# form: {
# id: "fTnmgpdDN4hF9re8F",
# name: "workAI",
# icon: "http://data.tiegushi.com/fTnmgpdDN4hF9re8F_1493176458747.jpg"
# }
form:{
id: deviceUser._id,
name: deviceUser.profile.fullname,
icon: deviceUser.profile.icon
}
to: {
id: relation.app_user_id
name: relation.app_user_name
icon: ''
}
images: [data.images]
to_type: "user"
type: "text"
text: fomat_greeting_text(create_time,time_offset)
create_time: new Date()
checkin_time:create_time
is_agent_check:true
offsetTimeZone:time_offset
group_id:data.group_id
people_uuid: data.people_uuid
is_read: false
checkin_out:'in'
})
# 对data 进行处理, data 必须是数组
insertFaces = (face)->
device = Devices.findOne({uuid: face.uuid})
if device and device.name
face.device_name = device.name
face.createdAt = new Date()
Faces.insert(face)
insert_msg2 = (id, url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts,tracker_id,p_ids)->
#people = People.findOne({id: id, uuid: uuid})
name = null
#device = PERSON.upsetDevice(uuid, null)
create_time = new Date()
console.log("insert_msg2: img_ts="+img_ts+", current_ts="+current_ts+", create_time="+create_time)
###
if img_ts and current_ts
img_ts = Number(img_ts)
current_ts = Number(current_ts)
time_diff = img_ts + (create_time.getTime() - current_ts)
create_time = new Date(time_diff)
###
create_time = new Date()
if img_ts and current_ts
img_ts = Number(img_ts)
current_ts = Number(current_ts)
time_diff = img_ts + getTimeZoneDiffByMs(create_time.getTime(), current_ts)
create_time = new Date(time_diff)
#if !people
# people = {_id: new Mongo.ObjectID()._str, id: id, uuid: uuid,name: name,embed: null,local_url: null,aliyun_url: url}
# People.insert(people)
#else
# People.update({_id: people._id}, {$set: {aliyun_url: url}})
device = Devices.findOne({uuid: uuid})
PeopleHis.insert {id: id,uuid: uuid,name: name, people_id: id, embed: null,local_url: null,aliyun_url: url}, (err, _id)->
if err or !_id
return
user = Meteor.users.findOne({username: uuid})
unless user
return
userGroups = SimpleChat.GroupUsers.find({user_id: user._id})
unless userGroups
return
userGroups.forEach((userGroup)->
group = SimpleChat.Groups.findOne({_id:userGroup.group_id});
if group.template and group.template._id
if group.template.img_type != img_type
return
name = null
name = PERSON.getName(null, userGroup.group_id,id)
p_ids_name = [];
#存在可能性最大的三个人的id
# if p_ids and p_ids.length > 0
# for pid in p_ids
# person = Person.findOne({group_id:userGroup.group_id,'faces.id':pid},{sort:{createAt:1}});
# if person
# p_person = {
# name:person.name,
# id:pid,
# url:person.url,
# p_id:person._id
# }
# if(_.pluck(p_ids_name, 'p_id').indexOf(person._id) is -1)
# p_ids_name.push(p_person)
#没有准确度的人一定是没有识别出来的
name = if accuracy then name else null
#没有识别的人的准确度清0
Accuracy = if name then accuracy else false
Fuzziness = fuzziness
if true #name and checkIfSendRecoMsg(userGroup.group_id, uuid, id)
console.log('--------send reco msg to --------', uuid, '----', id, '----', name)
sendMqttMessage('/msg/g/'+ userGroup.group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
icon: user.profile.icon
}
to: {
id: userGroup.group_id
name: userGroup.group_name
icon: userGroup.group_icon
}
images: [
{_id: new Mongo.ObjectID()._str, id: id, people_his_id: _id, url: url, label: name, img_type: img_type, accuracy: Accuracy, fuzziness: Fuzziness, sqlid: sqlid, style: style,p_ids:p_ids_name} # 暂一次只能发一张图
]
to_type: "group"
type: "text"
text: if !name then 'Work AI发现有人在活动' else 'AI观察到 ' + name + ':'
create_time: create_time
people_id: id
people_uuid: uuid
people_his_id: _id
wait_lable: !name
is_people: true
is_read: false
tid:tracker_id
})
# update to DeviceTimeLine
timeObj = {
person_id: id,
person_name: <NAME>,
img_url: url,
sqlid: sqlid,
style: style,
accuracy: Accuracy, # 准确度(分数)
fuzziness: Fuzziness, # 模糊度
ts:create_time.getTime()
}
PERSON.updateToDeviceTimeline(uuid,userGroup.group_id,timeObj)
#识别准确度在0.85以上才自动打卡
#if name and accuracy >= withDefaultAccuracy
#if tablet recognizes this person, update it to mainpage.
if name
msg_data = {
group_id:userGroup.group_id,
create_time:create_time,
people_uuid:uuid,
in_out:userGroup.in_out,
images:{
id: id,
people_his_id: _id,
url: url,
label: <NAME>,
img_type: img_type,
accuracy: Accuracy,
fuzziness: Fuzziness,
sqlid: sqlid,
style: style
}
}
person = Person.findOne({group_id: userGroup.group_id, name: name}, {sort: {createAt: 1}});
person_info = null
if img_type == 'face' && person && person.faceId
#console.log('post person info to aixd.raidcdn')
person_info = {
'id': person._id,
'uuid': uuid,
'name': <NAME>,
'group_id': userGroup.group_id,
'img_url': url,
'type': img_type,
'ts': create_time.getTime(),
'accuracy': accuracy,
'fuzziness': fuzziness
}
relation = WorkAIUserRelations.findOne({'ai_persons.id': person._id})
if (device.in_out is 'in' and relation and relation.app_user_id)
wsts = WorkStatus.findOne({group_id: userGroup.group_id, app_user_id: relation.app_user_id}, {sort: {date: -1}})
if (wsts and !wsts.whats_up)
CreateSatsUpTipTask(relation.app_user_id, userGroup.group_id, device.uuid)
if (device.in_out is 'out' and relation and relation.app_user_id)
checkout_msg = {
userId: relation.app_user_id,
userName: relation.app_user_name,
createAt: new Date(),
params: {
msg_data: msg_data,
person: person,
person_info: person_info
}
}
# UserCheckoutEndLog.remove({userId: relation.app_user_id})
# UserCheckoutEndLog.insert(checkout_msg)
# sendUserCheckoutEvent(uuid, relation.app_user_id)
# return
# 到下班时间后,不终止后续处理
group_outtime = '18:00'
time_offset = 8
if (group and group.group_outtime)
group_outtime = group.group_outtime
if group and group.offsetTimeZone
time_offset = group.offsetTimeZone
group_outtime_H = parseInt(group_outtime.split(":")[0])
group_outtime_M = parseInt(group_outtime.split(":")[1])
group_out_minutes = group_outtime_H * 60 + group_outtime_M
out_time_H = parseInt(create_time.getUTCHours() + time_offset)
out_time_M = create_time.getMinutes()
out_time_minutes = out_time_H * 60 + out_time_M
# 到下班时间后,不自动 checkout(这里先取消, 目前:统一采用自动checkout的方式,但保留手动checkout)
# if (out_time_minutes < group_out_minutes)
# return
send_greeting_msg(msg_data);
PERSON.updateWorkStatus(person._id)
if person_info
PERSON.sendPersonInfoToWeb(person_info)
console.log("device.in_out", device, relation)
if ((device.name.includes('inout') or device.in_out is 'inout' or device.uuid is '28D6R17505001070') and relation)
Devices.update({_id: device._id}, {$set: {in_out:'inout'}});
console.log("activity_update_time")
activity_update_time(person._id, create_time, url)
)
@insert_msg2forTest = (id, url, uuid, accuracy, fuzziness)->
insert_msg2(id, url, uuid, 'face', accuracy, fuzziness, 0, 0)
# 平板 发现 某张图片为 错误识别(不涉及标记), 需要移除 或 修正 相应数据
padCallRemove = (id, url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts,tracker_id,p_ids)->
console.log("padCallRemove: id="+id+", url="+url+", uuid="+uuid+", img_type="+img_type+", accuracy="+accuracy+", fuzziness="+fuzziness+", sqlid="+sqlid+", style="+style+", img_ts="+img_ts+", current_ts="+current_ts+", tracker_id="+tracker_id+", p_ids="+p_ids)
create_time = new Date()
if img_ts and current_ts
img_ts = Number(img_ts)
current_ts = Number(current_ts)
time_diff = img_ts + getTimeZoneDiffByMs(create_time.getTime(), current_ts)
create_time = new Date(time_diff)
hour = new Date(create_time.getTime())
hour.setMinutes(0)
hour.setSeconds(0)
hour.setMilliseconds(0)
console.log("hour="+hour)
minutes = new Date(create_time.getTime())
minutes = minutes.getMinutes()
console.log("minutes="+minutes)
# Step 1. 修正出现记录, WorkAIUserRelations或workStatus
fixWorkStatus = (work_status,in_out)->
today = new Date(create_time.getTime())
today.setHours(0,0,0,0)
console.log('hour='+hour+', today='+today+', uuid='+uuid)
timeline = DeviceTimeLine.findOne({hour:{$lte: hour, $gt: today},uuid: uuid},{sort: {hour: -1}});
if timeline and timeline.perMin # 通过历史记录中的 数据 fix WorkStatus
time = null
imgUrl = null
timelineArray = for mins of timeline.perMin
timeline.perMin[mins]
for obj in timelineArray
if obj.img_url is url
time = Number(obj.ts)
imgUrl = obj.img_url
break
if in_out is 'in'
setObj = {
in_time: time,
in_image: imgUrl,
in_status: 'normal'
}
if !work_status.out_time
setObj.status = 'in'
else if time < work_status.out_time
setObj.status = 'out'
else if time >= work_status.out_time
setObj.status = 'in'
if in_out is 'out'
setObj = {
out_time: time,
out_image: imgUrl,
out_status: 'normal'
}
if !work_status.in_time
setObj.status = 'out'
setObj.out_status = 'warning'
else if time <= work_status.in_time
setObj.status = 'in'
else if time > work_status.in_time
setObj.status = 'out'
else
if in_out is 'in'
setObj = {
status: 'out',
in_uuid: null,
in_time: null,
in_image: null,
in_status: 'unknown'
}
if in_out is 'out'
setObj = {
status: 'in',
out_uuid: null,
out_time: null,
out_image: null,
out_status: 'unknown'
}
if !work_status.in_time
setObj.status = 'out'
WorkStatus.update({_id: work_status._id},$set: setObj)
work_status_in = WorkStatus.findOne({in_image: url})
# 匹配到进的出现
if work_status_in
console.log('padCallRemove Fix WorkStatus, 需要修正进的出现')
#fixWorkStatus(work_status_in,'in')
work_status_out = WorkStatus.findOne({out_image: url})
# 匹配到出的出现
if work_status_out
console.log('padCallRemove Fix WorkStatus, 需要修正出的出现')
#fixWorkStatus(work_status_out,'out')
# 删除出现
WorkStatus.remove({$or:[{in_image: url},{out_image: url}]});
# Step 2. 从设备时间轴中移除
selector = {
hour: hour,
uuid: uuid
}
selector["perMin."+minutes+".img_url"] = url;
###
console.log('selector='+JSON.stringify(selector))
timeline = DeviceTimeLine.findOne(selector)
console.log("timeline._id="+JSON.stringify(timeline._id))
if timeline
minuteArray = timeline.perMin[""+minutes]
console.log("minuteArray="+JSON.stringify(minuteArray))
minuteArray.splice(_.pluck(minuteArray, 'img_url').indexOf(url), 1)
console.log("2, minuteArray="+JSON.stringify(minuteArray))
modifier = {
$set:{}
}
modifier.$set["perMin."+minutes] = minuteArray
DeviceTimeLine.update({_id: timeline._id}, modifier, (err,res)->
if err
console.log('padCallRemove DeviceTimeLine, update Err:'+err)
else
console.log('padCallRemove DeviceTimeLine, update Success')
)
###
console.log('selector='+JSON.stringify(selector))
modifier = {$set:{}}
modifier.$set["perMin."+minutes+".$.person_name"] = null
modifier.$set["perMin."+minutes+".$.accuracy"] = false
DeviceTimeLine.update(selector, modifier, (err,res)->
if err
console.log('padCallRemove DeviceTimeLine, update Err:'+err)
else
console.log('padCallRemove DeviceTimeLine, update Success')
)
# Step 3. 如果 person 表中 有此图片记录, 需要移除
person = Person.findOne({'faces.id': id})
if person
faces = person.faces
faces.splice(_.pluck(faces, 'id').indexOf(obj.face_id), 1)
Person.update({_id: person._id},{$set: {faces: faces}})
# Step 4. 向Group 发送一条 mqtt 消息, 告知需要移除 错误识别 的照片
device = Devices.findOne({uuid: uuid});
if device and device.groupId
group_id = device.groupId
group = SimpleChat.Groups.findOne({_id: group_id})
to = {
id: group._id,
name: group.name,
icon: group.icon
}
device_user = Meteor.users.findOne({username: uuid})
form = {}
if device_user
form = {
id: device_user._id,
name: if (device_user.profile and device_user.profile.fullname) then device_user.profile.fullname else device_user.username,
icon: device_user.profile.icon
}
msg = {
_id: new Mongo.ObjectID()._str,
form: form,
to: to,
to_type: 'group',
type: 'remove_error_img',
id: id,
url: url,
uuid: uuid,
img_type: img_type,
img_ts: img_ts,
current_ts: current_ts,
tid: tracker_id,
pids: p_ids
}
try
sendMqttGroupMessage(group_id,msg)
catch error
console.log('try sendMqttGroupMessage Err:',error)
update_group_dataset = (group_id,dataset_url,uuid)->
unless group_id and dataset_url and uuid
return
group = SimpleChat.Groups.findOne({_id:group_id})
user = Meteor.users.findOne({username: uuid})
if group and user
announcement = group.announcement;
unless announcement
announcement = []
i = 0
isExit = false
while i < announcement.length
if announcement[i].uuid is uuid
announcement[i].dataset_url = dataset_url
isExit = true
break;
i++
unless isExit
announcementObj = {
uuid:uuid,
device_name:user.profile.fullname,
dataset_url:dataset_url
};
announcement.push(announcementObj);
SimpleChat.Groups.update({_id:group_id},{$set:{announcement:announcement}})
# test
# Meteor.startup ()->
# insert_msg2(
# '7YRBBDB72200271715027668215821893',
# 'http://workaiossqn.tiegushi.com/8acb7f90-92e1-11e7-8070-d065caa7da61',
# '28DDU17602003551',
# 'face',
# '0.9',
# '100',
# '0',
# 'front',
# 1506588441021,
# 1506588441021,
# ''
# )
# Faces API
# [{
# 'id': id,
# 'uuid': uuid,
# 'group_id': current_groupid,
# 'img_url': url,
# 'position': position,
# 'type': img_type,
# 'current_ts': int(time.time()*1000),
# 'accuracy': accuracy,
# 'fuzziness': fuzziness,
# 'sqlid': sqlId,
# 'style': style,
# 'tid': tid,
# 'img_ts': img_ts,
# 'p_ids': p_ids,
# }]
Router.route('/restapi/workai/faces', {where: 'server'}).post(()->
data = this.request.body
if (typeof data is 'object' and data.constructor is Array)
data.forEach((face)->
insertFaces(face)
)
this.response.end('{"result": "ok"}\n')
else
this.response.end('{"result": "ok", "reason": "params must be an Array"}\n')
)
Router.route('/restapi/list_device', {where: 'server'}).get(()->
uuid = this.params.query.uuid
console.log(groups)
device = Devices.findOne({"uuid" : uuid})
ret_str = ''
if device
user = {'_id': device._id, 'username': device.name, 'profile': {'icon': '/device_icon_192.png'}}
ret_str += 'Device['+uuid+'] in Devices deleted \n'
if device.groupId
group_id = device.groupId
#SimpleChat.GroupUsers.remove({group_id:group_id,user_id:user._id});
groups = SimpleChat.GroupUsers.find({group_id:group_id,user_name:uuid}).fetch();
console.log(groups)
ret_str += groups.toString()
user = Meteor.users.findOne({username: uuid})
if user
users = Meteor.users.find({username: uuid}).fetch()
console.log(users)
ret_str += users.toString()
if ret_str is ''
return this.response.end('nothing in db')
this.response.end(ret_str)
#userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
#unless userGroup or userGroup.group_id
# return this.response.end('{"result": "failed", "cause": "group not found"}\n')
)
Router.route('/restapi/get_name_by_faceid', {where: 'server'}).get(()->
face_id = this.params.query.face_id
group_id = this.params.query.group_id
if not face_id or not group_id
return this.response.end(JSON.stringify({result: 'invalid parameters'}))
person = Person.findOne({group_id: group_id, faceId: face_id})
if not person
return this.response.end(JSON.stringify({result: 'no such item'}))
return this.response.end(JSON.stringify({result: 'success', name: person.name}))
)
Router.route('/restapi/clean_device', {where: 'server'}).get(()->
uuid = this.params.query.uuid
device = Devices.findOne({"uuid" : uuid})
ret_str = ''
if device
Devices.remove({uuid : uuid})
Devices.remove({_id:device._id});
ret_str += 'Device['+uuid+'] in Devices deleted \n'
if device.groupId
group_id = device.groupId
#SimpleChat.GroupUsers.remove({group_id:group_id,user_id:user._id});
SimpleChat.GroupUsers.remove({group_id:group_id,user_name:uuid});
ret_str += 'Device in userGroup in SimpleChat.GroupUsers deleted \n'
user = Meteor.users.findOne({username: uuid})
if user
Meteor.users.remove({username: uuid})
ret_str += 'Device['+uuid+'] in Meteor.users deleted \n'
if ret_str is ''
return this.response.end('nothing to delete')
this.response.end(ret_str)
#userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
#unless userGroup or userGroup.group_id
# return this.response.end('{"result": "failed", "cause": "group not found"}\n')
)
###
payload = {'groupid': groupid, 'uuid': uuid,'fuzziness_from':fuzziness_from, 'fuzziness_to':fuzziness_to,
'blury_threshold': blury_threshold, 'score_threshold_main': score_threshold_main, 'score_threshold_2nd': score_threshold_2nd}
###
Router.route('/restapi/workai/model_param_update', {where: 'server'}).post(()->
group_id = this.request.body.groupid
uuid = this.request.body.uuid
if group_id and uuid
ModelParam.upsert({groupid: group_id, uuid: uuid}, {$set: this.request.body})
this.response.end('{"result": "ok"}\n')
else
this.response.end('{"result": "ok", "reason": "invalid params"}\n')
)
Router.route('/restapi/workai/model_param', {where: 'server'}).post(()->
group_id = this.request.body.groupid
uuid = this.request.body.uuid
if group_id and uuid
params = ModelParam.findOne({groupid: group_id, uuid: uuid})
this.response.end(JSON.stringify(params) + '\n')
else
this.response.end('{"result": "ok", "reason": "invalid params"}\n')
)
Router.route('/restapi/workai', {where: 'server'}).get(()->
id = this.params.query.id
img_url = this.params.query.img_url
uuid = this.params.query.uuid
img_type = this.params.query.type
tracker_id = this.params.query.tid
console.log '/restapi/workai get request, id:' + id + ', img_url:' + img_url + ',uuid:' + uuid
unless id or img_url or uuid
return this.response.end('{"result": "failed", "cause": "invalid params,check id,uuid,img_url"}\n')
accuracy = this.params.query.accuracy
sqlid = this.params.query.sqlid
style = this.params.query.style
fuzziness = this.params.query.fuzziness
img_ts = this.params.query.img_ts
current_ts = this.params.query.current_ts
if this.params.query.opt and this.params.query.opt is 'remove'
padCallRemove(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style, img_ts, current_ts, tracker_id)
else
insert_msg2(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts,tracker_id)
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('id')
id = this.request.body.id
if this.request.body.hasOwnProperty('img_url')
img_url = this.request.body.img_url
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('type')
img_type = this.request.body.type
if this.request.body.hasOwnProperty('sqlid')
sqlid = this.request.body.sqlid
else
sqlid = 0
if this.request.body.hasOwnProperty('style')
style = this.request.body.style
else
style = 0
if this.request.body.hasOwnProperty('img_ts')
img_ts = this.request.body.img_ts
if this.request.body.hasOwnProperty('current_ts')
current_ts = this.request.body.current_ts
if this.request.body.hasOwnProperty('tid')
tracker_id = this.request.body.tid
if this.request.body.hasOwnProperty('p_ids') #可能性最大的三个人的id
p_ids = this.request.body.p_ids
console.log '/restapi/workai post request, id:' + id + ', img_url:' + img_url + ',uuid:' + uuid + ' img_type=' + img_type + ' sqlid=' + sqlid + ' style=' + style + 'img_ts=' + img_ts
unless id or img_url or uuid
return this.response.end('{"result": "failed", "cause": "invalid params,check id,uuid,img_url"}\n')
accuracy = this.params.query.accuracy
fuzziness = this.params.query.fuzziness
if this.params.query.opt and this.params.query.opt is 'remove'
padCallRemove(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style, img_ts, current_ts, tracker_id)
else
insert_msg2(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts, tracker_id,p_ids)
this.response.end('{"result": "ok"}\n')
)
Router.route('restapi/workai_unknown', {where: 'server'}).get(()->
).post(()->
person_id = ''
persons = []
person_name = null
active_time = null
if this.request.body.hasOwnProperty('person_id')
person_id = this.request.body.person_id
if this.request.body.hasOwnProperty('persons')
persons = this.request.body.persons
console.log("restapi/workai_unknown post: person_id="+person_id+", persons="+JSON.stringify(persons))
if (!(persons instanceof Array) or persons.length < 1)
console.log("restapi/workai_unknown: this.request.body is not array.")
return this.response.end('{"result": "failed!", "cause": "this.request.body is not array."}\n')
console.log("restapi/workai_unknown: uuid = "+persons[0].uuid)
user = Meteor.users.findOne({username: persons[0].uuid})
unless user
console.log("restapi/workai_unknown: user is null")
return this.response.end('{"result": "failed!", "cause": "user is null."}\n')
userGroups = SimpleChat.GroupUsers.find({user_id: user._id})
unless userGroups
console.log("restapi/workai_unknown: userGroups is null")
return this.response.end('{"result": "failed!", "cause":"userGroups is null."}\n')
stranger_id = if person_id != '' then person_id else new Mongo.ObjectID()._str
#name = PERSON.getName(null, userGroup.group_id, person_id)
userGroups.forEach((userGroup)->
console.log("restapi/workai_unknown: userGroup.group_id="+userGroup.group_id)
stranger_name = if person_id != '' then PERSON.getName(null, userGroup.group_id, person_id) else new Mongo.ObjectID()._str
console.log("stranger_name="+stranger_name)
for person in persons
console.log("person="+JSON.stringify(person))
unless active_time
active_time = utilFormatTime(Number(person.img_ts))
if !person_name && person_id != ''
person_name = PERSON.getName(null, userGroup.group_id, person_id)
console.log("person_name="+person_name)
# update to DeviceTimeLine
create_time = new Date()
console.log("create_time.toString()="+create_time.toString())
if person.img_ts and person.current_ts
img_ts = Number(person.img_ts)
current_ts = Number(person.current_ts)
time_diff = img_ts + getTimeZoneDiffByMs(create_time.getTime(), current_ts)
console.log("time_diff="+time_diff)
create_time = new Date(time_diff)
timeObj = {
stranger_id: stranger_id,
stranger_name: stranger_name,
person_id: person.id,
person_name: person.name,
img_url: person.img_url,
sqlid: person.sqlid,
style: person.style,
accuracy: person.accuracy, # 准确度(分数)
fuzziness: person.fuzziness#, # 模糊度
ts:create_time.getTime()
}
uuid = person.uuid
PERSON.updateValueToDeviceTimeline(uuid,userGroup.group_id,timeObj)
if person_name
console.log("restapi/workai_unknown: person_name="+person_name)
#Get Configuration from DB
people_config = WorkAIUserRelations.find({'group_id':userGroup.group_id}, {fields:{'person_name':1, 'hide_it':1}}).fetch()
isShow = people_config.some((elem) => elem.person_name == person_name && !elem.hide_it)
console.log("people_config="+JSON.stringify(people_config))
if isShow and checkIfSendKnownUnknownPushNotification(userGroup.group_id,person_id)
group = SimpleChat.Groups.findOne({_id: userGroup.group_id})
group_name = '监控组'
if group && group.name
group_name = group.name
console.log("group_id="+userGroup.group_id)
console.log("Will notify one known people")
ai_person = Person.findOne({group_id:userGroup.group_id ,'faces.id': person_id});
ai_person_id = if ai_person then ai_person._id else null
sharpai_pushnotification("notify_knownPeople", {active_time:active_time, group_id:userGroup.group_id, group_name:group_name, person_name:person_name}, null, ai_person_id)
else
group = SimpleChat.Groups.findOne({_id: userGroup.group_id})
group_name = '监控组'
is_notify_stranger = true
if group && group.settings && group.settings.notify_stranger == false
is_notify_stranger = false
if group && group.name
group_name = group.name
console.log("group_id="+userGroup.group_id+", is_notify_stranger="+is_notify_stranger)
if is_notify_stranger and checkIfSendKnownUnknownPushNotification(userGroup.group_id,'0')
console.log("Will notify stranger")
sharpai_pushnotification("notify_stranger", {active_time:active_time, group_id:userGroup.group_id, group_name:group_name}, null, null)
)
this.response.end('{"result": "ok"}\n')
)
Router.route('restapi/workai_multiple_people', {where: 'server'}).get(()->
).post(()->
person_id = ''
persons = []
active_time = null
if this.request.body.hasOwnProperty('person_id')
person_id = this.request.body.person_id
if this.request.body.hasOwnProperty('persons')
persons = this.request.body.persons
console.log("restapi/workai_multiple_people post: person_id="+person_id+", persons="+JSON.stringify(persons))
if (!(persons instanceof Array) or persons.length < 1)
console.log("restapi/workai_multiple_people: this.request.body is not array.")
return this.response.end('{"result": "failed!", "cause": "this.request.body is not array."}\n')
console.log("restapi/workai_multiple_people: uuid = "+persons[0].uuid)
user = Meteor.users.findOne({username: persons[0].uuid})
unless user
console.log("restapi/workai_multiple_people: user is null")
return this.response.end('{"result": "failed!", "cause": "user is null."}\n')
userGroups = SimpleChat.GroupUsers.find({user_id: user._id})
unless userGroups
console.log("restapi/workai_multiple_people: userGroups is null")
return this.response.end('{"result": "failed!", "cause":"userGroups is null."}\n')
for person in persons
console.log("person="+JSON.stringify(person))
unless active_time
active_time = utilFormatTime(Number(person.img_ts))
userGroups.forEach((userGroup)->
console.log("restapi/workai_multiple_people: userGroup.group_id="+userGroup.group_id)
#Get Configuration from DB
people_config = WorkAIUserRelations.find({'group_id':userGroup.group_id}, {fields:{'person_name':1, 'hide_it':1}}).fetch()
console.log("people_config="+JSON.stringify(people_config))
multiple_persons = []
for person in persons
if person.accuracy == 0
continue
person_name = PERSON.getName(null, userGroup.group_id, person.id)
console.log("restapi/workai_multiple_people: person_name="+person_name)
isShow = people_config.some((elem) => elem.person_name == person_name && !elem.hide_it)
if isShow
if !multiple_persons.some((elem) => elem == person_name)
multiple_persons.push(person_name)
if multiple_persons.length == 0
console.log("restapi/workai_multiple_people: No people in the request body.")
return
group = SimpleChat.Groups.findOne({_id: userGroup.group_id})
group_name = '监控组'
is_notify_stranger = true
if group && group.settings && group.settings.notify_stranger == false
is_notify_stranger = false
if group && group.name
group_name = group.name
console.log("group_id="+userGroup.group_id)
console.log("Will notify known multiple people")
sharpai_pushnotification("notify_knownPeople", {active_time:active_time, group_id:userGroup.group_id, group_name:group_name, person_name:multiple_persons.join(', ')}, null)
)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-group-qrcode', {where: 'server'}).get(()->
group_id = this.params.query.group_id
console.log '/restapi/workai-group-qrcode get request, group_id: ', group_id
try
img = QRImage.image('http://' + server_domain_name + '/simple-chat/to/group?id=' + group_id, {size: 10})
this.response.writeHead(200, {'Content-Type': 'image/png'})
img.pipe(this.response)
catch
this.response.writeHead(414, {'Content-Type': 'text/html'})
this.response.end('<h1>414 Request-URI Too Large</h1>')
)
device_join_group = (uuid,group_id,name,in_out)->
device = PERSON.upsetDevice(uuid, group_id,name,in_out)
user = Meteor.users.findOne({username: uuid})
if !user
userId = Accounts.createUser({username: uuid, password: '<PASSWORD>', profile: {fullname: device.name, icon: '/device_icon_192.png'},is_device:true})
user = Meteor.users.findOne({_id: userId})
else
Meteor.users.update({_id:user._id},{$set:{'profile.fullname':device.name, 'profile.icon':'/device_icon_192.png', is_device:true }});
group = SimpleChat.Groups.findOne({_id: group_id})
#一个设备只允许加入一个群
groupUsers = SimpleChat.GroupUsers.find({user_id: user._id})
hasBeenJoined = false
if groupUsers.count() > 0
groupUsers.forEach((groupUser)->
if groupUser.group_id is group_id
SimpleChat.GroupUsers.update({_id:groupUser._id},{$set:{is_device:true,in_out:in_out,user_name:device.name}});
hasBeenJoined = true
else
_group = SimpleChat.Groups.findOne({_id: groupUser.group_id})
SimpleChat.GroupUsers.remove(groupUser._id)
sendMqttMessage('/msg/g/'+ _group._id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
icon: user.profile.icon
}
to: {
id: _group._id
name: _group.name
icon: _group.icon
}
images: []
to_type: "group"
type: "text"
text: if user.profile and user.profile.fullname then user.profile.fullname + '[' +user.username + '] 已退出该群!' else '设备 ['+user.username+'] 已退出该群!'
create_time: new Date()
is_read: false
})
)
if hasBeenJoined is false
SimpleChat.GroupUsers.insert({
group_id: group_id
group_name: group.name
group_icon: group.icon
user_id: user._id
user_name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
user_icon: if user.profile and user.profile.icon then user.profile.icon else '/device_icon_192.png'
create_time: new Date()
is_device:true
in_out:in_out
});
sendMqttMessage('/msg/g/'+ group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
icon: user.profile.icon
}
to: {
id: group_id
name: group.name
icon: group.icon
}
images: []
to_type: "group"
type: "text"
text: if user.profile and user.profile.fullname then user.profile.fullname + '[' +user.username + '] 已加入!' else '设备 ['+user.username+'] 已加入!'
create_time: new Date()
is_read: false
})
Meteor.call 'ai-system-register-devices',group_id,uuid, (err, result)->
if err or result isnt 'succ'
return console.log('register devices to AI-system failed ! err=' + err);
if result == 'succ'
return console.log('register devices to AI-system succ');
console.log('user:', user)
console.log('device:', device)
Meteor.methods {
"join-group":(uuid,group_id,name,in_out)->
console.log("uuid = "+uuid+" group id= "+group_id+" name= "+name+" inout = "+in_out)
device_join_group(uuid,group_id,name,'inout')
sendMqttMessage('/msg/d/'+uuid, {text:'groupchanged'});
return "ok"
}
Router.route('/restapi/workai-join-group', {where: 'server'}).get(()->
uuid = this.params.query.uuid
group_id = this.params.query.group_id
console.log '/restapi/workai-join-group get request, uuid:' + uuid + ', group_id:' + group_id
name = this.params.query.name
in_out = this.params.query.in_out
unless uuid or group_id or in_out or name
console.log '/restapi/workai-join-group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
device_join_group(uuid,group_id,name,'inout')
sendMqttMessage('/msg/d/'+uuid, {text:'groupchanged'});
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('name')
name = this.request.body.name
if this.request.body.hasOwnProperty('in_out')
in_out = this.request.body.in_out
console.log '/restapi/workai-join-group post request, uuid:' + uuid + ', group_id:' + group_id
unless uuid or group_id or in_out or name
console.log '/restapi/workai-join-group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
device_join_group(uuid,group_id,name,in_out)
sendMqttMessage('/msg/d/'+uuid, {text:'groupchanged'});
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-group-dataset', {where: 'server'}).get(()->
group_id = this.params.query.group_id
value = this.params.query.value
uuid = this.params.query.uuid
console.log '/restapi/workai-group-dataset get request, group_id:' + group_id + ', value:' + value + ', uuid:' + uuid
unless value and group_id and uuid
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
# insert_msg2(id, img_url, uuid)
update_group_dataset(group_id,value,uuid)
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.id
if this.request.body.hasOwnProperty('value')
value = this.request.body.img_url
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
console.log '/restapi/workai-group-dataset get request, group_id:' + group_id + ', value:' + value + ', uuid:' + uuid
unless value and group_id and uuid
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
#insert_msg2(id, img_url, uuid)
update_group_dataset(group_id,value,uuid)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-getgroupid', {where: 'server'}).get(()->
uuid = this.params.query.uuid
#console.log '/restapi/workai-getgroupid get request, uuid:' + uuid
unless uuid
console.log '/restapi/workai-getgroupid get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
user = Meteor.users.findOne({username: uuid})
device_group = ''
if user
groupUser = SimpleChat.GroupUsers.find({user_id: user._id})
groupUser.forEach((device)->
if device.group_id
device_group += device.group_id
device_group += ','
)
this.response.end(device_group)
)
Router.route('/restapi/workai-send2group', {where: 'server'}).get(()->
uuid = this.params.query.uuid
group_id = this.params.query.group_id
msg_type = this.params.query.type
msg_text = this.params.query.text
is_device_traing = this.params.query.is_device_traing
unless uuid or group_id
console.log '/restapi/workai-send2group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
if (msg_type == 'text' and msg_text)
user = null
userGroup = null
device = Devices.findOne({"uuid" : uuid})
if device and device.groupId
user = {'_id': device._id, 'username': device.name, 'profile': {'icon': '/device_icon_192.png'}}
userGroup = SimpleChat.GroupUsers.findOne({group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
else
user = Meteor.users.findOne({username: uuid})
unless user
return this.response.end('{"result": "failed", "cause": "device not registered"}\n')
userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
sendMqttMessage('/msg/g/'+ userGroup.group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname + '['+user.username+']' else user.username
icon: user.profile.icon
}
to: {
id: userGroup.group_id
name: userGroup.group_name
icon: userGroup.group_icon
}
images: []
to_type: "group"
type: "text"
text: msg_text
create_time: new Date()
is_read: false
is_device_traing: is_device_traing
})
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('type')
msg_type = this.request.body.type
if this.request.body.hasOwnProperty('text')
msg_text = this.request.body.text
if this.request.body.hasOwnProperty('is_device_traing')
is_device_traing = this.request.body.is_device_traing
unless uuid or group_id
console.log '/restapi/workai-send2group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
if (msg_type == 'text' and msg_text)
user = null
userGroup = null
device = Devices.findOne({"uuid" : uuid})
if device and device.groupId
user = {'_id': device._id, 'username': device.name, 'profile': {'icon': '/device_icon_192.png'}}
userGroup = SimpleChat.GroupUsers.findOne({group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
else
user = Meteor.users.findOne({username: uuid})
unless user
return this.response.end('{"result": "failed", "cause": "device not registered"}\n')
userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
sendMqttMessage('/msg/g/'+ userGroup.group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname + '['+user.username+']' else user.username
icon: user.profile.icon
}
to: {
id: userGroup.group_id
name: userGroup.group_name
icon: userGroup.group_icon
}
images: []
to_type: "group"
type: "text"
text: msg_text
create_time: new Date()
is_read: false
is_device_traing: is_device_traing
})
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-group-template', {where: 'server'}).get(()->
result = {
group_templates:[
{
"_id" : new Mongo.ObjectID()._str,
"name": "Work AI工作效能模版",
"icon": rest_api_url + "/workAIGroupTemplate/efficiency.jpg",
"img_type": "face"
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "家庭安全模版",
"icon": rest_api_url + "/workAIGroupTemplate/safety.jpg",
"img_type": "object"
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "NLP情绪分析模版",
"icon": rest_api_url + "/workAIGroupTemplate/sentiment.jpg"
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "NLP通用文本分类模版",
"icon": rest_api_url + "/workAIGroupTemplate/classification.jpg",
"type":'nlp_classify'
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "ChatBot训练模版",
"icon": rest_api_url + "/workAIGroupTemplate/chatBot.jpg"
}
]}
this.response.end(JSON.stringify(result))
)
onNewHotSharePost = (postData)->
console.log 'onNewHotSharePost:' , postData
nlp_group = SimpleChat.Groups.findOne({_id:'92bf785ddbe299bac9d1ca82'});
nlp_user = Meteor.users.findOne({_id: 'xWA3KLXDprNe8Lczw'});
#nlp_classname = NLP_CLASSIFY.getName()
nlp_classname = postData.classname
if nlp_classname
NLP_CLASSIFY.setName(nlp_group._id,nlp_classname)
sendMqttMessage('/msg/g/'+ nlp_group._id, {
_id: new Mongo.ObjectID()._str
form: {
id: nlp_user._id
name: if nlp_user.profile and nlp_user.profile.fullname then nlp_user.profile.fullname + '['+nlp_user.username+']' else nlp_user.username
icon: nlp_user.profile.icon
}
to: {
id: nlp_group._id
name: nlp_group.name
icon: nlp_group.icon
}
to_type: "group"
type: "url"
text: if !nlp_classname then '1 个链接需要标注' else nlp_className + ':'
urls:[{
_id:new Mongo.ObjectID()._str,
label: nlp_classname,
#class_id:postData.classid,
url:postData.posturl,
title:postData.posttitle,
thumbData:postData.mainimage,
description:if postData.description then postData.description else postData.posturl
}]
create_time: new Date()
class_name: nlp_classname
wait_lable: !nlp_classname
is_read: false
})
Router.route('/restapi/workai-hotshare-newpost', {where: 'server'}).get(()->
classname = this.params.query.classname
#username = this.params.query.username
posttitle = this.params.query.posttitle
posturl = this.params.query.posturl
mainimage = this.params.query.mainimage
description = this.params.query.description
postData = { classname: classname, posttitle: posttitle, posturl: posturl ,mainimage:mainimage, description:description}
onNewHotSharePost(postData)
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('classname')
classname = this.request.body.classname
if this.request.body.hasOwnProperty('posttitle')
posttitle = this.request.body.posttitle
if this.request.body.hasOwnProperty('posturl')
posturl = this.request.body.posturl
if this.request.body.hasOwnProperty('mainimage')
mainimage = this.request.body.mainimage
if this.request.body.hasOwnProperty('description')
description = this.request.body.description
postData = { classname: classname, posttitle: posttitle, posturl: posturl, mainimage:mainimage, description:description}
onNewHotSharePost(postData)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-motion-imgs/:id', {where: 'server'}).get(()->
id = this.params.id
post = Posts.findOne({_id: id})
html = Assets.getText('workai-motion-imgs.html');
imgs = ''
post.docSource.imgs.forEach (img)->
imgs += '<li><img src="'+img+'" /></li>'
html = html.replace('{{imgs}}', imgs)
this.response.end(html)
)
Router.route('/restapi/workai-motion', {where: 'server'}).post(()->
payload = this.request.body || {}
deviceUser = Meteor.users.findOne({username: payload.uuid})|| {}
groupUser = SimpleChat.GroupUsers.findOne({user_id: deviceUser._id}) || {} # 一个平板只对应一个聊天群
group = SimpleChat.Groups.findOne({_id: groupUser.group_id})
if (!group)
return this.response.end('{"result": "error"}\n')
if (payload.motion_gif)
imgs = [payload.motion_gif]
# if (payload.imgs)
# imgs = payload.imgs
if (!imgs or imgs.length <= 0)
return this.response.end('{"result": "error"}\n')
if (imgs.length > 10)
imgs = imgs.slice(0, 9)
deferSetImmediate ()->
# update follow
SimpleChat.GroupUsers.find({group_id: group._id}).forEach (item)->
if (Follower.find({userId: item.user_id, followerId: deviceUser._id}).count() <= 0)
console.log('insert follower:', item.user_id)
Follower.insert({
userId: item.user_id
followerId: deviceUser._id
createAt: new Date()
})
#一个设备一天的动作只放在一个帖子里
devicePost = Posts.findOne({owner:deviceUser._id})
isTodayPost = false;
if(devicePost)
today = new Date().toDateString()
isTodayPost = if devicePost.createdAt.toDateString() is today then true else false;
console.log 'isTodayPost:'+isTodayPost
name = PERSON.getName(payload.uuid, group._id, payload.id)
postId = if isTodayPost then devicePost._id else new Mongo.ObjectID()._str
deviceName = if deviceUser.profile and deviceUser.profile.fullname then deviceUser.profile.fullname else deviceUser.username
title = if name then "摄像头看到#{name} 在#{deviceName}" else (if payload.type is 'face' then "摄像头看到有人在#{deviceName}" else "摄像头看到#{deviceName}有动静")
time = '时间:' + new Date().toString()
post = {
pub: if isTodayPost then devicePost.pub else []
title: title
addontitle: time
browse: 0
heart: []
retweet: []
comment: []
commentsCount: 0
mainImage: if payload.motion_gif then payload.motion_gif else payload.img_url
publish: true
owner: deviceUser._id
ownerName: <NAME>Name
ownerIcon: if deviceUser.profile and deviceUser.profile.icon then deviceUser.profile.icon else '/userPicture.png'
createdAt: new Date # new Date(payload.ts)
isReview: true
insertHook: true
import_status: 'done'
fromUrl: ''
docType: 'motion'
docSource: payload
}
newPub = []
# newPub.push({
# _id: new Mongo.ObjectID()._str
# type: 'text'
# isImage: false
# owner: deviceUser._id
# text: "类 型:#{if payload.type is 'face' then '人' else '对像'}\n准确度:#{payload.accuracy}\n模糊度:#{payload.fuzziness}\n设 备:#{deviceName}\n动 作:#{payload.mid}\n"
# style: ''
# data_row: 1
# data_col: 1
# data_sizex: 6
# data_sizey: 1
# data_wait_init: true
# })
# newPub.push({
# _id: new Mongo.ObjectID()._str
# type: 'text'
# isImage: false
# owner: deviceUser._id
# text: '以下为设备的截图:'
# style: ''
# data_row: 2
# data_col: 1
# data_sizex: 6
# data_sizey: 1
# data_wait_init: true
# })
data_row = 3
imgs.forEach (img)->
newPub.push({
_id: new Mongo.ObjectID()._str
type: 'image'
isImage: true
# inIframe: true
owner: deviceUser._id
# text: '您当前程序不支持视频观看',
# iframe: '<iframe height="100%" width="100%" src="'+rest_api_url+'/restapi/workai-motion-imgs/'+postId+'" frameborder="0" allowfullscreen></iframe>'
imgUrl: img,
data_row: data_row
data_col: 1
data_sizex: 6
data_sizey: 5
data_wait_init: true
})
data_row += 5
newPub.push({
_id: new Mongo.ObjectID()._str
type: 'text'
isImage: false
owner: deviceUser._id
text: time
style: ''
data_row: 1
data_col: 1
data_sizex: 6
data_sizey: 1
data_wait_init: true
isTime:true
})
newPub.push({
_id: new Mongo.ObjectID()._str
type: 'text'
isImage: false
owner: deviceUser._id
text: title
style: ''
data_row: 1
data_col: 1
data_sizex: 6
data_sizey: 1
data_wait_init: true
})
Array.prototype.push.apply(newPub, post.pub)
post.pub = newPub
# formatPostPub(post.pub)
if isTodayPost
console.log('update motion post:', postId)
Posts.update({_id:postId},{$set:post})
globalPostsUpdateHookDeferHandle(post.owner, postId,null,{$set:post})
return;
post._id = postId
globalPostsInsertHookDeferHandle(post.owner, post._id)
Posts.insert(post)
console.log('insert motion post:', post._id)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/date', (req, res, next)->
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
this.response.end(Date.now().toString())
, {where: 'server'})
Router.route('/restapi/allgroupsid/:token/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token
limit = this.params.limit
skip = this.params.skip
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/allgroupsid get request, token:' + token + ' limit:' + limit + ' skip:' + skip
allgroups = []
groups = SimpleChat.Groups.find({}, {fields:{"_id": 1, "name": 1}, limit: parseInt(limit), skip: parseInt(skip)})
unless groups
return this.response.end('[]\n')
groups.forEach((group)->
allgroups.push({'id':group._id, 'name': group.name})
)
this.response.end(JSON.stringify(allgroups))
)
Router.route('/restapi/groupusers/:token/:groupid/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token
limit = this.params.limit
skip = this.params.skip
groupid = this.params.groupid
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/groupusers get request, token:' + token + ' limit:' + limit + ' skip:' + skip + ' groupid:' + groupid
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
#groupDevices = Devices.find({'groupId': groupid}).fetch()
#console.log 'no group found:' + groupDevices
allUsers = []
userGroups = SimpleChat.GroupUsers.find({group_id: groupid}, {fields:{"user_id": 1, "user_name": 1}, limit: parseInt(limit), skip: parseInt(skip)})
unless userGroups
return this.response.end('[]\n')
userGroups.forEach((userGroup)->
#if _.pluck(groupDevices, 'uuid').indexOf(userGroup.user_id) is -1
allUsers.push({'user_id':userGroup.user_id, 'user_name': userGroup.user_name})
)
this.response.end(JSON.stringify(allUsers))
)
Router.route('/restapi/activity/:token/:direction/:groupid/:ts/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token
groupid = this.params.groupid
limit = this.params.limit
skip = this.params.skip
direction = this.params.direction
starttime = this.params.ts
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/user get request, token:' + token + ' limit:' + limit + ' skip:' + skip + ' groupid:' + groupid + ' Direction:' + direction + ' starttime:' + starttime
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
allActivity = []
#Activity.id is id of person name
groupActivity = Activity.find(
{'group_id': groupid, 'ts': {$gt: parseInt(starttime)}, 'in_out': direction}
{fields:{'id': 1, 'name': 1, 'ts': 1, 'in_out': 1, 'img_url':1}, limit: parseInt(limit), skip: parseInt(skip)}
)
unless groupActivity
return this.response.end('[]\n')
groupActivity.forEach((activity)->
allActivity.push({'user_id': activity.id, 'user_name': activity.name, 'in_out': activity.in_out, 'img_url': activity.img_url})
)
this.response.end(JSON.stringify(allActivity))
)
Router.route('/restapi/active/:active/:token/:direction/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token #
limit = this.params.limit #
skip = this.params.skip #
direction = this.params.direction #'in'/'out'
active = this.params.active #'active'/'notactive'
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/:active get request, token:' + token + ' limit:' + limit + ' skip:' + skip + ' Direction:' + direction + ' active:' + active
allnotActivity = []
daytime = new Date()
daytime.setSeconds(0)
daytime.setMinutes(0)
daytime.setHours(0)
daytime = new Date(daytime).getTime()
notActivity = WorkAIUserRelations.find({}, {limit: parseInt(limit), skip: parseInt(skip)})
unless notActivity
return this.response.end('[]\n')
notActivity.forEach((item)->
#console.log(item)
if !item.checkin_time
item.checkin_time = 0
if !item.ai_in_time
item.ai_in_time= 0
if !item.checkout_time
item.checkout_time = 0
if !item.ai_out_time
item.ai_out_time = 0
if active is 'notactive'
if direction is 'in' and item.checkin_time < daytime and item.ai_in_time < daytime
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.in_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
else if direction is 'out' and item.checkout_time < daytime and item.ai_out_time < daytime
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.out_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
else if active is 'active'
if direction is 'in' and (item.checkin_time > daytime or item.ai_in_time > daytime)
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.in_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
else if direction is 'out' and (item.checkout_time > daytime or item.ai_out_time > daytime)
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.out_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
)
this.response.end(JSON.stringify(allnotActivity))
)
Router.route('/restapi/resetworkstatus/:token', {where: 'server'}).get(()->
token = this.params.token #
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/resetworkstatus get request'
date = Date.now();
mod = 24*60*60*1000;
date = date - (date % mod)
nextday = date + mod
relations = WorkAIUserRelations.find({})
relations.forEach((fields)->
if fields && fields.group_id
# 按 group 所在时区初始化 workStatus 数据
timeOffset = 8
shouldInitWorkStatus = false
group = SimpleChat.Groups.findOne({_id: fields.group_id})
if (group and group.offsetTimeZone)
timeOffset = parseInt(group.offsetTimeZone)
# 根据时区 获取 group 对应时区时间
group_local_time = getLocalTimeByOffset(timeOffset)
group_local_time_hour = group_local_time.getHours()
if group_local_time_hour is 0
shouldInitWorkStatus = true
console.log('now should init the offsetTimeZone: ', timeOffset)
#console.log('>>> ' + JSON.stringify(fields))
workstatus = WorkStatus.findOne({'group_id': fields.group_id, 'date': nextday, 'person_name': fields.person_name})
if !workstatus and shouldInitWorkStatus
newWorkStatus = {
"app_user_id" : fields.app_user_id
"group_id" : fields.group_id
"date" : nextday
"person_id" : fields.ai_persons
"person_name" : fields.person_name
"status" : "out"
"in_status" : "unknown"
"out_status" : "unknown"
"in_uuid" : fields.in_uuid
"out_uuid" : fields.out_uuid
"whats_up" : ""
"in_time" : 0
"out_time" : 0
"hide_it" : if fields.hide_it then fields.hide_it else false
}
#console.log('>>> new a WorkStatus ' + JSON.stringify(newWorkStatus))
WorkStatus.insert(newWorkStatus)
)
# 计算没有确认下班的数据
docs = UserCheckoutEndLog.find({}).fetch()
docs.map (doc)->
# remove
UserCheckoutEndLog.remove({_id: doc._id})
# 状态
startUTC = Date.UTC(doc.params.msg_data.create_time.getUTCFullYear(), doc.params.msg_data.create_time.getUTCMonth(), doc.params.msg_data.create_time.getUTCDate(), 0, 0, 0, 0)
endUTC = Date.UTC(doc.params.msg_data.create_time.getUTCFullYear(), doc.params.msg_data.create_time.getUTCMonth(), doc.params.msg_data.create_time.getUTCDate(), 23, 59, 59, 0)
workstatus = WorkStatus.findOne({'group_id': doc.params.msg_data.group_id, 'date': {$gte: startUTC, $lte: endUTC}})
# local date
now = new Date()
group = SimpleChat.Groups.findOne({_id: doc.params.msg_data.group_id})
if (group and group.offsetTimeZone)
now = new Date((now.getTime()+(now.getTimezoneOffset()*60000)) + (3600000*group.offsetTimeZone))
else
now = new Date((now.getTime()+(now.getTimezoneOffset()*60000)) + (3600000*8))
# console.log('===1==', workstatus.status)
unless (workstatus and workstatus.status is 'out')
# console.log('===2==', doc.userName, doc.params.msg_data.create_time.getUTCDate(), now.getUTCDate())
# 当天数据
if (doc.params.msg_data.create_time.getUTCDate() is now.getUTCDate())
# console.log('===3==', doc.userName)
send_greeting_msg(doc.params.msg_data);
PERSON.updateWorkStatus(doc.params.person._id)
if (doc.params.person_info)
PERSON.sendPersonInfoToWeb(doc.params.person_info)
else
# TODO:
this.response.end(JSON.stringify({result: 'ok'}))
)
# params = {
# uuid: 设备UUID,
# person_id: id,
# video_post: 视频封面图地址,
# video_src: 视频播放地址
# ts: 时间戳
# ts_offset: 时区 (eg : 东八区 是 -8);
# }
Router.route('/restapi/timeline/video/', {where: 'server'}).post(()->
payload = this.request.body || {}
console.log('/restapi/timeline/video/ request body = ',JSON.stringify(payload))
if (!payload.uuid or !payload.person_id or !payload.video_post or !payload.video_src or !payload.ts or !payload.ts_offset)
return this.response.end('{"result": "error", "reson":"参数不全或格式错误!"}\n')
# step 1. get group_id by uuid
device = Devices.findOne({uuid: payload.uuid})
if device and device.groupId
group_id = device.groupId
# step 2. get person_name by person_id
person_name = PERSON.getName(payload.uuid, group_id, payload.person_id)
if (!person_name)
person_name = ""
PERSON.updateToDeviceTimeline(payload.uuid,group_id,{
is_video: true,
person_id: payload.person_id,
person_name: <NAME>_name,
video_post: payload.video_post,
video_src: payload.video_src,
ts: Number(payload.ts),
ts_offset: Number(payload.ts_offset)
})
return this.response.end('{"result": "success"}\n')
)
Router.route('/restapi/clustering', {where: 'server'}).get(()->
group_id = this.params.query.group_id
faceId = this.params.query.faceId
totalFaces = this.params.query.totalFaces
url = this.params.query.url
rawfilepath = this.params.query.rawfilepath
isOneSelf = this.params.query.isOneSelf
if isOneSelf == 'true'
isOneSelf = true
else
isOneSelf = false
console.log '/restapi/clustering get request, group_id:' + group_id + ', faceId:' + faceId + ',totalFaces:' + totalFaces + ',url' + url + ',rawfilepath' + rawfilepath + ',isOneSelf' + isOneSelf
unless group_id and isOneSelf
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
#取回这个组某个人所有正确/不正确的图片
if group_id and faceId
dataset={'group_id': group_id, 'faceId': faceId, 'dataset': []}
allClustering = Clustering.find({'group_id': group_id, 'faceId': faceId, 'isOneSelf': isOneSelf}).fetch()
allClustering.forEach((fields)->
dataset.dataset.push({url:fields.url, rawfilepath: fields.rawfilepath})
)
else
dataset={'group_id': group_id, 'dataset': []}
#取回这个组某个人所有不正确的图片
#返回标注过的数据集
this.response.end(JSON.stringify(dataset))
).post(()->
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('faceId')
faceId = this.request.body.faceId
if this.request.body.hasOwnProperty('totalFaces')
totalFaces = this.request.body.totalFaces
if this.request.body.hasOwnProperty('url')
url = this.request.body.url
if this.request.body.hasOwnProperty('rawfilepath')
rawfilepath = this.request.body.rawfilepath
if this.request.body.hasOwnProperty('isOneSelf')
isOneSelf = this.request.body.isOneSelf
if isOneSelf == "true"
isOneSelf = true
console.log '/restapi/clustering post request, group_id:' + group_id + ', faceId:' + faceId + ',totalFaces:' + totalFaces + ',url' + url + ',rawfilepath' + rawfilepath + ',isOneSelf' + isOneSelf
unless group_id and faceId and url
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
#插入数据库
person = Person.findOne({group_id: group_id, 'faceId': faceId},{sort: {createAt: 1}})
if !person
person = {
_id: new Mongo.ObjectID()._str,
id: 1,
group_id: group_id,
faceId: faceId,
url: url,
name: faceId,
faces: [],
deviceId: 'clustering',
DeviceName: 'clustering',
createAt: new Date(),
updateAt: new Date()
};
Person.insert(person)
console.log('>>> new people' + faceId)
clusteringObj = {
group_id: group_id,
faceId: faceId,
totalFaces: totalFaces,
url: url,
rawfilepath: rawfilepath,
isOneSelf: isOneSelf
}
Clustering.insert(clusteringObj)
#console.log('>>> ' + JSON.stringify(clusteringObj))
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/get-group-users', {where: 'server'}).get(()->
group_id = this.params.query.group_id
resObj = []
gUsers = Person.find({group_id: group_id})
if gUsers
gUsers.forEach((user)->
resObj.push(user)
)
this.response.end(JSON.stringify(resObj))
).post(()->
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
resObj = []
gUsers = Person.find({group_id: group_id})
if gUsers
gUsers.forEach((user)->
resObj.push(user)
)
this.response.end(JSON.stringify(resObj))
)
Router.route('/restapi/datasync/:token/:groupid', {where: 'server'}).get(()->
token = this.params.token
groupid = this.params.groupid
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/datasync get request, token:' + token + ' groupid:' + groupid
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
syncDateSet=[]
#取出群相册里面所有已经标注的数据
persons = Person.find({group_id: groupid},{fields:{name: 1, faceId:1}}).fetch()
persons.forEach((item)->
urls=[]
if item and item.name
dataset = LableDadaSet.find({group_id: groupid ,name: item.name}, {fields:{url: 1,style:1,sqlid:1}}).fetch()
dataset.forEach((item2)->
if item2 and item2.url
urls.push({
url:item2.url,
style: item2.style || 'front',
sqlid: item2.sqlid || null
})
)
if item and item.faceId
syncDateSet.push({faceId: item.faceId, urls: urls})
)
this.response.end(JSON.stringify(syncDateSet))
)
Router.route('/restapi/groupdatasync/:token/:groupid', {where: 'server'}).get(()->
token = this.params.token
groupid = this.params.groupid
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/datasync get request, token:' + token + ' groupid:' + groupid
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
syncDateSet=[]
#取出群相册里面所有已经标注的数据
person = GroupPerson.find({group_id: groupid},{fields:{name: 1, faceId:1}}).fetch()
person.forEach((item)->
urls=[]
if item and item.name
dataset = GroupLableDadaSet.find({group_id: groupid ,name: item.name}, {fields:{url: 1,style:1,sqlid:1}}).fetch()
dataset.forEach((item2)->
if item2 and item2.url
urls.push({
url:item2.url,
style: item2.style || 'front',
sqlid: item2.sqlid || null
})
)
if item and item.faceId
syncDateSet.push({faceId: item.faceId, urls: urls})
)
this.response.end(JSON.stringify(syncDateSet))
)
getInComTimeLen = (workstatus) ->
group_id = workstatus.group_id;
diff = 0;
out_time = workstatus.out_time;
today_end = workstatus.out_time;
time_offset = 8
group = SimpleChat.Groups.findOne({_id: group_id});
if (group && group.offsetTimeZone)
time_offset = group.offsetTimeZone;
DateTimezone = (d, time_offset) ->
if (time_offset == undefined)
if (d.getTimezoneOffset() == 420)
time_offset = -7
else
time_offset = 8
#取得 UTC time
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
local_now = new Date(utc + (3600000*time_offset))
today_now = new Date(local_now.getFullYear(), local_now.getMonth(), local_now.getDate(),
local_now.getHours(), local_now.getMinutes());
return today_now;
#计算out_time
if(workstatus.in_time)
date = new Date(workstatus.in_time);
fomatDate = date.shortTime(time_offset);
isToday = PERSON.checkIsToday(workstatus.in_time,group_id)
#不是今天的时间没有out_time的或者是不是今天时间,最后一次拍到的是进门的状态的都计算到当天结束
if((!out_time and !isToday) or (workstatus.status is 'in' and !isToday))
date = DateTimezone(date,time_offset);
day_end = new Date(date).setHours(23,59,59);
#day_end = new Date(this.in_time).setUTCHours(0,0,0,0) + (24 - time_offset)*60*60*1000 - 1;
out_time = day_end;
workstatus.in_time = date.getTime();
#今天的时间(没有离开过监控组)
else if(!out_time and isToday)
now_time = Date.now();
out_time = now_time;
#今天的时间(离开监控组又回到监控组)
else if(out_time and workstatus.status is 'in' and isToday)
now_time = Date.now();
out_time = now_time;
if(workstatus.in_time and out_time)
diff = out_time - workstatus.in_time;
if(diff > 24*60*60*1000)
diff = 24*60*60*1000;
else if(diff < 0)
diff = 0;
min = diff / 1000 / 60 ;
hour = Math.floor(min/60)+' h '+Math.floor(min%60) + ' min';
if(min < 60)
hour = Math.floor(min%60) + ' min';
if(diff == 0)
hour = '0 min';
return hour;
getShortTime = (ts,group_id)->
time_offset = 8
group = SimpleChat.Groups.findOne({_id: group_id});
if (group && group.offsetTimeZone)
time_offset = group.offsetTimeZone;
time = new Date(ts);
return time.shortTime(time_offset,true);
sendEmailToGroupUsers = (group_id)->
if !group_id
return
group = SimpleChat.Groups.findOne({_id:group_id});
if !group
return
date = Date.now();
mod = 24*60*60*1000;
date = date - (date % mod)
yesterday = date - mod
console.log 'date:'+ yesterday
workstatus_content = ''
WorkStatus.find({'group_id': group_id, 'date': yesterday}).forEach((target)->
unless target.hide_it
text = Assets.getText('email/work-status-content.html');
text = text.replace('{{person_name}}', target.person_name);
# app_user_status_color = 'gray'
# app_notifaction_status = ''
# if target.app_user_id
# app_user_status_color = 'green'
# if target.app_notifaction_status is 'on'
# app_notifaction_status = '<i class="fa fa-bell app-user-status" style="color:green;"></i>'
# app_user_status = '<i class="fa fa-user app-user-status" style="color:green;"></i>'+app_notifaction_status
# text = text.replace('{{app_user_status_color}}',app_user_status_color);
# text = text.replace('{{app_notifaction_status}}',app_notifaction_status);
isStatusIN_color = if target.status is 'in' then 'green' else 'gray'
# if target.in_time > 0
# if PERSON.checkIsToday(target.in_time,group_id)
# isStatusIN_color = 'gray'
# text = text.replace('{{isStatusIN_color}}',isStatusIN_color);
InComTimeLen = getInComTimeLen(target)
text = text.replace('{{InComTimeLen}}',InComTimeLen);
isInStatusNotUnknownStyle = if target.in_status is 'unknown' then 'display:none;' else 'display:table-cell;'
text = text.replace('{{isInStatusNotUnknownStyle}}',isInStatusNotUnknownStyle);
isInStatusUnknownStyle = if target.in_status is 'unknown' then 'display:table-cell;' else 'display:none;'
text = text.replace('{{isInStatusUnknownStyle}}',isInStatusUnknownStyle);
if target.in_status isnt 'unknown'
text = text.replace('{{in_image}}',target.in_image);
text = text.replace('{{in_time}}',getShortTime(target.in_time,group_id))
in_time_Color = 'green'
if target.in_status is 'warning'
in_time_Color = 'orange'
else if target.in_status is 'error'
in_time_Color = 'red'
text = text.replace('{{in_time_Color}}',in_time_Color);
historyUnknownOutStyle = 'display:none;'
if isStatusIN_color is 'green'
historyUnknownOutStyle = 'display:table-cell;color:red;'
else
if target.out_status is 'unknown'
historyUnknownOutStyle = 'display:table-cell;'
text = text.replace('{{historyUnknownOutStyle}}',historyUnknownOutStyle);
isOutStatusNotUnknownStyle = if historyUnknownOutStyle is 'display:none;' then 'display:table-cell;' else 'display:none;'
text = text.replace('{{isOutStatusNotUnknownStyle}}',isOutStatusNotUnknownStyle);
if historyUnknownOutStyle is 'display:none;'
text = text.replace('{{out_image}}',target.out_image);
text = text.replace('{{out_time}}',getShortTime(target.out_time,group_id));
out_time_Color = 'green'
if target.out_status is 'warning'
out_time_Color = 'orange'
else if target.out_status is 'error'
out_time_Color = 'red'
text = text.replace('{{out_time_Color}}',out_time_Color);
whats_up = ''
if target.whats_up
whatsUpLists = [];
if typeof(target.whats_up) is 'string'
whatsUpLists.push({
person_name:target.person_name,
content:target.whats_up,
ts:target.in_time
})
# ...
else
whatsUpLists = target.whats_up
for item in whatsUpLists
whats_up = whats_up + '<p style="white-space: pre-wrap;"><strong>'+item.person_name+'</strong>['+getShortTime(item.ts,group_id)+']'+item.content
else
whats_up = '今天还没有工作安排...'
text = text.replace('{{whats_up}}',whats_up);
workstatus_content = workstatus_content + text
)
if workstatus_content.length > 0
text = Assets.getText('email/work-status-report.html');
text = text.replace('{{group.name}}', group.name);
y_date = new Date(yesterday)
year = y_date.getFullYear();
month = y_date.getMonth() + 1;
y_date_title = '(' + year + '-' + month + '-' +y_date.getDate() + ')';
text = text.replace('{{date.fomatStr}}',y_date_title)
text = text.replace('{{workStatus.content}}', workstatus_content);
subject = group.name + ' 每日出勤报告'+y_date_title
else
return
#console.log 'html:'+ JSON.stringify(text)
SimpleChat.GroupUsers.find({group_id:group_id}).forEach(
(fields)->
if fields and fields.user_id
user_id = fields.user_id
#user_id = 'GriTByu7MhRGhQdPD'
user = Meteor.users.findOne({_id:user_id});
if user and user.emails and user.emails.length > 0
email_address = user.emails[0].address
#email_address = '<EMAIL>'
isUnavailable = UnavailableEmails.findOne({address:email_address});
unless isUnavailable
#email_address = user.emails[0].address
console.log 'groupuser : ' + user.profile.fullname + ' email address is :' + user.emails[0].address
try
Email.send({
to:email_address,
from:'点圈<<EMAIL>>',
subject:subject,
html : text,
envelope:{
from:'点圈<<EMAIL>>',
to:email_address + '<' + email_address + '>'
}
})
console.log 'try send mail to:'+email_address
catch e
console.log 'exception:send mail error = %s, userEmail = %s',e,email_address
###
unavailableEmail = UnavailableEmails.findOne({address:email_address})
if unavailableEmail
UnavailableEmails.update({reason:e});
else
UnavailableEmails.insert({address:email_address,reason:e,createAt:new Date()});
###
)
Router.route('/restapi/sendReportByEmail/:token',{where:'server'}).get(()->
token = this.params.token #
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/sendReportByEmail get request'
#sendEmailToGroupUsers('ae64c98bdff9b674fb5dad4b')
groups = SimpleChat.Groups.find({})
groups.forEach((fields)->
if fields
sendEmailToGroupUsers(fields._id)
)
this.response.end(JSON.stringify({result: 'ok'}))
)
# 定义相应的mailgun webhook, dropped,hardbounces,unsubscribe 下次不再向相应的邮件地址发信
# docs: https://documentation.mailgun.com/en/latest/user_manual.html#webhooks
@mailGunSendHooks = (address, type, reason)->
if !address and !reason
return console.log('need email address and webhook reason')
console.log('Email send Hooks, send to '+address + ' failed , reason: '+ reason)
unavailableEmail = UnavailableEmails.findOne({address: address})
if unavailableEmail
UnavailableEmails.update({_id: unavailableEmail._id},{$set:{
reason:reason
}})
else
UnavailableEmails.insert({
address: address,
reason: reason
createAt: new Date()
})
# 发信失败跟踪 (Dropped Messages)
Router.route('/hooks/emails/dropped', {where: 'server'}).post(()->
data = this.request.body
mailGunSendHooks(emails,'dropped')
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
# 硬/软 退信跟踪 (Hard Bounces)
Router.route('/hooks/emails/bounced', {where: 'server'}).post(()->
data = this.request.body
type = data.event || 'bounced'
mailGunSendHooks(data.recipient,type)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
# 垃圾邮件跟踪 (Spam Complaints)
Router.route('/hooks/emails/complained', {where: 'server'}).post(()->
data = this.request.body
type = data.event || 'complained'
mailGunSendHooks(data.recipient,type)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
# 取消订阅跟踪 (Unsubscribes)
Router.route('/hooks/emails/unsubscribe', {where: 'server'}).post(()->
data = this.request.body
type = data.event || 'unsubscribe'
mailGunSendHooks(data.recipient,type)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
#陌生人图片信息
Router.route('/restapi/updateStrangers', {where: 'server'}).post(()->
if this.request.body.hasOwnProperty('imgs')
imgs = this.request.body.imgs
if this.request.body.hasOwnProperty('img_gif')
img_gif = this.request.body.img_gif
if this.request.body.hasOwnProperty('isStrange')
isStrange = this.request.body.isStrange
if this.request.body.hasOwnProperty('createTime')
createTime = this.request.body.createTime
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('camera_id')
cid = this.request.body.camera_id
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('tid')
trackerId = this.request.body.tid
unless imgs and img_gif and group_id and uuid
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
Strangers.insert({
imgs: imgs,
img_gif: img_gif,
group_id: group_id,
camera_id: cid,
uuid: uuid,
trackerId: trackerId,
isStrange: isStrange,
createTime: new Date(),
avatar: imgs[0].url
})
#console.log(Strangers.find({}).fetch())
this.response.end('{"result": "ok"}\n')
)
| true | subs = new SubsManager({
#maximum number of cache subscriptions
cacheLimit: 999,
# any subscription will be expire after 30 days, if it's not subscribed again
expireIn: 60*24*30
});
if Meteor.isServer
request = Meteor.npmRequire('request')
Fiber = Meteor.npmRequire('fibers')
QRImage = Meteor.npmRequire('qr-image')
###
Router.route '/posts/:_id', {
waitOn: ->
[subs.subscribe("publicPosts",this.params._id),
subs.subscribe "pcomments"]
fastRender: true
}
###
injectSignData = (req,res)->
try
console.log(req.url)
if req.url
signature=generateSignature('http://'+server_domain_name+req.url)
if signature
console.log(signature)
InjectData.pushData(res, "wechatsign", signature);
catch error
return null
# 获取对应时区的时间
getLocalTimeByOffset = (i)->
if typeof i isnt 'number'
return
d = new Date()
len = d.getTime()
offset = d.getTimezoneOffset() * 60000
utcTime = len + offset
return new Date(utcTime + 3600000 * i)
Router.configure {
waitOn: ()->
if this and this.path
path=this.path
if path.indexOf('/posts/') is 0
if path.indexOf('?') > 0
path = path.split('?')[0]
params=path.replace('/posts/','')
params=params.split('/')
if params.length > 0
return [subs.subscribe("publicPosts",params[0]),
subs.subscribe("postsAuthor",params[0]),
subs.subscribe "pcomments"]
fastRender: true
}
Router.route('/download-reporter-logs', (req, res, next)->
data = reporterLogs.find({},{sort:{createdAt:-1}}).fetch()
fields = [
{
key:'postId',
title:'帖子Id',
},
{
key:'postTitle',
title:'帖子标题',
},
{
key:'postCreatedAt',
title:'帖子创建时间',
transform: (val, doc)->
d = new Date(val)
return d.toLocaleString()
},
{
key: 'userId',
title: '用户Id(涉及帖子操作时,为帖子Owner)'
},
{
key:'userName',
title:'用户昵称'
},
{
key:'userEmails',
title:'用户Email',
transform: (val, doc)->
emails = ''
if val and val isnt null
val.forEach (item)->
emails += item.address + '\r\n'
return emails;
},
{
key:'eventType',
title: '操作类型'
},
{
key:'loginUser',
title: '操作人员',
transform: (val, doc)->
user = Meteor.users.findOne({_id: val})
userInfo = '_id: '+val+'\r\n username: '+user.username
return userInfo
},
{
key: 'createdAt',
title: '操作时间',
transform: (val, doc)->
d = new Date(val)
return d.toLocaleString()
},
]
title = 'hotShareReporterLogs-'+ (new Date()).toLocaleDateString()
file = Excel.export(title, fields, data)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end(file, 'binary')
, { where: 'server' })
# Router.route('/apple-app-site-association', (req, res, next)->
# #name = 'apple-app-site-association'
# #name = 'import-server'
# fs = Npm.require("fs")
# path = Npm.require('path')
# base = path.resolve('.');
# filepath = path.resolve('.') + '/app/lib/apple-app-site-association';
# #filepath = path.join(__dirname,'../server/import-server.js')
# file = fs.readFileSync(filepath, 'binary');
# headers = {
# 'Content-type': 'application/vnd.openxmlformats',
# 'Content-Disposition': 'attachment; apple-app-site-association'
# }
# this.response.writeHead(200, headers)
# this.response.end(file, 'binary')
# , { where: 'server' })
if Meteor.isServer
workaiId = 'Lh4JcxG7CnmgR3YXe'
workaiName = 'Actiontec'
fomat_greeting_text = (time,time_offset)->
DateTimezone = (d, time_offset)->
if (time_offset == undefined)
if (d.getTimezoneOffset() == 420)
time_offset = -7
else
time_offset = 8
# 取得 UTC time
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
local_now = new Date(utc + (3600000*time_offset))
today_now = new Date(local_now.getFullYear(), local_now.getMonth(), local_now.getDate(),
local_now.getHours(), local_now.getMinutes());
return today_now;
self = time;
now = new Date();
result = '';
self = DateTimezone(time, time_offset);
# DayDiff = now.getDate() - self.getDate();
Minutes = self.getHours() * 60 + self.getMinutes();
# if (DayDiff === 0) {
# result += '今天 '
# } else if (DayDiff === 1) {
# result += '昨天 '
# } else {
# result += self.parseDate('YYYY-MM-DD') + ' ';
# }
if (Minutes >= 0 && Minutes < 360)
result += '凌晨 ';
if (Minutes >= 360 && Minutes < 660)
result += '上午 ';
if (Minutes >= 660 && Minutes < 780)
result += '中午 ';
if (Minutes >= 780 && Minutes < 960)
result += '下午 ';
if (Minutes >= 960 && Minutes < 1080)
result += '傍晚 ';
if (Minutes >= 1080 && Minutes < 1440)
result += '晚上 ';
result += self.parseDate('h:mm');
result = '您的上班时间是 ' + result;
return result;
@send_greeting_msg = (data)->
console.log 'try send_greeting_msg~ with data:'+JSON.stringify(data)
if !data || !data.images ||data.images.img_type isnt 'face'
#console.log 'invalid params'
return
if !data.in_out
device = Devices.findOne({uuid:data.people_uuid})
if !device || !device.in_out
#console.log ' not found device or in_device'
return
data.in_out = device.in_out
person = Person.findOne({group_id:data.group_id,'faces.id':data.images.id},{sort: {createAt: 1}})
if !person
console.log 'not find person with faceid is:'+data.images.id
return
relation = WorkAIUserRelations.findOne({'ai_persons.id':person._id})
create_time = new Date(data.create_time);
if !relation
#console.log 'not find workai user relations'
WorkAIUserRelations.insert({
group_id:data.group_id,
person_name:person.name,
in_uuid:data.people_uuid,
ai_in_time:create_time.getTime(),
ai_lastest_in_time:create_time.getTime(),
ai_in_image:data.images.url,
ai_lastest_in_image:data.images.url,
ai_persons: [
{
id : person._id
}
]
});
return
if data.in_out is 'out'
WorkAIUserRelations.update({_id:relation._id},{$set:{ai_out_time:create_time.getTime(), ai_out_image: data.images.url}});
return
WorkAIUserRelations.update({_id:relation._id},{$set:{ai_lastest_in_time:create_time.getTime(),ai_lastest_in_image:data.images.url}});#平板最新拍到的时间
#再次拍到进门需要把下班的提示移除
if relation.app_user_id
endlog = UserCheckoutEndLog.findOne({userId:relation.app_user_id});
if endlog
outtime = endlog.params.person_info.ts;
if outtime and PERSON.checkIsToday(outtime,data.group_id) and outtime < create_time.getTime()
UserCheckoutEndLog.remove({_id:endlog._id});
if relation.ai_in_time and PERSON.checkIsToday(relation.ai_in_time,data.group_id)
# ai_in_time = new Date(relation.ai_in_time);
# today = new Date(create_time.getFullYear(), create_time.getMonth(), create_time.getDate()).getTime(); #凌晨
# if ai_in_time.getTime() > today
console.log 'today greeting_msg had send'
#WorkAIUserRelations.update({_id:relation._id},{$set:{ai_in_time:create_time.getTime()}});
return
WorkAIUserRelations.update({_id:relation._id},{$set:{ai_in_time:create_time.getTime(), ai_in_image: data.images.url}});
if !relation.app_user_id
return
deviceUser = Meteor.users.findOne({username: data.people_uuid});
time_offset = 8;
group = SimpleChat.Groups.findOne({_id: data.group_id});
if (group && group.offsetTimeZone)
time_offset = group.offsetTimeZone;
sendMqttMessage('/msg/u/'+ relation.app_user_id, {
_id: new Mongo.ObjectID()._str
# form: {
# id: "fTnmgpdDN4hF9re8F",
# name: "workAI",
# icon: "http://data.tiegushi.com/fTnmgpdDN4hF9re8F_1493176458747.jpg"
# }
form:{
id: deviceUser._id,
name: deviceUser.profile.fullname,
icon: deviceUser.profile.icon
}
to: {
id: relation.app_user_id
name: relation.app_user_name
icon: ''
}
images: [data.images]
to_type: "user"
type: "text"
text: fomat_greeting_text(create_time,time_offset)
create_time: new Date()
checkin_time:create_time
is_agent_check:true
offsetTimeZone:time_offset
group_id:data.group_id
people_uuid: data.people_uuid
is_read: false
checkin_out:'in'
})
# 对data 进行处理, data 必须是数组
insertFaces = (face)->
device = Devices.findOne({uuid: face.uuid})
if device and device.name
face.device_name = device.name
face.createdAt = new Date()
Faces.insert(face)
insert_msg2 = (id, url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts,tracker_id,p_ids)->
#people = People.findOne({id: id, uuid: uuid})
name = null
#device = PERSON.upsetDevice(uuid, null)
create_time = new Date()
console.log("insert_msg2: img_ts="+img_ts+", current_ts="+current_ts+", create_time="+create_time)
###
if img_ts and current_ts
img_ts = Number(img_ts)
current_ts = Number(current_ts)
time_diff = img_ts + (create_time.getTime() - current_ts)
create_time = new Date(time_diff)
###
create_time = new Date()
if img_ts and current_ts
img_ts = Number(img_ts)
current_ts = Number(current_ts)
time_diff = img_ts + getTimeZoneDiffByMs(create_time.getTime(), current_ts)
create_time = new Date(time_diff)
#if !people
# people = {_id: new Mongo.ObjectID()._str, id: id, uuid: uuid,name: name,embed: null,local_url: null,aliyun_url: url}
# People.insert(people)
#else
# People.update({_id: people._id}, {$set: {aliyun_url: url}})
device = Devices.findOne({uuid: uuid})
PeopleHis.insert {id: id,uuid: uuid,name: name, people_id: id, embed: null,local_url: null,aliyun_url: url}, (err, _id)->
if err or !_id
return
user = Meteor.users.findOne({username: uuid})
unless user
return
userGroups = SimpleChat.GroupUsers.find({user_id: user._id})
unless userGroups
return
userGroups.forEach((userGroup)->
group = SimpleChat.Groups.findOne({_id:userGroup.group_id});
if group.template and group.template._id
if group.template.img_type != img_type
return
name = null
name = PERSON.getName(null, userGroup.group_id,id)
p_ids_name = [];
#存在可能性最大的三个人的id
# if p_ids and p_ids.length > 0
# for pid in p_ids
# person = Person.findOne({group_id:userGroup.group_id,'faces.id':pid},{sort:{createAt:1}});
# if person
# p_person = {
# name:person.name,
# id:pid,
# url:person.url,
# p_id:person._id
# }
# if(_.pluck(p_ids_name, 'p_id').indexOf(person._id) is -1)
# p_ids_name.push(p_person)
#没有准确度的人一定是没有识别出来的
name = if accuracy then name else null
#没有识别的人的准确度清0
Accuracy = if name then accuracy else false
Fuzziness = fuzziness
if true #name and checkIfSendRecoMsg(userGroup.group_id, uuid, id)
console.log('--------send reco msg to --------', uuid, '----', id, '----', name)
sendMqttMessage('/msg/g/'+ userGroup.group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
icon: user.profile.icon
}
to: {
id: userGroup.group_id
name: userGroup.group_name
icon: userGroup.group_icon
}
images: [
{_id: new Mongo.ObjectID()._str, id: id, people_his_id: _id, url: url, label: name, img_type: img_type, accuracy: Accuracy, fuzziness: Fuzziness, sqlid: sqlid, style: style,p_ids:p_ids_name} # 暂一次只能发一张图
]
to_type: "group"
type: "text"
text: if !name then 'Work AI发现有人在活动' else 'AI观察到 ' + name + ':'
create_time: create_time
people_id: id
people_uuid: uuid
people_his_id: _id
wait_lable: !name
is_people: true
is_read: false
tid:tracker_id
})
# update to DeviceTimeLine
timeObj = {
person_id: id,
person_name: PI:NAME:<NAME>END_PI,
img_url: url,
sqlid: sqlid,
style: style,
accuracy: Accuracy, # 准确度(分数)
fuzziness: Fuzziness, # 模糊度
ts:create_time.getTime()
}
PERSON.updateToDeviceTimeline(uuid,userGroup.group_id,timeObj)
#识别准确度在0.85以上才自动打卡
#if name and accuracy >= withDefaultAccuracy
#if tablet recognizes this person, update it to mainpage.
if name
msg_data = {
group_id:userGroup.group_id,
create_time:create_time,
people_uuid:uuid,
in_out:userGroup.in_out,
images:{
id: id,
people_his_id: _id,
url: url,
label: PI:NAME:<NAME>END_PI,
img_type: img_type,
accuracy: Accuracy,
fuzziness: Fuzziness,
sqlid: sqlid,
style: style
}
}
person = Person.findOne({group_id: userGroup.group_id, name: name}, {sort: {createAt: 1}});
person_info = null
if img_type == 'face' && person && person.faceId
#console.log('post person info to aixd.raidcdn')
person_info = {
'id': person._id,
'uuid': uuid,
'name': PI:NAME:<NAME>END_PI,
'group_id': userGroup.group_id,
'img_url': url,
'type': img_type,
'ts': create_time.getTime(),
'accuracy': accuracy,
'fuzziness': fuzziness
}
relation = WorkAIUserRelations.findOne({'ai_persons.id': person._id})
if (device.in_out is 'in' and relation and relation.app_user_id)
wsts = WorkStatus.findOne({group_id: userGroup.group_id, app_user_id: relation.app_user_id}, {sort: {date: -1}})
if (wsts and !wsts.whats_up)
CreateSatsUpTipTask(relation.app_user_id, userGroup.group_id, device.uuid)
if (device.in_out is 'out' and relation and relation.app_user_id)
checkout_msg = {
userId: relation.app_user_id,
userName: relation.app_user_name,
createAt: new Date(),
params: {
msg_data: msg_data,
person: person,
person_info: person_info
}
}
# UserCheckoutEndLog.remove({userId: relation.app_user_id})
# UserCheckoutEndLog.insert(checkout_msg)
# sendUserCheckoutEvent(uuid, relation.app_user_id)
# return
# 到下班时间后,不终止后续处理
group_outtime = '18:00'
time_offset = 8
if (group and group.group_outtime)
group_outtime = group.group_outtime
if group and group.offsetTimeZone
time_offset = group.offsetTimeZone
group_outtime_H = parseInt(group_outtime.split(":")[0])
group_outtime_M = parseInt(group_outtime.split(":")[1])
group_out_minutes = group_outtime_H * 60 + group_outtime_M
out_time_H = parseInt(create_time.getUTCHours() + time_offset)
out_time_M = create_time.getMinutes()
out_time_minutes = out_time_H * 60 + out_time_M
# 到下班时间后,不自动 checkout(这里先取消, 目前:统一采用自动checkout的方式,但保留手动checkout)
# if (out_time_minutes < group_out_minutes)
# return
send_greeting_msg(msg_data);
PERSON.updateWorkStatus(person._id)
if person_info
PERSON.sendPersonInfoToWeb(person_info)
console.log("device.in_out", device, relation)
if ((device.name.includes('inout') or device.in_out is 'inout' or device.uuid is '28D6R17505001070') and relation)
Devices.update({_id: device._id}, {$set: {in_out:'inout'}});
console.log("activity_update_time")
activity_update_time(person._id, create_time, url)
)
@insert_msg2forTest = (id, url, uuid, accuracy, fuzziness)->
insert_msg2(id, url, uuid, 'face', accuracy, fuzziness, 0, 0)
# 平板 发现 某张图片为 错误识别(不涉及标记), 需要移除 或 修正 相应数据
padCallRemove = (id, url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts,tracker_id,p_ids)->
console.log("padCallRemove: id="+id+", url="+url+", uuid="+uuid+", img_type="+img_type+", accuracy="+accuracy+", fuzziness="+fuzziness+", sqlid="+sqlid+", style="+style+", img_ts="+img_ts+", current_ts="+current_ts+", tracker_id="+tracker_id+", p_ids="+p_ids)
create_time = new Date()
if img_ts and current_ts
img_ts = Number(img_ts)
current_ts = Number(current_ts)
time_diff = img_ts + getTimeZoneDiffByMs(create_time.getTime(), current_ts)
create_time = new Date(time_diff)
hour = new Date(create_time.getTime())
hour.setMinutes(0)
hour.setSeconds(0)
hour.setMilliseconds(0)
console.log("hour="+hour)
minutes = new Date(create_time.getTime())
minutes = minutes.getMinutes()
console.log("minutes="+minutes)
# Step 1. 修正出现记录, WorkAIUserRelations或workStatus
fixWorkStatus = (work_status,in_out)->
today = new Date(create_time.getTime())
today.setHours(0,0,0,0)
console.log('hour='+hour+', today='+today+', uuid='+uuid)
timeline = DeviceTimeLine.findOne({hour:{$lte: hour, $gt: today},uuid: uuid},{sort: {hour: -1}});
if timeline and timeline.perMin # 通过历史记录中的 数据 fix WorkStatus
time = null
imgUrl = null
timelineArray = for mins of timeline.perMin
timeline.perMin[mins]
for obj in timelineArray
if obj.img_url is url
time = Number(obj.ts)
imgUrl = obj.img_url
break
if in_out is 'in'
setObj = {
in_time: time,
in_image: imgUrl,
in_status: 'normal'
}
if !work_status.out_time
setObj.status = 'in'
else if time < work_status.out_time
setObj.status = 'out'
else if time >= work_status.out_time
setObj.status = 'in'
if in_out is 'out'
setObj = {
out_time: time,
out_image: imgUrl,
out_status: 'normal'
}
if !work_status.in_time
setObj.status = 'out'
setObj.out_status = 'warning'
else if time <= work_status.in_time
setObj.status = 'in'
else if time > work_status.in_time
setObj.status = 'out'
else
if in_out is 'in'
setObj = {
status: 'out',
in_uuid: null,
in_time: null,
in_image: null,
in_status: 'unknown'
}
if in_out is 'out'
setObj = {
status: 'in',
out_uuid: null,
out_time: null,
out_image: null,
out_status: 'unknown'
}
if !work_status.in_time
setObj.status = 'out'
WorkStatus.update({_id: work_status._id},$set: setObj)
work_status_in = WorkStatus.findOne({in_image: url})
# 匹配到进的出现
if work_status_in
console.log('padCallRemove Fix WorkStatus, 需要修正进的出现')
#fixWorkStatus(work_status_in,'in')
work_status_out = WorkStatus.findOne({out_image: url})
# 匹配到出的出现
if work_status_out
console.log('padCallRemove Fix WorkStatus, 需要修正出的出现')
#fixWorkStatus(work_status_out,'out')
# 删除出现
WorkStatus.remove({$or:[{in_image: url},{out_image: url}]});
# Step 2. 从设备时间轴中移除
selector = {
hour: hour,
uuid: uuid
}
selector["perMin."+minutes+".img_url"] = url;
###
console.log('selector='+JSON.stringify(selector))
timeline = DeviceTimeLine.findOne(selector)
console.log("timeline._id="+JSON.stringify(timeline._id))
if timeline
minuteArray = timeline.perMin[""+minutes]
console.log("minuteArray="+JSON.stringify(minuteArray))
minuteArray.splice(_.pluck(minuteArray, 'img_url').indexOf(url), 1)
console.log("2, minuteArray="+JSON.stringify(minuteArray))
modifier = {
$set:{}
}
modifier.$set["perMin."+minutes] = minuteArray
DeviceTimeLine.update({_id: timeline._id}, modifier, (err,res)->
if err
console.log('padCallRemove DeviceTimeLine, update Err:'+err)
else
console.log('padCallRemove DeviceTimeLine, update Success')
)
###
console.log('selector='+JSON.stringify(selector))
modifier = {$set:{}}
modifier.$set["perMin."+minutes+".$.person_name"] = null
modifier.$set["perMin."+minutes+".$.accuracy"] = false
DeviceTimeLine.update(selector, modifier, (err,res)->
if err
console.log('padCallRemove DeviceTimeLine, update Err:'+err)
else
console.log('padCallRemove DeviceTimeLine, update Success')
)
# Step 3. 如果 person 表中 有此图片记录, 需要移除
person = Person.findOne({'faces.id': id})
if person
faces = person.faces
faces.splice(_.pluck(faces, 'id').indexOf(obj.face_id), 1)
Person.update({_id: person._id},{$set: {faces: faces}})
# Step 4. 向Group 发送一条 mqtt 消息, 告知需要移除 错误识别 的照片
device = Devices.findOne({uuid: uuid});
if device and device.groupId
group_id = device.groupId
group = SimpleChat.Groups.findOne({_id: group_id})
to = {
id: group._id,
name: group.name,
icon: group.icon
}
device_user = Meteor.users.findOne({username: uuid})
form = {}
if device_user
form = {
id: device_user._id,
name: if (device_user.profile and device_user.profile.fullname) then device_user.profile.fullname else device_user.username,
icon: device_user.profile.icon
}
msg = {
_id: new Mongo.ObjectID()._str,
form: form,
to: to,
to_type: 'group',
type: 'remove_error_img',
id: id,
url: url,
uuid: uuid,
img_type: img_type,
img_ts: img_ts,
current_ts: current_ts,
tid: tracker_id,
pids: p_ids
}
try
sendMqttGroupMessage(group_id,msg)
catch error
console.log('try sendMqttGroupMessage Err:',error)
update_group_dataset = (group_id,dataset_url,uuid)->
unless group_id and dataset_url and uuid
return
group = SimpleChat.Groups.findOne({_id:group_id})
user = Meteor.users.findOne({username: uuid})
if group and user
announcement = group.announcement;
unless announcement
announcement = []
i = 0
isExit = false
while i < announcement.length
if announcement[i].uuid is uuid
announcement[i].dataset_url = dataset_url
isExit = true
break;
i++
unless isExit
announcementObj = {
uuid:uuid,
device_name:user.profile.fullname,
dataset_url:dataset_url
};
announcement.push(announcementObj);
SimpleChat.Groups.update({_id:group_id},{$set:{announcement:announcement}})
# test
# Meteor.startup ()->
# insert_msg2(
# '7YRBBDB72200271715027668215821893',
# 'http://workaiossqn.tiegushi.com/8acb7f90-92e1-11e7-8070-d065caa7da61',
# '28DDU17602003551',
# 'face',
# '0.9',
# '100',
# '0',
# 'front',
# 1506588441021,
# 1506588441021,
# ''
# )
# Faces API
# [{
# 'id': id,
# 'uuid': uuid,
# 'group_id': current_groupid,
# 'img_url': url,
# 'position': position,
# 'type': img_type,
# 'current_ts': int(time.time()*1000),
# 'accuracy': accuracy,
# 'fuzziness': fuzziness,
# 'sqlid': sqlId,
# 'style': style,
# 'tid': tid,
# 'img_ts': img_ts,
# 'p_ids': p_ids,
# }]
Router.route('/restapi/workai/faces', {where: 'server'}).post(()->
data = this.request.body
if (typeof data is 'object' and data.constructor is Array)
data.forEach((face)->
insertFaces(face)
)
this.response.end('{"result": "ok"}\n')
else
this.response.end('{"result": "ok", "reason": "params must be an Array"}\n')
)
Router.route('/restapi/list_device', {where: 'server'}).get(()->
uuid = this.params.query.uuid
console.log(groups)
device = Devices.findOne({"uuid" : uuid})
ret_str = ''
if device
user = {'_id': device._id, 'username': device.name, 'profile': {'icon': '/device_icon_192.png'}}
ret_str += 'Device['+uuid+'] in Devices deleted \n'
if device.groupId
group_id = device.groupId
#SimpleChat.GroupUsers.remove({group_id:group_id,user_id:user._id});
groups = SimpleChat.GroupUsers.find({group_id:group_id,user_name:uuid}).fetch();
console.log(groups)
ret_str += groups.toString()
user = Meteor.users.findOne({username: uuid})
if user
users = Meteor.users.find({username: uuid}).fetch()
console.log(users)
ret_str += users.toString()
if ret_str is ''
return this.response.end('nothing in db')
this.response.end(ret_str)
#userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
#unless userGroup or userGroup.group_id
# return this.response.end('{"result": "failed", "cause": "group not found"}\n')
)
Router.route('/restapi/get_name_by_faceid', {where: 'server'}).get(()->
face_id = this.params.query.face_id
group_id = this.params.query.group_id
if not face_id or not group_id
return this.response.end(JSON.stringify({result: 'invalid parameters'}))
person = Person.findOne({group_id: group_id, faceId: face_id})
if not person
return this.response.end(JSON.stringify({result: 'no such item'}))
return this.response.end(JSON.stringify({result: 'success', name: person.name}))
)
Router.route('/restapi/clean_device', {where: 'server'}).get(()->
uuid = this.params.query.uuid
device = Devices.findOne({"uuid" : uuid})
ret_str = ''
if device
Devices.remove({uuid : uuid})
Devices.remove({_id:device._id});
ret_str += 'Device['+uuid+'] in Devices deleted \n'
if device.groupId
group_id = device.groupId
#SimpleChat.GroupUsers.remove({group_id:group_id,user_id:user._id});
SimpleChat.GroupUsers.remove({group_id:group_id,user_name:uuid});
ret_str += 'Device in userGroup in SimpleChat.GroupUsers deleted \n'
user = Meteor.users.findOne({username: uuid})
if user
Meteor.users.remove({username: uuid})
ret_str += 'Device['+uuid+'] in Meteor.users deleted \n'
if ret_str is ''
return this.response.end('nothing to delete')
this.response.end(ret_str)
#userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
#unless userGroup or userGroup.group_id
# return this.response.end('{"result": "failed", "cause": "group not found"}\n')
)
###
payload = {'groupid': groupid, 'uuid': uuid,'fuzziness_from':fuzziness_from, 'fuzziness_to':fuzziness_to,
'blury_threshold': blury_threshold, 'score_threshold_main': score_threshold_main, 'score_threshold_2nd': score_threshold_2nd}
###
Router.route('/restapi/workai/model_param_update', {where: 'server'}).post(()->
group_id = this.request.body.groupid
uuid = this.request.body.uuid
if group_id and uuid
ModelParam.upsert({groupid: group_id, uuid: uuid}, {$set: this.request.body})
this.response.end('{"result": "ok"}\n')
else
this.response.end('{"result": "ok", "reason": "invalid params"}\n')
)
Router.route('/restapi/workai/model_param', {where: 'server'}).post(()->
group_id = this.request.body.groupid
uuid = this.request.body.uuid
if group_id and uuid
params = ModelParam.findOne({groupid: group_id, uuid: uuid})
this.response.end(JSON.stringify(params) + '\n')
else
this.response.end('{"result": "ok", "reason": "invalid params"}\n')
)
Router.route('/restapi/workai', {where: 'server'}).get(()->
id = this.params.query.id
img_url = this.params.query.img_url
uuid = this.params.query.uuid
img_type = this.params.query.type
tracker_id = this.params.query.tid
console.log '/restapi/workai get request, id:' + id + ', img_url:' + img_url + ',uuid:' + uuid
unless id or img_url or uuid
return this.response.end('{"result": "failed", "cause": "invalid params,check id,uuid,img_url"}\n')
accuracy = this.params.query.accuracy
sqlid = this.params.query.sqlid
style = this.params.query.style
fuzziness = this.params.query.fuzziness
img_ts = this.params.query.img_ts
current_ts = this.params.query.current_ts
if this.params.query.opt and this.params.query.opt is 'remove'
padCallRemove(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style, img_ts, current_ts, tracker_id)
else
insert_msg2(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts,tracker_id)
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('id')
id = this.request.body.id
if this.request.body.hasOwnProperty('img_url')
img_url = this.request.body.img_url
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('type')
img_type = this.request.body.type
if this.request.body.hasOwnProperty('sqlid')
sqlid = this.request.body.sqlid
else
sqlid = 0
if this.request.body.hasOwnProperty('style')
style = this.request.body.style
else
style = 0
if this.request.body.hasOwnProperty('img_ts')
img_ts = this.request.body.img_ts
if this.request.body.hasOwnProperty('current_ts')
current_ts = this.request.body.current_ts
if this.request.body.hasOwnProperty('tid')
tracker_id = this.request.body.tid
if this.request.body.hasOwnProperty('p_ids') #可能性最大的三个人的id
p_ids = this.request.body.p_ids
console.log '/restapi/workai post request, id:' + id + ', img_url:' + img_url + ',uuid:' + uuid + ' img_type=' + img_type + ' sqlid=' + sqlid + ' style=' + style + 'img_ts=' + img_ts
unless id or img_url or uuid
return this.response.end('{"result": "failed", "cause": "invalid params,check id,uuid,img_url"}\n')
accuracy = this.params.query.accuracy
fuzziness = this.params.query.fuzziness
if this.params.query.opt and this.params.query.opt is 'remove'
padCallRemove(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style, img_ts, current_ts, tracker_id)
else
insert_msg2(id, img_url, uuid, img_type, accuracy, fuzziness, sqlid, style,img_ts,current_ts, tracker_id,p_ids)
this.response.end('{"result": "ok"}\n')
)
Router.route('restapi/workai_unknown', {where: 'server'}).get(()->
).post(()->
person_id = ''
persons = []
person_name = null
active_time = null
if this.request.body.hasOwnProperty('person_id')
person_id = this.request.body.person_id
if this.request.body.hasOwnProperty('persons')
persons = this.request.body.persons
console.log("restapi/workai_unknown post: person_id="+person_id+", persons="+JSON.stringify(persons))
if (!(persons instanceof Array) or persons.length < 1)
console.log("restapi/workai_unknown: this.request.body is not array.")
return this.response.end('{"result": "failed!", "cause": "this.request.body is not array."}\n')
console.log("restapi/workai_unknown: uuid = "+persons[0].uuid)
user = Meteor.users.findOne({username: persons[0].uuid})
unless user
console.log("restapi/workai_unknown: user is null")
return this.response.end('{"result": "failed!", "cause": "user is null."}\n')
userGroups = SimpleChat.GroupUsers.find({user_id: user._id})
unless userGroups
console.log("restapi/workai_unknown: userGroups is null")
return this.response.end('{"result": "failed!", "cause":"userGroups is null."}\n')
stranger_id = if person_id != '' then person_id else new Mongo.ObjectID()._str
#name = PERSON.getName(null, userGroup.group_id, person_id)
userGroups.forEach((userGroup)->
console.log("restapi/workai_unknown: userGroup.group_id="+userGroup.group_id)
stranger_name = if person_id != '' then PERSON.getName(null, userGroup.group_id, person_id) else new Mongo.ObjectID()._str
console.log("stranger_name="+stranger_name)
for person in persons
console.log("person="+JSON.stringify(person))
unless active_time
active_time = utilFormatTime(Number(person.img_ts))
if !person_name && person_id != ''
person_name = PERSON.getName(null, userGroup.group_id, person_id)
console.log("person_name="+person_name)
# update to DeviceTimeLine
create_time = new Date()
console.log("create_time.toString()="+create_time.toString())
if person.img_ts and person.current_ts
img_ts = Number(person.img_ts)
current_ts = Number(person.current_ts)
time_diff = img_ts + getTimeZoneDiffByMs(create_time.getTime(), current_ts)
console.log("time_diff="+time_diff)
create_time = new Date(time_diff)
timeObj = {
stranger_id: stranger_id,
stranger_name: stranger_name,
person_id: person.id,
person_name: person.name,
img_url: person.img_url,
sqlid: person.sqlid,
style: person.style,
accuracy: person.accuracy, # 准确度(分数)
fuzziness: person.fuzziness#, # 模糊度
ts:create_time.getTime()
}
uuid = person.uuid
PERSON.updateValueToDeviceTimeline(uuid,userGroup.group_id,timeObj)
if person_name
console.log("restapi/workai_unknown: person_name="+person_name)
#Get Configuration from DB
people_config = WorkAIUserRelations.find({'group_id':userGroup.group_id}, {fields:{'person_name':1, 'hide_it':1}}).fetch()
isShow = people_config.some((elem) => elem.person_name == person_name && !elem.hide_it)
console.log("people_config="+JSON.stringify(people_config))
if isShow and checkIfSendKnownUnknownPushNotification(userGroup.group_id,person_id)
group = SimpleChat.Groups.findOne({_id: userGroup.group_id})
group_name = '监控组'
if group && group.name
group_name = group.name
console.log("group_id="+userGroup.group_id)
console.log("Will notify one known people")
ai_person = Person.findOne({group_id:userGroup.group_id ,'faces.id': person_id});
ai_person_id = if ai_person then ai_person._id else null
sharpai_pushnotification("notify_knownPeople", {active_time:active_time, group_id:userGroup.group_id, group_name:group_name, person_name:person_name}, null, ai_person_id)
else
group = SimpleChat.Groups.findOne({_id: userGroup.group_id})
group_name = '监控组'
is_notify_stranger = true
if group && group.settings && group.settings.notify_stranger == false
is_notify_stranger = false
if group && group.name
group_name = group.name
console.log("group_id="+userGroup.group_id+", is_notify_stranger="+is_notify_stranger)
if is_notify_stranger and checkIfSendKnownUnknownPushNotification(userGroup.group_id,'0')
console.log("Will notify stranger")
sharpai_pushnotification("notify_stranger", {active_time:active_time, group_id:userGroup.group_id, group_name:group_name}, null, null)
)
this.response.end('{"result": "ok"}\n')
)
Router.route('restapi/workai_multiple_people', {where: 'server'}).get(()->
).post(()->
person_id = ''
persons = []
active_time = null
if this.request.body.hasOwnProperty('person_id')
person_id = this.request.body.person_id
if this.request.body.hasOwnProperty('persons')
persons = this.request.body.persons
console.log("restapi/workai_multiple_people post: person_id="+person_id+", persons="+JSON.stringify(persons))
if (!(persons instanceof Array) or persons.length < 1)
console.log("restapi/workai_multiple_people: this.request.body is not array.")
return this.response.end('{"result": "failed!", "cause": "this.request.body is not array."}\n')
console.log("restapi/workai_multiple_people: uuid = "+persons[0].uuid)
user = Meteor.users.findOne({username: persons[0].uuid})
unless user
console.log("restapi/workai_multiple_people: user is null")
return this.response.end('{"result": "failed!", "cause": "user is null."}\n')
userGroups = SimpleChat.GroupUsers.find({user_id: user._id})
unless userGroups
console.log("restapi/workai_multiple_people: userGroups is null")
return this.response.end('{"result": "failed!", "cause":"userGroups is null."}\n')
for person in persons
console.log("person="+JSON.stringify(person))
unless active_time
active_time = utilFormatTime(Number(person.img_ts))
userGroups.forEach((userGroup)->
console.log("restapi/workai_multiple_people: userGroup.group_id="+userGroup.group_id)
#Get Configuration from DB
people_config = WorkAIUserRelations.find({'group_id':userGroup.group_id}, {fields:{'person_name':1, 'hide_it':1}}).fetch()
console.log("people_config="+JSON.stringify(people_config))
multiple_persons = []
for person in persons
if person.accuracy == 0
continue
person_name = PERSON.getName(null, userGroup.group_id, person.id)
console.log("restapi/workai_multiple_people: person_name="+person_name)
isShow = people_config.some((elem) => elem.person_name == person_name && !elem.hide_it)
if isShow
if !multiple_persons.some((elem) => elem == person_name)
multiple_persons.push(person_name)
if multiple_persons.length == 0
console.log("restapi/workai_multiple_people: No people in the request body.")
return
group = SimpleChat.Groups.findOne({_id: userGroup.group_id})
group_name = '监控组'
is_notify_stranger = true
if group && group.settings && group.settings.notify_stranger == false
is_notify_stranger = false
if group && group.name
group_name = group.name
console.log("group_id="+userGroup.group_id)
console.log("Will notify known multiple people")
sharpai_pushnotification("notify_knownPeople", {active_time:active_time, group_id:userGroup.group_id, group_name:group_name, person_name:multiple_persons.join(', ')}, null)
)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-group-qrcode', {where: 'server'}).get(()->
group_id = this.params.query.group_id
console.log '/restapi/workai-group-qrcode get request, group_id: ', group_id
try
img = QRImage.image('http://' + server_domain_name + '/simple-chat/to/group?id=' + group_id, {size: 10})
this.response.writeHead(200, {'Content-Type': 'image/png'})
img.pipe(this.response)
catch
this.response.writeHead(414, {'Content-Type': 'text/html'})
this.response.end('<h1>414 Request-URI Too Large</h1>')
)
device_join_group = (uuid,group_id,name,in_out)->
device = PERSON.upsetDevice(uuid, group_id,name,in_out)
user = Meteor.users.findOne({username: uuid})
if !user
userId = Accounts.createUser({username: uuid, password: 'PI:PASSWORD:<PASSWORD>END_PI', profile: {fullname: device.name, icon: '/device_icon_192.png'},is_device:true})
user = Meteor.users.findOne({_id: userId})
else
Meteor.users.update({_id:user._id},{$set:{'profile.fullname':device.name, 'profile.icon':'/device_icon_192.png', is_device:true }});
group = SimpleChat.Groups.findOne({_id: group_id})
#一个设备只允许加入一个群
groupUsers = SimpleChat.GroupUsers.find({user_id: user._id})
hasBeenJoined = false
if groupUsers.count() > 0
groupUsers.forEach((groupUser)->
if groupUser.group_id is group_id
SimpleChat.GroupUsers.update({_id:groupUser._id},{$set:{is_device:true,in_out:in_out,user_name:device.name}});
hasBeenJoined = true
else
_group = SimpleChat.Groups.findOne({_id: groupUser.group_id})
SimpleChat.GroupUsers.remove(groupUser._id)
sendMqttMessage('/msg/g/'+ _group._id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
icon: user.profile.icon
}
to: {
id: _group._id
name: _group.name
icon: _group.icon
}
images: []
to_type: "group"
type: "text"
text: if user.profile and user.profile.fullname then user.profile.fullname + '[' +user.username + '] 已退出该群!' else '设备 ['+user.username+'] 已退出该群!'
create_time: new Date()
is_read: false
})
)
if hasBeenJoined is false
SimpleChat.GroupUsers.insert({
group_id: group_id
group_name: group.name
group_icon: group.icon
user_id: user._id
user_name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
user_icon: if user.profile and user.profile.icon then user.profile.icon else '/device_icon_192.png'
create_time: new Date()
is_device:true
in_out:in_out
});
sendMqttMessage('/msg/g/'+ group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname else user.username
icon: user.profile.icon
}
to: {
id: group_id
name: group.name
icon: group.icon
}
images: []
to_type: "group"
type: "text"
text: if user.profile and user.profile.fullname then user.profile.fullname + '[' +user.username + '] 已加入!' else '设备 ['+user.username+'] 已加入!'
create_time: new Date()
is_read: false
})
Meteor.call 'ai-system-register-devices',group_id,uuid, (err, result)->
if err or result isnt 'succ'
return console.log('register devices to AI-system failed ! err=' + err);
if result == 'succ'
return console.log('register devices to AI-system succ');
console.log('user:', user)
console.log('device:', device)
Meteor.methods {
"join-group":(uuid,group_id,name,in_out)->
console.log("uuid = "+uuid+" group id= "+group_id+" name= "+name+" inout = "+in_out)
device_join_group(uuid,group_id,name,'inout')
sendMqttMessage('/msg/d/'+uuid, {text:'groupchanged'});
return "ok"
}
Router.route('/restapi/workai-join-group', {where: 'server'}).get(()->
uuid = this.params.query.uuid
group_id = this.params.query.group_id
console.log '/restapi/workai-join-group get request, uuid:' + uuid + ', group_id:' + group_id
name = this.params.query.name
in_out = this.params.query.in_out
unless uuid or group_id or in_out or name
console.log '/restapi/workai-join-group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
device_join_group(uuid,group_id,name,'inout')
sendMqttMessage('/msg/d/'+uuid, {text:'groupchanged'});
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('name')
name = this.request.body.name
if this.request.body.hasOwnProperty('in_out')
in_out = this.request.body.in_out
console.log '/restapi/workai-join-group post request, uuid:' + uuid + ', group_id:' + group_id
unless uuid or group_id or in_out or name
console.log '/restapi/workai-join-group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
device_join_group(uuid,group_id,name,in_out)
sendMqttMessage('/msg/d/'+uuid, {text:'groupchanged'});
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-group-dataset', {where: 'server'}).get(()->
group_id = this.params.query.group_id
value = this.params.query.value
uuid = this.params.query.uuid
console.log '/restapi/workai-group-dataset get request, group_id:' + group_id + ', value:' + value + ', uuid:' + uuid
unless value and group_id and uuid
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
# insert_msg2(id, img_url, uuid)
update_group_dataset(group_id,value,uuid)
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.id
if this.request.body.hasOwnProperty('value')
value = this.request.body.img_url
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
console.log '/restapi/workai-group-dataset get request, group_id:' + group_id + ', value:' + value + ', uuid:' + uuid
unless value and group_id and uuid
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
#insert_msg2(id, img_url, uuid)
update_group_dataset(group_id,value,uuid)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-getgroupid', {where: 'server'}).get(()->
uuid = this.params.query.uuid
#console.log '/restapi/workai-getgroupid get request, uuid:' + uuid
unless uuid
console.log '/restapi/workai-getgroupid get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
user = Meteor.users.findOne({username: uuid})
device_group = ''
if user
groupUser = SimpleChat.GroupUsers.find({user_id: user._id})
groupUser.forEach((device)->
if device.group_id
device_group += device.group_id
device_group += ','
)
this.response.end(device_group)
)
Router.route('/restapi/workai-send2group', {where: 'server'}).get(()->
uuid = this.params.query.uuid
group_id = this.params.query.group_id
msg_type = this.params.query.type
msg_text = this.params.query.text
is_device_traing = this.params.query.is_device_traing
unless uuid or group_id
console.log '/restapi/workai-send2group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
if (msg_type == 'text' and msg_text)
user = null
userGroup = null
device = Devices.findOne({"uuid" : uuid})
if device and device.groupId
user = {'_id': device._id, 'username': device.name, 'profile': {'icon': '/device_icon_192.png'}}
userGroup = SimpleChat.GroupUsers.findOne({group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
else
user = Meteor.users.findOne({username: uuid})
unless user
return this.response.end('{"result": "failed", "cause": "device not registered"}\n')
userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
sendMqttMessage('/msg/g/'+ userGroup.group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname + '['+user.username+']' else user.username
icon: user.profile.icon
}
to: {
id: userGroup.group_id
name: userGroup.group_name
icon: userGroup.group_icon
}
images: []
to_type: "group"
type: "text"
text: msg_text
create_time: new Date()
is_read: false
is_device_traing: is_device_traing
})
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('type')
msg_type = this.request.body.type
if this.request.body.hasOwnProperty('text')
msg_text = this.request.body.text
if this.request.body.hasOwnProperty('is_device_traing')
is_device_traing = this.request.body.is_device_traing
unless uuid or group_id
console.log '/restapi/workai-send2group get unless resturn'
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
if (msg_type == 'text' and msg_text)
user = null
userGroup = null
device = Devices.findOne({"uuid" : uuid})
if device and device.groupId
user = {'_id': device._id, 'username': device.name, 'profile': {'icon': '/device_icon_192.png'}}
userGroup = SimpleChat.GroupUsers.findOne({group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
else
user = Meteor.users.findOne({username: uuid})
unless user
return this.response.end('{"result": "failed", "cause": "device not registered"}\n')
userGroup = SimpleChat.GroupUsers.findOne({user_id: user._id, group_id: group_id})
unless userGroup or userGroup.group_id
return this.response.end('{"result": "failed", "cause": "group not found"}\n')
sendMqttMessage('/msg/g/'+ userGroup.group_id, {
_id: new Mongo.ObjectID()._str
form: {
id: user._id
name: if user.profile and user.profile.fullname then user.profile.fullname + '['+user.username+']' else user.username
icon: user.profile.icon
}
to: {
id: userGroup.group_id
name: userGroup.group_name
icon: userGroup.group_icon
}
images: []
to_type: "group"
type: "text"
text: msg_text
create_time: new Date()
is_read: false
is_device_traing: is_device_traing
})
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-group-template', {where: 'server'}).get(()->
result = {
group_templates:[
{
"_id" : new Mongo.ObjectID()._str,
"name": "Work AI工作效能模版",
"icon": rest_api_url + "/workAIGroupTemplate/efficiency.jpg",
"img_type": "face"
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "家庭安全模版",
"icon": rest_api_url + "/workAIGroupTemplate/safety.jpg",
"img_type": "object"
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "NLP情绪分析模版",
"icon": rest_api_url + "/workAIGroupTemplate/sentiment.jpg"
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "NLP通用文本分类模版",
"icon": rest_api_url + "/workAIGroupTemplate/classification.jpg",
"type":'nlp_classify'
},
{
"_id" : new Mongo.ObjectID()._str,
"name": "ChatBot训练模版",
"icon": rest_api_url + "/workAIGroupTemplate/chatBot.jpg"
}
]}
this.response.end(JSON.stringify(result))
)
onNewHotSharePost = (postData)->
console.log 'onNewHotSharePost:' , postData
nlp_group = SimpleChat.Groups.findOne({_id:'92bf785ddbe299bac9d1ca82'});
nlp_user = Meteor.users.findOne({_id: 'xWA3KLXDprNe8Lczw'});
#nlp_classname = NLP_CLASSIFY.getName()
nlp_classname = postData.classname
if nlp_classname
NLP_CLASSIFY.setName(nlp_group._id,nlp_classname)
sendMqttMessage('/msg/g/'+ nlp_group._id, {
_id: new Mongo.ObjectID()._str
form: {
id: nlp_user._id
name: if nlp_user.profile and nlp_user.profile.fullname then nlp_user.profile.fullname + '['+nlp_user.username+']' else nlp_user.username
icon: nlp_user.profile.icon
}
to: {
id: nlp_group._id
name: nlp_group.name
icon: nlp_group.icon
}
to_type: "group"
type: "url"
text: if !nlp_classname then '1 个链接需要标注' else nlp_className + ':'
urls:[{
_id:new Mongo.ObjectID()._str,
label: nlp_classname,
#class_id:postData.classid,
url:postData.posturl,
title:postData.posttitle,
thumbData:postData.mainimage,
description:if postData.description then postData.description else postData.posturl
}]
create_time: new Date()
class_name: nlp_classname
wait_lable: !nlp_classname
is_read: false
})
Router.route('/restapi/workai-hotshare-newpost', {where: 'server'}).get(()->
classname = this.params.query.classname
#username = this.params.query.username
posttitle = this.params.query.posttitle
posturl = this.params.query.posturl
mainimage = this.params.query.mainimage
description = this.params.query.description
postData = { classname: classname, posttitle: posttitle, posturl: posturl ,mainimage:mainimage, description:description}
onNewHotSharePost(postData)
this.response.end('{"result": "ok"}\n')
).post(()->
if this.request.body.hasOwnProperty('classname')
classname = this.request.body.classname
if this.request.body.hasOwnProperty('posttitle')
posttitle = this.request.body.posttitle
if this.request.body.hasOwnProperty('posturl')
posturl = this.request.body.posturl
if this.request.body.hasOwnProperty('mainimage')
mainimage = this.request.body.mainimage
if this.request.body.hasOwnProperty('description')
description = this.request.body.description
postData = { classname: classname, posttitle: posttitle, posturl: posturl, mainimage:mainimage, description:description}
onNewHotSharePost(postData)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/workai-motion-imgs/:id', {where: 'server'}).get(()->
id = this.params.id
post = Posts.findOne({_id: id})
html = Assets.getText('workai-motion-imgs.html');
imgs = ''
post.docSource.imgs.forEach (img)->
imgs += '<li><img src="'+img+'" /></li>'
html = html.replace('{{imgs}}', imgs)
this.response.end(html)
)
Router.route('/restapi/workai-motion', {where: 'server'}).post(()->
payload = this.request.body || {}
deviceUser = Meteor.users.findOne({username: payload.uuid})|| {}
groupUser = SimpleChat.GroupUsers.findOne({user_id: deviceUser._id}) || {} # 一个平板只对应一个聊天群
group = SimpleChat.Groups.findOne({_id: groupUser.group_id})
if (!group)
return this.response.end('{"result": "error"}\n')
if (payload.motion_gif)
imgs = [payload.motion_gif]
# if (payload.imgs)
# imgs = payload.imgs
if (!imgs or imgs.length <= 0)
return this.response.end('{"result": "error"}\n')
if (imgs.length > 10)
imgs = imgs.slice(0, 9)
deferSetImmediate ()->
# update follow
SimpleChat.GroupUsers.find({group_id: group._id}).forEach (item)->
if (Follower.find({userId: item.user_id, followerId: deviceUser._id}).count() <= 0)
console.log('insert follower:', item.user_id)
Follower.insert({
userId: item.user_id
followerId: deviceUser._id
createAt: new Date()
})
#一个设备一天的动作只放在一个帖子里
devicePost = Posts.findOne({owner:deviceUser._id})
isTodayPost = false;
if(devicePost)
today = new Date().toDateString()
isTodayPost = if devicePost.createdAt.toDateString() is today then true else false;
console.log 'isTodayPost:'+isTodayPost
name = PERSON.getName(payload.uuid, group._id, payload.id)
postId = if isTodayPost then devicePost._id else new Mongo.ObjectID()._str
deviceName = if deviceUser.profile and deviceUser.profile.fullname then deviceUser.profile.fullname else deviceUser.username
title = if name then "摄像头看到#{name} 在#{deviceName}" else (if payload.type is 'face' then "摄像头看到有人在#{deviceName}" else "摄像头看到#{deviceName}有动静")
time = '时间:' + new Date().toString()
post = {
pub: if isTodayPost then devicePost.pub else []
title: title
addontitle: time
browse: 0
heart: []
retweet: []
comment: []
commentsCount: 0
mainImage: if payload.motion_gif then payload.motion_gif else payload.img_url
publish: true
owner: deviceUser._id
ownerName: PI:NAME:<NAME>END_PIName
ownerIcon: if deviceUser.profile and deviceUser.profile.icon then deviceUser.profile.icon else '/userPicture.png'
createdAt: new Date # new Date(payload.ts)
isReview: true
insertHook: true
import_status: 'done'
fromUrl: ''
docType: 'motion'
docSource: payload
}
newPub = []
# newPub.push({
# _id: new Mongo.ObjectID()._str
# type: 'text'
# isImage: false
# owner: deviceUser._id
# text: "类 型:#{if payload.type is 'face' then '人' else '对像'}\n准确度:#{payload.accuracy}\n模糊度:#{payload.fuzziness}\n设 备:#{deviceName}\n动 作:#{payload.mid}\n"
# style: ''
# data_row: 1
# data_col: 1
# data_sizex: 6
# data_sizey: 1
# data_wait_init: true
# })
# newPub.push({
# _id: new Mongo.ObjectID()._str
# type: 'text'
# isImage: false
# owner: deviceUser._id
# text: '以下为设备的截图:'
# style: ''
# data_row: 2
# data_col: 1
# data_sizex: 6
# data_sizey: 1
# data_wait_init: true
# })
data_row = 3
imgs.forEach (img)->
newPub.push({
_id: new Mongo.ObjectID()._str
type: 'image'
isImage: true
# inIframe: true
owner: deviceUser._id
# text: '您当前程序不支持视频观看',
# iframe: '<iframe height="100%" width="100%" src="'+rest_api_url+'/restapi/workai-motion-imgs/'+postId+'" frameborder="0" allowfullscreen></iframe>'
imgUrl: img,
data_row: data_row
data_col: 1
data_sizex: 6
data_sizey: 5
data_wait_init: true
})
data_row += 5
newPub.push({
_id: new Mongo.ObjectID()._str
type: 'text'
isImage: false
owner: deviceUser._id
text: time
style: ''
data_row: 1
data_col: 1
data_sizex: 6
data_sizey: 1
data_wait_init: true
isTime:true
})
newPub.push({
_id: new Mongo.ObjectID()._str
type: 'text'
isImage: false
owner: deviceUser._id
text: title
style: ''
data_row: 1
data_col: 1
data_sizex: 6
data_sizey: 1
data_wait_init: true
})
Array.prototype.push.apply(newPub, post.pub)
post.pub = newPub
# formatPostPub(post.pub)
if isTodayPost
console.log('update motion post:', postId)
Posts.update({_id:postId},{$set:post})
globalPostsUpdateHookDeferHandle(post.owner, postId,null,{$set:post})
return;
post._id = postId
globalPostsInsertHookDeferHandle(post.owner, post._id)
Posts.insert(post)
console.log('insert motion post:', post._id)
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/date', (req, res, next)->
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
this.response.end(Date.now().toString())
, {where: 'server'})
Router.route('/restapi/allgroupsid/:token/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token
limit = this.params.limit
skip = this.params.skip
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/allgroupsid get request, token:' + token + ' limit:' + limit + ' skip:' + skip
allgroups = []
groups = SimpleChat.Groups.find({}, {fields:{"_id": 1, "name": 1}, limit: parseInt(limit), skip: parseInt(skip)})
unless groups
return this.response.end('[]\n')
groups.forEach((group)->
allgroups.push({'id':group._id, 'name': group.name})
)
this.response.end(JSON.stringify(allgroups))
)
Router.route('/restapi/groupusers/:token/:groupid/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token
limit = this.params.limit
skip = this.params.skip
groupid = this.params.groupid
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/groupusers get request, token:' + token + ' limit:' + limit + ' skip:' + skip + ' groupid:' + groupid
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
#groupDevices = Devices.find({'groupId': groupid}).fetch()
#console.log 'no group found:' + groupDevices
allUsers = []
userGroups = SimpleChat.GroupUsers.find({group_id: groupid}, {fields:{"user_id": 1, "user_name": 1}, limit: parseInt(limit), skip: parseInt(skip)})
unless userGroups
return this.response.end('[]\n')
userGroups.forEach((userGroup)->
#if _.pluck(groupDevices, 'uuid').indexOf(userGroup.user_id) is -1
allUsers.push({'user_id':userGroup.user_id, 'user_name': userGroup.user_name})
)
this.response.end(JSON.stringify(allUsers))
)
Router.route('/restapi/activity/:token/:direction/:groupid/:ts/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token
groupid = this.params.groupid
limit = this.params.limit
skip = this.params.skip
direction = this.params.direction
starttime = this.params.ts
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/user get request, token:' + token + ' limit:' + limit + ' skip:' + skip + ' groupid:' + groupid + ' Direction:' + direction + ' starttime:' + starttime
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
allActivity = []
#Activity.id is id of person name
groupActivity = Activity.find(
{'group_id': groupid, 'ts': {$gt: parseInt(starttime)}, 'in_out': direction}
{fields:{'id': 1, 'name': 1, 'ts': 1, 'in_out': 1, 'img_url':1}, limit: parseInt(limit), skip: parseInt(skip)}
)
unless groupActivity
return this.response.end('[]\n')
groupActivity.forEach((activity)->
allActivity.push({'user_id': activity.id, 'user_name': activity.name, 'in_out': activity.in_out, 'img_url': activity.img_url})
)
this.response.end(JSON.stringify(allActivity))
)
Router.route('/restapi/active/:active/:token/:direction/:skip/:limit', {where: 'server'}).get(()->
token = this.params.token #
limit = this.params.limit #
skip = this.params.skip #
direction = this.params.direction #'in'/'out'
active = this.params.active #'active'/'notactive'
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/:active get request, token:' + token + ' limit:' + limit + ' skip:' + skip + ' Direction:' + direction + ' active:' + active
allnotActivity = []
daytime = new Date()
daytime.setSeconds(0)
daytime.setMinutes(0)
daytime.setHours(0)
daytime = new Date(daytime).getTime()
notActivity = WorkAIUserRelations.find({}, {limit: parseInt(limit), skip: parseInt(skip)})
unless notActivity
return this.response.end('[]\n')
notActivity.forEach((item)->
#console.log(item)
if !item.checkin_time
item.checkin_time = 0
if !item.ai_in_time
item.ai_in_time= 0
if !item.checkout_time
item.checkout_time = 0
if !item.ai_out_time
item.ai_out_time = 0
if active is 'notactive'
if direction is 'in' and item.checkin_time < daytime and item.ai_in_time < daytime
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.in_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
else if direction is 'out' and item.checkout_time < daytime and item.ai_out_time < daytime
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.out_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
else if active is 'active'
if direction is 'in' and (item.checkin_time > daytime or item.ai_in_time > daytime)
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.in_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
else if direction is 'out' and (item.checkout_time > daytime or item.ai_out_time > daytime)
allnotActivity.push({
'app_user_id': item.app_user_id
'app_user_name': item.app_user_name
'uuid': item.out_uuid
'groupid': item.group_id
'msgid': new Mongo.ObjectID()._str
})
)
this.response.end(JSON.stringify(allnotActivity))
)
Router.route('/restapi/resetworkstatus/:token', {where: 'server'}).get(()->
token = this.params.token #
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/resetworkstatus get request'
date = Date.now();
mod = 24*60*60*1000;
date = date - (date % mod)
nextday = date + mod
relations = WorkAIUserRelations.find({})
relations.forEach((fields)->
if fields && fields.group_id
# 按 group 所在时区初始化 workStatus 数据
timeOffset = 8
shouldInitWorkStatus = false
group = SimpleChat.Groups.findOne({_id: fields.group_id})
if (group and group.offsetTimeZone)
timeOffset = parseInt(group.offsetTimeZone)
# 根据时区 获取 group 对应时区时间
group_local_time = getLocalTimeByOffset(timeOffset)
group_local_time_hour = group_local_time.getHours()
if group_local_time_hour is 0
shouldInitWorkStatus = true
console.log('now should init the offsetTimeZone: ', timeOffset)
#console.log('>>> ' + JSON.stringify(fields))
workstatus = WorkStatus.findOne({'group_id': fields.group_id, 'date': nextday, 'person_name': fields.person_name})
if !workstatus and shouldInitWorkStatus
newWorkStatus = {
"app_user_id" : fields.app_user_id
"group_id" : fields.group_id
"date" : nextday
"person_id" : fields.ai_persons
"person_name" : fields.person_name
"status" : "out"
"in_status" : "unknown"
"out_status" : "unknown"
"in_uuid" : fields.in_uuid
"out_uuid" : fields.out_uuid
"whats_up" : ""
"in_time" : 0
"out_time" : 0
"hide_it" : if fields.hide_it then fields.hide_it else false
}
#console.log('>>> new a WorkStatus ' + JSON.stringify(newWorkStatus))
WorkStatus.insert(newWorkStatus)
)
# 计算没有确认下班的数据
docs = UserCheckoutEndLog.find({}).fetch()
docs.map (doc)->
# remove
UserCheckoutEndLog.remove({_id: doc._id})
# 状态
startUTC = Date.UTC(doc.params.msg_data.create_time.getUTCFullYear(), doc.params.msg_data.create_time.getUTCMonth(), doc.params.msg_data.create_time.getUTCDate(), 0, 0, 0, 0)
endUTC = Date.UTC(doc.params.msg_data.create_time.getUTCFullYear(), doc.params.msg_data.create_time.getUTCMonth(), doc.params.msg_data.create_time.getUTCDate(), 23, 59, 59, 0)
workstatus = WorkStatus.findOne({'group_id': doc.params.msg_data.group_id, 'date': {$gte: startUTC, $lte: endUTC}})
# local date
now = new Date()
group = SimpleChat.Groups.findOne({_id: doc.params.msg_data.group_id})
if (group and group.offsetTimeZone)
now = new Date((now.getTime()+(now.getTimezoneOffset()*60000)) + (3600000*group.offsetTimeZone))
else
now = new Date((now.getTime()+(now.getTimezoneOffset()*60000)) + (3600000*8))
# console.log('===1==', workstatus.status)
unless (workstatus and workstatus.status is 'out')
# console.log('===2==', doc.userName, doc.params.msg_data.create_time.getUTCDate(), now.getUTCDate())
# 当天数据
if (doc.params.msg_data.create_time.getUTCDate() is now.getUTCDate())
# console.log('===3==', doc.userName)
send_greeting_msg(doc.params.msg_data);
PERSON.updateWorkStatus(doc.params.person._id)
if (doc.params.person_info)
PERSON.sendPersonInfoToWeb(doc.params.person_info)
else
# TODO:
this.response.end(JSON.stringify({result: 'ok'}))
)
# params = {
# uuid: 设备UUID,
# person_id: id,
# video_post: 视频封面图地址,
# video_src: 视频播放地址
# ts: 时间戳
# ts_offset: 时区 (eg : 东八区 是 -8);
# }
Router.route('/restapi/timeline/video/', {where: 'server'}).post(()->
payload = this.request.body || {}
console.log('/restapi/timeline/video/ request body = ',JSON.stringify(payload))
if (!payload.uuid or !payload.person_id or !payload.video_post or !payload.video_src or !payload.ts or !payload.ts_offset)
return this.response.end('{"result": "error", "reson":"参数不全或格式错误!"}\n')
# step 1. get group_id by uuid
device = Devices.findOne({uuid: payload.uuid})
if device and device.groupId
group_id = device.groupId
# step 2. get person_name by person_id
person_name = PERSON.getName(payload.uuid, group_id, payload.person_id)
if (!person_name)
person_name = ""
PERSON.updateToDeviceTimeline(payload.uuid,group_id,{
is_video: true,
person_id: payload.person_id,
person_name: PI:NAME:<NAME>END_PI_name,
video_post: payload.video_post,
video_src: payload.video_src,
ts: Number(payload.ts),
ts_offset: Number(payload.ts_offset)
})
return this.response.end('{"result": "success"}\n')
)
Router.route('/restapi/clustering', {where: 'server'}).get(()->
group_id = this.params.query.group_id
faceId = this.params.query.faceId
totalFaces = this.params.query.totalFaces
url = this.params.query.url
rawfilepath = this.params.query.rawfilepath
isOneSelf = this.params.query.isOneSelf
if isOneSelf == 'true'
isOneSelf = true
else
isOneSelf = false
console.log '/restapi/clustering get request, group_id:' + group_id + ', faceId:' + faceId + ',totalFaces:' + totalFaces + ',url' + url + ',rawfilepath' + rawfilepath + ',isOneSelf' + isOneSelf
unless group_id and isOneSelf
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
#取回这个组某个人所有正确/不正确的图片
if group_id and faceId
dataset={'group_id': group_id, 'faceId': faceId, 'dataset': []}
allClustering = Clustering.find({'group_id': group_id, 'faceId': faceId, 'isOneSelf': isOneSelf}).fetch()
allClustering.forEach((fields)->
dataset.dataset.push({url:fields.url, rawfilepath: fields.rawfilepath})
)
else
dataset={'group_id': group_id, 'dataset': []}
#取回这个组某个人所有不正确的图片
#返回标注过的数据集
this.response.end(JSON.stringify(dataset))
).post(()->
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('faceId')
faceId = this.request.body.faceId
if this.request.body.hasOwnProperty('totalFaces')
totalFaces = this.request.body.totalFaces
if this.request.body.hasOwnProperty('url')
url = this.request.body.url
if this.request.body.hasOwnProperty('rawfilepath')
rawfilepath = this.request.body.rawfilepath
if this.request.body.hasOwnProperty('isOneSelf')
isOneSelf = this.request.body.isOneSelf
if isOneSelf == "true"
isOneSelf = true
console.log '/restapi/clustering post request, group_id:' + group_id + ', faceId:' + faceId + ',totalFaces:' + totalFaces + ',url' + url + ',rawfilepath' + rawfilepath + ',isOneSelf' + isOneSelf
unless group_id and faceId and url
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
#插入数据库
person = Person.findOne({group_id: group_id, 'faceId': faceId},{sort: {createAt: 1}})
if !person
person = {
_id: new Mongo.ObjectID()._str,
id: 1,
group_id: group_id,
faceId: faceId,
url: url,
name: faceId,
faces: [],
deviceId: 'clustering',
DeviceName: 'clustering',
createAt: new Date(),
updateAt: new Date()
};
Person.insert(person)
console.log('>>> new people' + faceId)
clusteringObj = {
group_id: group_id,
faceId: faceId,
totalFaces: totalFaces,
url: url,
rawfilepath: rawfilepath,
isOneSelf: isOneSelf
}
Clustering.insert(clusteringObj)
#console.log('>>> ' + JSON.stringify(clusteringObj))
this.response.end('{"result": "ok"}\n')
)
Router.route('/restapi/get-group-users', {where: 'server'}).get(()->
group_id = this.params.query.group_id
resObj = []
gUsers = Person.find({group_id: group_id})
if gUsers
gUsers.forEach((user)->
resObj.push(user)
)
this.response.end(JSON.stringify(resObj))
).post(()->
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
resObj = []
gUsers = Person.find({group_id: group_id})
if gUsers
gUsers.forEach((user)->
resObj.push(user)
)
this.response.end(JSON.stringify(resObj))
)
Router.route('/restapi/datasync/:token/:groupid', {where: 'server'}).get(()->
token = this.params.token
groupid = this.params.groupid
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/datasync get request, token:' + token + ' groupid:' + groupid
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
syncDateSet=[]
#取出群相册里面所有已经标注的数据
persons = Person.find({group_id: groupid},{fields:{name: 1, faceId:1}}).fetch()
persons.forEach((item)->
urls=[]
if item and item.name
dataset = LableDadaSet.find({group_id: groupid ,name: item.name}, {fields:{url: 1,style:1,sqlid:1}}).fetch()
dataset.forEach((item2)->
if item2 and item2.url
urls.push({
url:item2.url,
style: item2.style || 'front',
sqlid: item2.sqlid || null
})
)
if item and item.faceId
syncDateSet.push({faceId: item.faceId, urls: urls})
)
this.response.end(JSON.stringify(syncDateSet))
)
Router.route('/restapi/groupdatasync/:token/:groupid', {where: 'server'}).get(()->
token = this.params.token
groupid = this.params.groupid
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/datasync get request, token:' + token + ' groupid:' + groupid
group = SimpleChat.Groups.findOne({'_id': groupid})
unless group
console.log 'no group found:' + groupid
return this.response.end('[]\n')
syncDateSet=[]
#取出群相册里面所有已经标注的数据
person = GroupPerson.find({group_id: groupid},{fields:{name: 1, faceId:1}}).fetch()
person.forEach((item)->
urls=[]
if item and item.name
dataset = GroupLableDadaSet.find({group_id: groupid ,name: item.name}, {fields:{url: 1,style:1,sqlid:1}}).fetch()
dataset.forEach((item2)->
if item2 and item2.url
urls.push({
url:item2.url,
style: item2.style || 'front',
sqlid: item2.sqlid || null
})
)
if item and item.faceId
syncDateSet.push({faceId: item.faceId, urls: urls})
)
this.response.end(JSON.stringify(syncDateSet))
)
getInComTimeLen = (workstatus) ->
group_id = workstatus.group_id;
diff = 0;
out_time = workstatus.out_time;
today_end = workstatus.out_time;
time_offset = 8
group = SimpleChat.Groups.findOne({_id: group_id});
if (group && group.offsetTimeZone)
time_offset = group.offsetTimeZone;
DateTimezone = (d, time_offset) ->
if (time_offset == undefined)
if (d.getTimezoneOffset() == 420)
time_offset = -7
else
time_offset = 8
#取得 UTC time
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
local_now = new Date(utc + (3600000*time_offset))
today_now = new Date(local_now.getFullYear(), local_now.getMonth(), local_now.getDate(),
local_now.getHours(), local_now.getMinutes());
return today_now;
#计算out_time
if(workstatus.in_time)
date = new Date(workstatus.in_time);
fomatDate = date.shortTime(time_offset);
isToday = PERSON.checkIsToday(workstatus.in_time,group_id)
#不是今天的时间没有out_time的或者是不是今天时间,最后一次拍到的是进门的状态的都计算到当天结束
if((!out_time and !isToday) or (workstatus.status is 'in' and !isToday))
date = DateTimezone(date,time_offset);
day_end = new Date(date).setHours(23,59,59);
#day_end = new Date(this.in_time).setUTCHours(0,0,0,0) + (24 - time_offset)*60*60*1000 - 1;
out_time = day_end;
workstatus.in_time = date.getTime();
#今天的时间(没有离开过监控组)
else if(!out_time and isToday)
now_time = Date.now();
out_time = now_time;
#今天的时间(离开监控组又回到监控组)
else if(out_time and workstatus.status is 'in' and isToday)
now_time = Date.now();
out_time = now_time;
if(workstatus.in_time and out_time)
diff = out_time - workstatus.in_time;
if(diff > 24*60*60*1000)
diff = 24*60*60*1000;
else if(diff < 0)
diff = 0;
min = diff / 1000 / 60 ;
hour = Math.floor(min/60)+' h '+Math.floor(min%60) + ' min';
if(min < 60)
hour = Math.floor(min%60) + ' min';
if(diff == 0)
hour = '0 min';
return hour;
getShortTime = (ts,group_id)->
time_offset = 8
group = SimpleChat.Groups.findOne({_id: group_id});
if (group && group.offsetTimeZone)
time_offset = group.offsetTimeZone;
time = new Date(ts);
return time.shortTime(time_offset,true);
sendEmailToGroupUsers = (group_id)->
if !group_id
return
group = SimpleChat.Groups.findOne({_id:group_id});
if !group
return
date = Date.now();
mod = 24*60*60*1000;
date = date - (date % mod)
yesterday = date - mod
console.log 'date:'+ yesterday
workstatus_content = ''
WorkStatus.find({'group_id': group_id, 'date': yesterday}).forEach((target)->
unless target.hide_it
text = Assets.getText('email/work-status-content.html');
text = text.replace('{{person_name}}', target.person_name);
# app_user_status_color = 'gray'
# app_notifaction_status = ''
# if target.app_user_id
# app_user_status_color = 'green'
# if target.app_notifaction_status is 'on'
# app_notifaction_status = '<i class="fa fa-bell app-user-status" style="color:green;"></i>'
# app_user_status = '<i class="fa fa-user app-user-status" style="color:green;"></i>'+app_notifaction_status
# text = text.replace('{{app_user_status_color}}',app_user_status_color);
# text = text.replace('{{app_notifaction_status}}',app_notifaction_status);
isStatusIN_color = if target.status is 'in' then 'green' else 'gray'
# if target.in_time > 0
# if PERSON.checkIsToday(target.in_time,group_id)
# isStatusIN_color = 'gray'
# text = text.replace('{{isStatusIN_color}}',isStatusIN_color);
InComTimeLen = getInComTimeLen(target)
text = text.replace('{{InComTimeLen}}',InComTimeLen);
isInStatusNotUnknownStyle = if target.in_status is 'unknown' then 'display:none;' else 'display:table-cell;'
text = text.replace('{{isInStatusNotUnknownStyle}}',isInStatusNotUnknownStyle);
isInStatusUnknownStyle = if target.in_status is 'unknown' then 'display:table-cell;' else 'display:none;'
text = text.replace('{{isInStatusUnknownStyle}}',isInStatusUnknownStyle);
if target.in_status isnt 'unknown'
text = text.replace('{{in_image}}',target.in_image);
text = text.replace('{{in_time}}',getShortTime(target.in_time,group_id))
in_time_Color = 'green'
if target.in_status is 'warning'
in_time_Color = 'orange'
else if target.in_status is 'error'
in_time_Color = 'red'
text = text.replace('{{in_time_Color}}',in_time_Color);
historyUnknownOutStyle = 'display:none;'
if isStatusIN_color is 'green'
historyUnknownOutStyle = 'display:table-cell;color:red;'
else
if target.out_status is 'unknown'
historyUnknownOutStyle = 'display:table-cell;'
text = text.replace('{{historyUnknownOutStyle}}',historyUnknownOutStyle);
isOutStatusNotUnknownStyle = if historyUnknownOutStyle is 'display:none;' then 'display:table-cell;' else 'display:none;'
text = text.replace('{{isOutStatusNotUnknownStyle}}',isOutStatusNotUnknownStyle);
if historyUnknownOutStyle is 'display:none;'
text = text.replace('{{out_image}}',target.out_image);
text = text.replace('{{out_time}}',getShortTime(target.out_time,group_id));
out_time_Color = 'green'
if target.out_status is 'warning'
out_time_Color = 'orange'
else if target.out_status is 'error'
out_time_Color = 'red'
text = text.replace('{{out_time_Color}}',out_time_Color);
whats_up = ''
if target.whats_up
whatsUpLists = [];
if typeof(target.whats_up) is 'string'
whatsUpLists.push({
person_name:target.person_name,
content:target.whats_up,
ts:target.in_time
})
# ...
else
whatsUpLists = target.whats_up
for item in whatsUpLists
whats_up = whats_up + '<p style="white-space: pre-wrap;"><strong>'+item.person_name+'</strong>['+getShortTime(item.ts,group_id)+']'+item.content
else
whats_up = '今天还没有工作安排...'
text = text.replace('{{whats_up}}',whats_up);
workstatus_content = workstatus_content + text
)
if workstatus_content.length > 0
text = Assets.getText('email/work-status-report.html');
text = text.replace('{{group.name}}', group.name);
y_date = new Date(yesterday)
year = y_date.getFullYear();
month = y_date.getMonth() + 1;
y_date_title = '(' + year + '-' + month + '-' +y_date.getDate() + ')';
text = text.replace('{{date.fomatStr}}',y_date_title)
text = text.replace('{{workStatus.content}}', workstatus_content);
subject = group.name + ' 每日出勤报告'+y_date_title
else
return
#console.log 'html:'+ JSON.stringify(text)
SimpleChat.GroupUsers.find({group_id:group_id}).forEach(
(fields)->
if fields and fields.user_id
user_id = fields.user_id
#user_id = 'GriTByu7MhRGhQdPD'
user = Meteor.users.findOne({_id:user_id});
if user and user.emails and user.emails.length > 0
email_address = user.emails[0].address
#email_address = 'PI:EMAIL:<EMAIL>END_PI'
isUnavailable = UnavailableEmails.findOne({address:email_address});
unless isUnavailable
#email_address = user.emails[0].address
console.log 'groupuser : ' + user.profile.fullname + ' email address is :' + user.emails[0].address
try
Email.send({
to:email_address,
from:'点圈<PI:EMAIL:<EMAIL>END_PI>',
subject:subject,
html : text,
envelope:{
from:'点圈<PI:EMAIL:<EMAIL>END_PI>',
to:email_address + '<' + email_address + '>'
}
})
console.log 'try send mail to:'+email_address
catch e
console.log 'exception:send mail error = %s, userEmail = %s',e,email_address
###
unavailableEmail = UnavailableEmails.findOne({address:email_address})
if unavailableEmail
UnavailableEmails.update({reason:e});
else
UnavailableEmails.insert({address:email_address,reason:e,createAt:new Date()});
###
)
Router.route('/restapi/sendReportByEmail/:token',{where:'server'}).get(()->
token = this.params.token #
headers = {
'Content-type':'text/html;charest=utf-8',
'Date': Date.now()
}
this.response.writeHead(200, headers)
console.log '/restapi/sendReportByEmail get request'
#sendEmailToGroupUsers('ae64c98bdff9b674fb5dad4b')
groups = SimpleChat.Groups.find({})
groups.forEach((fields)->
if fields
sendEmailToGroupUsers(fields._id)
)
this.response.end(JSON.stringify({result: 'ok'}))
)
# 定义相应的mailgun webhook, dropped,hardbounces,unsubscribe 下次不再向相应的邮件地址发信
# docs: https://documentation.mailgun.com/en/latest/user_manual.html#webhooks
@mailGunSendHooks = (address, type, reason)->
if !address and !reason
return console.log('need email address and webhook reason')
console.log('Email send Hooks, send to '+address + ' failed , reason: '+ reason)
unavailableEmail = UnavailableEmails.findOne({address: address})
if unavailableEmail
UnavailableEmails.update({_id: unavailableEmail._id},{$set:{
reason:reason
}})
else
UnavailableEmails.insert({
address: address,
reason: reason
createAt: new Date()
})
# 发信失败跟踪 (Dropped Messages)
Router.route('/hooks/emails/dropped', {where: 'server'}).post(()->
data = this.request.body
mailGunSendHooks(emails,'dropped')
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
# 硬/软 退信跟踪 (Hard Bounces)
Router.route('/hooks/emails/bounced', {where: 'server'}).post(()->
data = this.request.body
type = data.event || 'bounced'
mailGunSendHooks(data.recipient,type)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
# 垃圾邮件跟踪 (Spam Complaints)
Router.route('/hooks/emails/complained', {where: 'server'}).post(()->
data = this.request.body
type = data.event || 'complained'
mailGunSendHooks(data.recipient,type)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
# 取消订阅跟踪 (Unsubscribes)
Router.route('/hooks/emails/unsubscribe', {where: 'server'}).post(()->
data = this.request.body
type = data.event || 'unsubscribe'
mailGunSendHooks(data.recipient,type)
headers = {
'Content-type': 'application/vnd.openxmlformats',
'Content-Disposition': 'attachment; filename=' + title + '.xlsx'
}
this.response.writeHead(200, headers)
this.response.end('{"result": "ok"}\n')
)
#陌生人图片信息
Router.route('/restapi/updateStrangers', {where: 'server'}).post(()->
if this.request.body.hasOwnProperty('imgs')
imgs = this.request.body.imgs
if this.request.body.hasOwnProperty('img_gif')
img_gif = this.request.body.img_gif
if this.request.body.hasOwnProperty('isStrange')
isStrange = this.request.body.isStrange
if this.request.body.hasOwnProperty('createTime')
createTime = this.request.body.createTime
if this.request.body.hasOwnProperty('group_id')
group_id = this.request.body.group_id
if this.request.body.hasOwnProperty('camera_id')
cid = this.request.body.camera_id
if this.request.body.hasOwnProperty('uuid')
uuid = this.request.body.uuid
if this.request.body.hasOwnProperty('tid')
trackerId = this.request.body.tid
unless imgs and img_gif and group_id and uuid
return this.response.end('{"result": "failed", "cause": "invalid params"}\n')
Strangers.insert({
imgs: imgs,
img_gif: img_gif,
group_id: group_id,
camera_id: cid,
uuid: uuid,
trackerId: trackerId,
isStrange: isStrange,
createTime: new Date(),
avatar: imgs[0].url
})
#console.log(Strangers.find({}).fetch())
this.response.end('{"result": "ok"}\n')
)
|
[
{
"context": "\nRep = r: 5, spacing: 12\n\nFactions = [\n { name: 'Die Linke', class: 'linke' }\n { name: 'SPD', ",
"end": 306,
"score": 0.9955400824546814,
"start": 297,
"tag": "NAME",
"value": "Die Linke"
},
{
"context": "SPD', class: 'spd' }\n { n... | coffee/main.coffee | opendatacity/nebeneinkuenfte_faz | 1 | 'use strict'
# Warning: This code is hideous.
# I solemnly swear that I will never write code as unmaintainable
# as this mess again. Sorry.
Viewport = width: 700, height: 350, center: {x: 350, y: 350}
Arc = innerR: 80, outerR: 350, phiMax: 180
Rep = r: 5, spacing: 12
Factions = [
{ name: 'Die Linke', class: 'linke' }
{ name: 'SPD', class: 'spd' }
{ name: 'Bündnis 90/Die Grünen', class: 'gruene' }
{ name: 'FDP', class: 'fdp' } # It's better to be future-proof than optimistic.
{ name: 'CDU/CSU', class: 'cducsu' }
]
termBegin = new Date 2013, 9, 22
T = (string) ->
return dictionary[string] if dictionary[string]
return string
Tp = (number, string) ->
return dictionary[string+number] if dictionary[string+number]
return number + ' ' + dictionary[string+'Plural'] if number != 1 and dictionary[string+'Plural']
return number + ' ' + dictionary[string] if dictionary[string]
return number + ' ' + string
abbreviate = (string) ->
return abbreviations[string] if abbreviations[string]
return string
formatDate = (date) ->
date.getDate() + '. ' +
T('month'+date.getMonth()) + ' ' +
date.getFullYear()
NebeneinkunftMinAmounts = [ 0.01, 1000, 3500, 7000, 15000, 30000, 50000, 75000, 100000, 150000, 250000 ]
PeriodLength =
monatlich: 1000 * 60 * 60 * 24 * 365 / 12,
'jährlich': 1000 * 60 * 60 * 24 * 365
nebeneinkunftMinAmount = (einkunft) ->
if einkunft.periodical is 'einmalig'
count = 1
else
begin = +new Date(einkunft.begin) or +termBegin
end = +new Date(einkunft.end) or Date.now()
duration = end - begin
count = Math.max 1, (duration / PeriodLength[einkunft.periodical]) | 0
return NebeneinkunftMinAmounts[einkunft.level] * count
nebeneinkuenfteMinSum = (rep) ->
return 0 if rep.nebeneinkuenfte.length == 0
sum = rep.nebeneinkuenfte.reduce ((sum, einkunft) -> sum += nebeneinkunftMinAmount(einkunft)), 0
return Math.max parseInt(sum, 10), 1
formatCurrency = _.memoize (amount, html = true) ->
prepend = if html then '<span class="digitGroup">' else ''
append = if html then '</span>' else ''
glue = if html then '' else ' '
currency = if html then '<span class="euro">€</span>' else '€'
amount = String Math.floor amount
groups = []
while amount.length > 0
group = amount.substr -3, 3
groups.unshift prepend + group + append
amount = amount.substr 0, amount.length - 3
return groups.join(glue) + glue + currency
updateCheckboxLabelState = (checkbox) ->
if checkbox.length > 1
return checkbox.each (i, box) -> updateCheckboxLabelState box
checked = $(checkbox).prop 'checked'
checked = true if typeof checked is 'undefined'
land = $(checkbox).attr 'value'
$(checkbox).parent('label').toggleClass 'active', checked
path = $("path[title=#{land}]")
if checked
path.attr 'class', 'active'
else
path.attr 'class', 'inactive'
showOrHideConvenienceButtons checkbox
showOrHideConvenienceButtons = (checkbox) ->
fieldset = $(checkbox).parents('fieldset')
all = fieldset.find ':checkbox'
checked = fieldset.find ':checkbox:checked'
buttons = fieldset.find('.convenienceButtons')
buttons.toggleClass 'allSelected', checked.length == all.length
buttons.toggleClass 'someSelected', checked.length > 0
buttons.toggleClass 'noneSelected', checked.length is 0
getEventPosition = (event) ->
if event.originalEvent.touches
offset = $(event.target).offset()
return x: offset.left - $(window).scrollLeft(), y: offset.top - $(window).scrollTop()
return x: event.pageX - $(window).scrollLeft(), y: event.pageY - $(window).scrollTop()
class RepInspector
constructor: (selector) ->
me = this
@tooltip = $(selector)
@tooltip.find('tbody').on 'scroll', @handleScroll
@tooltip.find('.closeButton').on 'click', null, inspector: this, (event) ->
event.data.inspector.hide()
event.preventDefault()
$(window).keyup (event) ->
me.hide() if event.keyCode is 27 # Escape
field: (field) -> @tooltip.find ".#{field}"
update: (rep) ->
@rep = rep
minSum = formatCurrency rep.nebeneinkuenfteMinSum, true
@field('name') .text rep.name
.attr 'href', rep.url
@field('faction') .text T rep.fraktion
.attr 'class', 'faction ' + _.find(Factions, name: rep.fraktion).class
@field('land') .text rep.land
@field('mandate') .text T rep.mandat
@field('constituency').text rep.wahlkreis
@field('minSum') .html minSum
@field('ended') .toggleClass 'hidden', !rep.ended
.html if rep.ended then 'ausgeschieden am ' + formatDate(rep.ended) else ''
@field('count') .text Tp(rep.nebeneinkuenfte.length, 'Nebentaetigkeit')
table = @tooltip.find 'table'
tableBody = table.find 'tbody'
tableRow = tableBody.find('tr').first().clone()
tableBody.empty()
for item in rep.nebeneinkuenfte
row = tableRow.clone()
row.addClass 'cat' + item.level
row.find('.description').text item.text
row.find('.minAmount').html formatCurrency nebeneinkunftMinAmount(item), true
tableBody.append row
handleScroll: (arg) ->
table = if arg.target then $(arg.target) else $(arg)
scrollTop = table.scrollTop()
max = table.prop 'scrollHeight'
height = table.height()
scrollBottom = max - scrollTop - height
topShadow = Math.max 0, 0.5 * Math.min(scrollTop, 15)
bottomShadow = Math.max 0, 0.5 * Math.min(scrollBottom, 15)
table.siblings('thead').css 'box-shadow', "0 #{topShadow}px .5em -.5em rgba(0, 0, 0, .3)"
table.siblings('tfoot').css 'box-shadow', "0 -#{bottomShadow}px .5em -.5em rgba(0, 0, 0, .3)"
measure: ->
# If it's currently hidden, we'll first move it to [0, 0] to measure it
# as the browser may otherwise interfere and do its own scaling.
clone = @tooltip.clone()
clone.addClass 'clone'
clone.removeAttr 'id style'
clone.insertAfter @tooltip
@width = clone.outerWidth()+1
@height = clone.outerHeight(true)
clone.remove()
show: (position) ->
@measure()
@moveTo position if position
@tooltip.addClass('visible').removeClass('hidden')
@visible = true
@unfix() if @fixed
hide: ->
@tooltip.addClass('hidden').removeClass('visible')
@visible = false
@unfix()
moveTo: (@position) ->
# See if the tooltip would extend beyond the side of the window.
topMargin = parseInt @tooltip.css('marginTop'), 10
x = @position.x
y = @position.y
if x + @width > windowSize.width
x = Math.max 0, windowSize.width - @width
if y + @height > windowSize.height
y = Math.max 0 - topMargin, windowSize.height - @height
@tooltip.css top: y, left: x
unfix: ->
@fixed = false
@tooltip.addClass('moving').removeClass('fixed')
$('body').removeClass 'inspectorFixed'
@measure()
@moveTo @position
fix: ->
@fixed = true
@tooltip.addClass('fixed').removeClass('moving')
$('body').addClass 'inspectorFixed'
tbody = @tooltip.find('tbody')
tbody.scrollTop 0
tbody.css maxHeight: Math.min 300, $(window).height() - 170
@handleScroll tbody
@measure()
@moveTo @position
JSONSuccess = (data) ->
lastUpdated = new Date data.date
$('.lastUpdated').html 'Stand der Daten: ' +
formatDate(lastUpdated) + '.'
data = data.data.filter (f) -> !f.hasLeftParliament
window._data = _(data)
# Which of the possible factions are actually represented in parliament?
factions = Factions.filter (faction) -> _data.find fraktion: faction.name
_data.each (rep, i) ->
rep.nebeneinkuenfteMinSum = nebeneinkuenfteMinSum rep
console.log(rep.nebeneinkuenfteMinSum, rep)
rep.nebeneinkuenfteCount = rep.nebeneinkuenfte.length
rep.alphabeticOrder = i
rep.nebeneinkuenfte.sort (a, b) -> b.level - a.level
rep.fraktion = rep.fraktion.replace /\s+\*/g, ''
rep.ended = new Date(rep.ended) if rep.ended
dataByFaction = _data.groupBy('fraktion').value()
seats = _.mapValues dataByFaction, (f) -> f.length
totalSeats = _.reduce seats, (sum, num) -> sum + num
minSumPerSeat = _.mapValues dataByFaction, (representatives, faction) ->
minSum = _.reduce representatives, ((sum, rep) -> sum + rep.nebeneinkuenfteMinSum), 0
factionSeats = seats[faction]
minSum/factionSeats
maxNebeneinkuenfteMinSum = _.max(data, 'nebeneinkuenfteMinSum').nebeneinkuenfteMinSum
repRadiusScaleFactor = 850 / _.max minSumPerSeat
repRadius = (rep) -> repRadiusScaleFactor * Math.sqrt rep.nebeneinkuenfteMinSum
_data.each (rep) -> rep.radius = repRadius rep
data = _data.where (rep) -> rep.nebeneinkuenfteMinSum > 1
.value()
# Recalculate dataByFaction from `data`
dataByFaction = _.groupBy data, 'fraktion'
# We'll create a clone of the data array that can be sorted in place
# for the data table
dataTable =
data: data.sort (rep1, rep2) -> rep2.nebeneinkuenfteMinSum - rep1.nebeneinkuenfteMinSum
sortedBy: 'nebeneinkuenfteMinSum'
sortOrder: -1
tick = (e) ->
alpha = e.alpha * e.alpha
qt = d3.geom.quadtree data
data.forEach (rep, i) ->
dX = rep.x - Viewport.center.x
dY = rep.y - Viewport.center.y
r = Math.sqrt dX * dX + dY * dY
# Angle of the line between the CENTRE of the rep and the centre of the parliament
phi = Math.atan2 dX, -dY
# Angle between - the line from the centre of parliament through the centre of the rep
# - and the the representative's tangent through the centre of parliament
phiOffset = Math.atan2 rep.radius, r
factionAngles = _.find seatsPie, (item) -> item.data.faction is rep.fraktion
minAngle = factionAngles.startAngle
maxAngle = factionAngles.endAngle
# Ensure representatives stay outside the inner radius
if r < Arc.innerR + rep.radius
missing = (Arc.innerR + rep.radius - r) / r
rep.x += dX * missing
rep.y += dY * missing
rep.phi = phi
rep.wrongPlacement = false
# …and ensure they stay within their factions
if phi < minAngle + phiOffset
destinationPhi = minAngle + phiOffset
rep.wrongPlacement = true
if phi > maxAngle - phiOffset
destinationPhi = maxAngle - phiOffset
rep.wrongPlacement = true
if destinationPhi
r = Math.max Arc.innerR + rep.radius, r
dY = -r * Math.cos destinationPhi
dX = r * Math.sin destinationPhi
destinationX = Viewport.center.x + dX
destinationY = Viewport.center.y + dY
rep.x = destinationX
rep.y = destinationY
collide(.3, qt)(rep) # .4
unless window.animationFrameRequested
window.requestAnimationFrame ->
window.animationFrameRequested = false
node.attr 'cx', (d) -> d.x
node.attr 'cy', (d) -> d.y
window.animationFrameRequested = true
collide = (alpha, qt) ->
return (d) ->
r = d.radius * 3
nx1 = d.x - r
nx2 = d.x + r
ny1 = d.y - r
ny2 = d.y + r
qt.visit (quad, x1, y1, x2, y2) ->
if quad.point and quad.point isnt d and quad.point.fraktion is d.fraktion
w = d.x - quad.point.x
h = d.y - quad.point.y
l = Math.sqrt(w*w + h*h)
r = d.radius + quad.point.radius + 1
if l < r
deltaL = (l - r) / l * alpha
d.x -= w *= deltaL
d.y -= h *= deltaL
quad.point.x += w
quad.point.y += h
return x1 > nx2 or x2 < nx1 or y1 > ny2 or y2 < ny1
svg = d3.select '#parliament'
.attr 'width', Viewport.width
.attr 'height', Viewport.height + 10
.attr 'viewBox', "0 0 #{Viewport.width} #{Viewport.height}"
# Draw parliament wedges first
pie = d3.layout.pie()
.sort null
.value (faction) -> faction.seats
.startAngle Math.PI * -0.5
.endAngle Math.PI * 0.5
# Now we finally have something to display to the user. About time, too.
$(document.body).removeClass 'loading'
# We'll be needing this not only for the pie chart but also in the collision
# detector to make sure that representatives stay inside their own faction
seatsPie = pie _.map factions, (faction) -> faction: faction.name, seats: seats[faction.name]
# Now we know where the factions are, we can initalize the representatives
# with sensible values.
initializeRepPositions = ->
for faction in seatsPie
factionName = faction.data.faction
# How many reps above the significance threshold are in this faction?
# This is not the same as the number of seats!
factionRepCount = dataByFaction[factionName].length
deltaAngles = faction.endAngle - faction.startAngle
height = Viewport.height
_(dataByFaction[factionName]).sortBy('nebeneinkuenfteMinSum').each (rep, i) ->
i = 2 * (i % 5) + 1
height += 2.5 * rep.radius if i == 1
rep.initialX = Viewport.center.x + height * Math.sin(faction.startAngle + deltaAngles * i * 0.1)
rep.initialY = Viewport.center.y - height * Math.cos(faction.startAngle + deltaAngles * i * 0.1)
parliament = svg.append 'g'
.attr 'width', Viewport.width
.attr 'height', Viewport.height
.attr 'transform', "translate(#{Viewport.center.x}, #{Viewport.center.y})"
g = parliament.selectAll '.faction'
.data seatsPie
.enter().append 'g'
.attr 'class', (seats) -> 'arc ' + _.find(factions, name: seats.data.faction).class
arc = d3.svg.arc()
.outerRadius Arc.outerR
.innerRadius Arc.innerR
g.append 'path'
.attr 'd', arc
# Now draw circles for the representatives
force = d3.layout.force()
.nodes data
.size [Viewport.width, Viewport.height*2]
.gravity .1 # .13
.charge (d) -> -2 * d.radius - 1
.chargeDistance (d) -> 3 * d.radius
.friction .9 # .75
.on 'tick', tick
node = null
initializeRepPositions()
window.drawRepresentatives = (initialize) ->
node = svg.selectAll 'circle'
.data data
node.enter().append 'circle'
.attr 'class', (rep) -> _.find(factions, name: rep.fraktion).class
.attr 'data-name', (rep) -> rep.name
.attr 'cx', (rep) -> rep.x = rep.initialX
.attr 'cy', (rep) -> rep.y = rep.initialY
node.transition()
.attr 'r', (rep) -> rep.radius
.style 'opacity', (rep) ->
if rep.radius < 1 then 0 else if rep.ended then 0.3 else 1
node.exit().remove()
force.start() if initialize
force.alpha .07
window.deferredAnimation = false
null
table = d3.select '#tableView tbody'
rowHTML = $('#tableView tbody tr').remove().html()
rows = table.selectAll('tr').data(dataTable.data)
tableRow = (rep) ->
$ rowHTML.replace /\{(?:([^\}]*?):)?([^\}]*?)\}/g, (match, type, property) ->
return formatCurrency rep[property] if type is 'currency'
return abbreviate rep[property] if type is 'abbr'
T rep[property]
rows.enter().append 'tr'
.each (rep) -> $(this).html tableRow(rep)
.style 'opacity', (rep) -> if rep.ended then 0.5 else 1
rows.select '.faction'
.attr 'class', (rep) -> 'faction ' + _.find(Factions, name: rep.fraktion).class
rows.select '.bar'
.style 'width', (rep) -> rep.nebeneinkuenfteMinSum / maxNebeneinkuenfteMinSum * 100 + '%'
$('#tableView tfoot td').html Math.round((1 - data.length / _data.value().length) * 100) +
' Prozent sind bislang neben ihrem Mandat keinen vergüteten Tätigkeiten nachgegangen.'
updateTable = ->
rows.attr 'class', (rep) -> if rep.radius >= 1 then 'visible' else 'hidden'
sortTable = (sortField) ->
# If the array is _already_ sorted by this field, reverse the sort order
if dataTable.sortedBy is sortField
dataTable.sortOrder *= -1
else
dataTable.sortOrder = 1
table.selectAll 'tr'
.sort (rep1, rep2) ->
return -dataTable.sortOrder if rep2[sortField] > rep1[sortField]
return dataTable.sortOrder if rep2[sortField] < rep1[sortField]
return 0
dataTable.sortedBy = sortField
$('#tableView thead').on 'click', 'th', (event) ->
event.preventDefault()
sortField = $(this).attr 'data-sortfield'
sortTable sortField
$(this).parent().children().removeClass 'sorted-1 sorted1'
$(this).addClass "sorted#{dataTable.sortOrder}"
$('#tableView tbody').on 'click', 'tr', (event) ->
rep = d3.select(this).datum()
position = getEventPosition event
inspector.update rep
inspector.show position
inspector.fix()
filterData = (filter) ->
_(data).each (rep) ->
visible = _.reduce filter, (sum, filterValues, filterProperty) ->
keep = _.contains filterValues, rep[filterProperty]
return Boolean(sum * keep)
, true
if visible
rep.radius = repRadius rep
rep.x = rep.initialX unless rep.previouslyVisible
rep.y = rep.initialY unless rep.previouslyVisible
else
rep.radius = 1e-2
rep.previouslyVisible = visible
return null
filterData {}
drawRepresentatives(true)
updateTable()
inspector = new RepInspector '#repInspector'
$('form').on 'submit', (event) ->
if $(this).data 'suspendSumbit'
event.preventDefault()
return false
form = $ this
inputs = form.find 'input[type=hidden], :checkbox:checked'
event.preventDefault()
filter = _(inputs.get())
.groupBy('name')
.mapValues (inputs) -> inputs.map (input) -> $(input).val()
.value()
filterData filter
if $('#parliamentView:visible').length > 0
drawRepresentatives()
else # We need to defer the animation until the Parliament tab is shown
window.deferredAnimation = true
updateTable()
#hideRepresentatives groupedData.false if groupedData.false
$('form').on 'change', 'input', ->
changedCheckbox = this
if $(changedCheckbox).parents('fieldset').find(':checked').length == 0
$(changedCheckbox).parents('fieldset').find(':checkbox').each (index, checkbox) ->
$(checkbox).prop('checked', true) unless checkbox is changedCheckbox
updateCheckboxLabelState checkbox
$(changedCheckbox).submit()
updateCheckboxLabelState changedCheckbox
$('svg').on 'mousemove touchend', 'circle', (event) ->
position = getEventPosition event
rep = d3.select(this).datum()
unless inspector.visible
inspector.update rep
inspector.show position
unless inspector.fixed
inspector.moveTo position
$('svg').on 'mouseleave', 'circle', -> inspector.hide() unless inspector.fixed
$(document).on 'mouseup', (event) ->
inspector.hide() if inspector.fixed and $(event.target).parents('.repInspector').length < 1
$('svg').on 'click', 'circle', (event) ->
position = getEventPosition event
rep = d3.select(this).datum()
if inspector.fixed and d3.select(this).datum() is inspector.rep
inspector.unfix()
inspector.moveTo position
else if inspector.fixed
inspector.update rep
inspector.show position
inspector.fix() if event.originalEvent.touches
else
event.stopPropagation() # Otherwise the click would fire on the document node and hide the inspector
inspector.fix()
event.stopPropagation()
$('.toggler').on 'click', (event) ->
event.stopPropagation()
$(this.getAttribute 'href').toggleClass 'hidden'
$(document.body).on 'mousedown touchstart', (event) ->
t = $(event.target)
$('.togglee').addClass 'hidden' unless t.hasClass('togglee') or t.parents('.togglee').length > 0
$(window).trigger('resize')
$(document).ready ->
FastClick.attach document.body
$.getJSON window.dataPath, JSONSuccess
if Modernizr.touch
$('html, body').css
width: Math.min(window.screen.availWidth - 20, 570) + 'px'
height: window.innerHeight + 'px'
# Collapse everything that's supposed to start collapsed
$('.startCollapsed').each (i, e) ->
$(e).css height: $(e).height()
.addClass 'collapsed'
.removeClass 'startCollapsed'
$('#map').on 'mouseenter', 'path', ->
# Move to the top of the map's child nodes
node = $ this
node.insertAfter node.siblings().last()
$('#map').on 'mouseleave', 'path', ->
node = $ this
nodeClass = node.attr 'class'
if nodeClass is 'active'
node.insertAfter node.siblings().last()
else
node.insertBefore node.siblings().first()
checkAllInParentFieldset = (element) ->
checkboxes = $(element).parents('fieldset').find(':checkbox')
checkboxes.prop 'checked', true
updateCheckboxLabelState checkboxes
$(element).parents('form').submit()
$('#map').on 'dblclick', 'path', -> checkAllInParentFieldset this
# Count clicks on the map so we can display a hint about multiple selection
# after the second click
mapClickCount = 0
mapClickCountResetTimeout = null
mapUserHasLearnt = false
ignoreNext = false
$('#map').on 'mouseup', 'path', (event) ->
mapClickCount++
clearTimeout mapClickCountResetTimeout
mapClickCountResetTimeout = setTimeout (-> mapClickCount = 0), 15000
event.preventDefault() # To avoid grey rectangle on iOS
return ignoreNext = false if ignoreNext
selectMultiple = event.shiftKey or event.metaKey or event.ctrlKey
land = $(this).attr 'title'
fieldset = $(this).parents 'fieldset'
# Return to "all selected" if the user clicks on the only selected land
selectAll = $(this).attr('class') == 'active' and $(this).siblings('.active').length is 0
if selectAll
fieldset.find(':checkbox').prop('checked', true)
$(this).parents('form').triggerHandler 'submit'
else
fieldset.find(':checkbox').prop('checked', false) unless selectMultiple
checkbox = fieldset.find "input[value=#{land}]"
checkbox.click()
updateCheckboxLabelState $(':checkbox')
mapUserHasLearnt = true if selectMultiple
hint = fieldset.find('.uiHint')
if mapClickCount == 2 and not mapUserHasLearnt
hint.removeClass 'collapsed'
setTimeout (-> hint.addClass 'collapsed'), 8000
else if mapClickCount > 2 and mapUserHasLearnt
hint.addClass 'collapsed'
# Add 'Select All' and 'Invert Selection buttons to fieldsets'
$('fieldset').each (i, fieldset) ->
div = $ '<div class="convenienceButtons">'
div.append $ '<input type="button" value="alle" title="Alle auswählen" class="selectAll">'
div.append $ '<input type="button" value="umkehren" title="Auswahl umkehren" class="invertSelection">'
$(fieldset).append div
updateCheckboxLabelState $(':checkbox')
$('.invertSelection, .selectAll').click (event) ->
fieldset = $(this).parents('fieldset')
selector = ':checkbox'
selector += ':not(:checked)' if $(this).hasClass 'selectAll'
checkboxes = fieldset.find selector
checkboxes.each (i, c) ->
$(c).prop 'checked', !$(c).prop 'checked'
updateCheckboxLabelState c
$(this).parents('form').triggerHandler 'submit'
# Make tab buttons do something
tabs = {}
$('nav.tabs').on 'click', 'a', (event) ->
event.preventDefault()
return null if $(this).hasClass 'active'
$(window).scrollTop 0
tabs.selected = this
tabs.selectedID = $(tabs.selected).attr('href')
tabs.anchors = $(tabs.selected).parents('nav').find('a') unless tabs.anchors
tabs.anchors.each (index, a) ->
if a is tabs.selected
$(a).addClass('active').removeClass('inactive')
$(tabs.selectedID).addClass('visible').removeClass('hidden')
else
anchorID = $(a).attr('href')
$(a).addClass('inactive').removeClass('active')
$(anchorID).addClass('hidden').removeClass('visible')
$('.tabs .parliament').click ->
if window.deferredAnimation
drawRepresentatives()
$('.tabs .parliament').trigger 'click'
$(window).on 'resize', (event) ->
window.windowSize = width: $(window).width(), height: $(window).height()
wScale = Math.min 1, (windowSize.width - 16) / Viewport.width
hScale = Math.min 1, (windowSize.height - 16) / (Viewport.height + 10)
scale = Math.min wScale, hScale
$('#parliament, #parliamentView').height (Viewport.height + 10) * scale
.width Viewport.width * scale
if window.deferredAnimation
drawRepresentatives()
# Due to the variable height of the parliament we can't reliably use media
# queries. Instead we'll attach/remove classes from the body depending on
# the most suitable layout.
body = $('body')
vSpace = windowSize.height - 26 - Viewport.height * scale
hSpace = windowSize.width - 16 - Viewport.width * scale
if vSpace < 300 or vSpace < 500 and Modernizr.touch
body.removeClass('tall').addClass('short')
else
body.addClass('tall').removeClass('short')
if hSpace > 220
body.addClass('wide').removeClass('narrow')
else
body.removeClass('wide').addClass('narrow')
if windowSize.width >= 900 and tabs.selectedID is '#filterView'
$('.tabs .parliament').trigger 'click'
$(window).triggerHandler 'resize'
# You read this far? That sort of devotion deserves a limerick!
#
# There once was a geek from Berlin
# With a project he was keen to begin.
# And – much though he wrote –
# He never refactored the code
# That still works but causes him chagrin.
| 100008 | 'use strict'
# Warning: This code is hideous.
# I solemnly swear that I will never write code as unmaintainable
# as this mess again. Sorry.
Viewport = width: 700, height: 350, center: {x: 350, y: 350}
Arc = innerR: 80, outerR: 350, phiMax: 180
Rep = r: 5, spacing: 12
Factions = [
{ name: '<NAME>', class: 'linke' }
{ name: 'SPD', class: 'spd' }
{ name: '<NAME> 90/Die <NAME>ünen', class: 'gruene' }
{ name: 'FDP', class: 'fdp' } # It's better to be future-proof than optimistic.
{ name: 'CDU/CSU', class: 'cducsu' }
]
termBegin = new Date 2013, 9, 22
T = (string) ->
return dictionary[string] if dictionary[string]
return string
Tp = (number, string) ->
return dictionary[string+number] if dictionary[string+number]
return number + ' ' + dictionary[string+'Plural'] if number != 1 and dictionary[string+'Plural']
return number + ' ' + dictionary[string] if dictionary[string]
return number + ' ' + string
abbreviate = (string) ->
return abbreviations[string] if abbreviations[string]
return string
formatDate = (date) ->
date.getDate() + '. ' +
T('month'+date.getMonth()) + ' ' +
date.getFullYear()
NebeneinkunftMinAmounts = [ 0.01, 1000, 3500, 7000, 15000, 30000, 50000, 75000, 100000, 150000, 250000 ]
PeriodLength =
monatlich: 1000 * 60 * 60 * 24 * 365 / 12,
'jährlich': 1000 * 60 * 60 * 24 * 365
nebeneinkunftMinAmount = (einkunft) ->
if einkunft.periodical is 'einmalig'
count = 1
else
begin = +new Date(einkunft.begin) or +termBegin
end = +new Date(einkunft.end) or Date.now()
duration = end - begin
count = Math.max 1, (duration / PeriodLength[einkunft.periodical]) | 0
return NebeneinkunftMinAmounts[einkunft.level] * count
nebeneinkuenfteMinSum = (rep) ->
return 0 if rep.nebeneinkuenfte.length == 0
sum = rep.nebeneinkuenfte.reduce ((sum, einkunft) -> sum += nebeneinkunftMinAmount(einkunft)), 0
return Math.max parseInt(sum, 10), 1
formatCurrency = _.memoize (amount, html = true) ->
prepend = if html then '<span class="digitGroup">' else ''
append = if html then '</span>' else ''
glue = if html then '' else ' '
currency = if html then '<span class="euro">€</span>' else '€'
amount = String Math.floor amount
groups = []
while amount.length > 0
group = amount.substr -3, 3
groups.unshift prepend + group + append
amount = amount.substr 0, amount.length - 3
return groups.join(glue) + glue + currency
updateCheckboxLabelState = (checkbox) ->
if checkbox.length > 1
return checkbox.each (i, box) -> updateCheckboxLabelState box
checked = $(checkbox).prop 'checked'
checked = true if typeof checked is 'undefined'
land = $(checkbox).attr 'value'
$(checkbox).parent('label').toggleClass 'active', checked
path = $("path[title=#{land}]")
if checked
path.attr 'class', 'active'
else
path.attr 'class', 'inactive'
showOrHideConvenienceButtons checkbox
showOrHideConvenienceButtons = (checkbox) ->
fieldset = $(checkbox).parents('fieldset')
all = fieldset.find ':checkbox'
checked = fieldset.find ':checkbox:checked'
buttons = fieldset.find('.convenienceButtons')
buttons.toggleClass 'allSelected', checked.length == all.length
buttons.toggleClass 'someSelected', checked.length > 0
buttons.toggleClass 'noneSelected', checked.length is 0
getEventPosition = (event) ->
if event.originalEvent.touches
offset = $(event.target).offset()
return x: offset.left - $(window).scrollLeft(), y: offset.top - $(window).scrollTop()
return x: event.pageX - $(window).scrollLeft(), y: event.pageY - $(window).scrollTop()
class RepInspector
constructor: (selector) ->
me = this
@tooltip = $(selector)
@tooltip.find('tbody').on 'scroll', @handleScroll
@tooltip.find('.closeButton').on 'click', null, inspector: this, (event) ->
event.data.inspector.hide()
event.preventDefault()
$(window).keyup (event) ->
me.hide() if event.keyCode is 27 # Escape
field: (field) -> @tooltip.find ".#{field}"
update: (rep) ->
@rep = rep
minSum = formatCurrency rep.nebeneinkuenfteMinSum, true
@field('name') .text rep.name
.attr 'href', rep.url
@field('faction') .text T rep.fraktion
.attr 'class', 'faction ' + _.find(Factions, name: rep.fraktion).class
@field('land') .text rep.land
@field('mandate') .text T rep.mandat
@field('constituency').text rep.wahlkreis
@field('minSum') .html minSum
@field('ended') .toggleClass 'hidden', !rep.ended
.html if rep.ended then 'ausgeschieden am ' + formatDate(rep.ended) else ''
@field('count') .text Tp(rep.nebeneinkuenfte.length, 'Nebentaetigkeit')
table = @tooltip.find 'table'
tableBody = table.find 'tbody'
tableRow = tableBody.find('tr').first().clone()
tableBody.empty()
for item in rep.nebeneinkuenfte
row = tableRow.clone()
row.addClass 'cat' + item.level
row.find('.description').text item.text
row.find('.minAmount').html formatCurrency nebeneinkunftMinAmount(item), true
tableBody.append row
handleScroll: (arg) ->
table = if arg.target then $(arg.target) else $(arg)
scrollTop = table.scrollTop()
max = table.prop 'scrollHeight'
height = table.height()
scrollBottom = max - scrollTop - height
topShadow = Math.max 0, 0.5 * Math.min(scrollTop, 15)
bottomShadow = Math.max 0, 0.5 * Math.min(scrollBottom, 15)
table.siblings('thead').css 'box-shadow', "0 #{topShadow}px .5em -.5em rgba(0, 0, 0, .3)"
table.siblings('tfoot').css 'box-shadow', "0 -#{bottomShadow}px .5em -.5em rgba(0, 0, 0, .3)"
measure: ->
# If it's currently hidden, we'll first move it to [0, 0] to measure it
# as the browser may otherwise interfere and do its own scaling.
clone = @tooltip.clone()
clone.addClass 'clone'
clone.removeAttr 'id style'
clone.insertAfter @tooltip
@width = clone.outerWidth()+1
@height = clone.outerHeight(true)
clone.remove()
show: (position) ->
@measure()
@moveTo position if position
@tooltip.addClass('visible').removeClass('hidden')
@visible = true
@unfix() if @fixed
hide: ->
@tooltip.addClass('hidden').removeClass('visible')
@visible = false
@unfix()
moveTo: (@position) ->
# See if the tooltip would extend beyond the side of the window.
topMargin = parseInt @tooltip.css('marginTop'), 10
x = @position.x
y = @position.y
if x + @width > windowSize.width
x = Math.max 0, windowSize.width - @width
if y + @height > windowSize.height
y = Math.max 0 - topMargin, windowSize.height - @height
@tooltip.css top: y, left: x
unfix: ->
@fixed = false
@tooltip.addClass('moving').removeClass('fixed')
$('body').removeClass 'inspectorFixed'
@measure()
@moveTo @position
fix: ->
@fixed = true
@tooltip.addClass('fixed').removeClass('moving')
$('body').addClass 'inspectorFixed'
tbody = @tooltip.find('tbody')
tbody.scrollTop 0
tbody.css maxHeight: Math.min 300, $(window).height() - 170
@handleScroll tbody
@measure()
@moveTo @position
JSONSuccess = (data) ->
lastUpdated = new Date data.date
$('.lastUpdated').html 'Stand der Daten: ' +
formatDate(lastUpdated) + '.'
data = data.data.filter (f) -> !f.hasLeftParliament
window._data = _(data)
# Which of the possible factions are actually represented in parliament?
factions = Factions.filter (faction) -> _data.find fraktion: faction.name
_data.each (rep, i) ->
rep.nebeneinkuenfteMinSum = nebeneinkuenfteMinSum rep
console.log(rep.nebeneinkuenfteMinSum, rep)
rep.nebeneinkuenfteCount = rep.nebeneinkuenfte.length
rep.alphabeticOrder = i
rep.nebeneinkuenfte.sort (a, b) -> b.level - a.level
rep.fraktion = rep.fraktion.replace /\s+\*/g, ''
rep.ended = new Date(rep.ended) if rep.ended
dataByFaction = _data.groupBy('fraktion').value()
seats = _.mapValues dataByFaction, (f) -> f.length
totalSeats = _.reduce seats, (sum, num) -> sum + num
minSumPerSeat = _.mapValues dataByFaction, (representatives, faction) ->
minSum = _.reduce representatives, ((sum, rep) -> sum + rep.nebeneinkuenfteMinSum), 0
factionSeats = seats[faction]
minSum/factionSeats
maxNebeneinkuenfteMinSum = _.max(data, 'nebeneinkuenfteMinSum').nebeneinkuenfteMinSum
repRadiusScaleFactor = 850 / _.max minSumPerSeat
repRadius = (rep) -> repRadiusScaleFactor * Math.sqrt rep.nebeneinkuenfteMinSum
_data.each (rep) -> rep.radius = repRadius rep
data = _data.where (rep) -> rep.nebeneinkuenfteMinSum > 1
.value()
# Recalculate dataByFaction from `data`
dataByFaction = _.groupBy data, 'fraktion'
# We'll create a clone of the data array that can be sorted in place
# for the data table
dataTable =
data: data.sort (rep1, rep2) -> rep2.nebeneinkuenfteMinSum - rep1.nebeneinkuenfteMinSum
sortedBy: 'nebeneinkuenfteMinSum'
sortOrder: -1
tick = (e) ->
alpha = e.alpha * e.alpha
qt = d3.geom.quadtree data
data.forEach (rep, i) ->
dX = rep.x - Viewport.center.x
dY = rep.y - Viewport.center.y
r = Math.sqrt dX * dX + dY * dY
# Angle of the line between the CENTRE of the rep and the centre of the parliament
phi = Math.atan2 dX, -dY
# Angle between - the line from the centre of parliament through the centre of the rep
# - and the the representative's tangent through the centre of parliament
phiOffset = Math.atan2 rep.radius, r
factionAngles = _.find seatsPie, (item) -> item.data.faction is rep.fraktion
minAngle = factionAngles.startAngle
maxAngle = factionAngles.endAngle
# Ensure representatives stay outside the inner radius
if r < Arc.innerR + rep.radius
missing = (Arc.innerR + rep.radius - r) / r
rep.x += dX * missing
rep.y += dY * missing
rep.phi = phi
rep.wrongPlacement = false
# …and ensure they stay within their factions
if phi < minAngle + phiOffset
destinationPhi = minAngle + phiOffset
rep.wrongPlacement = true
if phi > maxAngle - phiOffset
destinationPhi = maxAngle - phiOffset
rep.wrongPlacement = true
if destinationPhi
r = Math.max Arc.innerR + rep.radius, r
dY = -r * Math.cos destinationPhi
dX = r * Math.sin destinationPhi
destinationX = Viewport.center.x + dX
destinationY = Viewport.center.y + dY
rep.x = destinationX
rep.y = destinationY
collide(.3, qt)(rep) # .4
unless window.animationFrameRequested
window.requestAnimationFrame ->
window.animationFrameRequested = false
node.attr 'cx', (d) -> d.x
node.attr 'cy', (d) -> d.y
window.animationFrameRequested = true
collide = (alpha, qt) ->
return (d) ->
r = d.radius * 3
nx1 = d.x - r
nx2 = d.x + r
ny1 = d.y - r
ny2 = d.y + r
qt.visit (quad, x1, y1, x2, y2) ->
if quad.point and quad.point isnt d and quad.point.fraktion is d.fraktion
w = d.x - quad.point.x
h = d.y - quad.point.y
l = Math.sqrt(w*w + h*h)
r = d.radius + quad.point.radius + 1
if l < r
deltaL = (l - r) / l * alpha
d.x -= w *= deltaL
d.y -= h *= deltaL
quad.point.x += w
quad.point.y += h
return x1 > nx2 or x2 < nx1 or y1 > ny2 or y2 < ny1
svg = d3.select '#parliament'
.attr 'width', Viewport.width
.attr 'height', Viewport.height + 10
.attr 'viewBox', "0 0 #{Viewport.width} #{Viewport.height}"
# Draw parliament wedges first
pie = d3.layout.pie()
.sort null
.value (faction) -> faction.seats
.startAngle Math.PI * -0.5
.endAngle Math.PI * 0.5
# Now we finally have something to display to the user. About time, too.
$(document.body).removeClass 'loading'
# We'll be needing this not only for the pie chart but also in the collision
# detector to make sure that representatives stay inside their own faction
seatsPie = pie _.map factions, (faction) -> faction: faction.name, seats: seats[faction.name]
# Now we know where the factions are, we can initalize the representatives
# with sensible values.
initializeRepPositions = ->
for faction in seatsPie
factionName = faction.data.faction
# How many reps above the significance threshold are in this faction?
# This is not the same as the number of seats!
factionRepCount = dataByFaction[factionName].length
deltaAngles = faction.endAngle - faction.startAngle
height = Viewport.height
_(dataByFaction[factionName]).sortBy('nebeneinkuenfteMinSum').each (rep, i) ->
i = 2 * (i % 5) + 1
height += 2.5 * rep.radius if i == 1
rep.initialX = Viewport.center.x + height * Math.sin(faction.startAngle + deltaAngles * i * 0.1)
rep.initialY = Viewport.center.y - height * Math.cos(faction.startAngle + deltaAngles * i * 0.1)
parliament = svg.append 'g'
.attr 'width', Viewport.width
.attr 'height', Viewport.height
.attr 'transform', "translate(#{Viewport.center.x}, #{Viewport.center.y})"
g = parliament.selectAll '.faction'
.data seatsPie
.enter().append 'g'
.attr 'class', (seats) -> 'arc ' + _.find(factions, name: seats.data.faction).class
arc = d3.svg.arc()
.outerRadius Arc.outerR
.innerRadius Arc.innerR
g.append 'path'
.attr 'd', arc
# Now draw circles for the representatives
force = d3.layout.force()
.nodes data
.size [Viewport.width, Viewport.height*2]
.gravity .1 # .13
.charge (d) -> -2 * d.radius - 1
.chargeDistance (d) -> 3 * d.radius
.friction .9 # .75
.on 'tick', tick
node = null
initializeRepPositions()
window.drawRepresentatives = (initialize) ->
node = svg.selectAll 'circle'
.data data
node.enter().append 'circle'
.attr 'class', (rep) -> _.find(factions, name: rep.fraktion).class
.attr 'data-name', (rep) -> rep.name
.attr 'cx', (rep) -> rep.x = rep.initialX
.attr 'cy', (rep) -> rep.y = rep.initialY
node.transition()
.attr 'r', (rep) -> rep.radius
.style 'opacity', (rep) ->
if rep.radius < 1 then 0 else if rep.ended then 0.3 else 1
node.exit().remove()
force.start() if initialize
force.alpha .07
window.deferredAnimation = false
null
table = d3.select '#tableView tbody'
rowHTML = $('#tableView tbody tr').remove().html()
rows = table.selectAll('tr').data(dataTable.data)
tableRow = (rep) ->
$ rowHTML.replace /\{(?:([^\}]*?):)?([^\}]*?)\}/g, (match, type, property) ->
return formatCurrency rep[property] if type is 'currency'
return abbreviate rep[property] if type is 'abbr'
T rep[property]
rows.enter().append 'tr'
.each (rep) -> $(this).html tableRow(rep)
.style 'opacity', (rep) -> if rep.ended then 0.5 else 1
rows.select '.faction'
.attr 'class', (rep) -> 'faction ' + _.find(Factions, name: rep.fraktion).class
rows.select '.bar'
.style 'width', (rep) -> rep.nebeneinkuenfteMinSum / maxNebeneinkuenfteMinSum * 100 + '%'
$('#tableView tfoot td').html Math.round((1 - data.length / _data.value().length) * 100) +
' Prozent sind bislang neben ihrem Mandat keinen vergüteten Tätigkeiten nachgegangen.'
updateTable = ->
rows.attr 'class', (rep) -> if rep.radius >= 1 then 'visible' else 'hidden'
sortTable = (sortField) ->
# If the array is _already_ sorted by this field, reverse the sort order
if dataTable.sortedBy is sortField
dataTable.sortOrder *= -1
else
dataTable.sortOrder = 1
table.selectAll 'tr'
.sort (rep1, rep2) ->
return -dataTable.sortOrder if rep2[sortField] > rep1[sortField]
return dataTable.sortOrder if rep2[sortField] < rep1[sortField]
return 0
dataTable.sortedBy = sortField
$('#tableView thead').on 'click', 'th', (event) ->
event.preventDefault()
sortField = $(this).attr 'data-sortfield'
sortTable sortField
$(this).parent().children().removeClass 'sorted-1 sorted1'
$(this).addClass "sorted#{dataTable.sortOrder}"
$('#tableView tbody').on 'click', 'tr', (event) ->
rep = d3.select(this).datum()
position = getEventPosition event
inspector.update rep
inspector.show position
inspector.fix()
filterData = (filter) ->
_(data).each (rep) ->
visible = _.reduce filter, (sum, filterValues, filterProperty) ->
keep = _.contains filterValues, rep[filterProperty]
return Boolean(sum * keep)
, true
if visible
rep.radius = repRadius rep
rep.x = rep.initialX unless rep.previouslyVisible
rep.y = rep.initialY unless rep.previouslyVisible
else
rep.radius = 1e-2
rep.previouslyVisible = visible
return null
filterData {}
drawRepresentatives(true)
updateTable()
inspector = new RepInspector '#repInspector'
$('form').on 'submit', (event) ->
if $(this).data 'suspendSumbit'
event.preventDefault()
return false
form = $ this
inputs = form.find 'input[type=hidden], :checkbox:checked'
event.preventDefault()
filter = _(inputs.get())
.groupBy('name')
.mapValues (inputs) -> inputs.map (input) -> $(input).val()
.value()
filterData filter
if $('#parliamentView:visible').length > 0
drawRepresentatives()
else # We need to defer the animation until the Parliament tab is shown
window.deferredAnimation = true
updateTable()
#hideRepresentatives groupedData.false if groupedData.false
$('form').on 'change', 'input', ->
changedCheckbox = this
if $(changedCheckbox).parents('fieldset').find(':checked').length == 0
$(changedCheckbox).parents('fieldset').find(':checkbox').each (index, checkbox) ->
$(checkbox).prop('checked', true) unless checkbox is changedCheckbox
updateCheckboxLabelState checkbox
$(changedCheckbox).submit()
updateCheckboxLabelState changedCheckbox
$('svg').on 'mousemove touchend', 'circle', (event) ->
position = getEventPosition event
rep = d3.select(this).datum()
unless inspector.visible
inspector.update rep
inspector.show position
unless inspector.fixed
inspector.moveTo position
$('svg').on 'mouseleave', 'circle', -> inspector.hide() unless inspector.fixed
$(document).on 'mouseup', (event) ->
inspector.hide() if inspector.fixed and $(event.target).parents('.repInspector').length < 1
$('svg').on 'click', 'circle', (event) ->
position = getEventPosition event
rep = d3.select(this).datum()
if inspector.fixed and d3.select(this).datum() is inspector.rep
inspector.unfix()
inspector.moveTo position
else if inspector.fixed
inspector.update rep
inspector.show position
inspector.fix() if event.originalEvent.touches
else
event.stopPropagation() # Otherwise the click would fire on the document node and hide the inspector
inspector.fix()
event.stopPropagation()
$('.toggler').on 'click', (event) ->
event.stopPropagation()
$(this.getAttribute 'href').toggleClass 'hidden'
$(document.body).on 'mousedown touchstart', (event) ->
t = $(event.target)
$('.togglee').addClass 'hidden' unless t.hasClass('togglee') or t.parents('.togglee').length > 0
$(window).trigger('resize')
$(document).ready ->
FastClick.attach document.body
$.getJSON window.dataPath, JSONSuccess
if Modernizr.touch
$('html, body').css
width: Math.min(window.screen.availWidth - 20, 570) + 'px'
height: window.innerHeight + 'px'
# Collapse everything that's supposed to start collapsed
$('.startCollapsed').each (i, e) ->
$(e).css height: $(e).height()
.addClass 'collapsed'
.removeClass 'startCollapsed'
$('#map').on 'mouseenter', 'path', ->
# Move to the top of the map's child nodes
node = $ this
node.insertAfter node.siblings().last()
$('#map').on 'mouseleave', 'path', ->
node = $ this
nodeClass = node.attr 'class'
if nodeClass is 'active'
node.insertAfter node.siblings().last()
else
node.insertBefore node.siblings().first()
checkAllInParentFieldset = (element) ->
checkboxes = $(element).parents('fieldset').find(':checkbox')
checkboxes.prop 'checked', true
updateCheckboxLabelState checkboxes
$(element).parents('form').submit()
$('#map').on 'dblclick', 'path', -> checkAllInParentFieldset this
# Count clicks on the map so we can display a hint about multiple selection
# after the second click
mapClickCount = 0
mapClickCountResetTimeout = null
mapUserHasLearnt = false
ignoreNext = false
$('#map').on 'mouseup', 'path', (event) ->
mapClickCount++
clearTimeout mapClickCountResetTimeout
mapClickCountResetTimeout = setTimeout (-> mapClickCount = 0), 15000
event.preventDefault() # To avoid grey rectangle on iOS
return ignoreNext = false if ignoreNext
selectMultiple = event.shiftKey or event.metaKey or event.ctrlKey
land = $(this).attr 'title'
fieldset = $(this).parents 'fieldset'
# Return to "all selected" if the user clicks on the only selected land
selectAll = $(this).attr('class') == 'active' and $(this).siblings('.active').length is 0
if selectAll
fieldset.find(':checkbox').prop('checked', true)
$(this).parents('form').triggerHandler 'submit'
else
fieldset.find(':checkbox').prop('checked', false) unless selectMultiple
checkbox = fieldset.find "input[value=#{land}]"
checkbox.click()
updateCheckboxLabelState $(':checkbox')
mapUserHasLearnt = true if selectMultiple
hint = fieldset.find('.uiHint')
if mapClickCount == 2 and not mapUserHasLearnt
hint.removeClass 'collapsed'
setTimeout (-> hint.addClass 'collapsed'), 8000
else if mapClickCount > 2 and mapUserHasLearnt
hint.addClass 'collapsed'
# Add 'Select All' and 'Invert Selection buttons to fieldsets'
$('fieldset').each (i, fieldset) ->
div = $ '<div class="convenienceButtons">'
div.append $ '<input type="button" value="alle" title="Alle auswählen" class="selectAll">'
div.append $ '<input type="button" value="umkehren" title="Auswahl umkehren" class="invertSelection">'
$(fieldset).append div
updateCheckboxLabelState $(':checkbox')
$('.invertSelection, .selectAll').click (event) ->
fieldset = $(this).parents('fieldset')
selector = ':checkbox'
selector += ':not(:checked)' if $(this).hasClass 'selectAll'
checkboxes = fieldset.find selector
checkboxes.each (i, c) ->
$(c).prop 'checked', !$(c).prop 'checked'
updateCheckboxLabelState c
$(this).parents('form').triggerHandler 'submit'
# Make tab buttons do something
tabs = {}
$('nav.tabs').on 'click', 'a', (event) ->
event.preventDefault()
return null if $(this).hasClass 'active'
$(window).scrollTop 0
tabs.selected = this
tabs.selectedID = $(tabs.selected).attr('href')
tabs.anchors = $(tabs.selected).parents('nav').find('a') unless tabs.anchors
tabs.anchors.each (index, a) ->
if a is tabs.selected
$(a).addClass('active').removeClass('inactive')
$(tabs.selectedID).addClass('visible').removeClass('hidden')
else
anchorID = $(a).attr('href')
$(a).addClass('inactive').removeClass('active')
$(anchorID).addClass('hidden').removeClass('visible')
$('.tabs .parliament').click ->
if window.deferredAnimation
drawRepresentatives()
$('.tabs .parliament').trigger 'click'
$(window).on 'resize', (event) ->
window.windowSize = width: $(window).width(), height: $(window).height()
wScale = Math.min 1, (windowSize.width - 16) / Viewport.width
hScale = Math.min 1, (windowSize.height - 16) / (Viewport.height + 10)
scale = Math.min wScale, hScale
$('#parliament, #parliamentView').height (Viewport.height + 10) * scale
.width Viewport.width * scale
if window.deferredAnimation
drawRepresentatives()
# Due to the variable height of the parliament we can't reliably use media
# queries. Instead we'll attach/remove classes from the body depending on
# the most suitable layout.
body = $('body')
vSpace = windowSize.height - 26 - Viewport.height * scale
hSpace = windowSize.width - 16 - Viewport.width * scale
if vSpace < 300 or vSpace < 500 and Modernizr.touch
body.removeClass('tall').addClass('short')
else
body.addClass('tall').removeClass('short')
if hSpace > 220
body.addClass('wide').removeClass('narrow')
else
body.removeClass('wide').addClass('narrow')
if windowSize.width >= 900 and tabs.selectedID is '#filterView'
$('.tabs .parliament').trigger 'click'
$(window).triggerHandler 'resize'
# You read this far? That sort of devotion deserves a limerick!
#
# There once was a geek from Berlin
# With a project he was keen to begin.
# And – much though he wrote –
# He never refactored the code
# That still works but causes him chagrin.
| true | 'use strict'
# Warning: This code is hideous.
# I solemnly swear that I will never write code as unmaintainable
# as this mess again. Sorry.
Viewport = width: 700, height: 350, center: {x: 350, y: 350}
Arc = innerR: 80, outerR: 350, phiMax: 180
Rep = r: 5, spacing: 12
Factions = [
{ name: 'PI:NAME:<NAME>END_PI', class: 'linke' }
{ name: 'SPD', class: 'spd' }
{ name: 'PI:NAME:<NAME>END_PI 90/Die PI:NAME:<NAME>END_PIünen', class: 'gruene' }
{ name: 'FDP', class: 'fdp' } # It's better to be future-proof than optimistic.
{ name: 'CDU/CSU', class: 'cducsu' }
]
termBegin = new Date 2013, 9, 22
T = (string) ->
return dictionary[string] if dictionary[string]
return string
Tp = (number, string) ->
return dictionary[string+number] if dictionary[string+number]
return number + ' ' + dictionary[string+'Plural'] if number != 1 and dictionary[string+'Plural']
return number + ' ' + dictionary[string] if dictionary[string]
return number + ' ' + string
abbreviate = (string) ->
return abbreviations[string] if abbreviations[string]
return string
formatDate = (date) ->
date.getDate() + '. ' +
T('month'+date.getMonth()) + ' ' +
date.getFullYear()
NebeneinkunftMinAmounts = [ 0.01, 1000, 3500, 7000, 15000, 30000, 50000, 75000, 100000, 150000, 250000 ]
PeriodLength =
monatlich: 1000 * 60 * 60 * 24 * 365 / 12,
'jährlich': 1000 * 60 * 60 * 24 * 365
nebeneinkunftMinAmount = (einkunft) ->
if einkunft.periodical is 'einmalig'
count = 1
else
begin = +new Date(einkunft.begin) or +termBegin
end = +new Date(einkunft.end) or Date.now()
duration = end - begin
count = Math.max 1, (duration / PeriodLength[einkunft.periodical]) | 0
return NebeneinkunftMinAmounts[einkunft.level] * count
nebeneinkuenfteMinSum = (rep) ->
return 0 if rep.nebeneinkuenfte.length == 0
sum = rep.nebeneinkuenfte.reduce ((sum, einkunft) -> sum += nebeneinkunftMinAmount(einkunft)), 0
return Math.max parseInt(sum, 10), 1
formatCurrency = _.memoize (amount, html = true) ->
prepend = if html then '<span class="digitGroup">' else ''
append = if html then '</span>' else ''
glue = if html then '' else ' '
currency = if html then '<span class="euro">€</span>' else '€'
amount = String Math.floor amount
groups = []
while amount.length > 0
group = amount.substr -3, 3
groups.unshift prepend + group + append
amount = amount.substr 0, amount.length - 3
return groups.join(glue) + glue + currency
updateCheckboxLabelState = (checkbox) ->
if checkbox.length > 1
return checkbox.each (i, box) -> updateCheckboxLabelState box
checked = $(checkbox).prop 'checked'
checked = true if typeof checked is 'undefined'
land = $(checkbox).attr 'value'
$(checkbox).parent('label').toggleClass 'active', checked
path = $("path[title=#{land}]")
if checked
path.attr 'class', 'active'
else
path.attr 'class', 'inactive'
showOrHideConvenienceButtons checkbox
showOrHideConvenienceButtons = (checkbox) ->
fieldset = $(checkbox).parents('fieldset')
all = fieldset.find ':checkbox'
checked = fieldset.find ':checkbox:checked'
buttons = fieldset.find('.convenienceButtons')
buttons.toggleClass 'allSelected', checked.length == all.length
buttons.toggleClass 'someSelected', checked.length > 0
buttons.toggleClass 'noneSelected', checked.length is 0
getEventPosition = (event) ->
if event.originalEvent.touches
offset = $(event.target).offset()
return x: offset.left - $(window).scrollLeft(), y: offset.top - $(window).scrollTop()
return x: event.pageX - $(window).scrollLeft(), y: event.pageY - $(window).scrollTop()
class RepInspector
constructor: (selector) ->
me = this
@tooltip = $(selector)
@tooltip.find('tbody').on 'scroll', @handleScroll
@tooltip.find('.closeButton').on 'click', null, inspector: this, (event) ->
event.data.inspector.hide()
event.preventDefault()
$(window).keyup (event) ->
me.hide() if event.keyCode is 27 # Escape
field: (field) -> @tooltip.find ".#{field}"
update: (rep) ->
@rep = rep
minSum = formatCurrency rep.nebeneinkuenfteMinSum, true
@field('name') .text rep.name
.attr 'href', rep.url
@field('faction') .text T rep.fraktion
.attr 'class', 'faction ' + _.find(Factions, name: rep.fraktion).class
@field('land') .text rep.land
@field('mandate') .text T rep.mandat
@field('constituency').text rep.wahlkreis
@field('minSum') .html minSum
@field('ended') .toggleClass 'hidden', !rep.ended
.html if rep.ended then 'ausgeschieden am ' + formatDate(rep.ended) else ''
@field('count') .text Tp(rep.nebeneinkuenfte.length, 'Nebentaetigkeit')
table = @tooltip.find 'table'
tableBody = table.find 'tbody'
tableRow = tableBody.find('tr').first().clone()
tableBody.empty()
for item in rep.nebeneinkuenfte
row = tableRow.clone()
row.addClass 'cat' + item.level
row.find('.description').text item.text
row.find('.minAmount').html formatCurrency nebeneinkunftMinAmount(item), true
tableBody.append row
handleScroll: (arg) ->
table = if arg.target then $(arg.target) else $(arg)
scrollTop = table.scrollTop()
max = table.prop 'scrollHeight'
height = table.height()
scrollBottom = max - scrollTop - height
topShadow = Math.max 0, 0.5 * Math.min(scrollTop, 15)
bottomShadow = Math.max 0, 0.5 * Math.min(scrollBottom, 15)
table.siblings('thead').css 'box-shadow', "0 #{topShadow}px .5em -.5em rgba(0, 0, 0, .3)"
table.siblings('tfoot').css 'box-shadow', "0 -#{bottomShadow}px .5em -.5em rgba(0, 0, 0, .3)"
measure: ->
# If it's currently hidden, we'll first move it to [0, 0] to measure it
# as the browser may otherwise interfere and do its own scaling.
clone = @tooltip.clone()
clone.addClass 'clone'
clone.removeAttr 'id style'
clone.insertAfter @tooltip
@width = clone.outerWidth()+1
@height = clone.outerHeight(true)
clone.remove()
show: (position) ->
@measure()
@moveTo position if position
@tooltip.addClass('visible').removeClass('hidden')
@visible = true
@unfix() if @fixed
hide: ->
@tooltip.addClass('hidden').removeClass('visible')
@visible = false
@unfix()
moveTo: (@position) ->
# See if the tooltip would extend beyond the side of the window.
topMargin = parseInt @tooltip.css('marginTop'), 10
x = @position.x
y = @position.y
if x + @width > windowSize.width
x = Math.max 0, windowSize.width - @width
if y + @height > windowSize.height
y = Math.max 0 - topMargin, windowSize.height - @height
@tooltip.css top: y, left: x
unfix: ->
@fixed = false
@tooltip.addClass('moving').removeClass('fixed')
$('body').removeClass 'inspectorFixed'
@measure()
@moveTo @position
fix: ->
@fixed = true
@tooltip.addClass('fixed').removeClass('moving')
$('body').addClass 'inspectorFixed'
tbody = @tooltip.find('tbody')
tbody.scrollTop 0
tbody.css maxHeight: Math.min 300, $(window).height() - 170
@handleScroll tbody
@measure()
@moveTo @position
JSONSuccess = (data) ->
lastUpdated = new Date data.date
$('.lastUpdated').html 'Stand der Daten: ' +
formatDate(lastUpdated) + '.'
data = data.data.filter (f) -> !f.hasLeftParliament
window._data = _(data)
# Which of the possible factions are actually represented in parliament?
factions = Factions.filter (faction) -> _data.find fraktion: faction.name
_data.each (rep, i) ->
rep.nebeneinkuenfteMinSum = nebeneinkuenfteMinSum rep
console.log(rep.nebeneinkuenfteMinSum, rep)
rep.nebeneinkuenfteCount = rep.nebeneinkuenfte.length
rep.alphabeticOrder = i
rep.nebeneinkuenfte.sort (a, b) -> b.level - a.level
rep.fraktion = rep.fraktion.replace /\s+\*/g, ''
rep.ended = new Date(rep.ended) if rep.ended
dataByFaction = _data.groupBy('fraktion').value()
seats = _.mapValues dataByFaction, (f) -> f.length
totalSeats = _.reduce seats, (sum, num) -> sum + num
minSumPerSeat = _.mapValues dataByFaction, (representatives, faction) ->
minSum = _.reduce representatives, ((sum, rep) -> sum + rep.nebeneinkuenfteMinSum), 0
factionSeats = seats[faction]
minSum/factionSeats
maxNebeneinkuenfteMinSum = _.max(data, 'nebeneinkuenfteMinSum').nebeneinkuenfteMinSum
repRadiusScaleFactor = 850 / _.max minSumPerSeat
repRadius = (rep) -> repRadiusScaleFactor * Math.sqrt rep.nebeneinkuenfteMinSum
_data.each (rep) -> rep.radius = repRadius rep
data = _data.where (rep) -> rep.nebeneinkuenfteMinSum > 1
.value()
# Recalculate dataByFaction from `data`
dataByFaction = _.groupBy data, 'fraktion'
# We'll create a clone of the data array that can be sorted in place
# for the data table
dataTable =
data: data.sort (rep1, rep2) -> rep2.nebeneinkuenfteMinSum - rep1.nebeneinkuenfteMinSum
sortedBy: 'nebeneinkuenfteMinSum'
sortOrder: -1
tick = (e) ->
alpha = e.alpha * e.alpha
qt = d3.geom.quadtree data
data.forEach (rep, i) ->
dX = rep.x - Viewport.center.x
dY = rep.y - Viewport.center.y
r = Math.sqrt dX * dX + dY * dY
# Angle of the line between the CENTRE of the rep and the centre of the parliament
phi = Math.atan2 dX, -dY
# Angle between - the line from the centre of parliament through the centre of the rep
# - and the the representative's tangent through the centre of parliament
phiOffset = Math.atan2 rep.radius, r
factionAngles = _.find seatsPie, (item) -> item.data.faction is rep.fraktion
minAngle = factionAngles.startAngle
maxAngle = factionAngles.endAngle
# Ensure representatives stay outside the inner radius
if r < Arc.innerR + rep.radius
missing = (Arc.innerR + rep.radius - r) / r
rep.x += dX * missing
rep.y += dY * missing
rep.phi = phi
rep.wrongPlacement = false
# …and ensure they stay within their factions
if phi < minAngle + phiOffset
destinationPhi = minAngle + phiOffset
rep.wrongPlacement = true
if phi > maxAngle - phiOffset
destinationPhi = maxAngle - phiOffset
rep.wrongPlacement = true
if destinationPhi
r = Math.max Arc.innerR + rep.radius, r
dY = -r * Math.cos destinationPhi
dX = r * Math.sin destinationPhi
destinationX = Viewport.center.x + dX
destinationY = Viewport.center.y + dY
rep.x = destinationX
rep.y = destinationY
collide(.3, qt)(rep) # .4
unless window.animationFrameRequested
window.requestAnimationFrame ->
window.animationFrameRequested = false
node.attr 'cx', (d) -> d.x
node.attr 'cy', (d) -> d.y
window.animationFrameRequested = true
collide = (alpha, qt) ->
return (d) ->
r = d.radius * 3
nx1 = d.x - r
nx2 = d.x + r
ny1 = d.y - r
ny2 = d.y + r
qt.visit (quad, x1, y1, x2, y2) ->
if quad.point and quad.point isnt d and quad.point.fraktion is d.fraktion
w = d.x - quad.point.x
h = d.y - quad.point.y
l = Math.sqrt(w*w + h*h)
r = d.radius + quad.point.radius + 1
if l < r
deltaL = (l - r) / l * alpha
d.x -= w *= deltaL
d.y -= h *= deltaL
quad.point.x += w
quad.point.y += h
return x1 > nx2 or x2 < nx1 or y1 > ny2 or y2 < ny1
svg = d3.select '#parliament'
.attr 'width', Viewport.width
.attr 'height', Viewport.height + 10
.attr 'viewBox', "0 0 #{Viewport.width} #{Viewport.height}"
# Draw parliament wedges first
pie = d3.layout.pie()
.sort null
.value (faction) -> faction.seats
.startAngle Math.PI * -0.5
.endAngle Math.PI * 0.5
# Now we finally have something to display to the user. About time, too.
$(document.body).removeClass 'loading'
# We'll be needing this not only for the pie chart but also in the collision
# detector to make sure that representatives stay inside their own faction
seatsPie = pie _.map factions, (faction) -> faction: faction.name, seats: seats[faction.name]
# Now we know where the factions are, we can initalize the representatives
# with sensible values.
initializeRepPositions = ->
for faction in seatsPie
factionName = faction.data.faction
# How many reps above the significance threshold are in this faction?
# This is not the same as the number of seats!
factionRepCount = dataByFaction[factionName].length
deltaAngles = faction.endAngle - faction.startAngle
height = Viewport.height
_(dataByFaction[factionName]).sortBy('nebeneinkuenfteMinSum').each (rep, i) ->
i = 2 * (i % 5) + 1
height += 2.5 * rep.radius if i == 1
rep.initialX = Viewport.center.x + height * Math.sin(faction.startAngle + deltaAngles * i * 0.1)
rep.initialY = Viewport.center.y - height * Math.cos(faction.startAngle + deltaAngles * i * 0.1)
parliament = svg.append 'g'
.attr 'width', Viewport.width
.attr 'height', Viewport.height
.attr 'transform', "translate(#{Viewport.center.x}, #{Viewport.center.y})"
g = parliament.selectAll '.faction'
.data seatsPie
.enter().append 'g'
.attr 'class', (seats) -> 'arc ' + _.find(factions, name: seats.data.faction).class
arc = d3.svg.arc()
.outerRadius Arc.outerR
.innerRadius Arc.innerR
g.append 'path'
.attr 'd', arc
# Now draw circles for the representatives
force = d3.layout.force()
.nodes data
.size [Viewport.width, Viewport.height*2]
.gravity .1 # .13
.charge (d) -> -2 * d.radius - 1
.chargeDistance (d) -> 3 * d.radius
.friction .9 # .75
.on 'tick', tick
node = null
initializeRepPositions()
window.drawRepresentatives = (initialize) ->
node = svg.selectAll 'circle'
.data data
node.enter().append 'circle'
.attr 'class', (rep) -> _.find(factions, name: rep.fraktion).class
.attr 'data-name', (rep) -> rep.name
.attr 'cx', (rep) -> rep.x = rep.initialX
.attr 'cy', (rep) -> rep.y = rep.initialY
node.transition()
.attr 'r', (rep) -> rep.radius
.style 'opacity', (rep) ->
if rep.radius < 1 then 0 else if rep.ended then 0.3 else 1
node.exit().remove()
force.start() if initialize
force.alpha .07
window.deferredAnimation = false
null
table = d3.select '#tableView tbody'
rowHTML = $('#tableView tbody tr').remove().html()
rows = table.selectAll('tr').data(dataTable.data)
tableRow = (rep) ->
$ rowHTML.replace /\{(?:([^\}]*?):)?([^\}]*?)\}/g, (match, type, property) ->
return formatCurrency rep[property] if type is 'currency'
return abbreviate rep[property] if type is 'abbr'
T rep[property]
rows.enter().append 'tr'
.each (rep) -> $(this).html tableRow(rep)
.style 'opacity', (rep) -> if rep.ended then 0.5 else 1
rows.select '.faction'
.attr 'class', (rep) -> 'faction ' + _.find(Factions, name: rep.fraktion).class
rows.select '.bar'
.style 'width', (rep) -> rep.nebeneinkuenfteMinSum / maxNebeneinkuenfteMinSum * 100 + '%'
$('#tableView tfoot td').html Math.round((1 - data.length / _data.value().length) * 100) +
' Prozent sind bislang neben ihrem Mandat keinen vergüteten Tätigkeiten nachgegangen.'
updateTable = ->
rows.attr 'class', (rep) -> if rep.radius >= 1 then 'visible' else 'hidden'
sortTable = (sortField) ->
# If the array is _already_ sorted by this field, reverse the sort order
if dataTable.sortedBy is sortField
dataTable.sortOrder *= -1
else
dataTable.sortOrder = 1
table.selectAll 'tr'
.sort (rep1, rep2) ->
return -dataTable.sortOrder if rep2[sortField] > rep1[sortField]
return dataTable.sortOrder if rep2[sortField] < rep1[sortField]
return 0
dataTable.sortedBy = sortField
$('#tableView thead').on 'click', 'th', (event) ->
event.preventDefault()
sortField = $(this).attr 'data-sortfield'
sortTable sortField
$(this).parent().children().removeClass 'sorted-1 sorted1'
$(this).addClass "sorted#{dataTable.sortOrder}"
$('#tableView tbody').on 'click', 'tr', (event) ->
rep = d3.select(this).datum()
position = getEventPosition event
inspector.update rep
inspector.show position
inspector.fix()
filterData = (filter) ->
_(data).each (rep) ->
visible = _.reduce filter, (sum, filterValues, filterProperty) ->
keep = _.contains filterValues, rep[filterProperty]
return Boolean(sum * keep)
, true
if visible
rep.radius = repRadius rep
rep.x = rep.initialX unless rep.previouslyVisible
rep.y = rep.initialY unless rep.previouslyVisible
else
rep.radius = 1e-2
rep.previouslyVisible = visible
return null
filterData {}
drawRepresentatives(true)
updateTable()
inspector = new RepInspector '#repInspector'
$('form').on 'submit', (event) ->
if $(this).data 'suspendSumbit'
event.preventDefault()
return false
form = $ this
inputs = form.find 'input[type=hidden], :checkbox:checked'
event.preventDefault()
filter = _(inputs.get())
.groupBy('name')
.mapValues (inputs) -> inputs.map (input) -> $(input).val()
.value()
filterData filter
if $('#parliamentView:visible').length > 0
drawRepresentatives()
else # We need to defer the animation until the Parliament tab is shown
window.deferredAnimation = true
updateTable()
#hideRepresentatives groupedData.false if groupedData.false
$('form').on 'change', 'input', ->
changedCheckbox = this
if $(changedCheckbox).parents('fieldset').find(':checked').length == 0
$(changedCheckbox).parents('fieldset').find(':checkbox').each (index, checkbox) ->
$(checkbox).prop('checked', true) unless checkbox is changedCheckbox
updateCheckboxLabelState checkbox
$(changedCheckbox).submit()
updateCheckboxLabelState changedCheckbox
$('svg').on 'mousemove touchend', 'circle', (event) ->
position = getEventPosition event
rep = d3.select(this).datum()
unless inspector.visible
inspector.update rep
inspector.show position
unless inspector.fixed
inspector.moveTo position
$('svg').on 'mouseleave', 'circle', -> inspector.hide() unless inspector.fixed
$(document).on 'mouseup', (event) ->
inspector.hide() if inspector.fixed and $(event.target).parents('.repInspector').length < 1
$('svg').on 'click', 'circle', (event) ->
position = getEventPosition event
rep = d3.select(this).datum()
if inspector.fixed and d3.select(this).datum() is inspector.rep
inspector.unfix()
inspector.moveTo position
else if inspector.fixed
inspector.update rep
inspector.show position
inspector.fix() if event.originalEvent.touches
else
event.stopPropagation() # Otherwise the click would fire on the document node and hide the inspector
inspector.fix()
event.stopPropagation()
$('.toggler').on 'click', (event) ->
event.stopPropagation()
$(this.getAttribute 'href').toggleClass 'hidden'
$(document.body).on 'mousedown touchstart', (event) ->
t = $(event.target)
$('.togglee').addClass 'hidden' unless t.hasClass('togglee') or t.parents('.togglee').length > 0
$(window).trigger('resize')
$(document).ready ->
FastClick.attach document.body
$.getJSON window.dataPath, JSONSuccess
if Modernizr.touch
$('html, body').css
width: Math.min(window.screen.availWidth - 20, 570) + 'px'
height: window.innerHeight + 'px'
# Collapse everything that's supposed to start collapsed
$('.startCollapsed').each (i, e) ->
$(e).css height: $(e).height()
.addClass 'collapsed'
.removeClass 'startCollapsed'
$('#map').on 'mouseenter', 'path', ->
# Move to the top of the map's child nodes
node = $ this
node.insertAfter node.siblings().last()
$('#map').on 'mouseleave', 'path', ->
node = $ this
nodeClass = node.attr 'class'
if nodeClass is 'active'
node.insertAfter node.siblings().last()
else
node.insertBefore node.siblings().first()
checkAllInParentFieldset = (element) ->
checkboxes = $(element).parents('fieldset').find(':checkbox')
checkboxes.prop 'checked', true
updateCheckboxLabelState checkboxes
$(element).parents('form').submit()
$('#map').on 'dblclick', 'path', -> checkAllInParentFieldset this
# Count clicks on the map so we can display a hint about multiple selection
# after the second click
mapClickCount = 0
mapClickCountResetTimeout = null
mapUserHasLearnt = false
ignoreNext = false
$('#map').on 'mouseup', 'path', (event) ->
mapClickCount++
clearTimeout mapClickCountResetTimeout
mapClickCountResetTimeout = setTimeout (-> mapClickCount = 0), 15000
event.preventDefault() # To avoid grey rectangle on iOS
return ignoreNext = false if ignoreNext
selectMultiple = event.shiftKey or event.metaKey or event.ctrlKey
land = $(this).attr 'title'
fieldset = $(this).parents 'fieldset'
# Return to "all selected" if the user clicks on the only selected land
selectAll = $(this).attr('class') == 'active' and $(this).siblings('.active').length is 0
if selectAll
fieldset.find(':checkbox').prop('checked', true)
$(this).parents('form').triggerHandler 'submit'
else
fieldset.find(':checkbox').prop('checked', false) unless selectMultiple
checkbox = fieldset.find "input[value=#{land}]"
checkbox.click()
updateCheckboxLabelState $(':checkbox')
mapUserHasLearnt = true if selectMultiple
hint = fieldset.find('.uiHint')
if mapClickCount == 2 and not mapUserHasLearnt
hint.removeClass 'collapsed'
setTimeout (-> hint.addClass 'collapsed'), 8000
else if mapClickCount > 2 and mapUserHasLearnt
hint.addClass 'collapsed'
# Add 'Select All' and 'Invert Selection buttons to fieldsets'
$('fieldset').each (i, fieldset) ->
div = $ '<div class="convenienceButtons">'
div.append $ '<input type="button" value="alle" title="Alle auswählen" class="selectAll">'
div.append $ '<input type="button" value="umkehren" title="Auswahl umkehren" class="invertSelection">'
$(fieldset).append div
updateCheckboxLabelState $(':checkbox')
$('.invertSelection, .selectAll').click (event) ->
fieldset = $(this).parents('fieldset')
selector = ':checkbox'
selector += ':not(:checked)' if $(this).hasClass 'selectAll'
checkboxes = fieldset.find selector
checkboxes.each (i, c) ->
$(c).prop 'checked', !$(c).prop 'checked'
updateCheckboxLabelState c
$(this).parents('form').triggerHandler 'submit'
# Make tab buttons do something
tabs = {}
$('nav.tabs').on 'click', 'a', (event) ->
event.preventDefault()
return null if $(this).hasClass 'active'
$(window).scrollTop 0
tabs.selected = this
tabs.selectedID = $(tabs.selected).attr('href')
tabs.anchors = $(tabs.selected).parents('nav').find('a') unless tabs.anchors
tabs.anchors.each (index, a) ->
if a is tabs.selected
$(a).addClass('active').removeClass('inactive')
$(tabs.selectedID).addClass('visible').removeClass('hidden')
else
anchorID = $(a).attr('href')
$(a).addClass('inactive').removeClass('active')
$(anchorID).addClass('hidden').removeClass('visible')
$('.tabs .parliament').click ->
if window.deferredAnimation
drawRepresentatives()
$('.tabs .parliament').trigger 'click'
$(window).on 'resize', (event) ->
window.windowSize = width: $(window).width(), height: $(window).height()
wScale = Math.min 1, (windowSize.width - 16) / Viewport.width
hScale = Math.min 1, (windowSize.height - 16) / (Viewport.height + 10)
scale = Math.min wScale, hScale
$('#parliament, #parliamentView').height (Viewport.height + 10) * scale
.width Viewport.width * scale
if window.deferredAnimation
drawRepresentatives()
# Due to the variable height of the parliament we can't reliably use media
# queries. Instead we'll attach/remove classes from the body depending on
# the most suitable layout.
body = $('body')
vSpace = windowSize.height - 26 - Viewport.height * scale
hSpace = windowSize.width - 16 - Viewport.width * scale
if vSpace < 300 or vSpace < 500 and Modernizr.touch
body.removeClass('tall').addClass('short')
else
body.addClass('tall').removeClass('short')
if hSpace > 220
body.addClass('wide').removeClass('narrow')
else
body.removeClass('wide').addClass('narrow')
if windowSize.width >= 900 and tabs.selectedID is '#filterView'
$('.tabs .parliament').trigger 'click'
$(window).triggerHandler 'resize'
# You read this far? That sort of devotion deserves a limerick!
#
# There once was a geek from Berlin
# With a project he was keen to begin.
# And – much though he wrote –
# He never refactored the code
# That still works but causes him chagrin.
|
[
{
"context": "# Copyright (c) 2013 Taher Haveliwala\n# All Rights Reserved\n#\n# asteroids.coffee\n#\n# Se",
"end": 37,
"score": 0.9998696446418762,
"start": 21,
"tag": "NAME",
"value": "Taher Haveliwala"
}
] | src/coffeescript/asteroids.coffee | taherh/Astro | 0 | # Copyright (c) 2013 Taher Haveliwala
# All Rights Reserved
#
# asteroids.coffee
#
# See LICENSE for licensing
#
class ImageManager
constructor: ->
@imageCache = {}
imageMap:
ship: 'assets/img/ship.png'
bullet: 'assets/img/bullet.gif'
asteroid: 'assets/img/asteroid.gif'
# key: name of image asset
# callback(img): callback after img is loaded
loadImage: (key, callback) ->
if key of @imageCache
@imageCache[key].clone(callback) if callback
else
fabric.Image.fromURL(@imageMap[key],
(img) =>
@imageCache[key] = img
img.clone(callback) if callback)
class SoundManager
buffers: null
pending: null
enabled: true
context: null
mainNode: null
defaultVolume: 0.5
soundMap:
shoot: 'assets/sound/shoot.mp3'
explosion: 'assets/sound/explosion.mp3'
thruster: 'assets/sound/thruster.mp3'
constructor: ->
@buffers = {}
@pending = {}
try
@context = new AudioContext()
catch e
alert(e)
@mainNode = @context.createGain()
@mainNode.connect(@context.destination)
@mainNode.gain.value = @defaultVolume
loadSounds: ->
for key of @soundMap
@loadSound(key)
# key: name of sound
# callback(key): callback after sound 'key' is loaded
loadSound: (key, callback) ->
# check that it's a valid sound
if key not of @soundMap
throw "Sound key #{ key } not found"
# check if already loaded
if key of @buffers
callback(key) if callback
return
# check if loading
if key of @pending
@pending[key].push(callback) if callback
return
@pending[key] = []
@pending[key].push(callback) if callback
# jquery doesn't support arraybuffer, so fallback to raw api
request = new XMLHttpRequest()
request.open('GET', @soundMap[key], true)
request.responseType = 'arraybuffer'
request.onload =
=>
@context.decodeAudioData(request.response,
(buffer) =>
console.log("sound #{ key } loaded")
@buffers[key] = buffer
callback(key) for callback in @pending[key]
delete @pending[key]
(data) =>
throw "bad buffer for #{ key }")
request.send()
mute: ->
@mainNode.gain.value = 0
unmute: ->
@mainNode.gain.value = @defaultVolume
stopAll: ->
@mainNode.disconnect()
@mainNode = @context.createGain()
@mainNode.connect(@context.destination)
@mainNode.gain.value = @defaultVolume
getSoundSource: (key, settings) ->
if !@enabled then return false
def_settings =
looping: false
volume: 0.2
settings = $.extend {}, def_settings, settings
if not key in @buffers
throw "Sound #{ key } not loaded"
source = @context.createBufferSource()
source.buffer = @buffers[key]
source.loop = settings.looping
# handle volume level with a gain node
gainNode = @context.createGain()
gainNode.connect(@mainNode)
gainNode.gain.value = settings.volume
source.connect(gainNode)
if not source.start? then source.start = source.noteOn
if not source.stop? then source.stop = source.noteOff
return source
# Create a new sound object each time you want to play a sound.
# If you have a looping sound you want to pause and restart, you can
# reuse the same Sound object.
class Sound
key: null
looping: null
volume: null
source: null
playing: false
constructor: (key, @looping=false, @volume=0.5) ->
@key = key
@load()
load: (callback) ->
gGame.soundManager.loadSound(@key, callback)
# wrap the real play (_play()) in a load() call to ensure sound was loaded
# calling play on an already playing Sound object has no effect
play: () ->
if not @playing
@playing = true
@load(() => @_play(@looping, @volume))
_play: (looping, volume) ->
@source = gGame.soundManager.getSoundSource(@key, { looping: looping, volume: volume })
@source.onended = ( () => @playing = false )
@source.start(0)
stop: ->
if @playing
@source.stop(0)
@source = null
@playing = false
class AsteroidsGameEngine
GAME_WIDTH: 640
GAME_HEIGHT: 480
SHOOT_RATE: 5
canvas: null
ship: null
entities: null
pendingDestroyList: null
prevTime: null
lastShootTime: 0
paused: false
gameOver: false
constructor: ->
setup: ->
$canvas = $('<canvas>', {
'id': 'canvas'
})
$('#game').append($canvas)
@canvas = new fabric.StaticCanvas('canvas', {'selectable': false})
@canvas.setWidth(@GAME_WIDTH)
@canvas.setHeight(@GAME_HEIGHT)
@imageManager = new ImageManager()
@soundManager = new SoundManager()
@inputEngine = new InputEngine()
# pre-load sound and image assets
@soundManager.loadSounds()
@imageManager.loadImage('ship')
@imageManager.loadImage('asteroid')
@imageManager.loadImage('bullet')
$(document).on('click', '#resume', @resumeGame)
$(document).on('click', '#pause', @pauseGame)
$('#reset').click(@resetGame)
@resetGame()
@resumeGame()
resetGame: =>
@animRequest = null
@canvas.clear()
@ship = null
@entities =
ship: []
asteroid: []
bullet: []
@pendingDestroyList = []
@prevTime = null
@lastShootTime = 0
@gameOver = false
# add a ship entity
@ship = new Ship(@canvas.getWidth() / 2,
@canvas.getHeight() / 2,
0,
0)
@entities['ship'] = [@ship]
# add random asteroid field
@addAsteroidField(10)
@resumeGame()
resumeGame: =>
@soundManager.unmute()
@paused = false
@animRequest = requestAnimationFrame(gGame.step)
$('#resume').attr('id', 'pause')
.attr('value', 'Pause')
pauseGame: =>
return if @gameOver
@paused = true
@soundManager.mute()
@prevTime = null
if @animRequest? then cancelAnimationFrame(@animRequest)
@animRequest = null
$('#pause').attr('id', 'resume')
.attr('value', 'Resume')
# convert canvas mouse click (canvas) coords to normal cartesian coords
canvasToMath: (canvasX, canvasY, canvasAngle) ->
return [canvasX, @GAME_HEIGHT - canvasY, -canvasAngle]
# convert normal cartesian coords to canvas coords
mathToCanvas: (mathX, mathY, mathAngle) ->
return [mathX, @GAME_HEIGHT - mathY, -mathAngle]
addAsteroidField: (n) ->
for i in [0...n]
r = Math.random()*(@canvas.getHeight()/2-64) + 64
theta = Math.random()*2*Math.PI
x = r*Math.cos(theta)
y = r*Math.sin(theta)
velX = Math.random()*200 - 100 + 50
velY = Math.random()*200 - 100 + 50
@addAsteroid(x, y, velX, velY)
addAsteroid: (x, y, velX, velY) ->
@entities['asteroid'].push(new Asteroid(x, y, velX, velY))
step: (ts) =>
return if @paused or @gameOver
if not @prevTime
@prevTime = ts
@animRequest = requestAnimationFrame(@step)
return
curTime = ts
deltaTime = curTime - @prevTime
# handle any events (such as shooting)
@handleEvents(curTime, deltaTime)
# detect any collisions
@detectCollisions()
# detect if we won
@detectWin()
# update all the entities and render them
for key, entityList of @entities
for entity in entityList
entity.update(deltaTime)
entity.render()
# render the canvas
@canvas.renderAll()
# remove destroyed entities from entity list if necessary
for entity in @pendingDestroyList
util.remove(@entities[entity.key], entity)
@pendingDestroyList = []
@prevTime = curTime
@animRequest = requestAnimationFrame(@step) unless @gameOver
detectWin: ->
if @entities['asteroid'].length == 0
@endGame('win')
detectCollisions: ->
# ship<->asteroid
for asteroid in @entities['asteroid']
if asteroid.collidesWith(@ship)
@collideShip()
# bullet<->asteroid
for bullet in @entities['bullet']
for asteroid in @entities['asteroid']
if bullet.collidesWith(asteroid)
@collideBulletAsteroid(bullet, asteroid)
endGame: (state) ->
@gameOver = true
$('#canvas').off('.asteroids')
if state is "win"
text = 'You won!'
else
text = 'Game Over!'
@canvas.add(new fabric.Text(text, {
top: @GAME_HEIGHT / 2
left: @GAME_WIDTH / 2
fill: '#ffffff'
textBackgroundColor: 'rgb(64,128,128)'
}))
collideShip: (asteroid) ->
@destroy(@ship)
(new Sound('explosion')).play()
@endGame('lose')
collideBulletAsteroid: (bullet, asteroid) ->
@destroy(bullet)
@destroy(asteroid)
(new Sound('explosion')).play()
# handle any events that aren't handled by the entities themselves
# (e.g., spawning of new entities)
handleEvents: (curTime, deltaTime) ->
if @inputEngine.actionState['shoot']
if curTime - @lastShootTime > 1000/@SHOOT_RATE
@entities['bullet'].push(new Bullet(@ship))
(new Sound('shoot')).play()
@lastShootTime = curTime
destroy: (entity) ->
entity.destroy()
@pendingDestroyList.push(entity)
util = null
exports = this
exports.Sound = Sound
$ ->
gGame = new AsteroidsGameEngine()
window.gGame = gGame
util = Asteroids.util
gGame.setup()
| 83690 | # Copyright (c) 2013 <NAME>
# All Rights Reserved
#
# asteroids.coffee
#
# See LICENSE for licensing
#
class ImageManager
constructor: ->
@imageCache = {}
imageMap:
ship: 'assets/img/ship.png'
bullet: 'assets/img/bullet.gif'
asteroid: 'assets/img/asteroid.gif'
# key: name of image asset
# callback(img): callback after img is loaded
loadImage: (key, callback) ->
if key of @imageCache
@imageCache[key].clone(callback) if callback
else
fabric.Image.fromURL(@imageMap[key],
(img) =>
@imageCache[key] = img
img.clone(callback) if callback)
class SoundManager
buffers: null
pending: null
enabled: true
context: null
mainNode: null
defaultVolume: 0.5
soundMap:
shoot: 'assets/sound/shoot.mp3'
explosion: 'assets/sound/explosion.mp3'
thruster: 'assets/sound/thruster.mp3'
constructor: ->
@buffers = {}
@pending = {}
try
@context = new AudioContext()
catch e
alert(e)
@mainNode = @context.createGain()
@mainNode.connect(@context.destination)
@mainNode.gain.value = @defaultVolume
loadSounds: ->
for key of @soundMap
@loadSound(key)
# key: name of sound
# callback(key): callback after sound 'key' is loaded
loadSound: (key, callback) ->
# check that it's a valid sound
if key not of @soundMap
throw "Sound key #{ key } not found"
# check if already loaded
if key of @buffers
callback(key) if callback
return
# check if loading
if key of @pending
@pending[key].push(callback) if callback
return
@pending[key] = []
@pending[key].push(callback) if callback
# jquery doesn't support arraybuffer, so fallback to raw api
request = new XMLHttpRequest()
request.open('GET', @soundMap[key], true)
request.responseType = 'arraybuffer'
request.onload =
=>
@context.decodeAudioData(request.response,
(buffer) =>
console.log("sound #{ key } loaded")
@buffers[key] = buffer
callback(key) for callback in @pending[key]
delete @pending[key]
(data) =>
throw "bad buffer for #{ key }")
request.send()
mute: ->
@mainNode.gain.value = 0
unmute: ->
@mainNode.gain.value = @defaultVolume
stopAll: ->
@mainNode.disconnect()
@mainNode = @context.createGain()
@mainNode.connect(@context.destination)
@mainNode.gain.value = @defaultVolume
getSoundSource: (key, settings) ->
if !@enabled then return false
def_settings =
looping: false
volume: 0.2
settings = $.extend {}, def_settings, settings
if not key in @buffers
throw "Sound #{ key } not loaded"
source = @context.createBufferSource()
source.buffer = @buffers[key]
source.loop = settings.looping
# handle volume level with a gain node
gainNode = @context.createGain()
gainNode.connect(@mainNode)
gainNode.gain.value = settings.volume
source.connect(gainNode)
if not source.start? then source.start = source.noteOn
if not source.stop? then source.stop = source.noteOff
return source
# Create a new sound object each time you want to play a sound.
# If you have a looping sound you want to pause and restart, you can
# reuse the same Sound object.
class Sound
key: null
looping: null
volume: null
source: null
playing: false
constructor: (key, @looping=false, @volume=0.5) ->
@key = key
@load()
load: (callback) ->
gGame.soundManager.loadSound(@key, callback)
# wrap the real play (_play()) in a load() call to ensure sound was loaded
# calling play on an already playing Sound object has no effect
play: () ->
if not @playing
@playing = true
@load(() => @_play(@looping, @volume))
_play: (looping, volume) ->
@source = gGame.soundManager.getSoundSource(@key, { looping: looping, volume: volume })
@source.onended = ( () => @playing = false )
@source.start(0)
stop: ->
if @playing
@source.stop(0)
@source = null
@playing = false
class AsteroidsGameEngine
GAME_WIDTH: 640
GAME_HEIGHT: 480
SHOOT_RATE: 5
canvas: null
ship: null
entities: null
pendingDestroyList: null
prevTime: null
lastShootTime: 0
paused: false
gameOver: false
constructor: ->
setup: ->
$canvas = $('<canvas>', {
'id': 'canvas'
})
$('#game').append($canvas)
@canvas = new fabric.StaticCanvas('canvas', {'selectable': false})
@canvas.setWidth(@GAME_WIDTH)
@canvas.setHeight(@GAME_HEIGHT)
@imageManager = new ImageManager()
@soundManager = new SoundManager()
@inputEngine = new InputEngine()
# pre-load sound and image assets
@soundManager.loadSounds()
@imageManager.loadImage('ship')
@imageManager.loadImage('asteroid')
@imageManager.loadImage('bullet')
$(document).on('click', '#resume', @resumeGame)
$(document).on('click', '#pause', @pauseGame)
$('#reset').click(@resetGame)
@resetGame()
@resumeGame()
resetGame: =>
@animRequest = null
@canvas.clear()
@ship = null
@entities =
ship: []
asteroid: []
bullet: []
@pendingDestroyList = []
@prevTime = null
@lastShootTime = 0
@gameOver = false
# add a ship entity
@ship = new Ship(@canvas.getWidth() / 2,
@canvas.getHeight() / 2,
0,
0)
@entities['ship'] = [@ship]
# add random asteroid field
@addAsteroidField(10)
@resumeGame()
resumeGame: =>
@soundManager.unmute()
@paused = false
@animRequest = requestAnimationFrame(gGame.step)
$('#resume').attr('id', 'pause')
.attr('value', 'Pause')
pauseGame: =>
return if @gameOver
@paused = true
@soundManager.mute()
@prevTime = null
if @animRequest? then cancelAnimationFrame(@animRequest)
@animRequest = null
$('#pause').attr('id', 'resume')
.attr('value', 'Resume')
# convert canvas mouse click (canvas) coords to normal cartesian coords
canvasToMath: (canvasX, canvasY, canvasAngle) ->
return [canvasX, @GAME_HEIGHT - canvasY, -canvasAngle]
# convert normal cartesian coords to canvas coords
mathToCanvas: (mathX, mathY, mathAngle) ->
return [mathX, @GAME_HEIGHT - mathY, -mathAngle]
addAsteroidField: (n) ->
for i in [0...n]
r = Math.random()*(@canvas.getHeight()/2-64) + 64
theta = Math.random()*2*Math.PI
x = r*Math.cos(theta)
y = r*Math.sin(theta)
velX = Math.random()*200 - 100 + 50
velY = Math.random()*200 - 100 + 50
@addAsteroid(x, y, velX, velY)
addAsteroid: (x, y, velX, velY) ->
@entities['asteroid'].push(new Asteroid(x, y, velX, velY))
step: (ts) =>
return if @paused or @gameOver
if not @prevTime
@prevTime = ts
@animRequest = requestAnimationFrame(@step)
return
curTime = ts
deltaTime = curTime - @prevTime
# handle any events (such as shooting)
@handleEvents(curTime, deltaTime)
# detect any collisions
@detectCollisions()
# detect if we won
@detectWin()
# update all the entities and render them
for key, entityList of @entities
for entity in entityList
entity.update(deltaTime)
entity.render()
# render the canvas
@canvas.renderAll()
# remove destroyed entities from entity list if necessary
for entity in @pendingDestroyList
util.remove(@entities[entity.key], entity)
@pendingDestroyList = []
@prevTime = curTime
@animRequest = requestAnimationFrame(@step) unless @gameOver
detectWin: ->
if @entities['asteroid'].length == 0
@endGame('win')
detectCollisions: ->
# ship<->asteroid
for asteroid in @entities['asteroid']
if asteroid.collidesWith(@ship)
@collideShip()
# bullet<->asteroid
for bullet in @entities['bullet']
for asteroid in @entities['asteroid']
if bullet.collidesWith(asteroid)
@collideBulletAsteroid(bullet, asteroid)
endGame: (state) ->
@gameOver = true
$('#canvas').off('.asteroids')
if state is "win"
text = 'You won!'
else
text = 'Game Over!'
@canvas.add(new fabric.Text(text, {
top: @GAME_HEIGHT / 2
left: @GAME_WIDTH / 2
fill: '#ffffff'
textBackgroundColor: 'rgb(64,128,128)'
}))
collideShip: (asteroid) ->
@destroy(@ship)
(new Sound('explosion')).play()
@endGame('lose')
collideBulletAsteroid: (bullet, asteroid) ->
@destroy(bullet)
@destroy(asteroid)
(new Sound('explosion')).play()
# handle any events that aren't handled by the entities themselves
# (e.g., spawning of new entities)
handleEvents: (curTime, deltaTime) ->
if @inputEngine.actionState['shoot']
if curTime - @lastShootTime > 1000/@SHOOT_RATE
@entities['bullet'].push(new Bullet(@ship))
(new Sound('shoot')).play()
@lastShootTime = curTime
destroy: (entity) ->
entity.destroy()
@pendingDestroyList.push(entity)
util = null
exports = this
exports.Sound = Sound
$ ->
gGame = new AsteroidsGameEngine()
window.gGame = gGame
util = Asteroids.util
gGame.setup()
| true | # Copyright (c) 2013 PI:NAME:<NAME>END_PI
# All Rights Reserved
#
# asteroids.coffee
#
# See LICENSE for licensing
#
class ImageManager
constructor: ->
@imageCache = {}
imageMap:
ship: 'assets/img/ship.png'
bullet: 'assets/img/bullet.gif'
asteroid: 'assets/img/asteroid.gif'
# key: name of image asset
# callback(img): callback after img is loaded
loadImage: (key, callback) ->
if key of @imageCache
@imageCache[key].clone(callback) if callback
else
fabric.Image.fromURL(@imageMap[key],
(img) =>
@imageCache[key] = img
img.clone(callback) if callback)
class SoundManager
buffers: null
pending: null
enabled: true
context: null
mainNode: null
defaultVolume: 0.5
soundMap:
shoot: 'assets/sound/shoot.mp3'
explosion: 'assets/sound/explosion.mp3'
thruster: 'assets/sound/thruster.mp3'
constructor: ->
@buffers = {}
@pending = {}
try
@context = new AudioContext()
catch e
alert(e)
@mainNode = @context.createGain()
@mainNode.connect(@context.destination)
@mainNode.gain.value = @defaultVolume
loadSounds: ->
for key of @soundMap
@loadSound(key)
# key: name of sound
# callback(key): callback after sound 'key' is loaded
loadSound: (key, callback) ->
# check that it's a valid sound
if key not of @soundMap
throw "Sound key #{ key } not found"
# check if already loaded
if key of @buffers
callback(key) if callback
return
# check if loading
if key of @pending
@pending[key].push(callback) if callback
return
@pending[key] = []
@pending[key].push(callback) if callback
# jquery doesn't support arraybuffer, so fallback to raw api
request = new XMLHttpRequest()
request.open('GET', @soundMap[key], true)
request.responseType = 'arraybuffer'
request.onload =
=>
@context.decodeAudioData(request.response,
(buffer) =>
console.log("sound #{ key } loaded")
@buffers[key] = buffer
callback(key) for callback in @pending[key]
delete @pending[key]
(data) =>
throw "bad buffer for #{ key }")
request.send()
mute: ->
@mainNode.gain.value = 0
unmute: ->
@mainNode.gain.value = @defaultVolume
stopAll: ->
@mainNode.disconnect()
@mainNode = @context.createGain()
@mainNode.connect(@context.destination)
@mainNode.gain.value = @defaultVolume
getSoundSource: (key, settings) ->
if !@enabled then return false
def_settings =
looping: false
volume: 0.2
settings = $.extend {}, def_settings, settings
if not key in @buffers
throw "Sound #{ key } not loaded"
source = @context.createBufferSource()
source.buffer = @buffers[key]
source.loop = settings.looping
# handle volume level with a gain node
gainNode = @context.createGain()
gainNode.connect(@mainNode)
gainNode.gain.value = settings.volume
source.connect(gainNode)
if not source.start? then source.start = source.noteOn
if not source.stop? then source.stop = source.noteOff
return source
# Create a new sound object each time you want to play a sound.
# If you have a looping sound you want to pause and restart, you can
# reuse the same Sound object.
class Sound
key: null
looping: null
volume: null
source: null
playing: false
constructor: (key, @looping=false, @volume=0.5) ->
@key = key
@load()
load: (callback) ->
gGame.soundManager.loadSound(@key, callback)
# wrap the real play (_play()) in a load() call to ensure sound was loaded
# calling play on an already playing Sound object has no effect
play: () ->
if not @playing
@playing = true
@load(() => @_play(@looping, @volume))
_play: (looping, volume) ->
@source = gGame.soundManager.getSoundSource(@key, { looping: looping, volume: volume })
@source.onended = ( () => @playing = false )
@source.start(0)
stop: ->
if @playing
@source.stop(0)
@source = null
@playing = false
class AsteroidsGameEngine
GAME_WIDTH: 640
GAME_HEIGHT: 480
SHOOT_RATE: 5
canvas: null
ship: null
entities: null
pendingDestroyList: null
prevTime: null
lastShootTime: 0
paused: false
gameOver: false
constructor: ->
setup: ->
$canvas = $('<canvas>', {
'id': 'canvas'
})
$('#game').append($canvas)
@canvas = new fabric.StaticCanvas('canvas', {'selectable': false})
@canvas.setWidth(@GAME_WIDTH)
@canvas.setHeight(@GAME_HEIGHT)
@imageManager = new ImageManager()
@soundManager = new SoundManager()
@inputEngine = new InputEngine()
# pre-load sound and image assets
@soundManager.loadSounds()
@imageManager.loadImage('ship')
@imageManager.loadImage('asteroid')
@imageManager.loadImage('bullet')
$(document).on('click', '#resume', @resumeGame)
$(document).on('click', '#pause', @pauseGame)
$('#reset').click(@resetGame)
@resetGame()
@resumeGame()
resetGame: =>
@animRequest = null
@canvas.clear()
@ship = null
@entities =
ship: []
asteroid: []
bullet: []
@pendingDestroyList = []
@prevTime = null
@lastShootTime = 0
@gameOver = false
# add a ship entity
@ship = new Ship(@canvas.getWidth() / 2,
@canvas.getHeight() / 2,
0,
0)
@entities['ship'] = [@ship]
# add random asteroid field
@addAsteroidField(10)
@resumeGame()
resumeGame: =>
@soundManager.unmute()
@paused = false
@animRequest = requestAnimationFrame(gGame.step)
$('#resume').attr('id', 'pause')
.attr('value', 'Pause')
pauseGame: =>
return if @gameOver
@paused = true
@soundManager.mute()
@prevTime = null
if @animRequest? then cancelAnimationFrame(@animRequest)
@animRequest = null
$('#pause').attr('id', 'resume')
.attr('value', 'Resume')
# convert canvas mouse click (canvas) coords to normal cartesian coords
canvasToMath: (canvasX, canvasY, canvasAngle) ->
return [canvasX, @GAME_HEIGHT - canvasY, -canvasAngle]
# convert normal cartesian coords to canvas coords
mathToCanvas: (mathX, mathY, mathAngle) ->
return [mathX, @GAME_HEIGHT - mathY, -mathAngle]
addAsteroidField: (n) ->
for i in [0...n]
r = Math.random()*(@canvas.getHeight()/2-64) + 64
theta = Math.random()*2*Math.PI
x = r*Math.cos(theta)
y = r*Math.sin(theta)
velX = Math.random()*200 - 100 + 50
velY = Math.random()*200 - 100 + 50
@addAsteroid(x, y, velX, velY)
addAsteroid: (x, y, velX, velY) ->
@entities['asteroid'].push(new Asteroid(x, y, velX, velY))
step: (ts) =>
return if @paused or @gameOver
if not @prevTime
@prevTime = ts
@animRequest = requestAnimationFrame(@step)
return
curTime = ts
deltaTime = curTime - @prevTime
# handle any events (such as shooting)
@handleEvents(curTime, deltaTime)
# detect any collisions
@detectCollisions()
# detect if we won
@detectWin()
# update all the entities and render them
for key, entityList of @entities
for entity in entityList
entity.update(deltaTime)
entity.render()
# render the canvas
@canvas.renderAll()
# remove destroyed entities from entity list if necessary
for entity in @pendingDestroyList
util.remove(@entities[entity.key], entity)
@pendingDestroyList = []
@prevTime = curTime
@animRequest = requestAnimationFrame(@step) unless @gameOver
detectWin: ->
if @entities['asteroid'].length == 0
@endGame('win')
detectCollisions: ->
# ship<->asteroid
for asteroid in @entities['asteroid']
if asteroid.collidesWith(@ship)
@collideShip()
# bullet<->asteroid
for bullet in @entities['bullet']
for asteroid in @entities['asteroid']
if bullet.collidesWith(asteroid)
@collideBulletAsteroid(bullet, asteroid)
endGame: (state) ->
@gameOver = true
$('#canvas').off('.asteroids')
if state is "win"
text = 'You won!'
else
text = 'Game Over!'
@canvas.add(new fabric.Text(text, {
top: @GAME_HEIGHT / 2
left: @GAME_WIDTH / 2
fill: '#ffffff'
textBackgroundColor: 'rgb(64,128,128)'
}))
collideShip: (asteroid) ->
@destroy(@ship)
(new Sound('explosion')).play()
@endGame('lose')
collideBulletAsteroid: (bullet, asteroid) ->
@destroy(bullet)
@destroy(asteroid)
(new Sound('explosion')).play()
# handle any events that aren't handled by the entities themselves
# (e.g., spawning of new entities)
handleEvents: (curTime, deltaTime) ->
if @inputEngine.actionState['shoot']
if curTime - @lastShootTime > 1000/@SHOOT_RATE
@entities['bullet'].push(new Bullet(@ship))
(new Sound('shoot')).play()
@lastShootTime = curTime
destroy: (entity) ->
entity.destroy()
@pendingDestroyList.push(entity)
util = null
exports = this
exports.Sound = Sound
$ ->
gGame = new AsteroidsGameEngine()
window.gGame = gGame
util = Asteroids.util
gGame.setup()
|
[
{
"context": "\"mongodb://nodejitsu:#{ process.env.MONGODB_PWD }@staff.mongohq.com:10090/nodejitsudb407113725252\"\n\n # Attach the ap",
"end": 2249,
"score": 0.9951090812683105,
"start": 2232,
"tag": "EMAIL",
"value": "staff.mongohq.com"
}
] | site/app/application.coffee | isabella232/coffeedoc.info | 2 | http = require 'http'
path = require 'path'
fs = require 'fs'
Express = require 'express'
Codo = require 'codo'
HamlCoffee = require 'haml-coffee'
Assets = require 'connect-assets'
Mongoose = require 'mongoose'
CoffeeDocController = require './controllers/coffeedoc'
CodoController = require './controllers/codo'
GitHubController = require './controllers/github'
# CoffeeDoc.info Express.js application
#
module.exports = class Application
# Construct a new Express.js application
#
constructor: ->
@app = Express()
@app.engine '.hamlc', HamlCoffee.__express
@app.configure @configuration
@app.configure 'development', @development
@app.configure 'production', @production
# Start the application server
#
# @return [http.Server] the HTTP server
#
start: ->
http.createServer(@app).listen @app.get('port'), =>
console.log 'Site server listening on port %d in %s mode', @app.get('port'), @app.settings.env
# Application configuration for all environments.
#
# @private
#
configuration: =>
@app.set 'port', 8080
@app.set 'views', path.join(__dirname, 'views')
@app.set 'view engine', 'hamlc'
@app.set 'view options', { layout: false }
@app.locals = {
codoVersion: Codo.version()
coffeedocVersion: 'v' + JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'))['version']
}
@app.use Express.bodyParser()
@app.use Express.methodOverride()
# Configure assets
@app.use new Assets({ src: path.join(__dirname, 'assets') })
@app.use '/images', Express.static path.join(__dirname, 'assets', 'images')
@app.use Express.favicon path.join(__dirname, 'assets', 'images', 'favicon.ico')
@routes()
# Development configuration
#
# @private
#
development: =>
@app.use Express.logger 'dev'
@app.use Express.errorHandler({ dumpExceptions: true, showStack: true })
Mongoose.connect 'mongodb://localhost/coffeedoc'
# Production configuration
#
# @private
#
production: =>
@app.use Express.logger()
@app.use Express.errorHandler()
Mongoose.connect "mongodb://nodejitsu:#{ process.env.MONGODB_PWD }@staff.mongohq.com:10090/nodejitsudb407113725252"
# Attach the application routes to the controllers.
#
routes: =>
@app.get '/*', CoffeeDocController.redirect
@app.get '/', CoffeeDocController.index
@app.post '/add', CoffeeDocController.add
@app.get '/state/:id', CoffeeDocController.state
@app.get /github\/(.+)\/assets\/codo\.js$/, CodoController.script
@app.get /github\/(.+)\/assets\/codo\.css$/, CodoController.style
@app.get '/github/:user/:project', CodoController.latest
@app.get /github\/(.+)$/, CodoController.show
@app.get '/checkout', GitHubController.checkoutInfo
@app.post '/checkout', GitHubController.checkout
@app.get '*', CoffeeDocController.notFound
| 140664 | http = require 'http'
path = require 'path'
fs = require 'fs'
Express = require 'express'
Codo = require 'codo'
HamlCoffee = require 'haml-coffee'
Assets = require 'connect-assets'
Mongoose = require 'mongoose'
CoffeeDocController = require './controllers/coffeedoc'
CodoController = require './controllers/codo'
GitHubController = require './controllers/github'
# CoffeeDoc.info Express.js application
#
module.exports = class Application
# Construct a new Express.js application
#
constructor: ->
@app = Express()
@app.engine '.hamlc', HamlCoffee.__express
@app.configure @configuration
@app.configure 'development', @development
@app.configure 'production', @production
# Start the application server
#
# @return [http.Server] the HTTP server
#
start: ->
http.createServer(@app).listen @app.get('port'), =>
console.log 'Site server listening on port %d in %s mode', @app.get('port'), @app.settings.env
# Application configuration for all environments.
#
# @private
#
configuration: =>
@app.set 'port', 8080
@app.set 'views', path.join(__dirname, 'views')
@app.set 'view engine', 'hamlc'
@app.set 'view options', { layout: false }
@app.locals = {
codoVersion: Codo.version()
coffeedocVersion: 'v' + JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'))['version']
}
@app.use Express.bodyParser()
@app.use Express.methodOverride()
# Configure assets
@app.use new Assets({ src: path.join(__dirname, 'assets') })
@app.use '/images', Express.static path.join(__dirname, 'assets', 'images')
@app.use Express.favicon path.join(__dirname, 'assets', 'images', 'favicon.ico')
@routes()
# Development configuration
#
# @private
#
development: =>
@app.use Express.logger 'dev'
@app.use Express.errorHandler({ dumpExceptions: true, showStack: true })
Mongoose.connect 'mongodb://localhost/coffeedoc'
# Production configuration
#
# @private
#
production: =>
@app.use Express.logger()
@app.use Express.errorHandler()
Mongoose.connect "mongodb://nodejitsu:#{ process.env.MONGODB_PWD }@<EMAIL>:10090/nodejitsudb407113725252"
# Attach the application routes to the controllers.
#
routes: =>
@app.get '/*', CoffeeDocController.redirect
@app.get '/', CoffeeDocController.index
@app.post '/add', CoffeeDocController.add
@app.get '/state/:id', CoffeeDocController.state
@app.get /github\/(.+)\/assets\/codo\.js$/, CodoController.script
@app.get /github\/(.+)\/assets\/codo\.css$/, CodoController.style
@app.get '/github/:user/:project', CodoController.latest
@app.get /github\/(.+)$/, CodoController.show
@app.get '/checkout', GitHubController.checkoutInfo
@app.post '/checkout', GitHubController.checkout
@app.get '*', CoffeeDocController.notFound
| true | http = require 'http'
path = require 'path'
fs = require 'fs'
Express = require 'express'
Codo = require 'codo'
HamlCoffee = require 'haml-coffee'
Assets = require 'connect-assets'
Mongoose = require 'mongoose'
CoffeeDocController = require './controllers/coffeedoc'
CodoController = require './controllers/codo'
GitHubController = require './controllers/github'
# CoffeeDoc.info Express.js application
#
module.exports = class Application
# Construct a new Express.js application
#
constructor: ->
@app = Express()
@app.engine '.hamlc', HamlCoffee.__express
@app.configure @configuration
@app.configure 'development', @development
@app.configure 'production', @production
# Start the application server
#
# @return [http.Server] the HTTP server
#
start: ->
http.createServer(@app).listen @app.get('port'), =>
console.log 'Site server listening on port %d in %s mode', @app.get('port'), @app.settings.env
# Application configuration for all environments.
#
# @private
#
configuration: =>
@app.set 'port', 8080
@app.set 'views', path.join(__dirname, 'views')
@app.set 'view engine', 'hamlc'
@app.set 'view options', { layout: false }
@app.locals = {
codoVersion: Codo.version()
coffeedocVersion: 'v' + JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'))['version']
}
@app.use Express.bodyParser()
@app.use Express.methodOverride()
# Configure assets
@app.use new Assets({ src: path.join(__dirname, 'assets') })
@app.use '/images', Express.static path.join(__dirname, 'assets', 'images')
@app.use Express.favicon path.join(__dirname, 'assets', 'images', 'favicon.ico')
@routes()
# Development configuration
#
# @private
#
development: =>
@app.use Express.logger 'dev'
@app.use Express.errorHandler({ dumpExceptions: true, showStack: true })
Mongoose.connect 'mongodb://localhost/coffeedoc'
# Production configuration
#
# @private
#
production: =>
@app.use Express.logger()
@app.use Express.errorHandler()
Mongoose.connect "mongodb://nodejitsu:#{ process.env.MONGODB_PWD }@PI:EMAIL:<EMAIL>END_PI:10090/nodejitsudb407113725252"
# Attach the application routes to the controllers.
#
routes: =>
@app.get '/*', CoffeeDocController.redirect
@app.get '/', CoffeeDocController.index
@app.post '/add', CoffeeDocController.add
@app.get '/state/:id', CoffeeDocController.state
@app.get /github\/(.+)\/assets\/codo\.js$/, CodoController.script
@app.get /github\/(.+)\/assets\/codo\.css$/, CodoController.style
@app.get '/github/:user/:project', CodoController.latest
@app.get /github\/(.+)$/, CodoController.show
@app.get '/checkout', GitHubController.checkoutInfo
@app.post '/checkout', GitHubController.checkout
@app.get '*', CoffeeDocController.notFound
|
[
{
"context": "featherEditor = new Aviary.Feather\n apiKey: 'e7a5e1c28334eb7a',\n apiVersion: 3,\n theme: 'light',\n language: ",
"end": 62,
"score": 0.9996667504310608,
"start": 46,
"tag": "KEY",
"value": "e7a5e1c28334eb7a"
}
] | app/assets/javascripts/spina/admin/aviary.js.coffee | dbwest/Spina | 0 | featherEditor = new Aviary.Feather
apiKey: 'e7a5e1c28334eb7a',
apiVersion: 3,
theme: 'light',
language: 'nl',
minimumStyling: true,
tools: 'crop,enhance,contrast,sharpness,text,whiten,effects,warmth,orientation,brightness,saturation,redeye,blemish',
appendTo: '',
onSave: (imageID, newURL) ->
img = $('#' + imageID)
img.attr('src', newURL)
$.post(img.attr('data-posturl'), { new_image: newURL })
,
onError: (errorObj) ->
alert(errorObj.message)
launchEditor = (id, src) ->
featherEditor.launch
image: id,
url: src
return false
$(document).on 'click', '[data-aviary]', (e) ->
e.preventDefault()
image = $(this).parents('.item').find('img')
return launchEditor(image.attr('id'), image.attr('data-image'))
| 61301 | featherEditor = new Aviary.Feather
apiKey: '<KEY>',
apiVersion: 3,
theme: 'light',
language: 'nl',
minimumStyling: true,
tools: 'crop,enhance,contrast,sharpness,text,whiten,effects,warmth,orientation,brightness,saturation,redeye,blemish',
appendTo: '',
onSave: (imageID, newURL) ->
img = $('#' + imageID)
img.attr('src', newURL)
$.post(img.attr('data-posturl'), { new_image: newURL })
,
onError: (errorObj) ->
alert(errorObj.message)
launchEditor = (id, src) ->
featherEditor.launch
image: id,
url: src
return false
$(document).on 'click', '[data-aviary]', (e) ->
e.preventDefault()
image = $(this).parents('.item').find('img')
return launchEditor(image.attr('id'), image.attr('data-image'))
| true | featherEditor = new Aviary.Feather
apiKey: 'PI:KEY:<KEY>END_PI',
apiVersion: 3,
theme: 'light',
language: 'nl',
minimumStyling: true,
tools: 'crop,enhance,contrast,sharpness,text,whiten,effects,warmth,orientation,brightness,saturation,redeye,blemish',
appendTo: '',
onSave: (imageID, newURL) ->
img = $('#' + imageID)
img.attr('src', newURL)
$.post(img.attr('data-posturl'), { new_image: newURL })
,
onError: (errorObj) ->
alert(errorObj.message)
launchEditor = (id, src) ->
featherEditor.launch
image: id,
url: src
return false
$(document).on 'click', '[data-aviary]', (e) ->
e.preventDefault()
image = $(this).parents('.item').find('img')
return launchEditor(image.attr('id'), image.attr('data-image'))
|
[
{
"context": " []\n @trystring = ''\n @keystring = 'qwertyuiop|asdfghjkl|zxcvbnm'\n @breakpoints = ['-']\n @breakpatte",
"end": 307,
"score": 0.9996727108955383,
"start": 279,
"tag": "KEY",
"value": "qwertyuiop|asdfghjkl|zxcvbnm"
}
] | affix.coffee | devongovett/spellchecker.js | 5 | {parseFlags} = require './shared'
class Affix
constructor: (data) ->
@lines = data.split('\n')
@cur = 0
@rules = {}
@flags = {}
@compoundRules = []
@replacementTable = []
@trystring = ''
@keystring = 'qwertyuiop|asdfghjkl|zxcvbnm'
@breakpoints = ['-']
@breakpattern = /(^-)|(-$)/
@rules = @parse(data)
nextLine: ->
len = @lines.length
while @cur < len
line = @lines[@cur++].replace(/#.*/g, '').trim() # remove comments and trim
return line if line.length > 0 # ignore blank lines
return null
parse: (data) ->
rules = {}
while line = @nextLine()
parts = line.split /\s+/
type = parts.shift()
switch type
when 'TRY'
@trystring = parts[0]
when 'KEY'
@keystring = parts[0]
when 'PFX', 'SFX'
@parseRule(type, parts, rules)
when 'REP'
@replacementTable.push [new RegExp(parts[0]), parts[1]] if parts.length is 2
when 'COMPOUNDRULE'
for i in [0...+parts[0]]
parts = @nextLine().split /\s+/
@compoundRules.push parts[1]
when 'BREAK'
num = +parts[0]
if num is 0
@breakpoints = @breakpattern = null
break
@breakpoints = []
patterns = []
for i in [0...num]
pattern = @nextLine().split(/\s+/)[1]
if pattern[0] is '^' or pattern[pattern.length - 1] is '$'
patterns.push '(' + pattern + ')'
else
@breakpoints.push pattern
@breakpattern = new RegExp(patterns.join '|')
else
# ONLYINCOMPOUND
# COMPOUNDMIN
# FLAG
# KEEPCASE
# NEEDAFFIX
@flags[type] = parts[0]
return rules
parseRule: (type, parts, rules) ->
[code, combinable, count] = parts
prefix = if type is 'PFX' then '^' else ''
suffix = if type is 'SFX' then '$' else ''
entries = []
for i in [0...+count]
parts = @nextLine().split /\s+/
# string to strip or 0 for null
strip = parts[2]
strip = '' if strip is '0'
# affix string or 0 for null
affix = parts[3].split '/'
add = affix[0]
add = '' if add is '0'
continuation = parseFlags(@flags['FLAG'], affix[1])
# the conditions descriptions
regex = parts[4]
entry =
add: new RegExp(prefix + add + suffix)
remove: strip
entry.continuation = continuation if continuation.length > 0
entry.match = new RegExp(prefix + regex + suffix) unless regex is '.'
entries.push entry
rules[code] =
type: type
combinable: combinable is 'Y'
entries: entries
check: (word, dictionary) ->
for code, rule of @rules
for entry in rule.entries
tmp = word.replace(entry.add, entry.remove)
continue if tmp is word or entry.match?.test(tmp)
words = dictionary.lookup(tmp)
return true if words and code in words
# continuation?
# NEEDAFFIX
# affix matched but no root word was found
# check if the rule is continuable
return false
module.exports = Affix | 45083 | {parseFlags} = require './shared'
class Affix
constructor: (data) ->
@lines = data.split('\n')
@cur = 0
@rules = {}
@flags = {}
@compoundRules = []
@replacementTable = []
@trystring = ''
@keystring = '<KEY>'
@breakpoints = ['-']
@breakpattern = /(^-)|(-$)/
@rules = @parse(data)
nextLine: ->
len = @lines.length
while @cur < len
line = @lines[@cur++].replace(/#.*/g, '').trim() # remove comments and trim
return line if line.length > 0 # ignore blank lines
return null
parse: (data) ->
rules = {}
while line = @nextLine()
parts = line.split /\s+/
type = parts.shift()
switch type
when 'TRY'
@trystring = parts[0]
when 'KEY'
@keystring = parts[0]
when 'PFX', 'SFX'
@parseRule(type, parts, rules)
when 'REP'
@replacementTable.push [new RegExp(parts[0]), parts[1]] if parts.length is 2
when 'COMPOUNDRULE'
for i in [0...+parts[0]]
parts = @nextLine().split /\s+/
@compoundRules.push parts[1]
when 'BREAK'
num = +parts[0]
if num is 0
@breakpoints = @breakpattern = null
break
@breakpoints = []
patterns = []
for i in [0...num]
pattern = @nextLine().split(/\s+/)[1]
if pattern[0] is '^' or pattern[pattern.length - 1] is '$'
patterns.push '(' + pattern + ')'
else
@breakpoints.push pattern
@breakpattern = new RegExp(patterns.join '|')
else
# ONLYINCOMPOUND
# COMPOUNDMIN
# FLAG
# KEEPCASE
# NEEDAFFIX
@flags[type] = parts[0]
return rules
parseRule: (type, parts, rules) ->
[code, combinable, count] = parts
prefix = if type is 'PFX' then '^' else ''
suffix = if type is 'SFX' then '$' else ''
entries = []
for i in [0...+count]
parts = @nextLine().split /\s+/
# string to strip or 0 for null
strip = parts[2]
strip = '' if strip is '0'
# affix string or 0 for null
affix = parts[3].split '/'
add = affix[0]
add = '' if add is '0'
continuation = parseFlags(@flags['FLAG'], affix[1])
# the conditions descriptions
regex = parts[4]
entry =
add: new RegExp(prefix + add + suffix)
remove: strip
entry.continuation = continuation if continuation.length > 0
entry.match = new RegExp(prefix + regex + suffix) unless regex is '.'
entries.push entry
rules[code] =
type: type
combinable: combinable is 'Y'
entries: entries
check: (word, dictionary) ->
for code, rule of @rules
for entry in rule.entries
tmp = word.replace(entry.add, entry.remove)
continue if tmp is word or entry.match?.test(tmp)
words = dictionary.lookup(tmp)
return true if words and code in words
# continuation?
# NEEDAFFIX
# affix matched but no root word was found
# check if the rule is continuable
return false
module.exports = Affix | true | {parseFlags} = require './shared'
class Affix
constructor: (data) ->
@lines = data.split('\n')
@cur = 0
@rules = {}
@flags = {}
@compoundRules = []
@replacementTable = []
@trystring = ''
@keystring = 'PI:KEY:<KEY>END_PI'
@breakpoints = ['-']
@breakpattern = /(^-)|(-$)/
@rules = @parse(data)
nextLine: ->
len = @lines.length
while @cur < len
line = @lines[@cur++].replace(/#.*/g, '').trim() # remove comments and trim
return line if line.length > 0 # ignore blank lines
return null
parse: (data) ->
rules = {}
while line = @nextLine()
parts = line.split /\s+/
type = parts.shift()
switch type
when 'TRY'
@trystring = parts[0]
when 'KEY'
@keystring = parts[0]
when 'PFX', 'SFX'
@parseRule(type, parts, rules)
when 'REP'
@replacementTable.push [new RegExp(parts[0]), parts[1]] if parts.length is 2
when 'COMPOUNDRULE'
for i in [0...+parts[0]]
parts = @nextLine().split /\s+/
@compoundRules.push parts[1]
when 'BREAK'
num = +parts[0]
if num is 0
@breakpoints = @breakpattern = null
break
@breakpoints = []
patterns = []
for i in [0...num]
pattern = @nextLine().split(/\s+/)[1]
if pattern[0] is '^' or pattern[pattern.length - 1] is '$'
patterns.push '(' + pattern + ')'
else
@breakpoints.push pattern
@breakpattern = new RegExp(patterns.join '|')
else
# ONLYINCOMPOUND
# COMPOUNDMIN
# FLAG
# KEEPCASE
# NEEDAFFIX
@flags[type] = parts[0]
return rules
parseRule: (type, parts, rules) ->
[code, combinable, count] = parts
prefix = if type is 'PFX' then '^' else ''
suffix = if type is 'SFX' then '$' else ''
entries = []
for i in [0...+count]
parts = @nextLine().split /\s+/
# string to strip or 0 for null
strip = parts[2]
strip = '' if strip is '0'
# affix string or 0 for null
affix = parts[3].split '/'
add = affix[0]
add = '' if add is '0'
continuation = parseFlags(@flags['FLAG'], affix[1])
# the conditions descriptions
regex = parts[4]
entry =
add: new RegExp(prefix + add + suffix)
remove: strip
entry.continuation = continuation if continuation.length > 0
entry.match = new RegExp(prefix + regex + suffix) unless regex is '.'
entries.push entry
rules[code] =
type: type
combinable: combinable is 'Y'
entries: entries
check: (word, dictionary) ->
for code, rule of @rules
for entry in rule.entries
tmp = word.replace(entry.add, entry.remove)
continue if tmp is word or entry.match?.test(tmp)
words = dictionary.lookup(tmp)
return true if words and code in words
# continuation?
# NEEDAFFIX
# affix matched but no root word was found
# check if the rule is continuable
return false
module.exports = Affix |
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999122619628906,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/beatmapset-page/score-top.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { FlagCountry } from 'flag-country'
import { Mods } from 'mods'
import * as React from 'react'
import { div, a } from 'react-dom-factories'
el = React.createElement
bn = 'beatmap-score-top'
export ScoreTop = (props) ->
topClasses = (props.modifiers ? [])
.map (m) -> "#{bn}--#{m}"
.join ' '
position = if props.position? then "##{props.position}" else '-'
div className: "#{bn} #{topClasses}",
div className: "#{bn}__section",
div className: "#{bn}__wrapping-container #{bn}__wrapping-container--left",
div className: "#{bn}__position",
div className: "#{bn}__position-number", position
div className: "score-rank score-rank--tiny score-rank--#{props.score.rank}"
div className: "#{bn}__avatar",
a
href: laroute.route 'users.show', user: props.score.user.id
className: "avatar"
style:
backgroundImage: osu.urlPresence(props.score.user.avatar_url)
div className: "#{bn}__user-box",
a
className: "#{bn}__username js-usercard"
'data-user-id': props.score.user.id
href: laroute.route 'users.show', user: props.score.user.id
props.score.user.username
div
className: "#{bn}__achieved"
dangerouslySetInnerHTML:
__html: osu.trans('beatmapsets.show.scoreboard.achieved', when: osu.timeago(props.score.created_at))
a
href: laroute.route 'rankings',
mode: props.playmode
country: props.score.user.country_code
type: 'performance'
el FlagCountry,
country: props.countries[props.score.user.country_code]
modifiers: ['scoreboard', 'small-box']
div className: "#{bn}__wrapping-container #{bn}__wrapping-container--right",
div className: "#{bn}__stats",
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--wider",
osu.trans 'beatmapsets.show.scoreboard.headers.score_total'
div className: "#{bn}__stat-value #{bn}__stat-value--score",
osu.formatNumber(props.score.score)
div className: "#{bn}__stats",
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--wider",
osu.trans 'beatmapsets.show.scoreboard.headers.accuracy'
div className: "#{bn}__stat-value #{bn}__stat-value--score",
"#{osu.formatNumber(props.score.accuracy * 100, 2)}%"
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--wider",
osu.trans 'beatmapsets.show.scoreboard.headers.combo'
div className: "#{bn}__stat-value #{bn}__stat-value--score",
"#{osu.formatNumber(props.score.max_combo)}x"
div className: "#{bn}__stats #{bn}__stats--wrappable",
for stat in props.hitTypeMapping
div
key: stat[0]
className: "#{bn}__stat"
div className: "#{bn}__stat-header",
stat[0]
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
osu.formatNumber(props.score.statistics["count_#{stat[1]}"])
div className: "#{bn}__stat",
div className: "#{bn}__stat-header",
osu.trans 'beatmapsets.show.scoreboard.headers.miss'
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
osu.formatNumber(props.score.statistics.count_miss)
div className: "#{bn}__stat",
div className: "#{bn}__stat-header",
osu.trans 'beatmapsets.show.scoreboard.headers.pp'
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
_.round props.score.pp
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--mods",
osu.trans 'beatmapsets.show.scoreboard.headers.mods'
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
el Mods, modifiers: ['scoreboard'], mods: props.score.mods
| 94497 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { FlagCountry } from 'flag-country'
import { Mods } from 'mods'
import * as React from 'react'
import { div, a } from 'react-dom-factories'
el = React.createElement
bn = 'beatmap-score-top'
export ScoreTop = (props) ->
topClasses = (props.modifiers ? [])
.map (m) -> "#{bn}--#{m}"
.join ' '
position = if props.position? then "##{props.position}" else '-'
div className: "#{bn} #{topClasses}",
div className: "#{bn}__section",
div className: "#{bn}__wrapping-container #{bn}__wrapping-container--left",
div className: "#{bn}__position",
div className: "#{bn}__position-number", position
div className: "score-rank score-rank--tiny score-rank--#{props.score.rank}"
div className: "#{bn}__avatar",
a
href: laroute.route 'users.show', user: props.score.user.id
className: "avatar"
style:
backgroundImage: osu.urlPresence(props.score.user.avatar_url)
div className: "#{bn}__user-box",
a
className: "#{bn}__username js-usercard"
'data-user-id': props.score.user.id
href: laroute.route 'users.show', user: props.score.user.id
props.score.user.username
div
className: "#{bn}__achieved"
dangerouslySetInnerHTML:
__html: osu.trans('beatmapsets.show.scoreboard.achieved', when: osu.timeago(props.score.created_at))
a
href: laroute.route 'rankings',
mode: props.playmode
country: props.score.user.country_code
type: 'performance'
el FlagCountry,
country: props.countries[props.score.user.country_code]
modifiers: ['scoreboard', 'small-box']
div className: "#{bn}__wrapping-container #{bn}__wrapping-container--right",
div className: "#{bn}__stats",
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--wider",
osu.trans 'beatmapsets.show.scoreboard.headers.score_total'
div className: "#{bn}__stat-value #{bn}__stat-value--score",
osu.formatNumber(props.score.score)
div className: "#{bn}__stats",
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--wider",
osu.trans 'beatmapsets.show.scoreboard.headers.accuracy'
div className: "#{bn}__stat-value #{bn}__stat-value--score",
"#{osu.formatNumber(props.score.accuracy * 100, 2)}%"
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--wider",
osu.trans 'beatmapsets.show.scoreboard.headers.combo'
div className: "#{bn}__stat-value #{bn}__stat-value--score",
"#{osu.formatNumber(props.score.max_combo)}x"
div className: "#{bn}__stats #{bn}__stats--wrappable",
for stat in props.hitTypeMapping
div
key: stat[0]
className: "#{bn}__stat"
div className: "#{bn}__stat-header",
stat[0]
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
osu.formatNumber(props.score.statistics["count_#{stat[1]}"])
div className: "#{bn}__stat",
div className: "#{bn}__stat-header",
osu.trans 'beatmapsets.show.scoreboard.headers.miss'
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
osu.formatNumber(props.score.statistics.count_miss)
div className: "#{bn}__stat",
div className: "#{bn}__stat-header",
osu.trans 'beatmapsets.show.scoreboard.headers.pp'
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
_.round props.score.pp
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--mods",
osu.trans 'beatmapsets.show.scoreboard.headers.mods'
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
el Mods, modifiers: ['scoreboard'], mods: props.score.mods
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import { FlagCountry } from 'flag-country'
import { Mods } from 'mods'
import * as React from 'react'
import { div, a } from 'react-dom-factories'
el = React.createElement
bn = 'beatmap-score-top'
export ScoreTop = (props) ->
topClasses = (props.modifiers ? [])
.map (m) -> "#{bn}--#{m}"
.join ' '
position = if props.position? then "##{props.position}" else '-'
div className: "#{bn} #{topClasses}",
div className: "#{bn}__section",
div className: "#{bn}__wrapping-container #{bn}__wrapping-container--left",
div className: "#{bn}__position",
div className: "#{bn}__position-number", position
div className: "score-rank score-rank--tiny score-rank--#{props.score.rank}"
div className: "#{bn}__avatar",
a
href: laroute.route 'users.show', user: props.score.user.id
className: "avatar"
style:
backgroundImage: osu.urlPresence(props.score.user.avatar_url)
div className: "#{bn}__user-box",
a
className: "#{bn}__username js-usercard"
'data-user-id': props.score.user.id
href: laroute.route 'users.show', user: props.score.user.id
props.score.user.username
div
className: "#{bn}__achieved"
dangerouslySetInnerHTML:
__html: osu.trans('beatmapsets.show.scoreboard.achieved', when: osu.timeago(props.score.created_at))
a
href: laroute.route 'rankings',
mode: props.playmode
country: props.score.user.country_code
type: 'performance'
el FlagCountry,
country: props.countries[props.score.user.country_code]
modifiers: ['scoreboard', 'small-box']
div className: "#{bn}__wrapping-container #{bn}__wrapping-container--right",
div className: "#{bn}__stats",
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--wider",
osu.trans 'beatmapsets.show.scoreboard.headers.score_total'
div className: "#{bn}__stat-value #{bn}__stat-value--score",
osu.formatNumber(props.score.score)
div className: "#{bn}__stats",
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--wider",
osu.trans 'beatmapsets.show.scoreboard.headers.accuracy'
div className: "#{bn}__stat-value #{bn}__stat-value--score",
"#{osu.formatNumber(props.score.accuracy * 100, 2)}%"
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--wider",
osu.trans 'beatmapsets.show.scoreboard.headers.combo'
div className: "#{bn}__stat-value #{bn}__stat-value--score",
"#{osu.formatNumber(props.score.max_combo)}x"
div className: "#{bn}__stats #{bn}__stats--wrappable",
for stat in props.hitTypeMapping
div
key: stat[0]
className: "#{bn}__stat"
div className: "#{bn}__stat-header",
stat[0]
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
osu.formatNumber(props.score.statistics["count_#{stat[1]}"])
div className: "#{bn}__stat",
div className: "#{bn}__stat-header",
osu.trans 'beatmapsets.show.scoreboard.headers.miss'
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
osu.formatNumber(props.score.statistics.count_miss)
div className: "#{bn}__stat",
div className: "#{bn}__stat-header",
osu.trans 'beatmapsets.show.scoreboard.headers.pp'
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
_.round props.score.pp
div className: "#{bn}__stat",
div className: "#{bn}__stat-header #{bn}__stat-header--mods",
osu.trans 'beatmapsets.show.scoreboard.headers.mods'
div className: "#{bn}__stat-value #{bn}__stat-value--score #{bn}__stat-value--smaller",
el Mods, modifiers: ['scoreboard'], mods: props.score.mods
|
[
{
"context": "g me - Returns a random meme image\n#\n# Author:\n# EnriqueVidal \n#\n# Contributors:\n# dedeibel (gif support)\n\nSe",
"end": 282,
"score": 0.999499499797821,
"start": 270,
"tag": "NAME",
"value": "EnriqueVidal"
},
{
"context": "\n# Author:\n# EnriqueVidal \n#\n#... | src/scripts/9gag.coffee | contolini/hubot-scripts | 4 | # Description:
# None
#
# Dependencies:
# "htmlparser": "1.7.6"
# "soupselect": "0.2.0"
#
# Configuration:
# HUBOT_9GAG_NO_GIFS (optional, skips GIFs if defined; default is undefined)
#
# Commands:
# hubot 9gag me - Returns a random meme image
#
# Author:
# EnriqueVidal
#
# Contributors:
# dedeibel (gif support)
Select = require( "soupselect" ).select
HTMLParser = require "htmlparser"
module.exports = (robot)->
robot.logger.warning "9gag.coffee has moved from hubot-scripts to its own package. See https://github.com/luijose/hubot-9gag installation instructions"
robot.respond /9gag( me)?/i, (message)->
send_meme message, false, (title, src)->
message.send title, src
send_meme = (message, location, response_handler)->
meme_domain = "http://9gag.com"
location ||= "/random"
if location.substr(0, 4) != "http"
url = meme_domain + location
else
url = location
message.http( url ).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302
location = response.headers['location']
return send_meme( message, location, response_handler )
selectors = ["a img.badge-item-img"]
if ! process.env.HUBOT_9GAG_NO_GIFS?
selectors.unshift("div.badge-animated-container-animated img")
img_src = get_meme_image( body, selectors )
if img_src.substr(0, 4) != "http"
img_src = "http:#{img_src}"
img_title = escape_html_characters( get_meme_title( body, [".badge-item-title"] ) )
response_handler img_title, img_src
select_element = (body, selectors)->
html_handler = new HTMLParser.DefaultHandler((()->), ignoreWhitespace: true )
html_parser = new HTMLParser.Parser html_handler
html_parser.parseComplete body
for selector in selectors
img_container = Select( html_handler.dom, selector )
if img_container && img_container[0]
return img_container[0]
get_meme_image = ( body, selectors )->
select_element(body, selectors).attribs.src
get_meme_title = ( body, selectors )->
select_element(body, selectors).children[0].raw
escape_html_characters = (text)->
replacements = [
[/&/g, '&']
[/</g, '<']
[/"/g, '"']
[/'/g, ''']
]
for r in replacements
text = text.replace r[0], r[1]
return text
| 28413 | # Description:
# None
#
# Dependencies:
# "htmlparser": "1.7.6"
# "soupselect": "0.2.0"
#
# Configuration:
# HUBOT_9GAG_NO_GIFS (optional, skips GIFs if defined; default is undefined)
#
# Commands:
# hubot 9gag me - Returns a random meme image
#
# Author:
# <NAME>
#
# Contributors:
# dedeibel (gif support)
Select = require( "soupselect" ).select
HTMLParser = require "htmlparser"
module.exports = (robot)->
robot.logger.warning "9gag.coffee has moved from hubot-scripts to its own package. See https://github.com/luijose/hubot-9gag installation instructions"
robot.respond /9gag( me)?/i, (message)->
send_meme message, false, (title, src)->
message.send title, src
send_meme = (message, location, response_handler)->
meme_domain = "http://9gag.com"
location ||= "/random"
if location.substr(0, 4) != "http"
url = meme_domain + location
else
url = location
message.http( url ).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302
location = response.headers['location']
return send_meme( message, location, response_handler )
selectors = ["a img.badge-item-img"]
if ! process.env.HUBOT_9GAG_NO_GIFS?
selectors.unshift("div.badge-animated-container-animated img")
img_src = get_meme_image( body, selectors )
if img_src.substr(0, 4) != "http"
img_src = "http:#{img_src}"
img_title = escape_html_characters( get_meme_title( body, [".badge-item-title"] ) )
response_handler img_title, img_src
select_element = (body, selectors)->
html_handler = new HTMLParser.DefaultHandler((()->), ignoreWhitespace: true )
html_parser = new HTMLParser.Parser html_handler
html_parser.parseComplete body
for selector in selectors
img_container = Select( html_handler.dom, selector )
if img_container && img_container[0]
return img_container[0]
get_meme_image = ( body, selectors )->
select_element(body, selectors).attribs.src
get_meme_title = ( body, selectors )->
select_element(body, selectors).children[0].raw
escape_html_characters = (text)->
replacements = [
[/&/g, '&']
[/</g, '<']
[/"/g, '"']
[/'/g, ''']
]
for r in replacements
text = text.replace r[0], r[1]
return text
| true | # Description:
# None
#
# Dependencies:
# "htmlparser": "1.7.6"
# "soupselect": "0.2.0"
#
# Configuration:
# HUBOT_9GAG_NO_GIFS (optional, skips GIFs if defined; default is undefined)
#
# Commands:
# hubot 9gag me - Returns a random meme image
#
# Author:
# PI:NAME:<NAME>END_PI
#
# Contributors:
# dedeibel (gif support)
Select = require( "soupselect" ).select
HTMLParser = require "htmlparser"
module.exports = (robot)->
robot.logger.warning "9gag.coffee has moved from hubot-scripts to its own package. See https://github.com/luijose/hubot-9gag installation instructions"
robot.respond /9gag( me)?/i, (message)->
send_meme message, false, (title, src)->
message.send title, src
send_meme = (message, location, response_handler)->
meme_domain = "http://9gag.com"
location ||= "/random"
if location.substr(0, 4) != "http"
url = meme_domain + location
else
url = location
message.http( url ).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302
location = response.headers['location']
return send_meme( message, location, response_handler )
selectors = ["a img.badge-item-img"]
if ! process.env.HUBOT_9GAG_NO_GIFS?
selectors.unshift("div.badge-animated-container-animated img")
img_src = get_meme_image( body, selectors )
if img_src.substr(0, 4) != "http"
img_src = "http:#{img_src}"
img_title = escape_html_characters( get_meme_title( body, [".badge-item-title"] ) )
response_handler img_title, img_src
select_element = (body, selectors)->
html_handler = new HTMLParser.DefaultHandler((()->), ignoreWhitespace: true )
html_parser = new HTMLParser.Parser html_handler
html_parser.parseComplete body
for selector in selectors
img_container = Select( html_handler.dom, selector )
if img_container && img_container[0]
return img_container[0]
get_meme_image = ( body, selectors )->
select_element(body, selectors).attribs.src
get_meme_title = ( body, selectors )->
select_element(body, selectors).children[0].raw
escape_html_characters = (text)->
replacements = [
[/&/g, '&']
[/</g, '<']
[/"/g, '"']
[/'/g, ''']
]
for r in replacements
text = text.replace r[0], r[1]
return text
|
[
{
"context": "'throws without password', ->\n yargs ['-u', 'tester@testing.org'], true\n _.partial(require, '..').should.Thr",
"end": 476,
"score": 0.999913215637207,
"start": 458,
"tag": "EMAIL",
"value": "tester@testing.org"
},
{
"context": "e', ->\n inflate = null\n\n ... | test/test.coffee | jdcrensh/force-coverage | 2 | _ = require 'lodash'
# bdd
chai = require 'chai'
chai.should()
describe 'argv', ->
describe 'when credentials are not provided', ->
@timeout 10000
it 'throws with neither username nor password', ->
yargs [], true
_.partial(require, '..').should.Throw()
it 'throws without username', ->
yargs ['-p', 'password'], true
_.partial(require, '..').should.Throw()
it 'throws without password', ->
yargs ['-u', 'tester@testing.org'], true
_.partial(require, '..').should.Throw()
describe 'inflate', ->
inflate = null
before ->
yargs '-u tester@testing.org -p password'.split ' '
{inflate} = require '..'
it 'should be instantiated', ->
inflate.should.not.be.null
yargs = (args=[], graceful) ->
argv = require('yargs')(args)
argv.exitProcess not graceful
argv.showHelpOnFail not graceful
| 101587 | _ = require 'lodash'
# bdd
chai = require 'chai'
chai.should()
describe 'argv', ->
describe 'when credentials are not provided', ->
@timeout 10000
it 'throws with neither username nor password', ->
yargs [], true
_.partial(require, '..').should.Throw()
it 'throws without username', ->
yargs ['-p', 'password'], true
_.partial(require, '..').should.Throw()
it 'throws without password', ->
yargs ['-u', '<EMAIL>'], true
_.partial(require, '..').should.Throw()
describe 'inflate', ->
inflate = null
before ->
yargs '-u <EMAIL> -p password'.split ' '
{inflate} = require '..'
it 'should be instantiated', ->
inflate.should.not.be.null
yargs = (args=[], graceful) ->
argv = require('yargs')(args)
argv.exitProcess not graceful
argv.showHelpOnFail not graceful
| true | _ = require 'lodash'
# bdd
chai = require 'chai'
chai.should()
describe 'argv', ->
describe 'when credentials are not provided', ->
@timeout 10000
it 'throws with neither username nor password', ->
yargs [], true
_.partial(require, '..').should.Throw()
it 'throws without username', ->
yargs ['-p', 'password'], true
_.partial(require, '..').should.Throw()
it 'throws without password', ->
yargs ['-u', 'PI:EMAIL:<EMAIL>END_PI'], true
_.partial(require, '..').should.Throw()
describe 'inflate', ->
inflate = null
before ->
yargs '-u PI:EMAIL:<EMAIL>END_PI -p password'.split ' '
{inflate} = require '..'
it 'should be instantiated', ->
inflate.should.not.be.null
yargs = (args=[], graceful) ->
argv = require('yargs')(args)
argv.exitProcess not graceful
argv.showHelpOnFail not graceful
|
[
{
"context": " seems to be enforced by Devis\n password: 'too short'\n\n if attributes.password_confirmation.lengt",
"end": 641,
"score": 0.9986239671707153,
"start": 632,
"tag": "PASSWORD",
"value": "too short"
},
{
"context": "tributes.password\n password_confirm... | app/backbone/models/user_password.coffee | Factlink/feedforward | 0 | class window.UserPassword extends Backbone.Model
defaults:
current_password: ''
password: ''
password_confirmation: ''
initialize: (attributes, options) ->
@_user = options.user
url: -> @_user.url() + '/password'
isNew: -> false
# Weirdly, this is not default behaviour
clear: ->
@set @defaults
validate: (attributes, options) ->
errors = _.compact [
if attributes.current_password.length == 0
current_password: '*'
if attributes.password.length == 0
password: '*'
else if attributes.password.length < 6 # seems to be enforced by Devis
password: 'too short'
if attributes.password_confirmation.length == 0
password_confirmation: '*'
else if attributes.password_confirmation != attributes.password
password_confirmation: 'does not match'
]
errors.length && _.extend({}, errors...)
| 49267 | class window.UserPassword extends Backbone.Model
defaults:
current_password: ''
password: ''
password_confirmation: ''
initialize: (attributes, options) ->
@_user = options.user
url: -> @_user.url() + '/password'
isNew: -> false
# Weirdly, this is not default behaviour
clear: ->
@set @defaults
validate: (attributes, options) ->
errors = _.compact [
if attributes.current_password.length == 0
current_password: '*'
if attributes.password.length == 0
password: '*'
else if attributes.password.length < 6 # seems to be enforced by Devis
password: '<PASSWORD>'
if attributes.password_confirmation.length == 0
password_confirmation: '*'
else if attributes.password_confirmation != attributes.password
password_confirmation: '<PASSWORD>'
]
errors.length && _.extend({}, errors...)
| true | class window.UserPassword extends Backbone.Model
defaults:
current_password: ''
password: ''
password_confirmation: ''
initialize: (attributes, options) ->
@_user = options.user
url: -> @_user.url() + '/password'
isNew: -> false
# Weirdly, this is not default behaviour
clear: ->
@set @defaults
validate: (attributes, options) ->
errors = _.compact [
if attributes.current_password.length == 0
current_password: '*'
if attributes.password.length == 0
password: '*'
else if attributes.password.length < 6 # seems to be enforced by Devis
password: 'PI:PASSWORD:<PASSWORD>END_PI'
if attributes.password_confirmation.length == 0
password_confirmation: '*'
else if attributes.password_confirmation != attributes.password
password_confirmation: 'PI:PASSWORD:<PASSWORD>END_PI'
]
errors.length && _.extend({}, errors...)
|
[
{
"context": ">\n expect(validation.isValidEmailFormat 'user@example.com').to.be.ok\n\n describe 'invalid', ->\n ",
"end": 341,
"score": 0.9999162554740906,
"start": 325,
"tag": "EMAIL",
"value": "user@example.com"
},
{
"context": "\n expect(validation.i... | source/TextUml/Scripts/specs/application/models/validation.coffee | marufsiddiqui/textuml-dotnet | 1 | define (require) ->
validation = require '../../../application/models/validation'
repeatString = require('../../helpers').repeatString
describe 'models/validation', ->
describe '.isValidEmailFormat', ->
describe 'valid', ->
it 'returns true', ->
expect(validation.isValidEmailFormat 'user@example.com').to.be.ok
describe 'invalid', ->
it 'returns false', ->
expect(validation.isValidEmailFormat 'foo-bar').not.to.be.ok
describe '.isValidPasswordLength', ->
describe 'valid', ->
it 'returns true', ->
expect(validation.isValidPasswordLength '$ecre8').to.be.ok
describe 'invalid', ->
describe 'less than six characters', ->
it 'returns false', ->
expect(validation.isValidPasswordLength(repeatString 5))
.not.to.be.ok
describe 'more than sixty four characters', ->
it 'returns false', ->
expect(validation.isValidPasswordLength(repeatString 65))
.not.to.be.ok
describe '.addError', ->
errors = null
beforeEach ->
errors = {}
validation.addError errors, 'name', 'Name is required.'
it 'creates new attribute', -> expect(errors).to.include.key 'name'
it 'appends message', ->
expect(errors.name).to.include 'Name is required.' | 55987 | define (require) ->
validation = require '../../../application/models/validation'
repeatString = require('../../helpers').repeatString
describe 'models/validation', ->
describe '.isValidEmailFormat', ->
describe 'valid', ->
it 'returns true', ->
expect(validation.isValidEmailFormat '<EMAIL>').to.be.ok
describe 'invalid', ->
it 'returns false', ->
expect(validation.isValidEmailFormat 'foo-bar').not.to.be.ok
describe '.isValidPasswordLength', ->
describe 'valid', ->
it 'returns true', ->
expect(validation.isValidPasswordLength <PASSWORD>').to.be.ok
describe 'invalid', ->
describe 'less than six characters', ->
it 'returns false', ->
expect(validation.isValidPasswordLength(repeatString 5))
.not.to.be.ok
describe 'more than sixty four characters', ->
it 'returns false', ->
expect(validation.isValidPasswordLength(repeatString 65))
.not.to.be.ok
describe '.addError', ->
errors = null
beforeEach ->
errors = {}
validation.addError errors, 'name', 'Name is required.'
it 'creates new attribute', -> expect(errors).to.include.key 'name'
it 'appends message', ->
expect(errors.name).to.include 'Name is required.' | true | define (require) ->
validation = require '../../../application/models/validation'
repeatString = require('../../helpers').repeatString
describe 'models/validation', ->
describe '.isValidEmailFormat', ->
describe 'valid', ->
it 'returns true', ->
expect(validation.isValidEmailFormat 'PI:EMAIL:<EMAIL>END_PI').to.be.ok
describe 'invalid', ->
it 'returns false', ->
expect(validation.isValidEmailFormat 'foo-bar').not.to.be.ok
describe '.isValidPasswordLength', ->
describe 'valid', ->
it 'returns true', ->
expect(validation.isValidPasswordLength PI:PASSWORD:<PASSWORD>END_PI').to.be.ok
describe 'invalid', ->
describe 'less than six characters', ->
it 'returns false', ->
expect(validation.isValidPasswordLength(repeatString 5))
.not.to.be.ok
describe 'more than sixty four characters', ->
it 'returns false', ->
expect(validation.isValidPasswordLength(repeatString 65))
.not.to.be.ok
describe '.addError', ->
errors = null
beforeEach ->
errors = {}
validation.addError errors, 'name', 'Name is required.'
it 'creates new attribute', -> expect(errors).to.include.key 'name'
it 'appends message', ->
expect(errors.name).to.include 'Name is required.' |
[
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ",
"end": 38,
"score": 0.9998880624771118,
"start": 25,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright... | public/taiga-front/app/coffee/modules/related-tasks.coffee | mabotech/maboss | 0 | ###
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/related-tasks.coffee
###
taiga = @.taiga
trim = @.taiga.trim
debounce = @.taiga.debounce
module = angular.module("taigaRelatedTasks", [])
RelatedTaskRowDirective = ($repo, $compile, $confirm, $rootscope, $loading) ->
templateView = _.template("""
<div class="tasks">
<div class="task-name">
<span class="icon icon-iocaine"></span>
<a tg-nav="project-tasks-detail:project=project.slug,ref=task.ref" title="<%- task.ref %> <%- task.subject %>" class="clickable">
<span>#<%- task.ref %></span>
<span><%- task.subject %></span>
</a>
<div class="task-settings">
<% if(perms.modify_task) { %>
<a href="" title="Edit" class="icon icon-edit"></a>
<% } %>
<% if(perms.delete_task) { %>
<a href="" title="Delete" class="icon icon-delete delete-task"></a>
<% } %>
</div>
</div>
</div>
<div tg-related-task-status="task" ng-model="task" class="status">
<a href="" title="Status Name" class="task-status">
<span class="task-status-bind"></span>
<% if(perms.modify_task) { %>
<span class="icon icon-arrow-bottom"></span>
<% } %>
</a>
</div>
<div tg-related-task-assigned-to-inline-edition="task" class="assigned-to">
<div title="Assigned to" class="task-assignedto <% if(perms.modify_task) { %>editable<% } %>">
<figure class="avatar"></figure>
<% if(perms.modify_task) { %>
<span class="icon icon-arrow-bottom"></span>
<% } %>
</div>
</div>
""")
templateEdit = _.template("""
<div class="tasks">
<div class="task-name">
<input type="text" value="<%- task.subject %>" placeholder="Type the task subject" />
<div class="task-settings">
<a href="" title="Save" class="icon icon-floppy"></a>
<a href="" title="Cancel" class="icon icon-delete cancel-edit"></a>
</div>
</div>
</div>
<div tg-related-task-status="task" ng-model="task" class="status">
<a href="" title="Status Name" class="task-status">
<span class="task-status-bind"></span>
<span class="icon icon-arrow-bottom"></span>
</a>
</div>
<div tg-related-task-assigned-to-inline-edition="task" class="assigned-to">
<div title="Assigned to" class="task-assignedto">
<figure class="avatar"></figure>
<span class="icon icon-arrow-bottom"></span>
</div>
</div>
""")
link = ($scope, $el, $attrs, $model) ->
saveTask = debounce 2000, (task) ->
task.subject = $el.find('input').val()
$loading.start($el.find('.task-name'))
promise = $repo.save(task)
promise.then =>
$loading.finish($el.find('.task-name'))
$confirm.notify("success")
$rootscope.$broadcast("related-tasks:update")
promise.then null, =>
$loading.finish($el.find('.task-name'))
$el.find('input').val(task.subject)
$confirm.notify("error")
return promise
renderEdit = (task) ->
$el.html($compile(templateEdit({task: task}))($scope))
$el.on "keyup", "input", (event) ->
if event.keyCode == 13
saveTask($model.$modelValue).then ->
renderView($model.$modelValue)
else if event.keyCode == 27
renderView($model.$modelValue)
$el.on "click", ".icon-floppy", (event) ->
saveTask($model.$modelValue).then ->
renderView($model.$modelValue)
$el.on "click", ".cancel-edit", (event) ->
renderView($model.$modelValue)
renderView = (task) ->
$el.off()
perms = {
modify_task: $scope.project.my_permissions.indexOf("modify_task") != -1
delete_task: $scope.project.my_permissions.indexOf("delete_task") != -1
}
$el.html($compile(templateView({task: task, perms: perms}))($scope))
$el.on "click", ".icon-edit", ->
renderEdit($model.$modelValue)
$el.find('input').focus().select()
$el.on "click", ".delete-task", (event) ->
#TODO: i18n
task = $model.$modelValue
title = "Delete Task"
message = task.subject
$confirm.askOnDelete(title, message).then (finish) ->
promise = $repo.remove(task)
promise.then ->
finish()
$confirm.notify("success")
$scope.$emit("related-tasks:delete")
promise.then null, ->
$confirm.notify("error")
$scope.$watch $attrs.ngModel, (val) ->
return if not val
renderView(val)
$scope.$on "related-tasks:assigned-to-changed", ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "related-tasks:status-changed", ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "$destroy", ->
$el.off()
return {link:link, require:"ngModel"}
module.directive("tgRelatedTaskRow", ["$tgRepo", "$compile", "$tgConfirm", "$rootScope", "$tgLoading", "$tgAnalytics", RelatedTaskRowDirective])
RelatedTaskCreateFormDirective = ($repo, $compile, $confirm, $tgmodel, $loading, $analytics) ->
template = _.template("""
<div class="tasks">
<div class="task-name">
<input type="text" placeholder="Type the new task subject" />
<div class="task-settings">
<a href="" title="Save" class="icon icon-floppy"></a>
<a href="" title="Cancel" class="icon icon-delete cancel-edit"></a>
</div>
</div>
</div>
<div tg-related-task-status="newTask" ng-model="newTask" class="status" not-auto-save="true">
<a href="" title="Status Name" class="task-status">
<span class="task-status-bind"></span>
<span class="icon icon-arrow-bottom"></span>
</a>
</div>
<div tg-related-task-assigned-to-inline-edition="newTask" class="assigned-to" not-auto-save="true">
<div title="Assigned to" class="task-assignedto">
<figure class="avatar"></figure>
<span class="icon icon-arrow-bottom"></span>
</div>
</div>
""")
newTask = {
subject: ""
assigned_to: null
}
link = ($scope, $el, $attrs) ->
createTask = debounce 2000, (task) ->
task.subject = $el.find('input').val()
task.assigned_to = $scope.newTask.assigned_to
task.status = $scope.newTask.status
$scope.newTask.status = $scope.project.default_task_status
$scope.newTask.assigned_to = null
$loading.start($el.find('.task-name'))
promise = $repo.create("tasks", task)
promise.then ->
$analytics.trackEvent("task", "create", "create task on userstory", 1)
$loading.finish($el.find('.task-name'))
$scope.$emit("related-tasks:add")
$confirm.notify("success")
promise.then null, ->
$el.find('input').val(task.subject)
$loading.finish($el.find('.task-name'))
$confirm.notify("error")
return promise
render = ->
$el.off()
$el.html($compile(template())($scope))
$el.find('input').focus().select()
$el.addClass('active')
$el.on "keyup", "input", (event)->
if event.keyCode == 13
createTask(newTask).then ->
render()
else if event.keyCode == 27
$el.html("")
$el.on "click", ".icon-delete", (event)->
$el.html("")
$el.on "click", ".icon-floppy", (event)->
createTask(newTask).then ->
$el.html("")
taiga.bindOnce $scope, "us", (val) ->
newTask["status"] = $scope.project.default_task_status
newTask["project"] = $scope.project.id
newTask["user_story"] = $scope.us.id
$scope.newTask = $tgmodel.make_model("tasks", newTask)
$el.html("")
$scope.$on "related-tasks:show-form", ->
render()
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTaskCreateForm", ["$tgRepo", "$compile", "$tgConfirm", "$tgModel", "$tgLoading", "$tgAnalytics", RelatedTaskCreateFormDirective])
RelatedTaskCreateButtonDirective = ($repo, $compile, $confirm, $tgmodel) ->
template = _.template("""
<a class="icon icon-plus related-tasks-buttons"></a>
""")
link = ($scope, $el, $attrs) ->
$scope.$watch "project", (val) ->
return if not val
$el.off()
if $scope.project.my_permissions.indexOf("add_task") != -1
$el.html(template())
else
$el.html("")
$el.on "click", ".icon", (event)->
$scope.$emit("related-tasks:add-new-clicked")
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTaskCreateButton", ["$tgRepo", "$compile", "$tgConfirm", "$tgModel", RelatedTaskCreateButtonDirective])
RelatedTasksDirective = ($repo, $rs, $rootscope) ->
link = ($scope, $el, $attrs) ->
loadTasks = ->
return $rs.tasks.list($scope.projectId, null, $scope.usId).then (tasks) =>
$scope.tasks = tasks
return tasks
$scope.$on "related-tasks:add", ->
loadTasks().then ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "related-tasks:delete", ->
loadTasks().then ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "related-tasks:add-new-clicked", ->
$scope.$broadcast("related-tasks:show-form")
taiga.bindOnce $scope, "us", (val) ->
loadTasks()
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTasks", ["$tgRepo", "$tgResources", "$rootScope", RelatedTasksDirective])
RelatedTaskAssignedToInlineEditionDirective = ($repo, $rootscope, popoverService) ->
template = _.template("""
<img src="<%- imgurl %>" alt="<%- name %>"/>
<figcaption><%- name %></figcaption>
""")
link = ($scope, $el, $attrs) ->
updateRelatedTask = (task) ->
ctx = {name: "Unassigned", imgurl: "/images/unnamed.png"}
member = $scope.usersById[task.assigned_to]
if member
ctx.imgurl = member.photo
ctx.name = member.full_name_display
$el.find(".avatar").html(template(ctx))
$el.find(".task-assignedto").attr('title', ctx.name)
$ctrl = $el.controller()
task = $scope.$eval($attrs.tgRelatedTaskAssignedToInlineEdition)
notAutoSave = $scope.$eval($attrs.notAutoSave)
autoSave = !notAutoSave
updateRelatedTask(task)
$el.on "click", ".task-assignedto", (event) ->
$rootscope.$broadcast("assigned-to:add", task)
taiga.bindOnce $scope, "project", (project) ->
# If the user has not enough permissions the click events are unbinded
if project.my_permissions.indexOf("modify_task") == -1
$el.unbind("click")
$el.find("a").addClass("not-clickable")
$scope.$on "assigned-to:added", debounce 2000, (ctx, userId, updatedRelatedTask) =>
if updatedRelatedTask.id == task.id
updatedRelatedTask.assigned_to = userId
if autoSave
$repo.save(updatedRelatedTask).then ->
$scope.$emit("related-tasks:assigned-to-changed")
updateRelatedTask(updatedRelatedTask)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTaskAssignedToInlineEdition", ["$tgRepo", "$rootScope", RelatedTaskAssignedToInlineEditionDirective])
| 174604 | ###
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/related-tasks.coffee
###
taiga = @.taiga
trim = @.taiga.trim
debounce = @.taiga.debounce
module = angular.module("taigaRelatedTasks", [])
RelatedTaskRowDirective = ($repo, $compile, $confirm, $rootscope, $loading) ->
templateView = _.template("""
<div class="tasks">
<div class="task-name">
<span class="icon icon-iocaine"></span>
<a tg-nav="project-tasks-detail:project=project.slug,ref=task.ref" title="<%- task.ref %> <%- task.subject %>" class="clickable">
<span>#<%- task.ref %></span>
<span><%- task.subject %></span>
</a>
<div class="task-settings">
<% if(perms.modify_task) { %>
<a href="" title="Edit" class="icon icon-edit"></a>
<% } %>
<% if(perms.delete_task) { %>
<a href="" title="Delete" class="icon icon-delete delete-task"></a>
<% } %>
</div>
</div>
</div>
<div tg-related-task-status="task" ng-model="task" class="status">
<a href="" title="Status Name" class="task-status">
<span class="task-status-bind"></span>
<% if(perms.modify_task) { %>
<span class="icon icon-arrow-bottom"></span>
<% } %>
</a>
</div>
<div tg-related-task-assigned-to-inline-edition="task" class="assigned-to">
<div title="Assigned to" class="task-assignedto <% if(perms.modify_task) { %>editable<% } %>">
<figure class="avatar"></figure>
<% if(perms.modify_task) { %>
<span class="icon icon-arrow-bottom"></span>
<% } %>
</div>
</div>
""")
templateEdit = _.template("""
<div class="tasks">
<div class="task-name">
<input type="text" value="<%- task.subject %>" placeholder="Type the task subject" />
<div class="task-settings">
<a href="" title="Save" class="icon icon-floppy"></a>
<a href="" title="Cancel" class="icon icon-delete cancel-edit"></a>
</div>
</div>
</div>
<div tg-related-task-status="task" ng-model="task" class="status">
<a href="" title="Status Name" class="task-status">
<span class="task-status-bind"></span>
<span class="icon icon-arrow-bottom"></span>
</a>
</div>
<div tg-related-task-assigned-to-inline-edition="task" class="assigned-to">
<div title="Assigned to" class="task-assignedto">
<figure class="avatar"></figure>
<span class="icon icon-arrow-bottom"></span>
</div>
</div>
""")
link = ($scope, $el, $attrs, $model) ->
saveTask = debounce 2000, (task) ->
task.subject = $el.find('input').val()
$loading.start($el.find('.task-name'))
promise = $repo.save(task)
promise.then =>
$loading.finish($el.find('.task-name'))
$confirm.notify("success")
$rootscope.$broadcast("related-tasks:update")
promise.then null, =>
$loading.finish($el.find('.task-name'))
$el.find('input').val(task.subject)
$confirm.notify("error")
return promise
renderEdit = (task) ->
$el.html($compile(templateEdit({task: task}))($scope))
$el.on "keyup", "input", (event) ->
if event.keyCode == 13
saveTask($model.$modelValue).then ->
renderView($model.$modelValue)
else if event.keyCode == 27
renderView($model.$modelValue)
$el.on "click", ".icon-floppy", (event) ->
saveTask($model.$modelValue).then ->
renderView($model.$modelValue)
$el.on "click", ".cancel-edit", (event) ->
renderView($model.$modelValue)
renderView = (task) ->
$el.off()
perms = {
modify_task: $scope.project.my_permissions.indexOf("modify_task") != -1
delete_task: $scope.project.my_permissions.indexOf("delete_task") != -1
}
$el.html($compile(templateView({task: task, perms: perms}))($scope))
$el.on "click", ".icon-edit", ->
renderEdit($model.$modelValue)
$el.find('input').focus().select()
$el.on "click", ".delete-task", (event) ->
#TODO: i18n
task = $model.$modelValue
title = "Delete Task"
message = task.subject
$confirm.askOnDelete(title, message).then (finish) ->
promise = $repo.remove(task)
promise.then ->
finish()
$confirm.notify("success")
$scope.$emit("related-tasks:delete")
promise.then null, ->
$confirm.notify("error")
$scope.$watch $attrs.ngModel, (val) ->
return if not val
renderView(val)
$scope.$on "related-tasks:assigned-to-changed", ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "related-tasks:status-changed", ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "$destroy", ->
$el.off()
return {link:link, require:"ngModel"}
module.directive("tgRelatedTaskRow", ["$tgRepo", "$compile", "$tgConfirm", "$rootScope", "$tgLoading", "$tgAnalytics", RelatedTaskRowDirective])
RelatedTaskCreateFormDirective = ($repo, $compile, $confirm, $tgmodel, $loading, $analytics) ->
template = _.template("""
<div class="tasks">
<div class="task-name">
<input type="text" placeholder="Type the new task subject" />
<div class="task-settings">
<a href="" title="Save" class="icon icon-floppy"></a>
<a href="" title="Cancel" class="icon icon-delete cancel-edit"></a>
</div>
</div>
</div>
<div tg-related-task-status="newTask" ng-model="newTask" class="status" not-auto-save="true">
<a href="" title="Status Name" class="task-status">
<span class="task-status-bind"></span>
<span class="icon icon-arrow-bottom"></span>
</a>
</div>
<div tg-related-task-assigned-to-inline-edition="newTask" class="assigned-to" not-auto-save="true">
<div title="Assigned to" class="task-assignedto">
<figure class="avatar"></figure>
<span class="icon icon-arrow-bottom"></span>
</div>
</div>
""")
newTask = {
subject: ""
assigned_to: null
}
link = ($scope, $el, $attrs) ->
createTask = debounce 2000, (task) ->
task.subject = $el.find('input').val()
task.assigned_to = $scope.newTask.assigned_to
task.status = $scope.newTask.status
$scope.newTask.status = $scope.project.default_task_status
$scope.newTask.assigned_to = null
$loading.start($el.find('.task-name'))
promise = $repo.create("tasks", task)
promise.then ->
$analytics.trackEvent("task", "create", "create task on userstory", 1)
$loading.finish($el.find('.task-name'))
$scope.$emit("related-tasks:add")
$confirm.notify("success")
promise.then null, ->
$el.find('input').val(task.subject)
$loading.finish($el.find('.task-name'))
$confirm.notify("error")
return promise
render = ->
$el.off()
$el.html($compile(template())($scope))
$el.find('input').focus().select()
$el.addClass('active')
$el.on "keyup", "input", (event)->
if event.keyCode == 13
createTask(newTask).then ->
render()
else if event.keyCode == 27
$el.html("")
$el.on "click", ".icon-delete", (event)->
$el.html("")
$el.on "click", ".icon-floppy", (event)->
createTask(newTask).then ->
$el.html("")
taiga.bindOnce $scope, "us", (val) ->
newTask["status"] = $scope.project.default_task_status
newTask["project"] = $scope.project.id
newTask["user_story"] = $scope.us.id
$scope.newTask = $tgmodel.make_model("tasks", newTask)
$el.html("")
$scope.$on "related-tasks:show-form", ->
render()
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTaskCreateForm", ["$tgRepo", "$compile", "$tgConfirm", "$tgModel", "$tgLoading", "$tgAnalytics", RelatedTaskCreateFormDirective])
RelatedTaskCreateButtonDirective = ($repo, $compile, $confirm, $tgmodel) ->
template = _.template("""
<a class="icon icon-plus related-tasks-buttons"></a>
""")
link = ($scope, $el, $attrs) ->
$scope.$watch "project", (val) ->
return if not val
$el.off()
if $scope.project.my_permissions.indexOf("add_task") != -1
$el.html(template())
else
$el.html("")
$el.on "click", ".icon", (event)->
$scope.$emit("related-tasks:add-new-clicked")
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTaskCreateButton", ["$tgRepo", "$compile", "$tgConfirm", "$tgModel", RelatedTaskCreateButtonDirective])
RelatedTasksDirective = ($repo, $rs, $rootscope) ->
link = ($scope, $el, $attrs) ->
loadTasks = ->
return $rs.tasks.list($scope.projectId, null, $scope.usId).then (tasks) =>
$scope.tasks = tasks
return tasks
$scope.$on "related-tasks:add", ->
loadTasks().then ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "related-tasks:delete", ->
loadTasks().then ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "related-tasks:add-new-clicked", ->
$scope.$broadcast("related-tasks:show-form")
taiga.bindOnce $scope, "us", (val) ->
loadTasks()
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTasks", ["$tgRepo", "$tgResources", "$rootScope", RelatedTasksDirective])
RelatedTaskAssignedToInlineEditionDirective = ($repo, $rootscope, popoverService) ->
template = _.template("""
<img src="<%- imgurl %>" alt="<%- name %>"/>
<figcaption><%- name %></figcaption>
""")
link = ($scope, $el, $attrs) ->
updateRelatedTask = (task) ->
ctx = {name: "Unassigned", imgurl: "/images/unnamed.png"}
member = $scope.usersById[task.assigned_to]
if member
ctx.imgurl = member.photo
ctx.name = member.full_name_display
$el.find(".avatar").html(template(ctx))
$el.find(".task-assignedto").attr('title', ctx.name)
$ctrl = $el.controller()
task = $scope.$eval($attrs.tgRelatedTaskAssignedToInlineEdition)
notAutoSave = $scope.$eval($attrs.notAutoSave)
autoSave = !notAutoSave
updateRelatedTask(task)
$el.on "click", ".task-assignedto", (event) ->
$rootscope.$broadcast("assigned-to:add", task)
taiga.bindOnce $scope, "project", (project) ->
# If the user has not enough permissions the click events are unbinded
if project.my_permissions.indexOf("modify_task") == -1
$el.unbind("click")
$el.find("a").addClass("not-clickable")
$scope.$on "assigned-to:added", debounce 2000, (ctx, userId, updatedRelatedTask) =>
if updatedRelatedTask.id == task.id
updatedRelatedTask.assigned_to = userId
if autoSave
$repo.save(updatedRelatedTask).then ->
$scope.$emit("related-tasks:assigned-to-changed")
updateRelatedTask(updatedRelatedTask)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTaskAssignedToInlineEdition", ["$tgRepo", "$rootScope", RelatedTaskAssignedToInlineEditionDirective])
| true | ###
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# File: modules/related-tasks.coffee
###
taiga = @.taiga
trim = @.taiga.trim
debounce = @.taiga.debounce
module = angular.module("taigaRelatedTasks", [])
RelatedTaskRowDirective = ($repo, $compile, $confirm, $rootscope, $loading) ->
templateView = _.template("""
<div class="tasks">
<div class="task-name">
<span class="icon icon-iocaine"></span>
<a tg-nav="project-tasks-detail:project=project.slug,ref=task.ref" title="<%- task.ref %> <%- task.subject %>" class="clickable">
<span>#<%- task.ref %></span>
<span><%- task.subject %></span>
</a>
<div class="task-settings">
<% if(perms.modify_task) { %>
<a href="" title="Edit" class="icon icon-edit"></a>
<% } %>
<% if(perms.delete_task) { %>
<a href="" title="Delete" class="icon icon-delete delete-task"></a>
<% } %>
</div>
</div>
</div>
<div tg-related-task-status="task" ng-model="task" class="status">
<a href="" title="Status Name" class="task-status">
<span class="task-status-bind"></span>
<% if(perms.modify_task) { %>
<span class="icon icon-arrow-bottom"></span>
<% } %>
</a>
</div>
<div tg-related-task-assigned-to-inline-edition="task" class="assigned-to">
<div title="Assigned to" class="task-assignedto <% if(perms.modify_task) { %>editable<% } %>">
<figure class="avatar"></figure>
<% if(perms.modify_task) { %>
<span class="icon icon-arrow-bottom"></span>
<% } %>
</div>
</div>
""")
templateEdit = _.template("""
<div class="tasks">
<div class="task-name">
<input type="text" value="<%- task.subject %>" placeholder="Type the task subject" />
<div class="task-settings">
<a href="" title="Save" class="icon icon-floppy"></a>
<a href="" title="Cancel" class="icon icon-delete cancel-edit"></a>
</div>
</div>
</div>
<div tg-related-task-status="task" ng-model="task" class="status">
<a href="" title="Status Name" class="task-status">
<span class="task-status-bind"></span>
<span class="icon icon-arrow-bottom"></span>
</a>
</div>
<div tg-related-task-assigned-to-inline-edition="task" class="assigned-to">
<div title="Assigned to" class="task-assignedto">
<figure class="avatar"></figure>
<span class="icon icon-arrow-bottom"></span>
</div>
</div>
""")
link = ($scope, $el, $attrs, $model) ->
saveTask = debounce 2000, (task) ->
task.subject = $el.find('input').val()
$loading.start($el.find('.task-name'))
promise = $repo.save(task)
promise.then =>
$loading.finish($el.find('.task-name'))
$confirm.notify("success")
$rootscope.$broadcast("related-tasks:update")
promise.then null, =>
$loading.finish($el.find('.task-name'))
$el.find('input').val(task.subject)
$confirm.notify("error")
return promise
renderEdit = (task) ->
$el.html($compile(templateEdit({task: task}))($scope))
$el.on "keyup", "input", (event) ->
if event.keyCode == 13
saveTask($model.$modelValue).then ->
renderView($model.$modelValue)
else if event.keyCode == 27
renderView($model.$modelValue)
$el.on "click", ".icon-floppy", (event) ->
saveTask($model.$modelValue).then ->
renderView($model.$modelValue)
$el.on "click", ".cancel-edit", (event) ->
renderView($model.$modelValue)
renderView = (task) ->
$el.off()
perms = {
modify_task: $scope.project.my_permissions.indexOf("modify_task") != -1
delete_task: $scope.project.my_permissions.indexOf("delete_task") != -1
}
$el.html($compile(templateView({task: task, perms: perms}))($scope))
$el.on "click", ".icon-edit", ->
renderEdit($model.$modelValue)
$el.find('input').focus().select()
$el.on "click", ".delete-task", (event) ->
#TODO: i18n
task = $model.$modelValue
title = "Delete Task"
message = task.subject
$confirm.askOnDelete(title, message).then (finish) ->
promise = $repo.remove(task)
promise.then ->
finish()
$confirm.notify("success")
$scope.$emit("related-tasks:delete")
promise.then null, ->
$confirm.notify("error")
$scope.$watch $attrs.ngModel, (val) ->
return if not val
renderView(val)
$scope.$on "related-tasks:assigned-to-changed", ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "related-tasks:status-changed", ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "$destroy", ->
$el.off()
return {link:link, require:"ngModel"}
module.directive("tgRelatedTaskRow", ["$tgRepo", "$compile", "$tgConfirm", "$rootScope", "$tgLoading", "$tgAnalytics", RelatedTaskRowDirective])
RelatedTaskCreateFormDirective = ($repo, $compile, $confirm, $tgmodel, $loading, $analytics) ->
template = _.template("""
<div class="tasks">
<div class="task-name">
<input type="text" placeholder="Type the new task subject" />
<div class="task-settings">
<a href="" title="Save" class="icon icon-floppy"></a>
<a href="" title="Cancel" class="icon icon-delete cancel-edit"></a>
</div>
</div>
</div>
<div tg-related-task-status="newTask" ng-model="newTask" class="status" not-auto-save="true">
<a href="" title="Status Name" class="task-status">
<span class="task-status-bind"></span>
<span class="icon icon-arrow-bottom"></span>
</a>
</div>
<div tg-related-task-assigned-to-inline-edition="newTask" class="assigned-to" not-auto-save="true">
<div title="Assigned to" class="task-assignedto">
<figure class="avatar"></figure>
<span class="icon icon-arrow-bottom"></span>
</div>
</div>
""")
newTask = {
subject: ""
assigned_to: null
}
link = ($scope, $el, $attrs) ->
createTask = debounce 2000, (task) ->
task.subject = $el.find('input').val()
task.assigned_to = $scope.newTask.assigned_to
task.status = $scope.newTask.status
$scope.newTask.status = $scope.project.default_task_status
$scope.newTask.assigned_to = null
$loading.start($el.find('.task-name'))
promise = $repo.create("tasks", task)
promise.then ->
$analytics.trackEvent("task", "create", "create task on userstory", 1)
$loading.finish($el.find('.task-name'))
$scope.$emit("related-tasks:add")
$confirm.notify("success")
promise.then null, ->
$el.find('input').val(task.subject)
$loading.finish($el.find('.task-name'))
$confirm.notify("error")
return promise
render = ->
$el.off()
$el.html($compile(template())($scope))
$el.find('input').focus().select()
$el.addClass('active')
$el.on "keyup", "input", (event)->
if event.keyCode == 13
createTask(newTask).then ->
render()
else if event.keyCode == 27
$el.html("")
$el.on "click", ".icon-delete", (event)->
$el.html("")
$el.on "click", ".icon-floppy", (event)->
createTask(newTask).then ->
$el.html("")
taiga.bindOnce $scope, "us", (val) ->
newTask["status"] = $scope.project.default_task_status
newTask["project"] = $scope.project.id
newTask["user_story"] = $scope.us.id
$scope.newTask = $tgmodel.make_model("tasks", newTask)
$el.html("")
$scope.$on "related-tasks:show-form", ->
render()
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTaskCreateForm", ["$tgRepo", "$compile", "$tgConfirm", "$tgModel", "$tgLoading", "$tgAnalytics", RelatedTaskCreateFormDirective])
RelatedTaskCreateButtonDirective = ($repo, $compile, $confirm, $tgmodel) ->
template = _.template("""
<a class="icon icon-plus related-tasks-buttons"></a>
""")
link = ($scope, $el, $attrs) ->
$scope.$watch "project", (val) ->
return if not val
$el.off()
if $scope.project.my_permissions.indexOf("add_task") != -1
$el.html(template())
else
$el.html("")
$el.on "click", ".icon", (event)->
$scope.$emit("related-tasks:add-new-clicked")
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTaskCreateButton", ["$tgRepo", "$compile", "$tgConfirm", "$tgModel", RelatedTaskCreateButtonDirective])
RelatedTasksDirective = ($repo, $rs, $rootscope) ->
link = ($scope, $el, $attrs) ->
loadTasks = ->
return $rs.tasks.list($scope.projectId, null, $scope.usId).then (tasks) =>
$scope.tasks = tasks
return tasks
$scope.$on "related-tasks:add", ->
loadTasks().then ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "related-tasks:delete", ->
loadTasks().then ->
$rootscope.$broadcast("related-tasks:update")
$scope.$on "related-tasks:add-new-clicked", ->
$scope.$broadcast("related-tasks:show-form")
taiga.bindOnce $scope, "us", (val) ->
loadTasks()
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTasks", ["$tgRepo", "$tgResources", "$rootScope", RelatedTasksDirective])
RelatedTaskAssignedToInlineEditionDirective = ($repo, $rootscope, popoverService) ->
template = _.template("""
<img src="<%- imgurl %>" alt="<%- name %>"/>
<figcaption><%- name %></figcaption>
""")
link = ($scope, $el, $attrs) ->
updateRelatedTask = (task) ->
ctx = {name: "Unassigned", imgurl: "/images/unnamed.png"}
member = $scope.usersById[task.assigned_to]
if member
ctx.imgurl = member.photo
ctx.name = member.full_name_display
$el.find(".avatar").html(template(ctx))
$el.find(".task-assignedto").attr('title', ctx.name)
$ctrl = $el.controller()
task = $scope.$eval($attrs.tgRelatedTaskAssignedToInlineEdition)
notAutoSave = $scope.$eval($attrs.notAutoSave)
autoSave = !notAutoSave
updateRelatedTask(task)
$el.on "click", ".task-assignedto", (event) ->
$rootscope.$broadcast("assigned-to:add", task)
taiga.bindOnce $scope, "project", (project) ->
# If the user has not enough permissions the click events are unbinded
if project.my_permissions.indexOf("modify_task") == -1
$el.unbind("click")
$el.find("a").addClass("not-clickable")
$scope.$on "assigned-to:added", debounce 2000, (ctx, userId, updatedRelatedTask) =>
if updatedRelatedTask.id == task.id
updatedRelatedTask.assigned_to = userId
if autoSave
$repo.save(updatedRelatedTask).then ->
$scope.$emit("related-tasks:assigned-to-changed")
updateRelatedTask(updatedRelatedTask)
$scope.$on "$destroy", ->
$el.off()
return {link: link}
module.directive("tgRelatedTaskAssignedToInlineEdition", ["$tgRepo", "$rootScope", RelatedTaskAssignedToInlineEditionDirective])
|
[
{
"context": "n\n\t\texpiration = expiration.toISOString()\n\n\t\tkey = \"#{ops.path}/#{ops.file_name}\"\n\n\t\tpolicy =\n\t\t\t\"expiration\":expiration\n\t\t\t\"condit",
"end": 650,
"score": 0.9953253865242004,
"start": 620,
"tag": "KEY",
"value": "\"#{ops.path}/#{ops.file_name}\""
}
] | server/sign_request.coffee | mli-r7/S3 | 0 | Meteor.methods
_s3_sign: (ops={}) ->
@unblock()
# ops.expiration: the signature expires after x milliseconds | defaults to 30 minutes
# ops.path
# ops.file_type
# ops.file_name
# ops.file_size
# ops.acl
# ops.bucket
_.defaults ops,
expiration:1800000
path:""
bucket:S3.config.bucket
acl:"public-read"
region:S3.config.region
check ops,
expiration:Number
path:String
bucket:String
acl:String
region:String
file_type:String
file_name:String
file_size:Number
expiration = new Date Date.now() + ops.expiration
expiration = expiration.toISOString()
key = "#{ops.path}/#{ops.file_name}"
policy =
"expiration":expiration
"conditions":[
["content-length-range",0,ops.file_size]
{"key":key}
{"bucket":ops.bucket}
{"Content-Type":ops.file_type}
{"acl":ops.acl}
{"Content-Disposition":"inline; filename='#{ops.file_name}'"}
]
# Encode the policy
policy = Buffer(JSON.stringify(policy), "utf-8").toString("base64")
# Sign the policy
signature = calculate_signature policy
# Identify post_url
if ops.region is "us-east-1" or ops.region is "us-standard"
post_url = "https://s3.amazonaws.com/#{ops.bucket}"
else
post_url = "https://s3-#{ops.region}.amazonaws.com/#{ops.bucket}"
# Return results
policy:policy
signature:signature
access_key:S3.config.key
post_url:post_url
url:"#{post_url}/#{key}".replace("https://","http://")
secure_url:"#{post_url}/#{key}"
relative_url:"/#{key}"
bucket:ops.bucket
acl:ops.acl
key:key
file_type:ops.file_type
file_name:ops.file_name
crypto = Npm.require("crypto")
calculate_signature = (policy) ->
crypto.createHmac("sha1", S3.config.secret)
.update(new Buffer(policy, "utf-8"))
.digest("base64")
| 95107 | Meteor.methods
_s3_sign: (ops={}) ->
@unblock()
# ops.expiration: the signature expires after x milliseconds | defaults to 30 minutes
# ops.path
# ops.file_type
# ops.file_name
# ops.file_size
# ops.acl
# ops.bucket
_.defaults ops,
expiration:1800000
path:""
bucket:S3.config.bucket
acl:"public-read"
region:S3.config.region
check ops,
expiration:Number
path:String
bucket:String
acl:String
region:String
file_type:String
file_name:String
file_size:Number
expiration = new Date Date.now() + ops.expiration
expiration = expiration.toISOString()
key = <KEY>
policy =
"expiration":expiration
"conditions":[
["content-length-range",0,ops.file_size]
{"key":key}
{"bucket":ops.bucket}
{"Content-Type":ops.file_type}
{"acl":ops.acl}
{"Content-Disposition":"inline; filename='#{ops.file_name}'"}
]
# Encode the policy
policy = Buffer(JSON.stringify(policy), "utf-8").toString("base64")
# Sign the policy
signature = calculate_signature policy
# Identify post_url
if ops.region is "us-east-1" or ops.region is "us-standard"
post_url = "https://s3.amazonaws.com/#{ops.bucket}"
else
post_url = "https://s3-#{ops.region}.amazonaws.com/#{ops.bucket}"
# Return results
policy:policy
signature:signature
access_key:S3.config.key
post_url:post_url
url:"#{post_url}/#{key}".replace("https://","http://")
secure_url:"#{post_url}/#{key}"
relative_url:"/#{key}"
bucket:ops.bucket
acl:ops.acl
key:key
file_type:ops.file_type
file_name:ops.file_name
crypto = Npm.require("crypto")
calculate_signature = (policy) ->
crypto.createHmac("sha1", S3.config.secret)
.update(new Buffer(policy, "utf-8"))
.digest("base64")
| true | Meteor.methods
_s3_sign: (ops={}) ->
@unblock()
# ops.expiration: the signature expires after x milliseconds | defaults to 30 minutes
# ops.path
# ops.file_type
# ops.file_name
# ops.file_size
# ops.acl
# ops.bucket
_.defaults ops,
expiration:1800000
path:""
bucket:S3.config.bucket
acl:"public-read"
region:S3.config.region
check ops,
expiration:Number
path:String
bucket:String
acl:String
region:String
file_type:String
file_name:String
file_size:Number
expiration = new Date Date.now() + ops.expiration
expiration = expiration.toISOString()
key = PI:KEY:<KEY>END_PI
policy =
"expiration":expiration
"conditions":[
["content-length-range",0,ops.file_size]
{"key":key}
{"bucket":ops.bucket}
{"Content-Type":ops.file_type}
{"acl":ops.acl}
{"Content-Disposition":"inline; filename='#{ops.file_name}'"}
]
# Encode the policy
policy = Buffer(JSON.stringify(policy), "utf-8").toString("base64")
# Sign the policy
signature = calculate_signature policy
# Identify post_url
if ops.region is "us-east-1" or ops.region is "us-standard"
post_url = "https://s3.amazonaws.com/#{ops.bucket}"
else
post_url = "https://s3-#{ops.region}.amazonaws.com/#{ops.bucket}"
# Return results
policy:policy
signature:signature
access_key:S3.config.key
post_url:post_url
url:"#{post_url}/#{key}".replace("https://","http://")
secure_url:"#{post_url}/#{key}"
relative_url:"/#{key}"
bucket:ops.bucket
acl:ops.acl
key:key
file_type:ops.file_type
file_name:ops.file_name
crypto = Npm.require("crypto")
calculate_signature = (policy) ->
crypto.createHmac("sha1", S3.config.secret)
.update(new Buffer(policy, "utf-8"))
.digest("base64")
|
[
{
"context": ") 2013-2014 TheGrid (Rituwall Inc.)\n# (c) 2013 Henri Bergius, Nemein\n# NoFlo may be freely distributed und",
"end": 124,
"score": 0.9998469352722168,
"start": 111,
"tag": "NAME",
"value": "Henri Bergius"
},
{
"context": "Grid (Rituwall Inc.)\n# (c) 2013 He... | src/lib/ComponentLoader.coffee | jonnor/noflo | 1 | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2014 TheGrid (Rituwall Inc.)
# (c) 2013 Henri Bergius, Nemein
# NoFlo may be freely distributed under the MIT license
#
# This is the browser version of the ComponentLoader.
internalSocket = require './InternalSocket'
nofloGraph = require './Graph'
utils = require './Utils'
{EventEmitter} = require 'events'
class ComponentLoader extends EventEmitter
constructor: (@baseDir, @options = {}) ->
@components = null
@componentLoaders = []
@checked = []
@revalidate = false
@libraryIcons = {}
@processing = false
@ready = false
getModulePrefix: (name) ->
return '' unless name
return '' if name is 'noflo'
name = name.replace /\@[a-z\-]+\//, '' if name[0] is '@'
name.replace 'noflo-', ''
getModuleComponents: (moduleName) ->
return unless @checked.indexOf(moduleName) is -1
@checked.push moduleName
try
definition = require "/#{moduleName}/component.json"
catch e
if moduleName.substr(0, 1) is '/'
return @getModuleComponents "noflo-#{moduleName.substr(1)}"
return
for dependency of definition.dependencies
@getModuleComponents dependency.replace '/', '-'
return unless definition.noflo
prefix = @getModulePrefix definition.name
if definition.noflo.icon
@libraryIcons[prefix] = definition.noflo.icon
if moduleName[0] is '/'
moduleName = moduleName.substr 1
if definition.noflo.loader
# Run a custom component loader
loaderPath = "/#{moduleName}/#{definition.noflo.loader}"
@componentLoaders.push loaderPath
loader = require loaderPath
@registerLoader loader, ->
if definition.noflo.components
for name, cPath of definition.noflo.components
if cPath.indexOf('.coffee') isnt -1
cPath = cPath.replace '.coffee', '.js'
if cPath.substr(0, 2) is './'
cPath = cPath.substr 2
@registerComponent prefix, name, "/#{moduleName}/#{cPath}"
if definition.noflo.graphs
for name, cPath of definition.noflo.graphs
@registerGraph prefix, name, "/#{moduleName}/#{cPath}"
listComponents: (callback) ->
if @processing
@once 'ready', =>
callback @components
return
return callback @components if @components
@ready = false
@processing = true
setTimeout =>
@components = {}
@getModuleComponents @baseDir
@processing = false
@ready = true
@emit 'ready', true
callback @components if callback
, 1
load: (name, callback, metadata) ->
unless @ready
@listComponents =>
@load name, callback, metadata
return
component = @components[name]
unless component
# Try an alias
for componentName of @components
if componentName.split('/')[1] is name
component = @components[componentName]
break
unless component
# Failure to load
callback new Error "Component #{name} not available with base #{@baseDir}"
return
if @isGraph component
if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1
# nextTick is faster on Node.js
process.nextTick =>
@loadGraph name, component, callback, metadata
else
setTimeout =>
@loadGraph name, component, callback, metadata
, 0
return
@createComponent name, component, metadata, (err, instance) =>
return callback err if err
if not instance
callback new Error "Component #{name} could not be loaded."
return
instance.baseDir = @baseDir if name is 'Graph'
@setIcon name, instance
callback null, instance
# Creates an instance of a component.
createComponent: (name, component, metadata, callback) ->
implementation = component
# If a string was specified, attempt to `require` it.
if typeof implementation is 'string'
try
implementation = require implementation
catch e
return callback e
# Attempt to create the component instance using the `getComponent` method.
if typeof implementation.getComponent is 'function'
instance = implementation.getComponent metadata
# Attempt to create a component using a factory function.
else if typeof implementation is 'function'
instance = implementation metadata
else
callback new Error "Invalid type #{typeof(implementation)} for component #{name}."
return
instance.componentName = name if typeof name is 'string'
callback null, instance
isGraph: (cPath) ->
return true if typeof cPath is 'object' and cPath instanceof nofloGraph.Graph
return false unless typeof cPath is 'string'
cPath.indexOf('.fbp') isnt -1 or cPath.indexOf('.json') isnt -1
loadGraph: (name, component, callback, metadata) ->
graphImplementation = require @components['Graph']
graphSocket = internalSocket.createSocket()
graph = graphImplementation.getComponent metadata
graph.loader = @
graph.baseDir = @baseDir
graph.inPorts.graph.attach graphSocket
graph.componentName = name if typeof name is 'string'
graphSocket.send component
graphSocket.disconnect()
graph.inPorts.remove 'graph'
@setIcon name, graph
callback null, graph
setIcon: (name, instance) ->
# See if component has an icon
return if not instance.getIcon or instance.getIcon()
# See if library has an icon
[library, componentName] = name.split '/'
if componentName and @getLibraryIcon library
instance.setIcon @getLibraryIcon library
return
# See if instance is a subgraph
if instance.isSubgraph()
instance.setIcon 'sitemap'
return
instance.setIcon 'square'
return
getLibraryIcon: (prefix) ->
if @libraryIcons[prefix]
return @libraryIcons[prefix]
return null
normalizeName: (packageId, name) ->
prefix = @getModulePrefix packageId
fullName = "#{prefix}/#{name}"
fullName = name unless packageId
fullName
registerComponent: (packageId, name, cPath, callback) ->
fullName = @normalizeName packageId, name
@components[fullName] = cPath
do callback if callback
registerGraph: (packageId, name, gPath, callback) ->
@registerComponent packageId, name, gPath, callback
registerLoader: (loader, callback) ->
loader @, callback
setSource: (packageId, name, source, language, callback) ->
unless @ready
@listComponents =>
@setSource packageId, name, source, language, callback
return
if language is 'coffeescript'
unless window.CoffeeScript
return callback new Error 'CoffeeScript compiler not available'
try
source = CoffeeScript.compile source,
bare: true
catch e
return callback e
else if language in ['es6', 'es2015']
unless window.babel
return callback new Error 'Babel compiler not available'
try
source = babel.transform(source).code
catch e
return callback e
# We eval the contents to get a runnable component
try
# Modify require path for NoFlo since we're inside the NoFlo context
source = source.replace "require('noflo')", "require('./NoFlo')"
source = source.replace 'require("noflo")', 'require("./NoFlo")'
# Eval so we can get a function
implementation = eval "(function () { var exports = {}; #{source}; return exports; })()"
catch e
return callback e
unless implementation or implementation.getComponent
return callback new Error 'Provided source failed to create a runnable component'
@registerComponent packageId, name, implementation, ->
callback null
getSource: (name, callback) ->
unless @ready
@listComponents =>
@getSource name, callback
return
component = @components[name]
unless component
# Try an alias
for componentName of @components
if componentName.split('/')[1] is name
component = @components[componentName]
name = componentName
break
unless component
return callback new Error "Component #{name} not installed"
if typeof component isnt 'string'
return callback new Error "Can't provide source for #{name}. Not a file"
nameParts = name.split '/'
if nameParts.length is 1
nameParts[1] = nameParts[0]
nameParts[0] = ''
if @isGraph component
nofloGraph.loadFile component, (graph) ->
return callback new Error 'Unable to load graph' unless graph
callback null,
name: nameParts[1]
library: nameParts[0]
code: JSON.stringify graph.toJSON()
language: 'json'
return
path = window.require.resolve component
unless path
return callback new Error "Component #{name} is not resolvable to a path"
callback null,
name: nameParts[1]
library: nameParts[0]
code: window.require.modules[path].toString()
language: utils.guessLanguageFromFilename component
clear: ->
@components = null
@checked = []
@revalidate = true
@ready = false
@processing = false
exports.ComponentLoader = ComponentLoader
| 85478 | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2014 TheGrid (Rituwall Inc.)
# (c) 2013 <NAME>, <NAME>
# NoFlo may be freely distributed under the MIT license
#
# This is the browser version of the ComponentLoader.
internalSocket = require './InternalSocket'
nofloGraph = require './Graph'
utils = require './Utils'
{EventEmitter} = require 'events'
class ComponentLoader extends EventEmitter
constructor: (@baseDir, @options = {}) ->
@components = null
@componentLoaders = []
@checked = []
@revalidate = false
@libraryIcons = {}
@processing = false
@ready = false
getModulePrefix: (name) ->
return '' unless name
return '' if name is 'noflo'
name = name.replace /\@[a-z\-]+\//, '' if name[0] is '@'
name.replace 'noflo-', ''
getModuleComponents: (moduleName) ->
return unless @checked.indexOf(moduleName) is -1
@checked.push moduleName
try
definition = require "/#{moduleName}/component.json"
catch e
if moduleName.substr(0, 1) is '/'
return @getModuleComponents "noflo-#{moduleName.substr(1)}"
return
for dependency of definition.dependencies
@getModuleComponents dependency.replace '/', '-'
return unless definition.noflo
prefix = @getModulePrefix definition.name
if definition.noflo.icon
@libraryIcons[prefix] = definition.noflo.icon
if moduleName[0] is '/'
moduleName = moduleName.substr 1
if definition.noflo.loader
# Run a custom component loader
loaderPath = "/#{moduleName}/#{definition.noflo.loader}"
@componentLoaders.push loaderPath
loader = require loaderPath
@registerLoader loader, ->
if definition.noflo.components
for name, cPath of definition.noflo.components
if cPath.indexOf('.coffee') isnt -1
cPath = cPath.replace '.coffee', '.js'
if cPath.substr(0, 2) is './'
cPath = cPath.substr 2
@registerComponent prefix, name, "/#{moduleName}/#{cPath}"
if definition.noflo.graphs
for name, cPath of definition.noflo.graphs
@registerGraph prefix, name, "/#{moduleName}/#{cPath}"
listComponents: (callback) ->
if @processing
@once 'ready', =>
callback @components
return
return callback @components if @components
@ready = false
@processing = true
setTimeout =>
@components = {}
@getModuleComponents @baseDir
@processing = false
@ready = true
@emit 'ready', true
callback @components if callback
, 1
load: (name, callback, metadata) ->
unless @ready
@listComponents =>
@load name, callback, metadata
return
component = @components[name]
unless component
# Try an alias
for componentName of @components
if componentName.split('/')[1] is name
component = @components[componentName]
break
unless component
# Failure to load
callback new Error "Component #{name} not available with base #{@baseDir}"
return
if @isGraph component
if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1
# nextTick is faster on Node.js
process.nextTick =>
@loadGraph name, component, callback, metadata
else
setTimeout =>
@loadGraph name, component, callback, metadata
, 0
return
@createComponent name, component, metadata, (err, instance) =>
return callback err if err
if not instance
callback new Error "Component #{name} could not be loaded."
return
instance.baseDir = @baseDir if name is 'Graph'
@setIcon name, instance
callback null, instance
# Creates an instance of a component.
createComponent: (name, component, metadata, callback) ->
implementation = component
# If a string was specified, attempt to `require` it.
if typeof implementation is 'string'
try
implementation = require implementation
catch e
return callback e
# Attempt to create the component instance using the `getComponent` method.
if typeof implementation.getComponent is 'function'
instance = implementation.getComponent metadata
# Attempt to create a component using a factory function.
else if typeof implementation is 'function'
instance = implementation metadata
else
callback new Error "Invalid type #{typeof(implementation)} for component #{name}."
return
instance.componentName = name if typeof name is 'string'
callback null, instance
isGraph: (cPath) ->
return true if typeof cPath is 'object' and cPath instanceof nofloGraph.Graph
return false unless typeof cPath is 'string'
cPath.indexOf('.fbp') isnt -1 or cPath.indexOf('.json') isnt -1
loadGraph: (name, component, callback, metadata) ->
graphImplementation = require @components['Graph']
graphSocket = internalSocket.createSocket()
graph = graphImplementation.getComponent metadata
graph.loader = @
graph.baseDir = @baseDir
graph.inPorts.graph.attach graphSocket
graph.componentName = name if typeof name is 'string'
graphSocket.send component
graphSocket.disconnect()
graph.inPorts.remove 'graph'
@setIcon name, graph
callback null, graph
setIcon: (name, instance) ->
# See if component has an icon
return if not instance.getIcon or instance.getIcon()
# See if library has an icon
[library, componentName] = name.split '/'
if componentName and @getLibraryIcon library
instance.setIcon @getLibraryIcon library
return
# See if instance is a subgraph
if instance.isSubgraph()
instance.setIcon 'sitemap'
return
instance.setIcon 'square'
return
getLibraryIcon: (prefix) ->
if @libraryIcons[prefix]
return @libraryIcons[prefix]
return null
normalizeName: (packageId, name) ->
prefix = @getModulePrefix packageId
fullName = "#{prefix}/#{name}"
fullName = name unless packageId
fullName
registerComponent: (packageId, name, cPath, callback) ->
fullName = @normalizeName packageId, name
@components[fullName] = cPath
do callback if callback
registerGraph: (packageId, name, gPath, callback) ->
@registerComponent packageId, name, gPath, callback
registerLoader: (loader, callback) ->
loader @, callback
setSource: (packageId, name, source, language, callback) ->
unless @ready
@listComponents =>
@setSource packageId, name, source, language, callback
return
if language is 'coffeescript'
unless window.CoffeeScript
return callback new Error 'CoffeeScript compiler not available'
try
source = CoffeeScript.compile source,
bare: true
catch e
return callback e
else if language in ['es6', 'es2015']
unless window.babel
return callback new Error 'Babel compiler not available'
try
source = babel.transform(source).code
catch e
return callback e
# We eval the contents to get a runnable component
try
# Modify require path for NoFlo since we're inside the NoFlo context
source = source.replace "require('noflo')", "require('./NoFlo')"
source = source.replace 'require("noflo")', 'require("./NoFlo")'
# Eval so we can get a function
implementation = eval "(function () { var exports = {}; #{source}; return exports; })()"
catch e
return callback e
unless implementation or implementation.getComponent
return callback new Error 'Provided source failed to create a runnable component'
@registerComponent packageId, name, implementation, ->
callback null
getSource: (name, callback) ->
unless @ready
@listComponents =>
@getSource name, callback
return
component = @components[name]
unless component
# Try an alias
for componentName of @components
if componentName.split('/')[1] is name
component = @components[componentName]
name = componentName
break
unless component
return callback new Error "Component #{name} not installed"
if typeof component isnt 'string'
return callback new Error "Can't provide source for #{name}. Not a file"
nameParts = name.split '/'
if nameParts.length is 1
nameParts[1] = nameParts[0]
nameParts[0] = ''
if @isGraph component
nofloGraph.loadFile component, (graph) ->
return callback new Error 'Unable to load graph' unless graph
callback null,
name: nameParts[1]
library: nameParts[0]
code: JSON.stringify graph.toJSON()
language: 'json'
return
path = window.require.resolve component
unless path
return callback new Error "Component #{name} is not resolvable to a path"
callback null,
name: nameParts[1]
library: nameParts[0]
code: window.require.modules[path].toString()
language: utils.guessLanguageFromFilename component
clear: ->
@components = null
@checked = []
@revalidate = true
@ready = false
@processing = false
exports.ComponentLoader = ComponentLoader
| true | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2014 TheGrid (Rituwall Inc.)
# (c) 2013 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
# NoFlo may be freely distributed under the MIT license
#
# This is the browser version of the ComponentLoader.
internalSocket = require './InternalSocket'
nofloGraph = require './Graph'
utils = require './Utils'
{EventEmitter} = require 'events'
class ComponentLoader extends EventEmitter
constructor: (@baseDir, @options = {}) ->
@components = null
@componentLoaders = []
@checked = []
@revalidate = false
@libraryIcons = {}
@processing = false
@ready = false
getModulePrefix: (name) ->
return '' unless name
return '' if name is 'noflo'
name = name.replace /\@[a-z\-]+\//, '' if name[0] is '@'
name.replace 'noflo-', ''
getModuleComponents: (moduleName) ->
return unless @checked.indexOf(moduleName) is -1
@checked.push moduleName
try
definition = require "/#{moduleName}/component.json"
catch e
if moduleName.substr(0, 1) is '/'
return @getModuleComponents "noflo-#{moduleName.substr(1)}"
return
for dependency of definition.dependencies
@getModuleComponents dependency.replace '/', '-'
return unless definition.noflo
prefix = @getModulePrefix definition.name
if definition.noflo.icon
@libraryIcons[prefix] = definition.noflo.icon
if moduleName[0] is '/'
moduleName = moduleName.substr 1
if definition.noflo.loader
# Run a custom component loader
loaderPath = "/#{moduleName}/#{definition.noflo.loader}"
@componentLoaders.push loaderPath
loader = require loaderPath
@registerLoader loader, ->
if definition.noflo.components
for name, cPath of definition.noflo.components
if cPath.indexOf('.coffee') isnt -1
cPath = cPath.replace '.coffee', '.js'
if cPath.substr(0, 2) is './'
cPath = cPath.substr 2
@registerComponent prefix, name, "/#{moduleName}/#{cPath}"
if definition.noflo.graphs
for name, cPath of definition.noflo.graphs
@registerGraph prefix, name, "/#{moduleName}/#{cPath}"
listComponents: (callback) ->
if @processing
@once 'ready', =>
callback @components
return
return callback @components if @components
@ready = false
@processing = true
setTimeout =>
@components = {}
@getModuleComponents @baseDir
@processing = false
@ready = true
@emit 'ready', true
callback @components if callback
, 1
load: (name, callback, metadata) ->
unless @ready
@listComponents =>
@load name, callback, metadata
return
component = @components[name]
unless component
# Try an alias
for componentName of @components
if componentName.split('/')[1] is name
component = @components[componentName]
break
unless component
# Failure to load
callback new Error "Component #{name} not available with base #{@baseDir}"
return
if @isGraph component
if typeof process isnt 'undefined' and process.execPath and process.execPath.indexOf('node') isnt -1
# nextTick is faster on Node.js
process.nextTick =>
@loadGraph name, component, callback, metadata
else
setTimeout =>
@loadGraph name, component, callback, metadata
, 0
return
@createComponent name, component, metadata, (err, instance) =>
return callback err if err
if not instance
callback new Error "Component #{name} could not be loaded."
return
instance.baseDir = @baseDir if name is 'Graph'
@setIcon name, instance
callback null, instance
# Creates an instance of a component.
createComponent: (name, component, metadata, callback) ->
implementation = component
# If a string was specified, attempt to `require` it.
if typeof implementation is 'string'
try
implementation = require implementation
catch e
return callback e
# Attempt to create the component instance using the `getComponent` method.
if typeof implementation.getComponent is 'function'
instance = implementation.getComponent metadata
# Attempt to create a component using a factory function.
else if typeof implementation is 'function'
instance = implementation metadata
else
callback new Error "Invalid type #{typeof(implementation)} for component #{name}."
return
instance.componentName = name if typeof name is 'string'
callback null, instance
isGraph: (cPath) ->
return true if typeof cPath is 'object' and cPath instanceof nofloGraph.Graph
return false unless typeof cPath is 'string'
cPath.indexOf('.fbp') isnt -1 or cPath.indexOf('.json') isnt -1
loadGraph: (name, component, callback, metadata) ->
graphImplementation = require @components['Graph']
graphSocket = internalSocket.createSocket()
graph = graphImplementation.getComponent metadata
graph.loader = @
graph.baseDir = @baseDir
graph.inPorts.graph.attach graphSocket
graph.componentName = name if typeof name is 'string'
graphSocket.send component
graphSocket.disconnect()
graph.inPorts.remove 'graph'
@setIcon name, graph
callback null, graph
setIcon: (name, instance) ->
# See if component has an icon
return if not instance.getIcon or instance.getIcon()
# See if library has an icon
[library, componentName] = name.split '/'
if componentName and @getLibraryIcon library
instance.setIcon @getLibraryIcon library
return
# See if instance is a subgraph
if instance.isSubgraph()
instance.setIcon 'sitemap'
return
instance.setIcon 'square'
return
getLibraryIcon: (prefix) ->
if @libraryIcons[prefix]
return @libraryIcons[prefix]
return null
normalizeName: (packageId, name) ->
prefix = @getModulePrefix packageId
fullName = "#{prefix}/#{name}"
fullName = name unless packageId
fullName
registerComponent: (packageId, name, cPath, callback) ->
fullName = @normalizeName packageId, name
@components[fullName] = cPath
do callback if callback
registerGraph: (packageId, name, gPath, callback) ->
@registerComponent packageId, name, gPath, callback
registerLoader: (loader, callback) ->
loader @, callback
setSource: (packageId, name, source, language, callback) ->
unless @ready
@listComponents =>
@setSource packageId, name, source, language, callback
return
if language is 'coffeescript'
unless window.CoffeeScript
return callback new Error 'CoffeeScript compiler not available'
try
source = CoffeeScript.compile source,
bare: true
catch e
return callback e
else if language in ['es6', 'es2015']
unless window.babel
return callback new Error 'Babel compiler not available'
try
source = babel.transform(source).code
catch e
return callback e
# We eval the contents to get a runnable component
try
# Modify require path for NoFlo since we're inside the NoFlo context
source = source.replace "require('noflo')", "require('./NoFlo')"
source = source.replace 'require("noflo")', 'require("./NoFlo")'
# Eval so we can get a function
implementation = eval "(function () { var exports = {}; #{source}; return exports; })()"
catch e
return callback e
unless implementation or implementation.getComponent
return callback new Error 'Provided source failed to create a runnable component'
@registerComponent packageId, name, implementation, ->
callback null
getSource: (name, callback) ->
unless @ready
@listComponents =>
@getSource name, callback
return
component = @components[name]
unless component
# Try an alias
for componentName of @components
if componentName.split('/')[1] is name
component = @components[componentName]
name = componentName
break
unless component
return callback new Error "Component #{name} not installed"
if typeof component isnt 'string'
return callback new Error "Can't provide source for #{name}. Not a file"
nameParts = name.split '/'
if nameParts.length is 1
nameParts[1] = nameParts[0]
nameParts[0] = ''
if @isGraph component
nofloGraph.loadFile component, (graph) ->
return callback new Error 'Unable to load graph' unless graph
callback null,
name: nameParts[1]
library: nameParts[0]
code: JSON.stringify graph.toJSON()
language: 'json'
return
path = window.require.resolve component
unless path
return callback new Error "Component #{name} is not resolvable to a path"
callback null,
name: nameParts[1]
library: nameParts[0]
code: window.require.modules[path].toString()
language: utils.guessLanguageFromFilename component
clear: ->
@components = null
@checked = []
@revalidate = true
@ready = false
@processing = false
exports.ComponentLoader = ComponentLoader
|
[
{
"context": "SON OT type.\n#\n# Spec is here: https://github.com/josephg/ShareJS/wiki/JSON-Operations\n\nif WEB?\n text = ex",
"end": 94,
"score": 0.9997073411941528,
"start": 87,
"tag": "USERNAME",
"value": "josephg"
},
{
"context": "entkey = null\n elem = container\n ke... | public/coffee/ide/editor/sharejs/vendor/types/json.coffee | mickaobrien/web-sharelatex | 1 | # This is the implementation of the JSON OT type.
#
# Spec is here: https://github.com/josephg/ShareJS/wiki/JSON-Operations
if WEB?
text = exports.types.text
else
text = require './text'
json = {}
json.name = 'json'
json.create = -> null
json.invertComponent = (c) ->
c_ = {p: c.p}
c_.sd = c.si if c.si != undefined
c_.si = c.sd if c.sd != undefined
c_.od = c.oi if c.oi != undefined
c_.oi = c.od if c.od != undefined
c_.ld = c.li if c.li != undefined
c_.li = c.ld if c.ld != undefined
c_.na = -c.na if c.na != undefined
if c.lm != undefined
c_.lm = c.p[c.p.length-1]
c_.p = c.p[0...c.p.length - 1].concat([c.lm])
c_
json.invert = (op) -> json.invertComponent c for c in op.slice().reverse()
json.checkValidOp = (op) ->
isArray = (o) -> Object.prototype.toString.call(o) == '[object Array]'
json.checkList = (elem) ->
throw new Error 'Referenced element not a list' unless isArray(elem)
json.checkObj = (elem) ->
throw new Error "Referenced element not an object (it was #{JSON.stringify elem})" unless elem.constructor is Object
json.apply = (snapshot, op) ->
json.checkValidOp op
op = clone op
container = {data: clone snapshot}
try
for c, i in op
parent = null
parentkey = null
elem = container
key = 'data'
for p in c.p
parent = elem
parentkey = key
elem = elem[key]
key = p
throw new Error 'Path invalid' unless parent?
if c.na != undefined
# Number add
throw new Error 'Referenced element not a number' unless typeof elem[key] is 'number'
elem[key] += c.na
else if c.si != undefined
# String insert
throw new Error "Referenced element not a string (it was #{JSON.stringify elem})" unless typeof elem is 'string'
parent[parentkey] = elem[...key] + c.si + elem[key..]
else if c.sd != undefined
# String delete
throw new Error 'Referenced element not a string' unless typeof elem is 'string'
throw new Error 'Deleted string does not match' unless elem[key...key + c.sd.length] == c.sd
parent[parentkey] = elem[...key] + elem[key + c.sd.length..]
else if c.li != undefined && c.ld != undefined
# List replace
json.checkList elem
# Should check the list element matches c.ld
elem[key] = c.li
else if c.li != undefined
# List insert
json.checkList elem
elem.splice key, 0, c.li
else if c.ld != undefined
# List delete
json.checkList elem
# Should check the list element matches c.ld here too.
elem.splice key, 1
else if c.lm != undefined
# List move
json.checkList elem
if c.lm != key
e = elem[key]
# Remove it...
elem.splice key, 1
# And insert it back.
elem.splice c.lm, 0, e
else if c.oi != undefined
# Object insert / replace
json.checkObj elem
# Should check that elem[key] == c.od
elem[key] = c.oi
else if c.od != undefined
# Object delete
json.checkObj elem
# Should check that elem[key] == c.od
delete elem[key]
else
throw new Error 'invalid / missing instruction in op'
catch error
# TODO: Roll back all already applied changes. Write tests before implementing this code.
throw error
container.data
# Checks if two paths, p1 and p2 match.
json.pathMatches = (p1, p2, ignoreLast) ->
return false unless p1.length == p2.length
for p, i in p1
return false if p != p2[i] and (!ignoreLast or i != p1.length - 1)
true
json.append = (dest, c) ->
c = clone c
if dest.length != 0 and json.pathMatches c.p, (last = dest[dest.length - 1]).p
if last.na != undefined and c.na != undefined
dest[dest.length - 1] = { p: last.p, na: last.na + c.na }
else if last.li != undefined and c.li == undefined and c.ld == last.li
# insert immediately followed by delete becomes a noop.
if last.ld != undefined
# leave the delete part of the replace
delete last.li
else
dest.pop()
else if last.od != undefined and last.oi == undefined and
c.oi != undefined and c.od == undefined
last.oi = c.oi
else if c.lm != undefined and c.p[c.p.length-1] == c.lm
null # don't do anything
else
dest.push c
else
dest.push c
json.compose = (op1, op2) ->
json.checkValidOp op1
json.checkValidOp op2
newOp = clone op1
json.append newOp, c for c in op2
newOp
json.normalize = (op) ->
newOp = []
op = [op] unless isArray op
for c in op
c.p ?= []
json.append newOp, c
newOp
# hax, copied from test/types/json. Apparently this is still the fastest way to deep clone an object, assuming
# we have browser support for JSON.
# http://jsperf.com/cloning-an-object/12
clone = (o) -> JSON.parse(JSON.stringify o)
json.commonPath = (p1, p2) ->
p1 = p1.slice()
p2 = p2.slice()
p1.unshift('data')
p2.unshift('data')
p1 = p1[...p1.length-1]
p2 = p2[...p2.length-1]
return -1 if p2.length == 0
i = 0
while p1[i] == p2[i] && i < p1.length
i++
if i == p2.length
return i-1
return
# transform c so it applies to a document with otherC applied.
json.transformComponent = (dest, c, otherC, type) ->
c = clone c
c.p.push(0) if c.na != undefined
otherC.p.push(0) if otherC.na != undefined
common = json.commonPath c.p, otherC.p
common2 = json.commonPath otherC.p, c.p
cplength = c.p.length
otherCplength = otherC.p.length
c.p.pop() if c.na != undefined # hax
otherC.p.pop() if otherC.na != undefined
if otherC.na
if common2? && otherCplength >= cplength && otherC.p[common2] == c.p[common2]
if c.ld != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.ld = json.apply clone(c.ld), [oc]
else if c.od != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.od = json.apply clone(c.od), [oc]
json.append dest, c
return dest
if common2? && otherCplength > cplength && c.p[common2] == otherC.p[common2]
# transform based on c
if c.ld != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.ld = json.apply clone(c.ld), [oc]
else if c.od != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.od = json.apply clone(c.od), [oc]
if common?
commonOperand = cplength == otherCplength
# transform based on otherC
if otherC.na != undefined
# this case is handled above due to icky path hax
else if otherC.si != undefined || otherC.sd != undefined
# String op vs string op - pass through to text type
if c.si != undefined || c.sd != undefined
throw new Error("must be a string?") unless commonOperand
# Convert an op component to a text op component
convert = (component) ->
newC = p:component.p[component.p.length - 1]
if component.si
newC.i = component.si
else
newC.d = component.sd
newC
tc1 = convert c
tc2 = convert otherC
res = []
text._tc res, tc1, tc2, type
for tc in res
jc = { p: c.p[...common] }
jc.p.push(tc.p)
jc.si = tc.i if tc.i?
jc.sd = tc.d if tc.d?
json.append dest, jc
return dest
else if otherC.li != undefined && otherC.ld != undefined
if otherC.p[common] == c.p[common]
# noop
if !commonOperand
# we're below the deleted element, so -> noop
return dest
else if c.ld != undefined
# we're trying to delete the same element, -> noop
if c.li != undefined and type == 'left'
# we're both replacing one element with another. only one can
# survive!
c.ld = clone otherC.li
else
return dest
else if otherC.li != undefined
if c.li != undefined and c.ld == undefined and commonOperand and c.p[common] == otherC.p[common]
# in li vs. li, left wins.
if type == 'right'
c.p[common]++
else if otherC.p[common] <= c.p[common]
c.p[common]++
if c.lm != undefined
if commonOperand
# otherC edits the same list we edit
if otherC.p[common] <= c.lm
c.lm++
# changing c.from is handled above.
else if otherC.ld != undefined
if c.lm != undefined
if commonOperand
if otherC.p[common] == c.p[common]
# they deleted the thing we're trying to move
return dest
# otherC edits the same list we edit
p = otherC.p[common]
from = c.p[common]
to = c.lm
if p < to || (p == to && from < to)
c.lm--
if otherC.p[common] < c.p[common]
c.p[common]--
else if otherC.p[common] == c.p[common]
if otherCplength < cplength
# we're below the deleted element, so -> noop
return dest
else if c.ld != undefined
if c.li != undefined
# we're replacing, they're deleting. we become an insert.
delete c.ld
else
# we're trying to delete the same element, -> noop
return dest
else if otherC.lm != undefined
if c.lm != undefined and cplength == otherCplength
# lm vs lm, here we go!
from = c.p[common]
to = c.lm
otherFrom = otherC.p[common]
otherTo = otherC.lm
if otherFrom != otherTo
# if otherFrom == otherTo, we don't need to change our op.
# where did my thing go?
if from == otherFrom
# they moved it! tie break.
if type == 'left'
c.p[common] = otherTo
if from == to # ugh
c.lm = otherTo
else
return dest
else
# they moved around it
if from > otherFrom
c.p[common]--
if from > otherTo
c.p[common]++
else if from == otherTo
if otherFrom > otherTo
c.p[common]++
if from == to # ugh, again
c.lm++
# step 2: where am i going to put it?
if to > otherFrom
c.lm--
else if to == otherFrom
if to > from
c.lm--
if to > otherTo
c.lm++
else if to == otherTo
# if we're both moving in the same direction, tie break
if (otherTo > otherFrom and to > from) or
(otherTo < otherFrom and to < from)
if type == 'right'
c.lm++
else
if to > from
c.lm++
else if to == otherFrom
c.lm--
else if c.li != undefined and c.ld == undefined and commonOperand
# li
from = otherC.p[common]
to = otherC.lm
p = c.p[common]
if p > from
c.p[common]--
if p > to
c.p[common]++
else
# ld, ld+li, si, sd, na, oi, od, oi+od, any li on an element beneath
# the lm
#
# i.e. things care about where their item is after the move.
from = otherC.p[common]
to = otherC.lm
p = c.p[common]
if p == from
c.p[common] = to
else
if p > from
c.p[common]--
if p > to
c.p[common]++
else if p == to
if from > to
c.p[common]++
else if otherC.oi != undefined && otherC.od != undefined
if c.p[common] == otherC.p[common]
if c.oi != undefined and commonOperand
# we inserted where someone else replaced
if type == 'right'
# left wins
return dest
else
# we win, make our op replace what they inserted
c.od = otherC.oi
else
# -> noop if the other component is deleting the same object (or any
# parent)
return dest
else if otherC.oi != undefined
if c.oi != undefined and c.p[common] == otherC.p[common]
# left wins if we try to insert at the same place
if type == 'left'
json.append dest, {p:c.p, od:otherC.oi}
else
return dest
else if otherC.od != undefined
if c.p[common] == otherC.p[common]
return dest if !commonOperand
if c.oi != undefined
delete c.od
else
return dest
json.append dest, c
return dest
if WEB?
exports.types ||= {}
# This is kind of awful - come up with a better way to hook this helper code up.
exports._bt(json, json.transformComponent, json.checkValidOp, json.append)
# [] is used to prevent closure from renaming types.text
exports.types.json = json
else
module.exports = json
require('./helpers').bootstrapTransform(json, json.transformComponent, json.checkValidOp, json.append)
| 104918 | # This is the implementation of the JSON OT type.
#
# Spec is here: https://github.com/josephg/ShareJS/wiki/JSON-Operations
if WEB?
text = exports.types.text
else
text = require './text'
json = {}
json.name = 'json'
json.create = -> null
json.invertComponent = (c) ->
c_ = {p: c.p}
c_.sd = c.si if c.si != undefined
c_.si = c.sd if c.sd != undefined
c_.od = c.oi if c.oi != undefined
c_.oi = c.od if c.od != undefined
c_.ld = c.li if c.li != undefined
c_.li = c.ld if c.ld != undefined
c_.na = -c.na if c.na != undefined
if c.lm != undefined
c_.lm = c.p[c.p.length-1]
c_.p = c.p[0...c.p.length - 1].concat([c.lm])
c_
json.invert = (op) -> json.invertComponent c for c in op.slice().reverse()
json.checkValidOp = (op) ->
isArray = (o) -> Object.prototype.toString.call(o) == '[object Array]'
json.checkList = (elem) ->
throw new Error 'Referenced element not a list' unless isArray(elem)
json.checkObj = (elem) ->
throw new Error "Referenced element not an object (it was #{JSON.stringify elem})" unless elem.constructor is Object
json.apply = (snapshot, op) ->
json.checkValidOp op
op = clone op
container = {data: clone snapshot}
try
for c, i in op
parent = null
parentkey = null
elem = container
key = '<KEY>
for p in c.p
parent = elem
parentkey = key
elem = elem[key]
key = p
throw new Error 'Path invalid' unless parent?
if c.na != undefined
# Number add
throw new Error 'Referenced element not a number' unless typeof elem[key] is 'number'
elem[key] += c.na
else if c.si != undefined
# String insert
throw new Error "Referenced element not a string (it was #{JSON.stringify elem})" unless typeof elem is 'string'
parent[parentkey] = elem[...key] + c.si + elem[key..]
else if c.sd != undefined
# String delete
throw new Error 'Referenced element not a string' unless typeof elem is 'string'
throw new Error 'Deleted string does not match' unless elem[key...key + c.sd.length] == c.sd
parent[parentkey] = elem[...key] + elem[key + c.sd.length..]
else if c.li != undefined && c.ld != undefined
# List replace
json.checkList elem
# Should check the list element matches c.ld
elem[key] = c.li
else if c.li != undefined
# List insert
json.checkList elem
elem.splice key, 0, c.li
else if c.ld != undefined
# List delete
json.checkList elem
# Should check the list element matches c.ld here too.
elem.splice key, 1
else if c.lm != undefined
# List move
json.checkList elem
if c.lm != key
e = elem[key]
# Remove it...
elem.splice key, 1
# And insert it back.
elem.splice c.lm, 0, e
else if c.oi != undefined
# Object insert / replace
json.checkObj elem
# Should check that elem[key] == c.od
elem[key] = c.oi
else if c.od != undefined
# Object delete
json.checkObj elem
# Should check that elem[key] == c.od
delete elem[key]
else
throw new Error 'invalid / missing instruction in op'
catch error
# TODO: Roll back all already applied changes. Write tests before implementing this code.
throw error
container.data
# Checks if two paths, p1 and p2 match.
json.pathMatches = (p1, p2, ignoreLast) ->
return false unless p1.length == p2.length
for p, i in p1
return false if p != p2[i] and (!ignoreLast or i != p1.length - 1)
true
json.append = (dest, c) ->
c = clone c
if dest.length != 0 and json.pathMatches c.p, (last = dest[dest.length - 1]).p
if last.na != undefined and c.na != undefined
dest[dest.length - 1] = { p: last.p, na: last.na + c.na }
else if last.li != undefined and c.li == undefined and c.ld == last.li
# insert immediately followed by delete becomes a noop.
if last.ld != undefined
# leave the delete part of the replace
delete last.li
else
dest.pop()
else if last.od != undefined and last.oi == undefined and
c.oi != undefined and c.od == undefined
last.oi = c.oi
else if c.lm != undefined and c.p[c.p.length-1] == c.lm
null # don't do anything
else
dest.push c
else
dest.push c
json.compose = (op1, op2) ->
json.checkValidOp op1
json.checkValidOp op2
newOp = clone op1
json.append newOp, c for c in op2
newOp
json.normalize = (op) ->
newOp = []
op = [op] unless isArray op
for c in op
c.p ?= []
json.append newOp, c
newOp
# hax, copied from test/types/json. Apparently this is still the fastest way to deep clone an object, assuming
# we have browser support for JSON.
# http://jsperf.com/cloning-an-object/12
clone = (o) -> JSON.parse(JSON.stringify o)
json.commonPath = (p1, p2) ->
p1 = p1.slice()
p2 = p2.slice()
p1.unshift('data')
p2.unshift('data')
p1 = p1[...p1.length-1]
p2 = p2[...p2.length-1]
return -1 if p2.length == 0
i = 0
while p1[i] == p2[i] && i < p1.length
i++
if i == p2.length
return i-1
return
# transform c so it applies to a document with otherC applied.
json.transformComponent = (dest, c, otherC, type) ->
c = clone c
c.p.push(0) if c.na != undefined
otherC.p.push(0) if otherC.na != undefined
common = json.commonPath c.p, otherC.p
common2 = json.commonPath otherC.p, c.p
cplength = c.p.length
otherCplength = otherC.p.length
c.p.pop() if c.na != undefined # hax
otherC.p.pop() if otherC.na != undefined
if otherC.na
if common2? && otherCplength >= cplength && otherC.p[common2] == c.p[common2]
if c.ld != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.ld = json.apply clone(c.ld), [oc]
else if c.od != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.od = json.apply clone(c.od), [oc]
json.append dest, c
return dest
if common2? && otherCplength > cplength && c.p[common2] == otherC.p[common2]
# transform based on c
if c.ld != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.ld = json.apply clone(c.ld), [oc]
else if c.od != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.od = json.apply clone(c.od), [oc]
if common?
commonOperand = cplength == otherCplength
# transform based on otherC
if otherC.na != undefined
# this case is handled above due to icky path hax
else if otherC.si != undefined || otherC.sd != undefined
# String op vs string op - pass through to text type
if c.si != undefined || c.sd != undefined
throw new Error("must be a string?") unless commonOperand
# Convert an op component to a text op component
convert = (component) ->
newC = p:component.p[component.p.length - 1]
if component.si
newC.i = component.si
else
newC.d = component.sd
newC
tc1 = convert c
tc2 = convert otherC
res = []
text._tc res, tc1, tc2, type
for tc in res
jc = { p: c.p[...common] }
jc.p.push(tc.p)
jc.si = tc.i if tc.i?
jc.sd = tc.d if tc.d?
json.append dest, jc
return dest
else if otherC.li != undefined && otherC.ld != undefined
if otherC.p[common] == c.p[common]
# noop
if !commonOperand
# we're below the deleted element, so -> noop
return dest
else if c.ld != undefined
# we're trying to delete the same element, -> noop
if c.li != undefined and type == 'left'
# we're both replacing one element with another. only one can
# survive!
c.ld = clone otherC.li
else
return dest
else if otherC.li != undefined
if c.li != undefined and c.ld == undefined and commonOperand and c.p[common] == otherC.p[common]
# in li vs. li, left wins.
if type == 'right'
c.p[common]++
else if otherC.p[common] <= c.p[common]
c.p[common]++
if c.lm != undefined
if commonOperand
# otherC edits the same list we edit
if otherC.p[common] <= c.lm
c.lm++
# changing c.from is handled above.
else if otherC.ld != undefined
if c.lm != undefined
if commonOperand
if otherC.p[common] == c.p[common]
# they deleted the thing we're trying to move
return dest
# otherC edits the same list we edit
p = otherC.p[common]
from = c.p[common]
to = c.lm
if p < to || (p == to && from < to)
c.lm--
if otherC.p[common] < c.p[common]
c.p[common]--
else if otherC.p[common] == c.p[common]
if otherCplength < cplength
# we're below the deleted element, so -> noop
return dest
else if c.ld != undefined
if c.li != undefined
# we're replacing, they're deleting. we become an insert.
delete c.ld
else
# we're trying to delete the same element, -> noop
return dest
else if otherC.lm != undefined
if c.lm != undefined and cplength == otherCplength
# lm vs lm, here we go!
from = c.p[common]
to = c.lm
otherFrom = otherC.p[common]
otherTo = otherC.lm
if otherFrom != otherTo
# if otherFrom == otherTo, we don't need to change our op.
# where did my thing go?
if from == otherFrom
# they moved it! tie break.
if type == 'left'
c.p[common] = otherTo
if from == to # ugh
c.lm = otherTo
else
return dest
else
# they moved around it
if from > otherFrom
c.p[common]--
if from > otherTo
c.p[common]++
else if from == otherTo
if otherFrom > otherTo
c.p[common]++
if from == to # ugh, again
c.lm++
# step 2: where am i going to put it?
if to > otherFrom
c.lm--
else if to == otherFrom
if to > from
c.lm--
if to > otherTo
c.lm++
else if to == otherTo
# if we're both moving in the same direction, tie break
if (otherTo > otherFrom and to > from) or
(otherTo < otherFrom and to < from)
if type == 'right'
c.lm++
else
if to > from
c.lm++
else if to == otherFrom
c.lm--
else if c.li != undefined and c.ld == undefined and commonOperand
# li
from = otherC.p[common]
to = otherC.lm
p = c.p[common]
if p > from
c.p[common]--
if p > to
c.p[common]++
else
# ld, ld+li, si, sd, na, oi, od, oi+od, any li on an element beneath
# the lm
#
# i.e. things care about where their item is after the move.
from = otherC.p[common]
to = otherC.lm
p = c.p[common]
if p == from
c.p[common] = to
else
if p > from
c.p[common]--
if p > to
c.p[common]++
else if p == to
if from > to
c.p[common]++
else if otherC.oi != undefined && otherC.od != undefined
if c.p[common] == otherC.p[common]
if c.oi != undefined and commonOperand
# we inserted where someone else replaced
if type == 'right'
# left wins
return dest
else
# we win, make our op replace what they inserted
c.od = otherC.oi
else
# -> noop if the other component is deleting the same object (or any
# parent)
return dest
else if otherC.oi != undefined
if c.oi != undefined and c.p[common] == otherC.p[common]
# left wins if we try to insert at the same place
if type == 'left'
json.append dest, {p:c.p, od:otherC.oi}
else
return dest
else if otherC.od != undefined
if c.p[common] == otherC.p[common]
return dest if !commonOperand
if c.oi != undefined
delete c.od
else
return dest
json.append dest, c
return dest
if WEB?
exports.types ||= {}
# This is kind of awful - come up with a better way to hook this helper code up.
exports._bt(json, json.transformComponent, json.checkValidOp, json.append)
# [] is used to prevent closure from renaming types.text
exports.types.json = json
else
module.exports = json
require('./helpers').bootstrapTransform(json, json.transformComponent, json.checkValidOp, json.append)
| true | # This is the implementation of the JSON OT type.
#
# Spec is here: https://github.com/josephg/ShareJS/wiki/JSON-Operations
if WEB?
text = exports.types.text
else
text = require './text'
json = {}
json.name = 'json'
json.create = -> null
json.invertComponent = (c) ->
c_ = {p: c.p}
c_.sd = c.si if c.si != undefined
c_.si = c.sd if c.sd != undefined
c_.od = c.oi if c.oi != undefined
c_.oi = c.od if c.od != undefined
c_.ld = c.li if c.li != undefined
c_.li = c.ld if c.ld != undefined
c_.na = -c.na if c.na != undefined
if c.lm != undefined
c_.lm = c.p[c.p.length-1]
c_.p = c.p[0...c.p.length - 1].concat([c.lm])
c_
json.invert = (op) -> json.invertComponent c for c in op.slice().reverse()
json.checkValidOp = (op) ->
isArray = (o) -> Object.prototype.toString.call(o) == '[object Array]'
json.checkList = (elem) ->
throw new Error 'Referenced element not a list' unless isArray(elem)
json.checkObj = (elem) ->
throw new Error "Referenced element not an object (it was #{JSON.stringify elem})" unless elem.constructor is Object
json.apply = (snapshot, op) ->
json.checkValidOp op
op = clone op
container = {data: clone snapshot}
try
for c, i in op
parent = null
parentkey = null
elem = container
key = 'PI:KEY:<KEY>END_PI
for p in c.p
parent = elem
parentkey = key
elem = elem[key]
key = p
throw new Error 'Path invalid' unless parent?
if c.na != undefined
# Number add
throw new Error 'Referenced element not a number' unless typeof elem[key] is 'number'
elem[key] += c.na
else if c.si != undefined
# String insert
throw new Error "Referenced element not a string (it was #{JSON.stringify elem})" unless typeof elem is 'string'
parent[parentkey] = elem[...key] + c.si + elem[key..]
else if c.sd != undefined
# String delete
throw new Error 'Referenced element not a string' unless typeof elem is 'string'
throw new Error 'Deleted string does not match' unless elem[key...key + c.sd.length] == c.sd
parent[parentkey] = elem[...key] + elem[key + c.sd.length..]
else if c.li != undefined && c.ld != undefined
# List replace
json.checkList elem
# Should check the list element matches c.ld
elem[key] = c.li
else if c.li != undefined
# List insert
json.checkList elem
elem.splice key, 0, c.li
else if c.ld != undefined
# List delete
json.checkList elem
# Should check the list element matches c.ld here too.
elem.splice key, 1
else if c.lm != undefined
# List move
json.checkList elem
if c.lm != key
e = elem[key]
# Remove it...
elem.splice key, 1
# And insert it back.
elem.splice c.lm, 0, e
else if c.oi != undefined
# Object insert / replace
json.checkObj elem
# Should check that elem[key] == c.od
elem[key] = c.oi
else if c.od != undefined
# Object delete
json.checkObj elem
# Should check that elem[key] == c.od
delete elem[key]
else
throw new Error 'invalid / missing instruction in op'
catch error
# TODO: Roll back all already applied changes. Write tests before implementing this code.
throw error
container.data
# Checks if two paths, p1 and p2 match.
json.pathMatches = (p1, p2, ignoreLast) ->
return false unless p1.length == p2.length
for p, i in p1
return false if p != p2[i] and (!ignoreLast or i != p1.length - 1)
true
json.append = (dest, c) ->
c = clone c
if dest.length != 0 and json.pathMatches c.p, (last = dest[dest.length - 1]).p
if last.na != undefined and c.na != undefined
dest[dest.length - 1] = { p: last.p, na: last.na + c.na }
else if last.li != undefined and c.li == undefined and c.ld == last.li
# insert immediately followed by delete becomes a noop.
if last.ld != undefined
# leave the delete part of the replace
delete last.li
else
dest.pop()
else if last.od != undefined and last.oi == undefined and
c.oi != undefined and c.od == undefined
last.oi = c.oi
else if c.lm != undefined and c.p[c.p.length-1] == c.lm
null # don't do anything
else
dest.push c
else
dest.push c
json.compose = (op1, op2) ->
json.checkValidOp op1
json.checkValidOp op2
newOp = clone op1
json.append newOp, c for c in op2
newOp
json.normalize = (op) ->
newOp = []
op = [op] unless isArray op
for c in op
c.p ?= []
json.append newOp, c
newOp
# hax, copied from test/types/json. Apparently this is still the fastest way to deep clone an object, assuming
# we have browser support for JSON.
# http://jsperf.com/cloning-an-object/12
clone = (o) -> JSON.parse(JSON.stringify o)
json.commonPath = (p1, p2) ->
p1 = p1.slice()
p2 = p2.slice()
p1.unshift('data')
p2.unshift('data')
p1 = p1[...p1.length-1]
p2 = p2[...p2.length-1]
return -1 if p2.length == 0
i = 0
while p1[i] == p2[i] && i < p1.length
i++
if i == p2.length
return i-1
return
# transform c so it applies to a document with otherC applied.
json.transformComponent = (dest, c, otherC, type) ->
c = clone c
c.p.push(0) if c.na != undefined
otherC.p.push(0) if otherC.na != undefined
common = json.commonPath c.p, otherC.p
common2 = json.commonPath otherC.p, c.p
cplength = c.p.length
otherCplength = otherC.p.length
c.p.pop() if c.na != undefined # hax
otherC.p.pop() if otherC.na != undefined
if otherC.na
if common2? && otherCplength >= cplength && otherC.p[common2] == c.p[common2]
if c.ld != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.ld = json.apply clone(c.ld), [oc]
else if c.od != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.od = json.apply clone(c.od), [oc]
json.append dest, c
return dest
if common2? && otherCplength > cplength && c.p[common2] == otherC.p[common2]
# transform based on c
if c.ld != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.ld = json.apply clone(c.ld), [oc]
else if c.od != undefined
oc = clone otherC
oc.p = oc.p[cplength..]
c.od = json.apply clone(c.od), [oc]
if common?
commonOperand = cplength == otherCplength
# transform based on otherC
if otherC.na != undefined
# this case is handled above due to icky path hax
else if otherC.si != undefined || otherC.sd != undefined
# String op vs string op - pass through to text type
if c.si != undefined || c.sd != undefined
throw new Error("must be a string?") unless commonOperand
# Convert an op component to a text op component
convert = (component) ->
newC = p:component.p[component.p.length - 1]
if component.si
newC.i = component.si
else
newC.d = component.sd
newC
tc1 = convert c
tc2 = convert otherC
res = []
text._tc res, tc1, tc2, type
for tc in res
jc = { p: c.p[...common] }
jc.p.push(tc.p)
jc.si = tc.i if tc.i?
jc.sd = tc.d if tc.d?
json.append dest, jc
return dest
else if otherC.li != undefined && otherC.ld != undefined
if otherC.p[common] == c.p[common]
# noop
if !commonOperand
# we're below the deleted element, so -> noop
return dest
else if c.ld != undefined
# we're trying to delete the same element, -> noop
if c.li != undefined and type == 'left'
# we're both replacing one element with another. only one can
# survive!
c.ld = clone otherC.li
else
return dest
else if otherC.li != undefined
if c.li != undefined and c.ld == undefined and commonOperand and c.p[common] == otherC.p[common]
# in li vs. li, left wins.
if type == 'right'
c.p[common]++
else if otherC.p[common] <= c.p[common]
c.p[common]++
if c.lm != undefined
if commonOperand
# otherC edits the same list we edit
if otherC.p[common] <= c.lm
c.lm++
# changing c.from is handled above.
else if otherC.ld != undefined
if c.lm != undefined
if commonOperand
if otherC.p[common] == c.p[common]
# they deleted the thing we're trying to move
return dest
# otherC edits the same list we edit
p = otherC.p[common]
from = c.p[common]
to = c.lm
if p < to || (p == to && from < to)
c.lm--
if otherC.p[common] < c.p[common]
c.p[common]--
else if otherC.p[common] == c.p[common]
if otherCplength < cplength
# we're below the deleted element, so -> noop
return dest
else if c.ld != undefined
if c.li != undefined
# we're replacing, they're deleting. we become an insert.
delete c.ld
else
# we're trying to delete the same element, -> noop
return dest
else if otherC.lm != undefined
if c.lm != undefined and cplength == otherCplength
# lm vs lm, here we go!
from = c.p[common]
to = c.lm
otherFrom = otherC.p[common]
otherTo = otherC.lm
if otherFrom != otherTo
# if otherFrom == otherTo, we don't need to change our op.
# where did my thing go?
if from == otherFrom
# they moved it! tie break.
if type == 'left'
c.p[common] = otherTo
if from == to # ugh
c.lm = otherTo
else
return dest
else
# they moved around it
if from > otherFrom
c.p[common]--
if from > otherTo
c.p[common]++
else if from == otherTo
if otherFrom > otherTo
c.p[common]++
if from == to # ugh, again
c.lm++
# step 2: where am i going to put it?
if to > otherFrom
c.lm--
else if to == otherFrom
if to > from
c.lm--
if to > otherTo
c.lm++
else if to == otherTo
# if we're both moving in the same direction, tie break
if (otherTo > otherFrom and to > from) or
(otherTo < otherFrom and to < from)
if type == 'right'
c.lm++
else
if to > from
c.lm++
else if to == otherFrom
c.lm--
else if c.li != undefined and c.ld == undefined and commonOperand
# li
from = otherC.p[common]
to = otherC.lm
p = c.p[common]
if p > from
c.p[common]--
if p > to
c.p[common]++
else
# ld, ld+li, si, sd, na, oi, od, oi+od, any li on an element beneath
# the lm
#
# i.e. things care about where their item is after the move.
from = otherC.p[common]
to = otherC.lm
p = c.p[common]
if p == from
c.p[common] = to
else
if p > from
c.p[common]--
if p > to
c.p[common]++
else if p == to
if from > to
c.p[common]++
else if otherC.oi != undefined && otherC.od != undefined
if c.p[common] == otherC.p[common]
if c.oi != undefined and commonOperand
# we inserted where someone else replaced
if type == 'right'
# left wins
return dest
else
# we win, make our op replace what they inserted
c.od = otherC.oi
else
# -> noop if the other component is deleting the same object (or any
# parent)
return dest
else if otherC.oi != undefined
if c.oi != undefined and c.p[common] == otherC.p[common]
# left wins if we try to insert at the same place
if type == 'left'
json.append dest, {p:c.p, od:otherC.oi}
else
return dest
else if otherC.od != undefined
if c.p[common] == otherC.p[common]
return dest if !commonOperand
if c.oi != undefined
delete c.od
else
return dest
json.append dest, c
return dest
if WEB?
exports.types ||= {}
# This is kind of awful - come up with a better way to hook this helper code up.
exports._bt(json, json.transformComponent, json.checkValidOp, json.append)
# [] is used to prevent closure from renaming types.text
exports.types.json = json
else
module.exports = json
require('./helpers').bootstrapTransform(json, json.transformComponent, json.checkValidOp, json.append)
|
[
{
"context": "# express-mongoose-resource\n# Copyright (C) 2012 Marco Pantaleoni.\n#\n# Distributed under the MIT License.\n\n# Inspir",
"end": 65,
"score": 0.9998567700386047,
"start": 49,
"tag": "NAME",
"value": "Marco Pantaleoni"
},
{
"context": "T License.\n\n# Inspired by:\n# ... | src/index.coffee | panta/express-mongoose-resource | 5 | # express-mongoose-resource
# Copyright (C) 2012 Marco Pantaleoni.
#
# Distributed under the MIT License.
# Inspired by:
# https://github.com/visionmedia/express/blob/master/examples/mvc/mvc.js
# https://github.com/visionmedia/express-resource/
# https://github.com/jsmarkus/colibri
#
# See also:
# https://github.com/bebraw/rest-sugar
# https://github.com/enyo/mongo-rest
#
# Usage:
#
# app.resource('forums', {model: Forum})
# or
# app.resource({model: Forum})
#
# this will add automatically the following routes to the app:
#
# GET /forums/schema -> return the model schema
# GET /forums -> index
# GET /forums/new -> new
# POST /forums -> create
# GET /forums/:forum -> show
# GET /forums/:forum/edit -> edit
# PUT /forums/:forum -> update
# DELETE /forums/:forum -> destroy
#
# Note that if 'model' is not specified, app.resource falls back to
# express-resource implementation.
express = require('express')
Resource = exports.Resource = require('express-resource-middleware')
# Extend a source object with the properties of another object (shallow copy).
extend = (dst, src, overwrite=true) ->
if src?
for key, val of src
if (key not of dst) or overwrite
dst[key] = val
dst
# Add missing properties from a `src` object.
defaults = (dst, src) ->
for key, val of src
if not (key of dst)
dst[key] = val
dst
invoke_callbacks = (context, callbacks, req, res) ->
callback_invoke = (context, callbacks, i, err, req, res) ->
l = callbacks.length
if i >= l
return
next = (err) ->
return callback_invoke(context, callbacks, i+1, err)
cb = callbacks[i]
if cb.length >= 4
# error handler - (err, req, res, next)
return callbacks[i].call(context, err, req, res, next)
return callbacks[i].call(context, req, res, next)
callback_invoke(context, callbacks, 0, null, req, res)
old_Resource_add = Resource::add
Resource::add = (resource, opts) ->
if resource.controller? and opts.pivotField?
resource.controller.trace("specifying pivot field '#{opts.pivotField}' and req field '#{@id}'")
resource.controller.opts.pivot =
modelField: opts.pivotField
requestField: @id
else
console.log("no @controller or opts.pivotField")
old_Resource_add.call(@, resource)
class ModelController
@TOOBJECT_DEFAULT_OPTS:
getters: true
constructor: (@app, @name, @model, @opts) ->
@schema = @model.schema
@modelName = @model.modelName
@_trace = @opts.trace or true
@_default_format = @opts.format or 'json'
@_toObjectOpts = {}
@_pre_serialize_cbs = []
@_serialize_cb = null
@_post_serialize_cbs = []
@setSerializeCallback(@_default_serialize_cb)
if @opts.pre_serialize
for cb in @opts.pre_serialize
@addPreSerializeCallback(cb)
if @opts.serialize
@setSerializeCallback(@opts.serialize)
if @opts.post_serialize
for cb in @opts.post_serialize
@addPostSerializeCallback(cb)
@_computeToObjectOpts()
@trace(@schema)
if @name is null
@name = @modelName.toLowerCase()
@singular = @name
if 'plural' of @opts
@plural = @opts.plural
else
@plural = @name
if @plural[@plural.length-1] != 's'
@plural += 's'
@name = @plural
# @base is the url base - without model name
# (with leading slash and no trailing slash)
if 'base' of opts
@base = opts.base
else
@base = "/"
if @base[0] != '/'
@base = '/' + @base
if @base[@base.length-1] == '/'
@base = @base[0...@base.length-1]
# @url_prefix is the url prefix complete with model name
# (with leading slash and no trailing slash)
@url_prefix = @base + "/" + @name
if @url_prefix[0] != '/'
@url_prefix = '/' + @url_prefix
if @url_prefix[@url_prefix.length-1] == '/'
@url_prefix = @url_prefix[0...@url_prefix.length-1]
getSchema: ->
schema = {}
getPathInfo = (pathname, path) =>
#path = @model.schema.path(pathname)
# TODO: handle compound pathnames (like 'aaa.bbb')
pathInfo =
name: pathname
kind: path.instance
type: @model.schema.pathType(pathname)
if path.instance is 'ObjectID'
if 'ref' of path.options
pathInfo.references = path.options.ref
if 'auto' of path.options
pathInfo.auto = path.options.auto
pathInfo
@model.schema.eachPath (pathname) =>
path = @model.schema.path(pathname)
pathInfo = getPathInfo(pathname, path)
schema[pathname] = pathInfo
for pathname, virtual of @model.schema.virtuals
pathInfo = getPathInfo(pathname, virtual)
schema[pathname] = pathInfo
schema
_register_schema_action: ->
@app.get "#{@url_prefix}/schema", (req, res, next) =>
res.send(@getSchema())
# -- express-resource auto-loader ---------------------------------
_auto_load: (req, id, fn) ->
@trace("[auto-load] id:#{id} res.id:#{@resource.id}")
@get id, fn
# -- template rendering support -----------------------------------
getTemplateContext: (req, res, extra) ->
context =
model: @model
schema: @schema
modelName: @modelName
name: @name
base: @base
url_prefix: @url_prefix
resource_id: @resource.id
pivot = {}
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
pivot.pivot = @opts.pivot.requestField
pivot.pivot_id = req[@opts.pivot.requestField].id
pivot[@opts.pivot.requestField] = @preprocess_instance(req[@opts.pivot.requestField])
defaults context, pivot
return extend context, extra
getInstanceTemplateContext: (req, res, instance, extra) ->
serialized = @preprocess_instance(instance)
context = @getTemplateContext req, res,
instance: instance
json: JSON.stringify(serialized)
object: serialized
return extend context, extra
getSetTemplateContext: (req, res, instances, extra) ->
serialized = @preprocess_instances(instances)
context = @getTemplateContext req, res,
instances: instances
json: JSON.stringify(serialized)
objects: serialized
return extend context, extra
_renderTemplate: (res, name, context) ->
t_name = @url_prefix
if t_name[0] == '/'
t_name = t_name[1..]
if t_name[t_name.length-1] != '/'
t_name = t_name + '/'
t_name += name
return res.render t_name, context
renderTemplate: (res, name, data, context) ->
data.view ||= name
data.name = name
view = data.view
if @opts.render_cb?[view]?
@opts.render_cb[view].call @, data, context, (ctxt) =>
return @_renderTemplate res, name, ctxt
else
return @_renderTemplate res, name, context
# -- default actions ----------------------------------------------
# GET /NAME
_action_index: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'index', "#{@url_prefix} format:#{format}")
subquery = false
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
@trace("subquery on #{@opts.pivot.modelField} = #{req[@opts.pivot.requestField].id}")
subquery = true
else
@trace("NO SUBQUERY")
conditions = null
if subquery
conditions = {}
conditions[@opts.pivot.modelField] = req[@opts.pivot.requestField].id
@trace("conditions:", conditions)
@get_conditions conditions, (err, instances) =>
return next(err) if err
if format == 'html'
ctxt = @getSetTemplateContext req, res, instances,
format: format
view: 'index'
return @renderTemplate res, "index", {instances: instances}, ctxt
return res.send(@preprocess_instances(instances))
# GET /NAME/new
_action_new: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'new', "#{@url_prefix}/new format:#{format}")
instance = new @model
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
if (not @opts.pivot.requestField of instance) or (not instance[@opts.pivot.requestField])
instance[@opts.pivot.requestField] = req[@opts.pivot.requestField].id
if format == 'html'
ctxt = @getInstanceTemplateContext req, res, instance,
format: format
view: 'new'
mode: 'new'
return @renderTemplate res, "edit", {view: 'new', instance: instance}, ctxt
return res.send(@preprocess_instance(instance))
# POST /NAME
_action_create: (req, res, next) ->
redirect_to = req.redirect_to or req.body.redirect_to or null
format = req.format or @_default_format
@traceAction(req, 'create', "#{@url_prefix} format:#{format}")
# #console.log(req.body)
# console.log("REQUEST files:")
# console.log(req.files)
# instanceValues = @get_body_instance_values(req)
# instance = new @model(instanceValues)
instance = new @model()
@update_instance_from_body_values(req, instance)
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
if (not @opts.pivot.requestField of instance) or (not instance[@opts.pivot.requestField])
instance[@opts.pivot.requestField] = req[@opts.pivot.requestField].id
instance.save (err) =>
return next(err) if err
console.log("created #{@modelName} with id:#{instance.id}")
if (req.body._format? and req.body._format == 'html') or (format == 'html')
if redirect_to
return res.redirect redirect_to
return res.redirect @url_prefix + "/#{instance.id}" + ".html"
else
return res.send(@preprocess_instance(instance))
# GET /NAME/:NAME
_action_show: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'show', "#{@url_prefix}:#{@resource.id} format:#{format}")
@get @getId(req), (err, instance) =>
return next(err) if err
if format == 'html'
ctxt = @getInstanceTemplateContext req, res, instance,
format: format
view: 'show'
return @renderTemplate res, "show", {instance: instance}, ctxt
else
return res.send(@preprocess_instance(instance))
# GET /NAME/:NAME/edit
_action_edit: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'edit', "#{@url_prefix}:#{@resource.id}/edit format:#{format}")
@get @getId(req), (err, instance) =>
return next(err) if err
if format == 'html'
ctxt = @getInstanceTemplateContext req, res, instance,
format: format
view: 'edit'
mode: 'edit'
return @renderTemplate res, "edit", {instance: instance}, ctxt
res.send(@preprocess_instance(instance))
# PUT /NAME/:NAME
_action_update: (req, res, next) ->
redirect_to = req.redirect_to or req.body.redirect_to or null
id = @getId(req)
@traceAction(req, 'update', "#{@url_prefix}:#{@resource.id}")
@get id, (err, instance) =>
return next(err) if err
console.log("REQUEST files:")
console.log(req.files)
# instanceValues = @get_body_instance_values(req)
# extend(instance, instanceValues, true)
@update_instance_from_body_values(req, instance)
return instance.save (err) =>
return next(err) if err
console.log("updated #{@modelName} with id:#{id}")
if req.body._format? and req.body._format == 'html'
if redirect_to
return res.redirect redirect_to
return res.redirect @url_prefix + "/#{instance.id}" + ".html"
else
return res.send(@preprocess_instance(instance))
# DELETE /NAME/:NAME
_action_destroy: (req, res, next) ->
redirect_to = req.redirect_to or req.body.redirect_to or null
id = @getId(req)
@traceAction(req, 'destroy', "#{@url_prefix}:#{@resource.id}")
return @get id, (err, instance) =>
return next(err) if err
return instance.remove (err) =>
return next(err) if err
console.log("removed #{@modelName} with id:#{id}")
if redirect_to
return res.redirect redirect_to
return res.send('')
# -- express-resource support ---------------------------------------
getExpressResourceActions: (actions) ->
actions = actions or {}
controller = @
extend actions,
index: -> # GET /NAME
controller._action_index.apply(controller, arguments)
new: -> # GET /NAME/new
controller._action_new.apply(controller, arguments)
create: -> # POST /NAME
controller._action_create.apply(controller, arguments)
show: -> # GET /NAME/:NAME
controller._action_show.apply(controller, arguments)
edit: -> # GET /NAME/:NAME/edit
controller._action_edit.apply(controller, arguments)
update: -> # PUT /NAME/:NAME
controller._action_update.apply(controller, arguments)
destroy: -> # DELETE /NAME/:NAME
controller._action_destroy.apply(controller, arguments)
load: -> # express-resource auto-load
controller._auto_load.apply(controller, arguments)
actions
# -- serialization --------------------------------------------------
addPreSerializeCallback: (cb) ->
@_pre_serialize_cbs.push cb
@
setSerializeCallback: (cb) ->
@_serialize_cb = cb
@
addPostSerializeCallback: (cb) ->
@_post_serialize_cbs.push cb
@
# -- helper methods -------------------------------------------------
# trace
trace: (args...) ->
if @_trace
args = args or []
args.unshift("[#{@modelName}] ")
console?.log?(args...)
@
traceAction: (req, actionName, url) ->
if @_trace
msg = "[#{@modelName}/#{actionName}] #{req.method} #{url}"
if req.params? and (@resource.id or req.params)
id = req.params[@resource.id]
if id
msg = msg + " id:#{id}"
console?.log?(msg)
@
# return instance id value from req.params
getId: (req) ->
req.params[@resource.id]
_computeToObjectOpts: ->
@_toObjectOpts = {}
if @opts.toObject? and @opts.toObject
@_toObjectOpts = @opts.toObject
@_toObjectOpts = defaults(@_toObjectOpts, ModelController.TOOBJECT_DEFAULT_OPTS)
@
_default_serialize_cb: (instance, toObjectOpts) ->
instance.toObject(toObjectOpts)
preprocess_instance: (instance) ->
req =
instance: instance
toObject: @_toObjectOpts
res = {}
invoke_callbacks(@, @_pre_serialize_cbs, req, res)
req.object = @_serialize_cb(req.instance, req.toObject)
invoke_callbacks(@, @_post_serialize_cbs, req, res)
return req.object
preprocess_instances: (instances) ->
instances.map (instance) => @preprocess_instance(instance)
# views 'get' and 'get_all' helpers
get: (id, fn) ->
return @model.findById id, (err, item) =>
if (not err) and item
fn(null, item)
else
errtext = if err? then "\nError: #{err}" else ""
fn(new Error("#{@modelName} with id:#{id} does not exist.#{errtext}"))
get_conditions: (conditions, fn) ->
cb = (err, items) =>
if (not err) and items?
fn(null, items)
else
errtext = if err? then "\nError: #{err}" else ""
fn(new Error("Can't retrieve list of #{@modelName}.#{errtext}"))
if conditions?
return @model.find conditions, cb
return @model.find cb
get_all: (fn) ->
return @get_conditions null, fn
get_body_instance_values: (req, defaults) ->
iv = extend({}, defaults, false)
@model.schema.eachPath (pathname) =>
path = @model.schema.path(pathname)
# TODO: handle compound pathnames (like 'aaa.bbb')
if pathname of req.body
iv[pathname] = req.body[pathname]
else if req.files? and (pathname of req.files)
rf = req.files[pathname]
@trace("getting file name:#{rf.name} length:#{rf.length} filename:#{rf.filename} mime:#{rf.mime}")
# TODO: save also length, mime type, ... (provide a mongoose plugin?)
#iv[pathname] = req.files[pathname].path
iv[pathname] = {file: req.files[pathname]}
iv
update_instance_from_body_values: (req, instance) ->
@model.schema.eachPath (pathname) =>
path = @model.schema.path(pathname)
# TODO: handle compound pathnames (like 'aaa.bbb')
if pathname of req.body
instance.set(pathname, req.body[pathname])
else if req.files? and (pathname of req.files)
rf = req.files[pathname]
@trace("getting file name:#{rf.name} length:#{rf.length} filename:#{rf.filename} mime:#{rf.mime}")
# TODO: save also length, mime type, ... (provide a mongoose plugin?)
#instance[pathname] = req.files[pathname].path
instance.set("#{pathname}.file", req.files[pathname])
instance
exports.ModelController = ModelController
old_app_resource = express.HTTPServer::resource
express.HTTPServer::resource = express.HTTPSServer::resource = (name, actions, opts) ->
o_name = name
o_actions = actions
o_opts = opts
if "object" is typeof name
opts = actions
actions = name
name = null
opts = opts or {}
actions = actions or {}
if not (('model' of opts) or ('model' of actions))
return old_app_resource.call(@, o_name, o_actions, o_opts)
if 'model' of opts
model = opts.model
else if 'model' of actions
model = actions.model
delete actions['model']
controller = opts.controller or new ModelController(@, name, model, opts)
controller._register_schema_action()
res = old_app_resource.call(@, controller.name, controller.getExpressResourceActions(), opts)
controller.resource = res
res.controller = controller
res
| 218622 | # express-mongoose-resource
# Copyright (C) 2012 <NAME>.
#
# Distributed under the MIT License.
# Inspired by:
# https://github.com/visionmedia/express/blob/master/examples/mvc/mvc.js
# https://github.com/visionmedia/express-resource/
# https://github.com/jsmarkus/colibri
#
# See also:
# https://github.com/bebraw/rest-sugar
# https://github.com/enyo/mongo-rest
#
# Usage:
#
# app.resource('forums', {model: Forum})
# or
# app.resource({model: Forum})
#
# this will add automatically the following routes to the app:
#
# GET /forums/schema -> return the model schema
# GET /forums -> index
# GET /forums/new -> new
# POST /forums -> create
# GET /forums/:forum -> show
# GET /forums/:forum/edit -> edit
# PUT /forums/:forum -> update
# DELETE /forums/:forum -> destroy
#
# Note that if 'model' is not specified, app.resource falls back to
# express-resource implementation.
express = require('express')
Resource = exports.Resource = require('express-resource-middleware')
# Extend a source object with the properties of another object (shallow copy).
extend = (dst, src, overwrite=true) ->
if src?
for key, val of src
if (key not of dst) or overwrite
dst[key] = val
dst
# Add missing properties from a `src` object.
defaults = (dst, src) ->
for key, val of src
if not (key of dst)
dst[key] = val
dst
invoke_callbacks = (context, callbacks, req, res) ->
callback_invoke = (context, callbacks, i, err, req, res) ->
l = callbacks.length
if i >= l
return
next = (err) ->
return callback_invoke(context, callbacks, i+1, err)
cb = callbacks[i]
if cb.length >= 4
# error handler - (err, req, res, next)
return callbacks[i].call(context, err, req, res, next)
return callbacks[i].call(context, req, res, next)
callback_invoke(context, callbacks, 0, null, req, res)
old_Resource_add = Resource::add
Resource::add = (resource, opts) ->
if resource.controller? and opts.pivotField?
resource.controller.trace("specifying pivot field '#{opts.pivotField}' and req field '#{@id}'")
resource.controller.opts.pivot =
modelField: opts.pivotField
requestField: @id
else
console.log("no @controller or opts.pivotField")
old_Resource_add.call(@, resource)
class ModelController
@TOOBJECT_DEFAULT_OPTS:
getters: true
constructor: (@app, @name, @model, @opts) ->
@schema = @model.schema
@modelName = @model.modelName
@_trace = @opts.trace or true
@_default_format = @opts.format or 'json'
@_toObjectOpts = {}
@_pre_serialize_cbs = []
@_serialize_cb = null
@_post_serialize_cbs = []
@setSerializeCallback(@_default_serialize_cb)
if @opts.pre_serialize
for cb in @opts.pre_serialize
@addPreSerializeCallback(cb)
if @opts.serialize
@setSerializeCallback(@opts.serialize)
if @opts.post_serialize
for cb in @opts.post_serialize
@addPostSerializeCallback(cb)
@_computeToObjectOpts()
@trace(@schema)
if @name is null
@name = @modelName.toLowerCase()
@singular = @name
if 'plural' of @opts
@plural = @opts.plural
else
@plural = @name
if @plural[@plural.length-1] != 's'
@plural += 's'
@name = @plural
# @base is the url base - without model name
# (with leading slash and no trailing slash)
if 'base' of opts
@base = opts.base
else
@base = "/"
if @base[0] != '/'
@base = '/' + @base
if @base[@base.length-1] == '/'
@base = @base[0...@base.length-1]
# @url_prefix is the url prefix complete with model name
# (with leading slash and no trailing slash)
@url_prefix = @base + "/" + @name
if @url_prefix[0] != '/'
@url_prefix = '/' + @url_prefix
if @url_prefix[@url_prefix.length-1] == '/'
@url_prefix = @url_prefix[0...@url_prefix.length-1]
getSchema: ->
schema = {}
getPathInfo = (pathname, path) =>
#path = @model.schema.path(pathname)
# TODO: handle compound pathnames (like 'aaa.bbb')
pathInfo =
name: pathname
kind: path.instance
type: @model.schema.pathType(pathname)
if path.instance is 'ObjectID'
if 'ref' of path.options
pathInfo.references = path.options.ref
if 'auto' of path.options
pathInfo.auto = path.options.auto
pathInfo
@model.schema.eachPath (pathname) =>
path = @model.schema.path(pathname)
pathInfo = getPathInfo(pathname, path)
schema[pathname] = pathInfo
for pathname, virtual of @model.schema.virtuals
pathInfo = getPathInfo(pathname, virtual)
schema[pathname] = pathInfo
schema
_register_schema_action: ->
@app.get "#{@url_prefix}/schema", (req, res, next) =>
res.send(@getSchema())
# -- express-resource auto-loader ---------------------------------
_auto_load: (req, id, fn) ->
@trace("[auto-load] id:#{id} res.id:#{@resource.id}")
@get id, fn
# -- template rendering support -----------------------------------
getTemplateContext: (req, res, extra) ->
context =
model: @model
schema: @schema
modelName: @modelName
name: @name
base: @base
url_prefix: @url_prefix
resource_id: @resource.id
pivot = {}
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
pivot.pivot = @opts.pivot.requestField
pivot.pivot_id = req[@opts.pivot.requestField].id
pivot[@opts.pivot.requestField] = @preprocess_instance(req[@opts.pivot.requestField])
defaults context, pivot
return extend context, extra
getInstanceTemplateContext: (req, res, instance, extra) ->
serialized = @preprocess_instance(instance)
context = @getTemplateContext req, res,
instance: instance
json: JSON.stringify(serialized)
object: serialized
return extend context, extra
getSetTemplateContext: (req, res, instances, extra) ->
serialized = @preprocess_instances(instances)
context = @getTemplateContext req, res,
instances: instances
json: JSON.stringify(serialized)
objects: serialized
return extend context, extra
_renderTemplate: (res, name, context) ->
t_name = @url_prefix
if t_name[0] == '/'
t_name = t_name[1..]
if t_name[t_name.length-1] != '/'
t_name = t_name + '/'
t_name += name
return res.render t_name, context
renderTemplate: (res, name, data, context) ->
data.view ||= name
data.name = name
view = data.view
if @opts.render_cb?[view]?
@opts.render_cb[view].call @, data, context, (ctxt) =>
return @_renderTemplate res, name, ctxt
else
return @_renderTemplate res, name, context
# -- default actions ----------------------------------------------
# GET /NAME
_action_index: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'index', "#{@url_prefix} format:#{format}")
subquery = false
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
@trace("subquery on #{@opts.pivot.modelField} = #{req[@opts.pivot.requestField].id}")
subquery = true
else
@trace("NO SUBQUERY")
conditions = null
if subquery
conditions = {}
conditions[@opts.pivot.modelField] = req[@opts.pivot.requestField].id
@trace("conditions:", conditions)
@get_conditions conditions, (err, instances) =>
return next(err) if err
if format == 'html'
ctxt = @getSetTemplateContext req, res, instances,
format: format
view: 'index'
return @renderTemplate res, "index", {instances: instances}, ctxt
return res.send(@preprocess_instances(instances))
# GET /NAME/new
_action_new: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'new', "#{@url_prefix}/new format:#{format}")
instance = new @model
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
if (not @opts.pivot.requestField of instance) or (not instance[@opts.pivot.requestField])
instance[@opts.pivot.requestField] = req[@opts.pivot.requestField].id
if format == 'html'
ctxt = @getInstanceTemplateContext req, res, instance,
format: format
view: 'new'
mode: 'new'
return @renderTemplate res, "edit", {view: 'new', instance: instance}, ctxt
return res.send(@preprocess_instance(instance))
# POST /NAME
_action_create: (req, res, next) ->
redirect_to = req.redirect_to or req.body.redirect_to or null
format = req.format or @_default_format
@traceAction(req, 'create', "#{@url_prefix} format:#{format}")
# #console.log(req.body)
# console.log("REQUEST files:")
# console.log(req.files)
# instanceValues = @get_body_instance_values(req)
# instance = new @model(instanceValues)
instance = new @model()
@update_instance_from_body_values(req, instance)
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
if (not @opts.pivot.requestField of instance) or (not instance[@opts.pivot.requestField])
instance[@opts.pivot.requestField] = req[@opts.pivot.requestField].id
instance.save (err) =>
return next(err) if err
console.log("created #{@modelName} with id:#{instance.id}")
if (req.body._format? and req.body._format == 'html') or (format == 'html')
if redirect_to
return res.redirect redirect_to
return res.redirect @url_prefix + "/#{instance.id}" + ".html"
else
return res.send(@preprocess_instance(instance))
# GET /NAME/:NAME
_action_show: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'show', "#{@url_prefix}:#{@resource.id} format:#{format}")
@get @getId(req), (err, instance) =>
return next(err) if err
if format == 'html'
ctxt = @getInstanceTemplateContext req, res, instance,
format: format
view: 'show'
return @renderTemplate res, "show", {instance: instance}, ctxt
else
return res.send(@preprocess_instance(instance))
# GET /NAME/:NAME/edit
_action_edit: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'edit', "#{@url_prefix}:#{@resource.id}/edit format:#{format}")
@get @getId(req), (err, instance) =>
return next(err) if err
if format == 'html'
ctxt = @getInstanceTemplateContext req, res, instance,
format: format
view: 'edit'
mode: 'edit'
return @renderTemplate res, "edit", {instance: instance}, ctxt
res.send(@preprocess_instance(instance))
# PUT /NAME/:NAME
_action_update: (req, res, next) ->
redirect_to = req.redirect_to or req.body.redirect_to or null
id = @getId(req)
@traceAction(req, 'update', "#{@url_prefix}:#{@resource.id}")
@get id, (err, instance) =>
return next(err) if err
console.log("REQUEST files:")
console.log(req.files)
# instanceValues = @get_body_instance_values(req)
# extend(instance, instanceValues, true)
@update_instance_from_body_values(req, instance)
return instance.save (err) =>
return next(err) if err
console.log("updated #{@modelName} with id:#{id}")
if req.body._format? and req.body._format == 'html'
if redirect_to
return res.redirect redirect_to
return res.redirect @url_prefix + "/#{instance.id}" + ".html"
else
return res.send(@preprocess_instance(instance))
# DELETE /NAME/:NAME
_action_destroy: (req, res, next) ->
redirect_to = req.redirect_to or req.body.redirect_to or null
id = @getId(req)
@traceAction(req, 'destroy', "#{@url_prefix}:#{@resource.id}")
return @get id, (err, instance) =>
return next(err) if err
return instance.remove (err) =>
return next(err) if err
console.log("removed #{@modelName} with id:#{id}")
if redirect_to
return res.redirect redirect_to
return res.send('')
# -- express-resource support ---------------------------------------
getExpressResourceActions: (actions) ->
actions = actions or {}
controller = @
extend actions,
index: -> # GET /NAME
controller._action_index.apply(controller, arguments)
new: -> # GET /NAME/new
controller._action_new.apply(controller, arguments)
create: -> # POST /NAME
controller._action_create.apply(controller, arguments)
show: -> # GET /NAME/:NAME
controller._action_show.apply(controller, arguments)
edit: -> # GET /NAME/:NAME/edit
controller._action_edit.apply(controller, arguments)
update: -> # PUT /NAME/:NAME
controller._action_update.apply(controller, arguments)
destroy: -> # DELETE /NAME/:NAME
controller._action_destroy.apply(controller, arguments)
load: -> # express-resource auto-load
controller._auto_load.apply(controller, arguments)
actions
# -- serialization --------------------------------------------------
addPreSerializeCallback: (cb) ->
@_pre_serialize_cbs.push cb
@
setSerializeCallback: (cb) ->
@_serialize_cb = cb
@
addPostSerializeCallback: (cb) ->
@_post_serialize_cbs.push cb
@
# -- helper methods -------------------------------------------------
# trace
trace: (args...) ->
if @_trace
args = args or []
args.unshift("[#{@modelName}] ")
console?.log?(args...)
@
traceAction: (req, actionName, url) ->
if @_trace
msg = "[#{@modelName}/#{actionName}] #{req.method} #{url}"
if req.params? and (@resource.id or req.params)
id = req.params[@resource.id]
if id
msg = msg + " id:#{id}"
console?.log?(msg)
@
# return instance id value from req.params
getId: (req) ->
req.params[@resource.id]
_computeToObjectOpts: ->
@_toObjectOpts = {}
if @opts.toObject? and @opts.toObject
@_toObjectOpts = @opts.toObject
@_toObjectOpts = defaults(@_toObjectOpts, ModelController.TOOBJECT_DEFAULT_OPTS)
@
_default_serialize_cb: (instance, toObjectOpts) ->
instance.toObject(toObjectOpts)
preprocess_instance: (instance) ->
req =
instance: instance
toObject: @_toObjectOpts
res = {}
invoke_callbacks(@, @_pre_serialize_cbs, req, res)
req.object = @_serialize_cb(req.instance, req.toObject)
invoke_callbacks(@, @_post_serialize_cbs, req, res)
return req.object
preprocess_instances: (instances) ->
instances.map (instance) => @preprocess_instance(instance)
# views 'get' and 'get_all' helpers
get: (id, fn) ->
return @model.findById id, (err, item) =>
if (not err) and item
fn(null, item)
else
errtext = if err? then "\nError: #{err}" else ""
fn(new Error("#{@modelName} with id:#{id} does not exist.#{errtext}"))
get_conditions: (conditions, fn) ->
cb = (err, items) =>
if (not err) and items?
fn(null, items)
else
errtext = if err? then "\nError: #{err}" else ""
fn(new Error("Can't retrieve list of #{@modelName}.#{errtext}"))
if conditions?
return @model.find conditions, cb
return @model.find cb
get_all: (fn) ->
return @get_conditions null, fn
get_body_instance_values: (req, defaults) ->
iv = extend({}, defaults, false)
@model.schema.eachPath (pathname) =>
path = @model.schema.path(pathname)
# TODO: handle compound pathnames (like 'aaa.bbb')
if pathname of req.body
iv[pathname] = req.body[pathname]
else if req.files? and (pathname of req.files)
rf = req.files[pathname]
@trace("getting file name:#{rf.name} length:#{rf.length} filename:#{rf.filename} mime:#{rf.mime}")
# TODO: save also length, mime type, ... (provide a mongoose plugin?)
#iv[pathname] = req.files[pathname].path
iv[pathname] = {file: req.files[pathname]}
iv
update_instance_from_body_values: (req, instance) ->
@model.schema.eachPath (pathname) =>
path = @model.schema.path(pathname)
# TODO: handle compound pathnames (like 'aaa.bbb')
if pathname of req.body
instance.set(pathname, req.body[pathname])
else if req.files? and (pathname of req.files)
rf = req.files[pathname]
@trace("getting file name:#{rf.name} length:#{rf.length} filename:#{rf.filename} mime:#{rf.mime}")
# TODO: save also length, mime type, ... (provide a mongoose plugin?)
#instance[pathname] = req.files[pathname].path
instance.set("#{pathname}.file", req.files[pathname])
instance
exports.ModelController = ModelController
old_app_resource = express.HTTPServer::resource
express.HTTPServer::resource = express.HTTPSServer::resource = (name, actions, opts) ->
o_name = name
o_actions = actions
o_opts = opts
if "object" is typeof name
opts = actions
actions = name
name = null
opts = opts or {}
actions = actions or {}
if not (('model' of opts) or ('model' of actions))
return old_app_resource.call(@, o_name, o_actions, o_opts)
if 'model' of opts
model = opts.model
else if 'model' of actions
model = actions.model
delete actions['model']
controller = opts.controller or new ModelController(@, name, model, opts)
controller._register_schema_action()
res = old_app_resource.call(@, controller.name, controller.getExpressResourceActions(), opts)
controller.resource = res
res.controller = controller
res
| true | # express-mongoose-resource
# Copyright (C) 2012 PI:NAME:<NAME>END_PI.
#
# Distributed under the MIT License.
# Inspired by:
# https://github.com/visionmedia/express/blob/master/examples/mvc/mvc.js
# https://github.com/visionmedia/express-resource/
# https://github.com/jsmarkus/colibri
#
# See also:
# https://github.com/bebraw/rest-sugar
# https://github.com/enyo/mongo-rest
#
# Usage:
#
# app.resource('forums', {model: Forum})
# or
# app.resource({model: Forum})
#
# this will add automatically the following routes to the app:
#
# GET /forums/schema -> return the model schema
# GET /forums -> index
# GET /forums/new -> new
# POST /forums -> create
# GET /forums/:forum -> show
# GET /forums/:forum/edit -> edit
# PUT /forums/:forum -> update
# DELETE /forums/:forum -> destroy
#
# Note that if 'model' is not specified, app.resource falls back to
# express-resource implementation.
express = require('express')
Resource = exports.Resource = require('express-resource-middleware')
# Extend a source object with the properties of another object (shallow copy).
extend = (dst, src, overwrite=true) ->
if src?
for key, val of src
if (key not of dst) or overwrite
dst[key] = val
dst
# Add missing properties from a `src` object.
defaults = (dst, src) ->
for key, val of src
if not (key of dst)
dst[key] = val
dst
invoke_callbacks = (context, callbacks, req, res) ->
callback_invoke = (context, callbacks, i, err, req, res) ->
l = callbacks.length
if i >= l
return
next = (err) ->
return callback_invoke(context, callbacks, i+1, err)
cb = callbacks[i]
if cb.length >= 4
# error handler - (err, req, res, next)
return callbacks[i].call(context, err, req, res, next)
return callbacks[i].call(context, req, res, next)
callback_invoke(context, callbacks, 0, null, req, res)
old_Resource_add = Resource::add
Resource::add = (resource, opts) ->
if resource.controller? and opts.pivotField?
resource.controller.trace("specifying pivot field '#{opts.pivotField}' and req field '#{@id}'")
resource.controller.opts.pivot =
modelField: opts.pivotField
requestField: @id
else
console.log("no @controller or opts.pivotField")
old_Resource_add.call(@, resource)
class ModelController
@TOOBJECT_DEFAULT_OPTS:
getters: true
constructor: (@app, @name, @model, @opts) ->
@schema = @model.schema
@modelName = @model.modelName
@_trace = @opts.trace or true
@_default_format = @opts.format or 'json'
@_toObjectOpts = {}
@_pre_serialize_cbs = []
@_serialize_cb = null
@_post_serialize_cbs = []
@setSerializeCallback(@_default_serialize_cb)
if @opts.pre_serialize
for cb in @opts.pre_serialize
@addPreSerializeCallback(cb)
if @opts.serialize
@setSerializeCallback(@opts.serialize)
if @opts.post_serialize
for cb in @opts.post_serialize
@addPostSerializeCallback(cb)
@_computeToObjectOpts()
@trace(@schema)
if @name is null
@name = @modelName.toLowerCase()
@singular = @name
if 'plural' of @opts
@plural = @opts.plural
else
@plural = @name
if @plural[@plural.length-1] != 's'
@plural += 's'
@name = @plural
# @base is the url base - without model name
# (with leading slash and no trailing slash)
if 'base' of opts
@base = opts.base
else
@base = "/"
if @base[0] != '/'
@base = '/' + @base
if @base[@base.length-1] == '/'
@base = @base[0...@base.length-1]
# @url_prefix is the url prefix complete with model name
# (with leading slash and no trailing slash)
@url_prefix = @base + "/" + @name
if @url_prefix[0] != '/'
@url_prefix = '/' + @url_prefix
if @url_prefix[@url_prefix.length-1] == '/'
@url_prefix = @url_prefix[0...@url_prefix.length-1]
getSchema: ->
schema = {}
getPathInfo = (pathname, path) =>
#path = @model.schema.path(pathname)
# TODO: handle compound pathnames (like 'aaa.bbb')
pathInfo =
name: pathname
kind: path.instance
type: @model.schema.pathType(pathname)
if path.instance is 'ObjectID'
if 'ref' of path.options
pathInfo.references = path.options.ref
if 'auto' of path.options
pathInfo.auto = path.options.auto
pathInfo
@model.schema.eachPath (pathname) =>
path = @model.schema.path(pathname)
pathInfo = getPathInfo(pathname, path)
schema[pathname] = pathInfo
for pathname, virtual of @model.schema.virtuals
pathInfo = getPathInfo(pathname, virtual)
schema[pathname] = pathInfo
schema
_register_schema_action: ->
@app.get "#{@url_prefix}/schema", (req, res, next) =>
res.send(@getSchema())
# -- express-resource auto-loader ---------------------------------
_auto_load: (req, id, fn) ->
@trace("[auto-load] id:#{id} res.id:#{@resource.id}")
@get id, fn
# -- template rendering support -----------------------------------
getTemplateContext: (req, res, extra) ->
context =
model: @model
schema: @schema
modelName: @modelName
name: @name
base: @base
url_prefix: @url_prefix
resource_id: @resource.id
pivot = {}
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
pivot.pivot = @opts.pivot.requestField
pivot.pivot_id = req[@opts.pivot.requestField].id
pivot[@opts.pivot.requestField] = @preprocess_instance(req[@opts.pivot.requestField])
defaults context, pivot
return extend context, extra
getInstanceTemplateContext: (req, res, instance, extra) ->
serialized = @preprocess_instance(instance)
context = @getTemplateContext req, res,
instance: instance
json: JSON.stringify(serialized)
object: serialized
return extend context, extra
getSetTemplateContext: (req, res, instances, extra) ->
serialized = @preprocess_instances(instances)
context = @getTemplateContext req, res,
instances: instances
json: JSON.stringify(serialized)
objects: serialized
return extend context, extra
_renderTemplate: (res, name, context) ->
t_name = @url_prefix
if t_name[0] == '/'
t_name = t_name[1..]
if t_name[t_name.length-1] != '/'
t_name = t_name + '/'
t_name += name
return res.render t_name, context
renderTemplate: (res, name, data, context) ->
data.view ||= name
data.name = name
view = data.view
if @opts.render_cb?[view]?
@opts.render_cb[view].call @, data, context, (ctxt) =>
return @_renderTemplate res, name, ctxt
else
return @_renderTemplate res, name, context
# -- default actions ----------------------------------------------
# GET /NAME
_action_index: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'index', "#{@url_prefix} format:#{format}")
subquery = false
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
@trace("subquery on #{@opts.pivot.modelField} = #{req[@opts.pivot.requestField].id}")
subquery = true
else
@trace("NO SUBQUERY")
conditions = null
if subquery
conditions = {}
conditions[@opts.pivot.modelField] = req[@opts.pivot.requestField].id
@trace("conditions:", conditions)
@get_conditions conditions, (err, instances) =>
return next(err) if err
if format == 'html'
ctxt = @getSetTemplateContext req, res, instances,
format: format
view: 'index'
return @renderTemplate res, "index", {instances: instances}, ctxt
return res.send(@preprocess_instances(instances))
# GET /NAME/new
_action_new: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'new', "#{@url_prefix}/new format:#{format}")
instance = new @model
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
if (not @opts.pivot.requestField of instance) or (not instance[@opts.pivot.requestField])
instance[@opts.pivot.requestField] = req[@opts.pivot.requestField].id
if format == 'html'
ctxt = @getInstanceTemplateContext req, res, instance,
format: format
view: 'new'
mode: 'new'
return @renderTemplate res, "edit", {view: 'new', instance: instance}, ctxt
return res.send(@preprocess_instance(instance))
# POST /NAME
_action_create: (req, res, next) ->
redirect_to = req.redirect_to or req.body.redirect_to or null
format = req.format or @_default_format
@traceAction(req, 'create', "#{@url_prefix} format:#{format}")
# #console.log(req.body)
# console.log("REQUEST files:")
# console.log(req.files)
# instanceValues = @get_body_instance_values(req)
# instance = new @model(instanceValues)
instance = new @model()
@update_instance_from_body_values(req, instance)
if @opts.pivot?
@trace("we have a pivot model field: '#{@opts.pivot.modelField}' req field: '#{@opts.pivot.requestField}'")
@trace("req.#{@opts.pivot.requestField} = #{req[@opts.pivot.requestField]}")
if @opts.pivot.requestField of req
if (not @opts.pivot.requestField of instance) or (not instance[@opts.pivot.requestField])
instance[@opts.pivot.requestField] = req[@opts.pivot.requestField].id
instance.save (err) =>
return next(err) if err
console.log("created #{@modelName} with id:#{instance.id}")
if (req.body._format? and req.body._format == 'html') or (format == 'html')
if redirect_to
return res.redirect redirect_to
return res.redirect @url_prefix + "/#{instance.id}" + ".html"
else
return res.send(@preprocess_instance(instance))
# GET /NAME/:NAME
_action_show: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'show', "#{@url_prefix}:#{@resource.id} format:#{format}")
@get @getId(req), (err, instance) =>
return next(err) if err
if format == 'html'
ctxt = @getInstanceTemplateContext req, res, instance,
format: format
view: 'show'
return @renderTemplate res, "show", {instance: instance}, ctxt
else
return res.send(@preprocess_instance(instance))
# GET /NAME/:NAME/edit
_action_edit: (req, res, next) ->
format = req.format or @_default_format
@traceAction(req, 'edit', "#{@url_prefix}:#{@resource.id}/edit format:#{format}")
@get @getId(req), (err, instance) =>
return next(err) if err
if format == 'html'
ctxt = @getInstanceTemplateContext req, res, instance,
format: format
view: 'edit'
mode: 'edit'
return @renderTemplate res, "edit", {instance: instance}, ctxt
res.send(@preprocess_instance(instance))
# PUT /NAME/:NAME
_action_update: (req, res, next) ->
redirect_to = req.redirect_to or req.body.redirect_to or null
id = @getId(req)
@traceAction(req, 'update', "#{@url_prefix}:#{@resource.id}")
@get id, (err, instance) =>
return next(err) if err
console.log("REQUEST files:")
console.log(req.files)
# instanceValues = @get_body_instance_values(req)
# extend(instance, instanceValues, true)
@update_instance_from_body_values(req, instance)
return instance.save (err) =>
return next(err) if err
console.log("updated #{@modelName} with id:#{id}")
if req.body._format? and req.body._format == 'html'
if redirect_to
return res.redirect redirect_to
return res.redirect @url_prefix + "/#{instance.id}" + ".html"
else
return res.send(@preprocess_instance(instance))
# DELETE /NAME/:NAME
_action_destroy: (req, res, next) ->
redirect_to = req.redirect_to or req.body.redirect_to or null
id = @getId(req)
@traceAction(req, 'destroy', "#{@url_prefix}:#{@resource.id}")
return @get id, (err, instance) =>
return next(err) if err
return instance.remove (err) =>
return next(err) if err
console.log("removed #{@modelName} with id:#{id}")
if redirect_to
return res.redirect redirect_to
return res.send('')
# -- express-resource support ---------------------------------------
getExpressResourceActions: (actions) ->
actions = actions or {}
controller = @
extend actions,
index: -> # GET /NAME
controller._action_index.apply(controller, arguments)
new: -> # GET /NAME/new
controller._action_new.apply(controller, arguments)
create: -> # POST /NAME
controller._action_create.apply(controller, arguments)
show: -> # GET /NAME/:NAME
controller._action_show.apply(controller, arguments)
edit: -> # GET /NAME/:NAME/edit
controller._action_edit.apply(controller, arguments)
update: -> # PUT /NAME/:NAME
controller._action_update.apply(controller, arguments)
destroy: -> # DELETE /NAME/:NAME
controller._action_destroy.apply(controller, arguments)
load: -> # express-resource auto-load
controller._auto_load.apply(controller, arguments)
actions
# -- serialization --------------------------------------------------
addPreSerializeCallback: (cb) ->
@_pre_serialize_cbs.push cb
@
setSerializeCallback: (cb) ->
@_serialize_cb = cb
@
addPostSerializeCallback: (cb) ->
@_post_serialize_cbs.push cb
@
# -- helper methods -------------------------------------------------
# trace
trace: (args...) ->
if @_trace
args = args or []
args.unshift("[#{@modelName}] ")
console?.log?(args...)
@
traceAction: (req, actionName, url) ->
if @_trace
msg = "[#{@modelName}/#{actionName}] #{req.method} #{url}"
if req.params? and (@resource.id or req.params)
id = req.params[@resource.id]
if id
msg = msg + " id:#{id}"
console?.log?(msg)
@
# return instance id value from req.params
getId: (req) ->
req.params[@resource.id]
_computeToObjectOpts: ->
@_toObjectOpts = {}
if @opts.toObject? and @opts.toObject
@_toObjectOpts = @opts.toObject
@_toObjectOpts = defaults(@_toObjectOpts, ModelController.TOOBJECT_DEFAULT_OPTS)
@
_default_serialize_cb: (instance, toObjectOpts) ->
instance.toObject(toObjectOpts)
preprocess_instance: (instance) ->
req =
instance: instance
toObject: @_toObjectOpts
res = {}
invoke_callbacks(@, @_pre_serialize_cbs, req, res)
req.object = @_serialize_cb(req.instance, req.toObject)
invoke_callbacks(@, @_post_serialize_cbs, req, res)
return req.object
preprocess_instances: (instances) ->
instances.map (instance) => @preprocess_instance(instance)
# views 'get' and 'get_all' helpers
get: (id, fn) ->
return @model.findById id, (err, item) =>
if (not err) and item
fn(null, item)
else
errtext = if err? then "\nError: #{err}" else ""
fn(new Error("#{@modelName} with id:#{id} does not exist.#{errtext}"))
get_conditions: (conditions, fn) ->
cb = (err, items) =>
if (not err) and items?
fn(null, items)
else
errtext = if err? then "\nError: #{err}" else ""
fn(new Error("Can't retrieve list of #{@modelName}.#{errtext}"))
if conditions?
return @model.find conditions, cb
return @model.find cb
get_all: (fn) ->
return @get_conditions null, fn
get_body_instance_values: (req, defaults) ->
iv = extend({}, defaults, false)
@model.schema.eachPath (pathname) =>
path = @model.schema.path(pathname)
# TODO: handle compound pathnames (like 'aaa.bbb')
if pathname of req.body
iv[pathname] = req.body[pathname]
else if req.files? and (pathname of req.files)
rf = req.files[pathname]
@trace("getting file name:#{rf.name} length:#{rf.length} filename:#{rf.filename} mime:#{rf.mime}")
# TODO: save also length, mime type, ... (provide a mongoose plugin?)
#iv[pathname] = req.files[pathname].path
iv[pathname] = {file: req.files[pathname]}
iv
update_instance_from_body_values: (req, instance) ->
@model.schema.eachPath (pathname) =>
path = @model.schema.path(pathname)
# TODO: handle compound pathnames (like 'aaa.bbb')
if pathname of req.body
instance.set(pathname, req.body[pathname])
else if req.files? and (pathname of req.files)
rf = req.files[pathname]
@trace("getting file name:#{rf.name} length:#{rf.length} filename:#{rf.filename} mime:#{rf.mime}")
# TODO: save also length, mime type, ... (provide a mongoose plugin?)
#instance[pathname] = req.files[pathname].path
instance.set("#{pathname}.file", req.files[pathname])
instance
exports.ModelController = ModelController
old_app_resource = express.HTTPServer::resource
express.HTTPServer::resource = express.HTTPSServer::resource = (name, actions, opts) ->
o_name = name
o_actions = actions
o_opts = opts
if "object" is typeof name
opts = actions
actions = name
name = null
opts = opts or {}
actions = actions or {}
if not (('model' of opts) or ('model' of actions))
return old_app_resource.call(@, o_name, o_actions, o_opts)
if 'model' of opts
model = opts.model
else if 'model' of actions
model = actions.model
delete actions['model']
controller = opts.controller or new ModelController(@, name, model, opts)
controller._register_schema_action()
res = old_app_resource.call(@, controller.name, controller.getExpressResourceActions(), opts)
controller.resource = res
res.controller = controller
res
|
[
{
"context": "k.js\n# @namespeace Desk\n#\n# @version 0.1\n# @author Jhon Marroquin || @jhon3rick\n# @author Jonatan Herran || @jonata",
"end": 74,
"score": 0.9998936057090759,
"start": 60,
"tag": "NAME",
"value": "Jhon Marroquin"
},
{
"context": " Desk\n#\n# @version 0.1\n# @author ... | source/coffee/Desktop.coffee | jhon3rick/Desk | 0 | ###
# Desk.js
# @namespeace Desk
#
# @version 0.1
# @author Jhon Marroquin || @jhon3rick
# @author Jonatan Herran || @jonatan2874
#
###
"use strict"
Desk = do ->
Desk = {}
Desk.Create = (obj) ->
alignment = obj.alignment || 'left'
widthIcons = obj.widthIcons || 5
taskbar = obj.taskbar || {}
user = obj.user or {}
htmlUser = ''
position = obj.position || 'top'
background = obj.background || {}
htmlBackground = ''
if obj is null
console.warn("Debe enviar el objeto con los parametros para crear el Desktop")
return
if obj.modules is null
console.warn("Debe enviar el objeto con los modulos a agregar al Desktop")
return
if background != {} and alignment=='left' then htmlBackground = _backgroundLeft(background)
color = ''
img = ''
type = ''
style = ''
styl = ''
if alignment=='center'
styl = 'display:table;'
if background != {}
color = background.color || ''
img = background.img || ''
type = background.type || ''
style = background.style || ''
if color != '' then color = "background-color:#{color};"
if img != '' then img = "background-image:url(#{img});"
if type != '' then type = "background-position:#{type};"
else styl = 'position:absolute;'
htmlTaskbar = "<div id=\"Desk-task-bar\" class=\"Desk-task-bar\"></div>"
htmlDesktop = "<div id=\"Desk-body\" class=\"Desk-body\">
<div id=\"Desk-content-apps-menu\" class=\"Desk-content-apps-menu\" onclick=\"return; Desk.EventTaskBarApps()\">
<div id=\"Desk-menuApps\" class=\"Desk-menuApps\"></div>
</div>
<div id=\"Desk_content_icons\" class=\"Desk-content-icons\" style=\"#{styl} #{color} #{img} #{type} #{style}\"> </div>
#{htmlBackground}
</div>"
html = "";
if position == 'top' then html += "#{htmlTaskbar}#{htmlDesktop}"
else if position == 'bottom' then html += "#{htmlDesktop}#{htmlTaskbar}"
document.body.innerHTML += html
_addTaskbar(taskbar)
htmlModule = if alignment=='left' then _createModulesLeft obj.modules,position else _createModulesCenter obj.modules,position
if(user != '') then htmlUser = _createUserInfo user
document.getElementById('Desk_content_icons').innerHTML = htmlModule.desk
document.getElementById('Desk-menuApps').innerHTML = htmlModule.menu
document.getElementById("Desk-body").innerHTML += htmlUser
Desk.Reload = (id) ->
url = document.getElementById("module-#{id}").getAttribute("src")
document.getElementById("module-#{id}").setAttribute("src",url)
Desk.Logout = () ->
if !confirm("Esta seguro que desea salir de la aplicacion!") then return
document.querySelector('body').setAttribute('onbeforeunload','')
document.location = "logout.php"
Desk.EventTaskBarApps = (e) ->
e.preventDefault
e.stopPropagation()
parentMenu = document.getElementById('Desk-content-apps-menu')
divMenu = document.getElementById('Desk-menuApps')
style = divMenu.getAttribute('style')
if style == '' || style == null
parentMenu.setAttribute('style','width:100%;')
divMenu.setAttribute('style','left:0px;')
else
parentMenu.setAttribute('style','')
divMenu.setAttribute('style','')
Desk.OpenModule = (id,text,icon,width,height,style,url) ->
if document.getElementById('Desk-content-module-'+id)
this.ModuleActive(id)
return
div = document.createElement("div");
div.setAttribute("id","Desk-content-module-#{id}")
div.setAttribute("class","Desk-content-module")
div.setAttribute("data-state","close")
div.setAttribute("data-module","module-#{id}")
div.innerHTML = "<div id=\"top-bar-#{id}\" class=\"Desk-top-bar-module\">
<div class=\"title-module\">#{text}</div>
<div class=\"reload\" onclick=\"Desk.Reload(\'#{id}\')\"></div>
<div class=\"minimize\" onclick=\"Desk.MinimizeModule(\'#{id}\')\"></div>
<div class=\"close\" onclick=\"Desk.CloseModule(\'#{id}\')\"></div>
</div>
<iframe type=\"text/html\" src=\"#{url}\" id=\"module-#{id}\" name=\"module-#{id}\"></object>'"
document.getElementById('Desk-body').appendChild(div)
# Delete div Empty
arrayEmpty = document.querySelectorAll("#Desk-barApps .divEmpty")
[].forEach.call(arrayEmpty, (divEmpty) -> divEmpty.parentNode.removeChild(divEmpty) )
# Add new div App Open
document.getElementById('Desk-barApps').innerHTML += "<div id=\"Desk-barApps-module-#{id}\" data-module=\"module-#{id}\" class=\"Desk-barApps-module\" onclick=\"Desk.ModuleActive('#{id}','barApps')\">
<div class=\"icon-access\">
<img src=\"#{icon}\">
</div>
<div class=\"label-access\">
<span>#{text}</span>
</div>
</div><div class=\"divEmpty\"></div>"
setTimeout( -> Desk.ModuleActive id,"icon" )
Desk.PositionModule('Desk-content-module-'+id,width,height,style)
Desk.CloseModule = (id) ->
document.getElementById('Desk-barApps-module-'+id).setAttribute('data-state','close')
document.getElementById('Desk-content-module-'+id).setAttribute('data-state','close')
document.getElementById('Desk-menuApps-module-'+id).setAttribute('data-state','close')
Desk.MinimizeModule = (id) ->
document.getElementById('Desk-content-module-'+id).setAttribute('data-state','minimize')
document.getElementById('Desk-barApps-module-'+id).setAttribute('data-state','minimize')
document.getElementById('Desk-menuApps-module-'+id).setAttribute('data-state','minimize')
Desk.PositionModule = (id,width,height,style) ->
body_width = document.body.offsetWidth
body_height = document.body.offsetHeight - 35
position = ""
height = height || ""
width = width || ""
style = style || ""
if isNaN(height) || isNaN(width)
if width == 0 || height == 0
width = body_width - 40
height = body_height - 40
top = (body_height - height)/2
left = (body_width - width)/2
position = "top:#{top}; left:#{left}; width:#{width}; height:#{height}; "
document.getElementById(id).setAttribute('style',"#{position} #{style}")
Desk.ModuleActive = (id,div_event) ->
if div_event == "barApps"
state = document.getElementById("Desk-barApps-module-#{id}").getAttribute("data-state")
if state == "open"
Desk.MinimizeModule(id)
return
modules = document.querySelectorAll(".Desk-content-module[data-state=open]")
[].forEach.call(modules, (modulo) ->
module = modulo.getAttribute("data-module")
modulo.setAttribute('data-state','minimize')
document.getElementById('Desk-barApps-'+module).setAttribute('data-state','minimize')
document.getElementById('Desk-menuApps-'+module).setAttribute('data-state','minimize')
)
document.getElementById('Desk-content-module-'+id).setAttribute('data-state','open')
document.getElementById('Desk-barApps-module-'+id).setAttribute('data-state','open')
document.getElementById('Desk-menuApps-module-'+id).setAttribute('data-state','open')
_createModulesCenter = (obj, position) ->
window.addEventListener "click", (event) ->
style = document.getElementById('Desk-menuApps').getAttribute('style')
if style != '' && style != null then Desk.EventTaskBarApps(event)
bodyWidth = document.getElementById("Desk_content_icons").offsetWidth
bodyHeight = document.getElementById("Desk_content_icons").offsetHeight
acumWidth = 0;
acumHeight = 0;
apps_menu = ""
apps_desk = ""
evt_module = ""
contModule = 0
# CLOSE SESSION MENU
html_exit = "<div id=\"Desk-menuApps-close\" class=\"Desk-menuApps-close\" onclick=\"Desk.Logout()\">
<div>
<div class=\"icon\">
<div class=\"logout\"></div>
</div>
<div class=\"text\">Salir del Aplicativo</div>
</div>
</div>"
for key, modulo of obj
state = "enable"
text = modulo.text or ''
width = modulo.width or ''
height = modulo.height or ''
style = modulo.style or ''
bigIcon = modulo.bigIcon or ''
minIcon = modulo.minIcon or ''
disabled = modulo.disabled or ''
evt_module = ''
url = modulo.autoLoad.url or ''
if disabled or disabled is 'true' then state = "disabled"
else evt_module = "onclick=\"Desk.OpenModule('#{contModule}','#{text}','#{minIcon}','#{width}','#{height}','#{style}','#{url}')\""
apps_menu += "<div id=\"Desk-menuApps-module-#{key}\" class=\"Desk-menuApps-module\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module}>
<div class=\"Desk-menu-row\">
<div class=\"icon\"><img src=\"#{bigIcon}\"></div>
<div class=\"text\">#{text}</div>
</div>
</div>"
apps_desk += "<div class=\"Desk-body-icons\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module} style=\"display:inline-table; margin:25px auto;\">
<div>
<div class=\"icon-image\"><img src=\"#{bigIcon}\"></div>
<div class=\"icon-label\">#{text}</div>
</div>
</div>"
contModule++
apps_menu = html_exit+apps_menu
{
desk : "<div style=\"display:table-cell; vertical-align:middle;\">
<div style=\"max-width:550px; overflow:hidden; margin:0 auto; text-align:center;\">#{apps_desk}</div>
</div>",
menu : apps_menu
}
_createModulesLeft = (obj, position) ->
window.addEventListener "click", (event) ->
style = document.getElementById('Desk-menuApps').getAttribute('style')
if style != '' && style != null then Desk.EventTaskBarApps(event)
bodyWidth = document.getElementById("Desk_content_icons").offsetWidth
bodyHeight = document.getElementById("Desk_content_icons").offsetHeight
acumWidth = 0;
acumHeight = 0;
apps_menu = ""
apps_desk = ""
evt_module = ""
contModule = 0
# CLOSE SESSION MENU
html_exit = "<div id=\"Desk-menuApps-close\" class=\"Desk-menuApps-close\" onclick=\"Desk.Logout()\">
<div>
<div class=\"icon\">
<div class=\"logout\"></div>
</div>
<div class=\"text\">Salir del Aplicativo</div>
</div>
</div>"
for key, modulo of obj
state = "enable"
text = modulo.text or ''
width = modulo.width or ''
height = modulo.height or ''
style = modulo.style or ''
bigIcon = modulo.bigIcon or ''
minIcon = modulo.minIcon or ''
disabled = modulo.disabled or ''
evt_module = ''
url = modulo.autoLoad.url or ''
if disabled or disabled is 'true' then state = "disabled"
else evt_module = "onclick=\"Desk.OpenModule('#{contModule}','#{text}','#{minIcon}','#{width}','#{height}','#{style}','#{url}')\""
apps_menu += "<div id=\"Desk-menuApps-module-#{key}\" class=\"Desk-menuApps-module\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module}>
<div class=\"Desk-menu-row\">
<div class=\"icon\"><img src=\"#{bigIcon}\"></div>
<div class=\"text\">#{text}</div>
</div>
</div>"
if acumHeight+90 > bodyHeight
acumHeight = 0
acumWidth += 110
apps_desk += "<div class=\"Desk-body-icons\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module} style=\"margin:10px; position:absolute; top:#{acumHeight}; left:#{acumWidth};\">
<div>
<div class=\"icon-image\"><img src=\"#{bigIcon}\"></div>
<div class=\"icon-label\">#{text}</div>
</div>
</div>"
acumHeight += 90
contModule++
apps_menu = html_exit+apps_menu
{desk:apps_desk, menu:apps_menu}
_createUserInfo = (obj) ->
name = obj.name or ''
firstName = obj.firstName or ''
lastName = obj.lastName or ''
role = obj.role or ''
image = obj.image or ''
office = obj.office or ''
company = obj.company or ''
if name == '' then htmlName = "<div class=\"name\">#{firstName}<br>#{lastName}</div>"
else htmlName = "<div class=\"name\">#{name}</div>"
html = "<div id=\"Desk-content-user-info\" class=\"Desk-content-user-info\">
<div class=\"picture\"><img src=\"#{image}\"></div>
<div class=\"text\">
#{htmlName}
<div class=\"function\">#{role}</div>
<div class=\"company\">#{company}</div>
<div class=\"branch\">#{office}</div>
</div>
</div>"
_addTaskbar = (obj) ->
menu = obj.menu || true
logout = obj.logout || true
items = obj.items || {}
size = 0
htmlMenu = ''
htmlLogout = ''
if menu is true
htmlMenu = "<div class=\"apps\" onclick=\"Desk.EventTaskBarApps(event)\"></div>"
size += 45
if logout is true
htmlLogout = "<div class=\"logout\" onclick=\"Desk.Logout()\"></div>"
size += 35
contAdd = 0
for key, item of items
contAdd++
if item.xtype == 'button'
id = item.id || 'itemTaskbar'+contAdd
icon = item.icon || ''
width = item.width || 25
style = item.style || ''
position = item.position || 'left'
htmlIcon = ''
stylePosition = ''
if position == 'right' then stylePosition = 'float:right;'
if icon != '' then htmlIcon = "<img src=\"#{icon}\" style=\"width:18px; height:18px; margin-top:3px;\">"
htmlAdd = "<div id=\"#{id}\" class=\"addTaskbar\" style=\"width:#{width}px; #{stylePosition} #{style}\">#{htmlIcon}</div>"
if position is 'left' then htmlMenu = htmlMenu+htmlAdd
else htmlLogout = htmlLogout+htmlAdd
size += width
document.getElementById("Desk-task-bar").innerHTML = "#{htmlMenu}<div id=\"Desk-barApps\" class=\"Desk-barApps\" style=\"width:calc(100% - #{size}px);\"></div>#{htmlLogout}"
contAdd = 0
for key, item of items
contAdd++
if item.xtype == 'button'
id = item.id || 'itemTaskbar'+contAdd
if document.getElementById(id) && item.handler
document.getElementById(id).addEventListener('click', ()->
if typeof(item.handler) == 'string' then eval(item.handler)
else item.handler(this)
, false)
_backgroundLeft = (obj) ->
img = obj.img || ''
type = obj.type || ''
color = obj.color || ''
style = obj.style || ''
if color != '' then color = "background-color:#{color}"
html = ""
if type == 'center'
html += "<div style=\"display:table-cell; vertical-align:middle;\">
<div style=\"text-align:center; padding: 10px 0; #{style} #{color}\">
<img src=\"#{img}\" />
</div>
</div>"
html
Desk.version = "0.0.1"
Desk
@Desk = @Desk = Desk
module?.exports = Desk | 1324 | ###
# Desk.js
# @namespeace Desk
#
# @version 0.1
# @author <NAME> || @jhon3rick
# @author <NAME> || @jonatan2874
#
###
"use strict"
Desk = do ->
Desk = {}
Desk.Create = (obj) ->
alignment = obj.alignment || 'left'
widthIcons = obj.widthIcons || 5
taskbar = obj.taskbar || {}
user = obj.user or {}
htmlUser = ''
position = obj.position || 'top'
background = obj.background || {}
htmlBackground = ''
if obj is null
console.warn("Debe enviar el objeto con los parametros para crear el Desktop")
return
if obj.modules is null
console.warn("Debe enviar el objeto con los modulos a agregar al Desktop")
return
if background != {} and alignment=='left' then htmlBackground = _backgroundLeft(background)
color = ''
img = ''
type = ''
style = ''
styl = ''
if alignment=='center'
styl = 'display:table;'
if background != {}
color = background.color || ''
img = background.img || ''
type = background.type || ''
style = background.style || ''
if color != '' then color = "background-color:#{color};"
if img != '' then img = "background-image:url(#{img});"
if type != '' then type = "background-position:#{type};"
else styl = 'position:absolute;'
htmlTaskbar = "<div id=\"Desk-task-bar\" class=\"Desk-task-bar\"></div>"
htmlDesktop = "<div id=\"Desk-body\" class=\"Desk-body\">
<div id=\"Desk-content-apps-menu\" class=\"Desk-content-apps-menu\" onclick=\"return; Desk.EventTaskBarApps()\">
<div id=\"Desk-menuApps\" class=\"Desk-menuApps\"></div>
</div>
<div id=\"Desk_content_icons\" class=\"Desk-content-icons\" style=\"#{styl} #{color} #{img} #{type} #{style}\"> </div>
#{htmlBackground}
</div>"
html = "";
if position == 'top' then html += "#{htmlTaskbar}#{htmlDesktop}"
else if position == 'bottom' then html += "#{htmlDesktop}#{htmlTaskbar}"
document.body.innerHTML += html
_addTaskbar(taskbar)
htmlModule = if alignment=='left' then _createModulesLeft obj.modules,position else _createModulesCenter obj.modules,position
if(user != '') then htmlUser = _createUserInfo user
document.getElementById('Desk_content_icons').innerHTML = htmlModule.desk
document.getElementById('Desk-menuApps').innerHTML = htmlModule.menu
document.getElementById("Desk-body").innerHTML += htmlUser
Desk.Reload = (id) ->
url = document.getElementById("module-#{id}").getAttribute("src")
document.getElementById("module-#{id}").setAttribute("src",url)
Desk.Logout = () ->
if !confirm("Esta seguro que desea salir de la aplicacion!") then return
document.querySelector('body').setAttribute('onbeforeunload','')
document.location = "logout.php"
Desk.EventTaskBarApps = (e) ->
e.preventDefault
e.stopPropagation()
parentMenu = document.getElementById('Desk-content-apps-menu')
divMenu = document.getElementById('Desk-menuApps')
style = divMenu.getAttribute('style')
if style == '' || style == null
parentMenu.setAttribute('style','width:100%;')
divMenu.setAttribute('style','left:0px;')
else
parentMenu.setAttribute('style','')
divMenu.setAttribute('style','')
Desk.OpenModule = (id,text,icon,width,height,style,url) ->
if document.getElementById('Desk-content-module-'+id)
this.ModuleActive(id)
return
div = document.createElement("div");
div.setAttribute("id","Desk-content-module-#{id}")
div.setAttribute("class","Desk-content-module")
div.setAttribute("data-state","close")
div.setAttribute("data-module","module-#{id}")
div.innerHTML = "<div id=\"top-bar-#{id}\" class=\"Desk-top-bar-module\">
<div class=\"title-module\">#{text}</div>
<div class=\"reload\" onclick=\"Desk.Reload(\'#{id}\')\"></div>
<div class=\"minimize\" onclick=\"Desk.MinimizeModule(\'#{id}\')\"></div>
<div class=\"close\" onclick=\"Desk.CloseModule(\'#{id}\')\"></div>
</div>
<iframe type=\"text/html\" src=\"#{url}\" id=\"module-#{id}\" name=\"module-#{id}\"></object>'"
document.getElementById('Desk-body').appendChild(div)
# Delete div Empty
arrayEmpty = document.querySelectorAll("#Desk-barApps .divEmpty")
[].forEach.call(arrayEmpty, (divEmpty) -> divEmpty.parentNode.removeChild(divEmpty) )
# Add new div App Open
document.getElementById('Desk-barApps').innerHTML += "<div id=\"Desk-barApps-module-#{id}\" data-module=\"module-#{id}\" class=\"Desk-barApps-module\" onclick=\"Desk.ModuleActive('#{id}','barApps')\">
<div class=\"icon-access\">
<img src=\"#{icon}\">
</div>
<div class=\"label-access\">
<span>#{text}</span>
</div>
</div><div class=\"divEmpty\"></div>"
setTimeout( -> Desk.ModuleActive id,"icon" )
Desk.PositionModule('Desk-content-module-'+id,width,height,style)
Desk.CloseModule = (id) ->
document.getElementById('Desk-barApps-module-'+id).setAttribute('data-state','close')
document.getElementById('Desk-content-module-'+id).setAttribute('data-state','close')
document.getElementById('Desk-menuApps-module-'+id).setAttribute('data-state','close')
Desk.MinimizeModule = (id) ->
document.getElementById('Desk-content-module-'+id).setAttribute('data-state','minimize')
document.getElementById('Desk-barApps-module-'+id).setAttribute('data-state','minimize')
document.getElementById('Desk-menuApps-module-'+id).setAttribute('data-state','minimize')
Desk.PositionModule = (id,width,height,style) ->
body_width = document.body.offsetWidth
body_height = document.body.offsetHeight - 35
position = ""
height = height || ""
width = width || ""
style = style || ""
if isNaN(height) || isNaN(width)
if width == 0 || height == 0
width = body_width - 40
height = body_height - 40
top = (body_height - height)/2
left = (body_width - width)/2
position = "top:#{top}; left:#{left}; width:#{width}; height:#{height}; "
document.getElementById(id).setAttribute('style',"#{position} #{style}")
Desk.ModuleActive = (id,div_event) ->
if div_event == "barApps"
state = document.getElementById("Desk-barApps-module-#{id}").getAttribute("data-state")
if state == "open"
Desk.MinimizeModule(id)
return
modules = document.querySelectorAll(".Desk-content-module[data-state=open]")
[].forEach.call(modules, (modulo) ->
module = modulo.getAttribute("data-module")
modulo.setAttribute('data-state','minimize')
document.getElementById('Desk-barApps-'+module).setAttribute('data-state','minimize')
document.getElementById('Desk-menuApps-'+module).setAttribute('data-state','minimize')
)
document.getElementById('Desk-content-module-'+id).setAttribute('data-state','open')
document.getElementById('Desk-barApps-module-'+id).setAttribute('data-state','open')
document.getElementById('Desk-menuApps-module-'+id).setAttribute('data-state','open')
_createModulesCenter = (obj, position) ->
window.addEventListener "click", (event) ->
style = document.getElementById('Desk-menuApps').getAttribute('style')
if style != '' && style != null then Desk.EventTaskBarApps(event)
bodyWidth = document.getElementById("Desk_content_icons").offsetWidth
bodyHeight = document.getElementById("Desk_content_icons").offsetHeight
acumWidth = 0;
acumHeight = 0;
apps_menu = ""
apps_desk = ""
evt_module = ""
contModule = 0
# CLOSE SESSION MENU
html_exit = "<div id=\"Desk-menuApps-close\" class=\"Desk-menuApps-close\" onclick=\"Desk.Logout()\">
<div>
<div class=\"icon\">
<div class=\"logout\"></div>
</div>
<div class=\"text\">Salir del Aplicativo</div>
</div>
</div>"
for key, modulo of obj
state = "enable"
text = modulo.text or ''
width = modulo.width or ''
height = modulo.height or ''
style = modulo.style or ''
bigIcon = modulo.bigIcon or ''
minIcon = modulo.minIcon or ''
disabled = modulo.disabled or ''
evt_module = ''
url = modulo.autoLoad.url or ''
if disabled or disabled is 'true' then state = "disabled"
else evt_module = "onclick=\"Desk.OpenModule('#{contModule}','#{text}','#{minIcon}','#{width}','#{height}','#{style}','#{url}')\""
apps_menu += "<div id=\"Desk-menuApps-module-#{key}\" class=\"Desk-menuApps-module\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module}>
<div class=\"Desk-menu-row\">
<div class=\"icon\"><img src=\"#{bigIcon}\"></div>
<div class=\"text\">#{text}</div>
</div>
</div>"
apps_desk += "<div class=\"Desk-body-icons\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module} style=\"display:inline-table; margin:25px auto;\">
<div>
<div class=\"icon-image\"><img src=\"#{bigIcon}\"></div>
<div class=\"icon-label\">#{text}</div>
</div>
</div>"
contModule++
apps_menu = html_exit+apps_menu
{
desk : "<div style=\"display:table-cell; vertical-align:middle;\">
<div style=\"max-width:550px; overflow:hidden; margin:0 auto; text-align:center;\">#{apps_desk}</div>
</div>",
menu : apps_menu
}
_createModulesLeft = (obj, position) ->
window.addEventListener "click", (event) ->
style = document.getElementById('Desk-menuApps').getAttribute('style')
if style != '' && style != null then Desk.EventTaskBarApps(event)
bodyWidth = document.getElementById("Desk_content_icons").offsetWidth
bodyHeight = document.getElementById("Desk_content_icons").offsetHeight
acumWidth = 0;
acumHeight = 0;
apps_menu = ""
apps_desk = ""
evt_module = ""
contModule = 0
# CLOSE SESSION MENU
html_exit = "<div id=\"Desk-menuApps-close\" class=\"Desk-menuApps-close\" onclick=\"Desk.Logout()\">
<div>
<div class=\"icon\">
<div class=\"logout\"></div>
</div>
<div class=\"text\">Salir del Aplicativo</div>
</div>
</div>"
for key, modulo of obj
state = "enable"
text = modulo.text or ''
width = modulo.width or ''
height = modulo.height or ''
style = modulo.style or ''
bigIcon = modulo.bigIcon or ''
minIcon = modulo.minIcon or ''
disabled = modulo.disabled or ''
evt_module = ''
url = modulo.autoLoad.url or ''
if disabled or disabled is 'true' then state = "disabled"
else evt_module = "onclick=\"Desk.OpenModule('#{contModule}','#{text}','#{minIcon}','#{width}','#{height}','#{style}','#{url}')\""
apps_menu += "<div id=\"Desk-menuApps-module-#{key}\" class=\"Desk-menuApps-module\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module}>
<div class=\"Desk-menu-row\">
<div class=\"icon\"><img src=\"#{bigIcon}\"></div>
<div class=\"text\">#{text}</div>
</div>
</div>"
if acumHeight+90 > bodyHeight
acumHeight = 0
acumWidth += 110
apps_desk += "<div class=\"Desk-body-icons\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module} style=\"margin:10px; position:absolute; top:#{acumHeight}; left:#{acumWidth};\">
<div>
<div class=\"icon-image\"><img src=\"#{bigIcon}\"></div>
<div class=\"icon-label\">#{text}</div>
</div>
</div>"
acumHeight += 90
contModule++
apps_menu = html_exit+apps_menu
{desk:apps_desk, menu:apps_menu}
_createUserInfo = (obj) ->
name = obj.name or ''
firstName = obj.firstName or ''
lastName = obj.lastName or ''
role = obj.role or ''
image = obj.image or ''
office = obj.office or ''
company = obj.company or ''
if name == '' then htmlName = "<div class=\"name\">#{firstName}<br>#{lastName}</div>"
else htmlName = "<div class=\"name\">#{name}</div>"
html = "<div id=\"Desk-content-user-info\" class=\"Desk-content-user-info\">
<div class=\"picture\"><img src=\"#{image}\"></div>
<div class=\"text\">
#{htmlName}
<div class=\"function\">#{role}</div>
<div class=\"company\">#{company}</div>
<div class=\"branch\">#{office}</div>
</div>
</div>"
_addTaskbar = (obj) ->
menu = obj.menu || true
logout = obj.logout || true
items = obj.items || {}
size = 0
htmlMenu = ''
htmlLogout = ''
if menu is true
htmlMenu = "<div class=\"apps\" onclick=\"Desk.EventTaskBarApps(event)\"></div>"
size += 45
if logout is true
htmlLogout = "<div class=\"logout\" onclick=\"Desk.Logout()\"></div>"
size += 35
contAdd = 0
for key, item of items
contAdd++
if item.xtype == 'button'
id = item.id || 'itemTaskbar'+contAdd
icon = item.icon || ''
width = item.width || 25
style = item.style || ''
position = item.position || 'left'
htmlIcon = ''
stylePosition = ''
if position == 'right' then stylePosition = 'float:right;'
if icon != '' then htmlIcon = "<img src=\"#{icon}\" style=\"width:18px; height:18px; margin-top:3px;\">"
htmlAdd = "<div id=\"#{id}\" class=\"addTaskbar\" style=\"width:#{width}px; #{stylePosition} #{style}\">#{htmlIcon}</div>"
if position is 'left' then htmlMenu = htmlMenu+htmlAdd
else htmlLogout = htmlLogout+htmlAdd
size += width
document.getElementById("Desk-task-bar").innerHTML = "#{htmlMenu}<div id=\"Desk-barApps\" class=\"Desk-barApps\" style=\"width:calc(100% - #{size}px);\"></div>#{htmlLogout}"
contAdd = 0
for key, item of items
contAdd++
if item.xtype == 'button'
id = item.id || 'itemTaskbar'+contAdd
if document.getElementById(id) && item.handler
document.getElementById(id).addEventListener('click', ()->
if typeof(item.handler) == 'string' then eval(item.handler)
else item.handler(this)
, false)
_backgroundLeft = (obj) ->
img = obj.img || ''
type = obj.type || ''
color = obj.color || ''
style = obj.style || ''
if color != '' then color = "background-color:#{color}"
html = ""
if type == 'center'
html += "<div style=\"display:table-cell; vertical-align:middle;\">
<div style=\"text-align:center; padding: 10px 0; #{style} #{color}\">
<img src=\"#{img}\" />
</div>
</div>"
html
Desk.version = "0.0.1"
Desk
@Desk = @Desk = Desk
module?.exports = Desk | true | ###
# Desk.js
# @namespeace Desk
#
# @version 0.1
# @author PI:NAME:<NAME>END_PI || @jhon3rick
# @author PI:NAME:<NAME>END_PI || @jonatan2874
#
###
"use strict"
Desk = do ->
Desk = {}
Desk.Create = (obj) ->
alignment = obj.alignment || 'left'
widthIcons = obj.widthIcons || 5
taskbar = obj.taskbar || {}
user = obj.user or {}
htmlUser = ''
position = obj.position || 'top'
background = obj.background || {}
htmlBackground = ''
if obj is null
console.warn("Debe enviar el objeto con los parametros para crear el Desktop")
return
if obj.modules is null
console.warn("Debe enviar el objeto con los modulos a agregar al Desktop")
return
if background != {} and alignment=='left' then htmlBackground = _backgroundLeft(background)
color = ''
img = ''
type = ''
style = ''
styl = ''
if alignment=='center'
styl = 'display:table;'
if background != {}
color = background.color || ''
img = background.img || ''
type = background.type || ''
style = background.style || ''
if color != '' then color = "background-color:#{color};"
if img != '' then img = "background-image:url(#{img});"
if type != '' then type = "background-position:#{type};"
else styl = 'position:absolute;'
htmlTaskbar = "<div id=\"Desk-task-bar\" class=\"Desk-task-bar\"></div>"
htmlDesktop = "<div id=\"Desk-body\" class=\"Desk-body\">
<div id=\"Desk-content-apps-menu\" class=\"Desk-content-apps-menu\" onclick=\"return; Desk.EventTaskBarApps()\">
<div id=\"Desk-menuApps\" class=\"Desk-menuApps\"></div>
</div>
<div id=\"Desk_content_icons\" class=\"Desk-content-icons\" style=\"#{styl} #{color} #{img} #{type} #{style}\"> </div>
#{htmlBackground}
</div>"
html = "";
if position == 'top' then html += "#{htmlTaskbar}#{htmlDesktop}"
else if position == 'bottom' then html += "#{htmlDesktop}#{htmlTaskbar}"
document.body.innerHTML += html
_addTaskbar(taskbar)
htmlModule = if alignment=='left' then _createModulesLeft obj.modules,position else _createModulesCenter obj.modules,position
if(user != '') then htmlUser = _createUserInfo user
document.getElementById('Desk_content_icons').innerHTML = htmlModule.desk
document.getElementById('Desk-menuApps').innerHTML = htmlModule.menu
document.getElementById("Desk-body").innerHTML += htmlUser
Desk.Reload = (id) ->
url = document.getElementById("module-#{id}").getAttribute("src")
document.getElementById("module-#{id}").setAttribute("src",url)
Desk.Logout = () ->
if !confirm("Esta seguro que desea salir de la aplicacion!") then return
document.querySelector('body').setAttribute('onbeforeunload','')
document.location = "logout.php"
Desk.EventTaskBarApps = (e) ->
e.preventDefault
e.stopPropagation()
parentMenu = document.getElementById('Desk-content-apps-menu')
divMenu = document.getElementById('Desk-menuApps')
style = divMenu.getAttribute('style')
if style == '' || style == null
parentMenu.setAttribute('style','width:100%;')
divMenu.setAttribute('style','left:0px;')
else
parentMenu.setAttribute('style','')
divMenu.setAttribute('style','')
Desk.OpenModule = (id,text,icon,width,height,style,url) ->
if document.getElementById('Desk-content-module-'+id)
this.ModuleActive(id)
return
div = document.createElement("div");
div.setAttribute("id","Desk-content-module-#{id}")
div.setAttribute("class","Desk-content-module")
div.setAttribute("data-state","close")
div.setAttribute("data-module","module-#{id}")
div.innerHTML = "<div id=\"top-bar-#{id}\" class=\"Desk-top-bar-module\">
<div class=\"title-module\">#{text}</div>
<div class=\"reload\" onclick=\"Desk.Reload(\'#{id}\')\"></div>
<div class=\"minimize\" onclick=\"Desk.MinimizeModule(\'#{id}\')\"></div>
<div class=\"close\" onclick=\"Desk.CloseModule(\'#{id}\')\"></div>
</div>
<iframe type=\"text/html\" src=\"#{url}\" id=\"module-#{id}\" name=\"module-#{id}\"></object>'"
document.getElementById('Desk-body').appendChild(div)
# Delete div Empty
arrayEmpty = document.querySelectorAll("#Desk-barApps .divEmpty")
[].forEach.call(arrayEmpty, (divEmpty) -> divEmpty.parentNode.removeChild(divEmpty) )
# Add new div App Open
document.getElementById('Desk-barApps').innerHTML += "<div id=\"Desk-barApps-module-#{id}\" data-module=\"module-#{id}\" class=\"Desk-barApps-module\" onclick=\"Desk.ModuleActive('#{id}','barApps')\">
<div class=\"icon-access\">
<img src=\"#{icon}\">
</div>
<div class=\"label-access\">
<span>#{text}</span>
</div>
</div><div class=\"divEmpty\"></div>"
setTimeout( -> Desk.ModuleActive id,"icon" )
Desk.PositionModule('Desk-content-module-'+id,width,height,style)
Desk.CloseModule = (id) ->
document.getElementById('Desk-barApps-module-'+id).setAttribute('data-state','close')
document.getElementById('Desk-content-module-'+id).setAttribute('data-state','close')
document.getElementById('Desk-menuApps-module-'+id).setAttribute('data-state','close')
Desk.MinimizeModule = (id) ->
document.getElementById('Desk-content-module-'+id).setAttribute('data-state','minimize')
document.getElementById('Desk-barApps-module-'+id).setAttribute('data-state','minimize')
document.getElementById('Desk-menuApps-module-'+id).setAttribute('data-state','minimize')
Desk.PositionModule = (id,width,height,style) ->
body_width = document.body.offsetWidth
body_height = document.body.offsetHeight - 35
position = ""
height = height || ""
width = width || ""
style = style || ""
if isNaN(height) || isNaN(width)
if width == 0 || height == 0
width = body_width - 40
height = body_height - 40
top = (body_height - height)/2
left = (body_width - width)/2
position = "top:#{top}; left:#{left}; width:#{width}; height:#{height}; "
document.getElementById(id).setAttribute('style',"#{position} #{style}")
Desk.ModuleActive = (id,div_event) ->
if div_event == "barApps"
state = document.getElementById("Desk-barApps-module-#{id}").getAttribute("data-state")
if state == "open"
Desk.MinimizeModule(id)
return
modules = document.querySelectorAll(".Desk-content-module[data-state=open]")
[].forEach.call(modules, (modulo) ->
module = modulo.getAttribute("data-module")
modulo.setAttribute('data-state','minimize')
document.getElementById('Desk-barApps-'+module).setAttribute('data-state','minimize')
document.getElementById('Desk-menuApps-'+module).setAttribute('data-state','minimize')
)
document.getElementById('Desk-content-module-'+id).setAttribute('data-state','open')
document.getElementById('Desk-barApps-module-'+id).setAttribute('data-state','open')
document.getElementById('Desk-menuApps-module-'+id).setAttribute('data-state','open')
_createModulesCenter = (obj, position) ->
window.addEventListener "click", (event) ->
style = document.getElementById('Desk-menuApps').getAttribute('style')
if style != '' && style != null then Desk.EventTaskBarApps(event)
bodyWidth = document.getElementById("Desk_content_icons").offsetWidth
bodyHeight = document.getElementById("Desk_content_icons").offsetHeight
acumWidth = 0;
acumHeight = 0;
apps_menu = ""
apps_desk = ""
evt_module = ""
contModule = 0
# CLOSE SESSION MENU
html_exit = "<div id=\"Desk-menuApps-close\" class=\"Desk-menuApps-close\" onclick=\"Desk.Logout()\">
<div>
<div class=\"icon\">
<div class=\"logout\"></div>
</div>
<div class=\"text\">Salir del Aplicativo</div>
</div>
</div>"
for key, modulo of obj
state = "enable"
text = modulo.text or ''
width = modulo.width or ''
height = modulo.height or ''
style = modulo.style or ''
bigIcon = modulo.bigIcon or ''
minIcon = modulo.minIcon or ''
disabled = modulo.disabled or ''
evt_module = ''
url = modulo.autoLoad.url or ''
if disabled or disabled is 'true' then state = "disabled"
else evt_module = "onclick=\"Desk.OpenModule('#{contModule}','#{text}','#{minIcon}','#{width}','#{height}','#{style}','#{url}')\""
apps_menu += "<div id=\"Desk-menuApps-module-#{key}\" class=\"Desk-menuApps-module\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module}>
<div class=\"Desk-menu-row\">
<div class=\"icon\"><img src=\"#{bigIcon}\"></div>
<div class=\"text\">#{text}</div>
</div>
</div>"
apps_desk += "<div class=\"Desk-body-icons\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module} style=\"display:inline-table; margin:25px auto;\">
<div>
<div class=\"icon-image\"><img src=\"#{bigIcon}\"></div>
<div class=\"icon-label\">#{text}</div>
</div>
</div>"
contModule++
apps_menu = html_exit+apps_menu
{
desk : "<div style=\"display:table-cell; vertical-align:middle;\">
<div style=\"max-width:550px; overflow:hidden; margin:0 auto; text-align:center;\">#{apps_desk}</div>
</div>",
menu : apps_menu
}
_createModulesLeft = (obj, position) ->
window.addEventListener "click", (event) ->
style = document.getElementById('Desk-menuApps').getAttribute('style')
if style != '' && style != null then Desk.EventTaskBarApps(event)
bodyWidth = document.getElementById("Desk_content_icons").offsetWidth
bodyHeight = document.getElementById("Desk_content_icons").offsetHeight
acumWidth = 0;
acumHeight = 0;
apps_menu = ""
apps_desk = ""
evt_module = ""
contModule = 0
# CLOSE SESSION MENU
html_exit = "<div id=\"Desk-menuApps-close\" class=\"Desk-menuApps-close\" onclick=\"Desk.Logout()\">
<div>
<div class=\"icon\">
<div class=\"logout\"></div>
</div>
<div class=\"text\">Salir del Aplicativo</div>
</div>
</div>"
for key, modulo of obj
state = "enable"
text = modulo.text or ''
width = modulo.width or ''
height = modulo.height or ''
style = modulo.style or ''
bigIcon = modulo.bigIcon or ''
minIcon = modulo.minIcon or ''
disabled = modulo.disabled or ''
evt_module = ''
url = modulo.autoLoad.url or ''
if disabled or disabled is 'true' then state = "disabled"
else evt_module = "onclick=\"Desk.OpenModule('#{contModule}','#{text}','#{minIcon}','#{width}','#{height}','#{style}','#{url}')\""
apps_menu += "<div id=\"Desk-menuApps-module-#{key}\" class=\"Desk-menuApps-module\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module}>
<div class=\"Desk-menu-row\">
<div class=\"icon\"><img src=\"#{bigIcon}\"></div>
<div class=\"text\">#{text}</div>
</div>
</div>"
if acumHeight+90 > bodyHeight
acumHeight = 0
acumWidth += 110
apps_desk += "<div class=\"Desk-body-icons\" data-state=\"#{state}\" data-module=\"module-#{contModule}\" #{evt_module} style=\"margin:10px; position:absolute; top:#{acumHeight}; left:#{acumWidth};\">
<div>
<div class=\"icon-image\"><img src=\"#{bigIcon}\"></div>
<div class=\"icon-label\">#{text}</div>
</div>
</div>"
acumHeight += 90
contModule++
apps_menu = html_exit+apps_menu
{desk:apps_desk, menu:apps_menu}
_createUserInfo = (obj) ->
name = obj.name or ''
firstName = obj.firstName or ''
lastName = obj.lastName or ''
role = obj.role or ''
image = obj.image or ''
office = obj.office or ''
company = obj.company or ''
if name == '' then htmlName = "<div class=\"name\">#{firstName}<br>#{lastName}</div>"
else htmlName = "<div class=\"name\">#{name}</div>"
html = "<div id=\"Desk-content-user-info\" class=\"Desk-content-user-info\">
<div class=\"picture\"><img src=\"#{image}\"></div>
<div class=\"text\">
#{htmlName}
<div class=\"function\">#{role}</div>
<div class=\"company\">#{company}</div>
<div class=\"branch\">#{office}</div>
</div>
</div>"
_addTaskbar = (obj) ->
menu = obj.menu || true
logout = obj.logout || true
items = obj.items || {}
size = 0
htmlMenu = ''
htmlLogout = ''
if menu is true
htmlMenu = "<div class=\"apps\" onclick=\"Desk.EventTaskBarApps(event)\"></div>"
size += 45
if logout is true
htmlLogout = "<div class=\"logout\" onclick=\"Desk.Logout()\"></div>"
size += 35
contAdd = 0
for key, item of items
contAdd++
if item.xtype == 'button'
id = item.id || 'itemTaskbar'+contAdd
icon = item.icon || ''
width = item.width || 25
style = item.style || ''
position = item.position || 'left'
htmlIcon = ''
stylePosition = ''
if position == 'right' then stylePosition = 'float:right;'
if icon != '' then htmlIcon = "<img src=\"#{icon}\" style=\"width:18px; height:18px; margin-top:3px;\">"
htmlAdd = "<div id=\"#{id}\" class=\"addTaskbar\" style=\"width:#{width}px; #{stylePosition} #{style}\">#{htmlIcon}</div>"
if position is 'left' then htmlMenu = htmlMenu+htmlAdd
else htmlLogout = htmlLogout+htmlAdd
size += width
document.getElementById("Desk-task-bar").innerHTML = "#{htmlMenu}<div id=\"Desk-barApps\" class=\"Desk-barApps\" style=\"width:calc(100% - #{size}px);\"></div>#{htmlLogout}"
contAdd = 0
for key, item of items
contAdd++
if item.xtype == 'button'
id = item.id || 'itemTaskbar'+contAdd
if document.getElementById(id) && item.handler
document.getElementById(id).addEventListener('click', ()->
if typeof(item.handler) == 'string' then eval(item.handler)
else item.handler(this)
, false)
_backgroundLeft = (obj) ->
img = obj.img || ''
type = obj.type || ''
color = obj.color || ''
style = obj.style || ''
if color != '' then color = "background-color:#{color}"
html = ""
if type == 'center'
html += "<div style=\"display:table-cell; vertical-align:middle;\">
<div style=\"text-align:center; padding: 10px 0; #{style} #{color}\">
<img src=\"#{img}\" />
</div>
</div>"
html
Desk.version = "0.0.1"
Desk
@Desk = @Desk = Desk
module?.exports = Desk |
[
{
"context": "d to parentWidget\n setting = {}\n setting.key = \"payroll\"\n setting.isInitialized = false\n\n # initializat",
"end": 826,
"score": 0.9625753164291382,
"start": 819,
"tag": "KEY",
"value": "payroll"
}
] | src/components/widgets-settings/payroll/payroll.directive.coffee | maestrano/impac-angular | 7 | module = angular.module('impac.components.widgets-settings.payroll',[])
module.controller('SettingPayrollCtrl', ($scope, ImpacDashboardsSvc) ->
w = $scope.parentWidget
$scope.togglePayroll = ->
$scope.selectedPayroll.enabled = !$scope.selectedPayroll.enabled
unless $scope.selectedPayroll.enabled
$scope.selectedPayroll.time_logged = false
$scope.toggleTimeSheetModifier= ->
if $scope.selectedPayroll.enabled
$scope.selectedPayroll.time_logged = !$scope.selectedPayroll.time_logged
$scope.isTogglePayroll = ->
if $scope.selectedPayroll?
return $scope.selectedPayroll.enabled
$scope.isToggleTimeSheetModifier= ->
if $scope.selectedPayroll?
return $scope.selectedPayroll.time_logged
# What will be passed to parentWidget
setting = {}
setting.key = "payroll"
setting.isInitialized = false
# initialization of selected organizations
setting.initialize = ->
ImpacDashboardsSvc.load().then(
(config) ->
currentDashboard = config.currentDashboard
$scope.selectedPayroll = { enabled: false, time_logged: false }
payroll = _.get(w, 'metadata.payroll')
$scope.selectedPayroll = w.metadata.payroll if _.isPlainObject(payroll)
setting.isInitialized = true
)
setting.toMetadata = ->
return { payroll: $scope.selectedPayroll }
w.settings.push(setting)
# Setting is ready: trigger load content
# ------------------------------------
$scope.deferred.resolve($scope.parentWidget)
)
module.directive('settingPayroll', ($templateCache) ->
return {
restrict: 'A',
scope: {
parentWidget: '='
mode: '@?'
deferred: '='
onSelect: '&?'
},
template: $templateCache.get('widgets-settings/payroll.tmpl.html'),
controller: 'SettingPayrollCtrl'
}
)
| 104176 | module = angular.module('impac.components.widgets-settings.payroll',[])
module.controller('SettingPayrollCtrl', ($scope, ImpacDashboardsSvc) ->
w = $scope.parentWidget
$scope.togglePayroll = ->
$scope.selectedPayroll.enabled = !$scope.selectedPayroll.enabled
unless $scope.selectedPayroll.enabled
$scope.selectedPayroll.time_logged = false
$scope.toggleTimeSheetModifier= ->
if $scope.selectedPayroll.enabled
$scope.selectedPayroll.time_logged = !$scope.selectedPayroll.time_logged
$scope.isTogglePayroll = ->
if $scope.selectedPayroll?
return $scope.selectedPayroll.enabled
$scope.isToggleTimeSheetModifier= ->
if $scope.selectedPayroll?
return $scope.selectedPayroll.time_logged
# What will be passed to parentWidget
setting = {}
setting.key = "<KEY>"
setting.isInitialized = false
# initialization of selected organizations
setting.initialize = ->
ImpacDashboardsSvc.load().then(
(config) ->
currentDashboard = config.currentDashboard
$scope.selectedPayroll = { enabled: false, time_logged: false }
payroll = _.get(w, 'metadata.payroll')
$scope.selectedPayroll = w.metadata.payroll if _.isPlainObject(payroll)
setting.isInitialized = true
)
setting.toMetadata = ->
return { payroll: $scope.selectedPayroll }
w.settings.push(setting)
# Setting is ready: trigger load content
# ------------------------------------
$scope.deferred.resolve($scope.parentWidget)
)
module.directive('settingPayroll', ($templateCache) ->
return {
restrict: 'A',
scope: {
parentWidget: '='
mode: '@?'
deferred: '='
onSelect: '&?'
},
template: $templateCache.get('widgets-settings/payroll.tmpl.html'),
controller: 'SettingPayrollCtrl'
}
)
| true | module = angular.module('impac.components.widgets-settings.payroll',[])
module.controller('SettingPayrollCtrl', ($scope, ImpacDashboardsSvc) ->
w = $scope.parentWidget
$scope.togglePayroll = ->
$scope.selectedPayroll.enabled = !$scope.selectedPayroll.enabled
unless $scope.selectedPayroll.enabled
$scope.selectedPayroll.time_logged = false
$scope.toggleTimeSheetModifier= ->
if $scope.selectedPayroll.enabled
$scope.selectedPayroll.time_logged = !$scope.selectedPayroll.time_logged
$scope.isTogglePayroll = ->
if $scope.selectedPayroll?
return $scope.selectedPayroll.enabled
$scope.isToggleTimeSheetModifier= ->
if $scope.selectedPayroll?
return $scope.selectedPayroll.time_logged
# What will be passed to parentWidget
setting = {}
setting.key = "PI:KEY:<KEY>END_PI"
setting.isInitialized = false
# initialization of selected organizations
setting.initialize = ->
ImpacDashboardsSvc.load().then(
(config) ->
currentDashboard = config.currentDashboard
$scope.selectedPayroll = { enabled: false, time_logged: false }
payroll = _.get(w, 'metadata.payroll')
$scope.selectedPayroll = w.metadata.payroll if _.isPlainObject(payroll)
setting.isInitialized = true
)
setting.toMetadata = ->
return { payroll: $scope.selectedPayroll }
w.settings.push(setting)
# Setting is ready: trigger load content
# ------------------------------------
$scope.deferred.resolve($scope.parentWidget)
)
module.directive('settingPayroll', ($templateCache) ->
return {
restrict: 'A',
scope: {
parentWidget: '='
mode: '@?'
deferred: '='
onSelect: '&?'
},
template: $templateCache.get('widgets-settings/payroll.tmpl.html'),
controller: 'SettingPayrollCtrl'
}
)
|
[
{
"context": "t =\n items: [\n text: \"kein Treffer\"\n value: undefined\n ]",
"end": 6922,
"score": 0.9992300271987915,
"start": 6910,
"tag": "NAME",
"value": "kein Treffer"
}
] | src/webfrontend/CustomDataTypeGetty.coffee | programmfabrik/custom-data-type-getty | 0 | class CustomDataTypeGetty extends CustomDataTypeWithCommons
#######################################################################
# return name of plugin
getCustomDataTypeName: ->
"custom:base.custom-data-type-getty.getty"
#######################################################################
# return name (l10n) of plugin
getCustomDataTypeNameLocalized: ->
$$("custom.data.type.getty.name")
#######################################################################
# NOT IMPLEMENTED YET!
__getAdditionalTooltipInfo: (uri, tooltip, extendedInfo_xhr) ->
# download infos
if extendedInfo_xhr.xhr != undefined
# abort eventually running request
extendedInfo_xhr.abort()
uriParts = uri.split('/')
gettyID = uriParts.pop()
gettyType = uriParts.pop()
uri = 'http://vocab.getty.edu/' + gettyType + '/' + gettyID + '.json'
# start new request
xurl = location.protocol + '//jsontojsonp.gbv.de/?url=' + uri
extendedInfo_xhr = new (CUI.XHR)(url: xurl)
extendedInfo_xhr.start()
.done((data, status, statusText) ->
if data.results
htmlContent = '<span style="padding: 10px 10px 0px 10px; font-weight: bold">' + $$('custom.data.type.getty.config.parameter.mask.infopop.info.label') + '</span>'
htmlContent += '<table style="border-spacing: 10px; border-collapse: separate;">'
# list all labels
htmlContent += "<tr><td>" + $$('custom.data.type.getty.config.parameter.mask.infopop.labels.label') + ":</td>"
bindings = data.results.bindings
labels = []
for binding, key in bindings
if binding.Predicate.type == 'uri' && binding.Predicate.value == 'http://www.w3.org/2000/01/rdf-schema#label'
labels.push('- ' + binding.Object.value)
htmlContent += "<td>" + labels.join('<br />') + "</td></tr>"
htmlContent += "</table>"
tooltip.DOM.innerHTML = htmlContent
tooltip.autoSize()
else
tooltip.hide()
tooltip.destroy()
return false
)
.fail((data, status, statusText) ->
tooltip.hide()
tooltip.destroy()
return false
)
return
#######################################################################
# handle suggestions-menu
__updateSuggestionsMenu: (cdata, cdata_form, searchstring, input, suggest_Menu, searchsuggest_xhr, layout, opts) ->
that = @
delayMillisseconds = 200
setTimeout ( ->
getty_searchterm = searchstring
getty_countSuggestions = 20
if (cdata_form)
getty_searchterm = cdata_form.getFieldsByName("searchbarInput")[0].getValue()
getty_searchtype = cdata_form.getFieldsByName("gettySelectType")[0].getValue()
getty_countSuggestions = cdata_form.getFieldsByName("countOfSuggestions")[0].getValue()
# if "search-all-types", search all allowed types
if getty_searchtype == 'all_supported_types' || !getty_searchtype
getty_searchtype = []
if that.getCustomSchemaSettings().add_aat?.value
getty_searchtype.push 'aat'
if that.getCustomSchemaSettings().add_tgn?.value
getty_searchtype.push 'tgn'
if that.getCustomSchemaSettings().add_ulan?.value
getty_searchtype.push 'ulan'
getty_searchtype = getty_searchtype.join(',')
if getty_searchterm.length == 0
return
# run autocomplete-search via xhr
if searchsuggest_xhr.xhr != undefined
# abort eventually running request
searchsuggest_xhr.xhr.abort()
# start new request
searchsuggest_xhr.xhr = new (CUI.XHR)(url: location.protocol + '//ws.gbv.de/suggest/getty/?searchstring=' + getty_searchterm + '&voc=' + getty_searchtype + '&count=' + getty_countSuggestions)
searchsuggest_xhr.xhr.start().done((data, status, statusText) ->
# init xhr for tooltipcontent
extendedInfo_xhr = { "xhr" : undefined }
# create new menu with suggestions
menu_items = []
for suggestion, key in data[1]
do(key) ->
# the actual Featureclass...
aktType = data[2][key]
lastType = ''
if key > 0
lastType = data[2][key-1]
if aktType != lastType
item =
divider: true
menu_items.push item
item =
label: aktType
menu_items.push item
item =
divider: true
menu_items.push item
item =
text: suggestion
value: data[3][key]
tooltip:
markdown: true
placement: "e"
content: (tooltip) ->
that.__getAdditionalTooltipInfo(data[3][key], tooltip, extendedInfo_xhr)
new CUI.Label(icon: "spinner", text: "lade Informationen")
menu_items.push item
# set new items to menu
itemList =
onClick: (ev2, btn) ->
# lock in save data
cdata.conceptURI = btn.getOpt("value")
cdata.conceptName = btn.getText()
cdata.conceptFulltext = cdata.conceptName
# try to get better fulltext
encodedURL = encodeURIComponent(cdata.conceptURI + '.json')
dataEntry_xhr = new (CUI.XHR)(url: location.protocol + '//jsontojsonp.gbv.de/?url=' + encodedURL)
dataEntry_xhr.start().done((data, status, statusText) ->
# generate fulltext from data
if data.results
bindings = data.results.bindings
# add labels to fulltext
labels = []
for binding, key in bindings
if binding.Predicate.type == 'uri' && binding.Predicate.value == 'http://www.w3.org/2000/01/rdf-schema#label'
labels.push(binding.Object.value)
cdata.conceptFulltext = labels.join(' ')
# update the layout in form
that.__updateResult(cdata, layout, opts)
# hide suggest-menu
suggest_Menu.hide()
# close popover
if that.popover
that.popover.hide()
)
.fail((data, status, statusText) ->
# update the layout in form
that.__updateResult(cdata, layout, opts)
# hide suggest-menu
suggest_Menu.hide()
# close popover
if that.popover
that.popover.hide()
)
items: menu_items
# if no hits set "empty" message to menu
if itemList.items.length == 0
itemList =
items: [
text: "kein Treffer"
value: undefined
]
suggest_Menu.setItemList(itemList)
suggest_Menu.show()
)
), delayMillisseconds
#######################################################################
# create form
__getEditorFields: (cdata) ->
# read searchtypes from datamodell-options
dropDownSearchOptions = []
# offer DifferentiatedPerson
if @getCustomSchemaSettings().add_aat?.value
option = (
value: 'aat'
text: 'Art & Architecture Thesaurus'
)
dropDownSearchOptions.push option
# offer CorporateBody?
if @getCustomSchemaSettings().add_tgn?.value
option = (
value: 'tgn'
text: 'Getty Thesaurus of Geographic Names'
)
dropDownSearchOptions.push option
# offer PlaceOrGeographicName?
if @getCustomSchemaSettings().add_ulan?.value
option = (
value: 'ulan'
text: 'Union List of Artist Names'
)
dropDownSearchOptions.push option
# add "Alle"-Option? If count of options > 1!
#if dropDownSearchOptions.length > 1
# option = (
# value: 'all_supported_types'
# text: 'Alle'
# )
# dropDownSearchOptions.unshift option
# if empty options -> offer all
if dropDownSearchOptions.length == 0
dropDownSearchOptions = [
(
value: 'aat'
text: 'Art & Architecture Thesaurus'
)
(
value: 'tgn'
text: 'Getty Thesaurus of Geographic Names'
)
(
value: 'ulan'
text: 'Union List of Artist Names'
)
]
[{
type: CUI.Select
undo_and_changed_support: false
form:
label: $$('custom.data.type.getty.modal.form.text.type')
options: dropDownSearchOptions
name: 'gettySelectType'
class: 'commonPlugin_Select'
}
{
type: CUI.Select
undo_and_changed_support: false
class: 'commonPlugin_Select'
form:
label: $$('custom.data.type.getty.modal.form.text.count')
options: [
(
value: 10
text: '10 Vorschläge'
)
(
value: 20
text: '20 Vorschläge'
)
(
value: 50
text: '50 Vorschläge'
)
(
value: 100
text: '100 Vorschläge'
)
]
name: 'countOfSuggestions'
}
{
type: CUI.Input
undo_and_changed_support: false
form:
label: $$("custom.data.type.getty.modal.form.text.searchbar")
placeholder: $$("custom.data.type.getty.modal.form.text.searchbar.placeholder")
name: "searchbarInput"
class: 'commonPlugin_Input'
}
]
#######################################################################
# renders the "result" in original form (outside popover)
__renderButtonByData: (cdata) ->
# when status is empty or invalid --> message
switch @getDataStatus(cdata)
when "empty"
return new CUI.EmptyLabel(text: $$("custom.data.type.getty.edit.no_getty")).DOM
when "invalid"
return new CUI.EmptyLabel(text: $$("custom.data.type.getty.edit.no_valid_getty")).DOM
# if status is ok
conceptURI = CUI.parseLocation(cdata.conceptURI).url
tt_text = $$("custom.data.type.getty.url.tooltip", name: cdata.conceptName)
# replace conceptUri with better human-readable website
# http://vocab.getty.edu/aat/300386183 turns http://vocab.getty.edu/page/aat/300386183
displayUri = cdata.conceptURI.replace('http://vocab.getty.edu', 'http://vocab.getty.edu/page')
# output Button with Name of picked Entry and URI
encodedURI = encodeURIComponent(displayUri)
new CUI.HorizontalLayout
maximize: true
left:
content:
new CUI.Label
centered: false
text: cdata.conceptName
center:
content:
# output Button with Name of picked Entry and Url to the Source
new CUI.ButtonHref
appearance: "link"
href: displayUri
target: "_blank"
tooltip:
markdown: true
text: tt_text
right: null
.DOM
#######################################################################
# zeige die gewählten Optionen im Datenmodell unter dem Button an
getCustomDataOptionsInDatamodelInfo: (custom_settings) ->
tags = []
if custom_settings.add_aat?.value
tags.push "✓ AAT"
else
tags.push "✘ AAT"
if custom_settings.add_tgn?.value
tags.push "✓ TGN"
else
tags.push "✘ TGN"
if custom_settings.add_ulan?.value
tags.push "✓ ULAN"
else
tags.push "✘ ULAN"
tags
CustomDataType.register(CustomDataTypeGetty)
| 15707 | class CustomDataTypeGetty extends CustomDataTypeWithCommons
#######################################################################
# return name of plugin
getCustomDataTypeName: ->
"custom:base.custom-data-type-getty.getty"
#######################################################################
# return name (l10n) of plugin
getCustomDataTypeNameLocalized: ->
$$("custom.data.type.getty.name")
#######################################################################
# NOT IMPLEMENTED YET!
__getAdditionalTooltipInfo: (uri, tooltip, extendedInfo_xhr) ->
# download infos
if extendedInfo_xhr.xhr != undefined
# abort eventually running request
extendedInfo_xhr.abort()
uriParts = uri.split('/')
gettyID = uriParts.pop()
gettyType = uriParts.pop()
uri = 'http://vocab.getty.edu/' + gettyType + '/' + gettyID + '.json'
# start new request
xurl = location.protocol + '//jsontojsonp.gbv.de/?url=' + uri
extendedInfo_xhr = new (CUI.XHR)(url: xurl)
extendedInfo_xhr.start()
.done((data, status, statusText) ->
if data.results
htmlContent = '<span style="padding: 10px 10px 0px 10px; font-weight: bold">' + $$('custom.data.type.getty.config.parameter.mask.infopop.info.label') + '</span>'
htmlContent += '<table style="border-spacing: 10px; border-collapse: separate;">'
# list all labels
htmlContent += "<tr><td>" + $$('custom.data.type.getty.config.parameter.mask.infopop.labels.label') + ":</td>"
bindings = data.results.bindings
labels = []
for binding, key in bindings
if binding.Predicate.type == 'uri' && binding.Predicate.value == 'http://www.w3.org/2000/01/rdf-schema#label'
labels.push('- ' + binding.Object.value)
htmlContent += "<td>" + labels.join('<br />') + "</td></tr>"
htmlContent += "</table>"
tooltip.DOM.innerHTML = htmlContent
tooltip.autoSize()
else
tooltip.hide()
tooltip.destroy()
return false
)
.fail((data, status, statusText) ->
tooltip.hide()
tooltip.destroy()
return false
)
return
#######################################################################
# handle suggestions-menu
__updateSuggestionsMenu: (cdata, cdata_form, searchstring, input, suggest_Menu, searchsuggest_xhr, layout, opts) ->
that = @
delayMillisseconds = 200
setTimeout ( ->
getty_searchterm = searchstring
getty_countSuggestions = 20
if (cdata_form)
getty_searchterm = cdata_form.getFieldsByName("searchbarInput")[0].getValue()
getty_searchtype = cdata_form.getFieldsByName("gettySelectType")[0].getValue()
getty_countSuggestions = cdata_form.getFieldsByName("countOfSuggestions")[0].getValue()
# if "search-all-types", search all allowed types
if getty_searchtype == 'all_supported_types' || !getty_searchtype
getty_searchtype = []
if that.getCustomSchemaSettings().add_aat?.value
getty_searchtype.push 'aat'
if that.getCustomSchemaSettings().add_tgn?.value
getty_searchtype.push 'tgn'
if that.getCustomSchemaSettings().add_ulan?.value
getty_searchtype.push 'ulan'
getty_searchtype = getty_searchtype.join(',')
if getty_searchterm.length == 0
return
# run autocomplete-search via xhr
if searchsuggest_xhr.xhr != undefined
# abort eventually running request
searchsuggest_xhr.xhr.abort()
# start new request
searchsuggest_xhr.xhr = new (CUI.XHR)(url: location.protocol + '//ws.gbv.de/suggest/getty/?searchstring=' + getty_searchterm + '&voc=' + getty_searchtype + '&count=' + getty_countSuggestions)
searchsuggest_xhr.xhr.start().done((data, status, statusText) ->
# init xhr for tooltipcontent
extendedInfo_xhr = { "xhr" : undefined }
# create new menu with suggestions
menu_items = []
for suggestion, key in data[1]
do(key) ->
# the actual Featureclass...
aktType = data[2][key]
lastType = ''
if key > 0
lastType = data[2][key-1]
if aktType != lastType
item =
divider: true
menu_items.push item
item =
label: aktType
menu_items.push item
item =
divider: true
menu_items.push item
item =
text: suggestion
value: data[3][key]
tooltip:
markdown: true
placement: "e"
content: (tooltip) ->
that.__getAdditionalTooltipInfo(data[3][key], tooltip, extendedInfo_xhr)
new CUI.Label(icon: "spinner", text: "lade Informationen")
menu_items.push item
# set new items to menu
itemList =
onClick: (ev2, btn) ->
# lock in save data
cdata.conceptURI = btn.getOpt("value")
cdata.conceptName = btn.getText()
cdata.conceptFulltext = cdata.conceptName
# try to get better fulltext
encodedURL = encodeURIComponent(cdata.conceptURI + '.json')
dataEntry_xhr = new (CUI.XHR)(url: location.protocol + '//jsontojsonp.gbv.de/?url=' + encodedURL)
dataEntry_xhr.start().done((data, status, statusText) ->
# generate fulltext from data
if data.results
bindings = data.results.bindings
# add labels to fulltext
labels = []
for binding, key in bindings
if binding.Predicate.type == 'uri' && binding.Predicate.value == 'http://www.w3.org/2000/01/rdf-schema#label'
labels.push(binding.Object.value)
cdata.conceptFulltext = labels.join(' ')
# update the layout in form
that.__updateResult(cdata, layout, opts)
# hide suggest-menu
suggest_Menu.hide()
# close popover
if that.popover
that.popover.hide()
)
.fail((data, status, statusText) ->
# update the layout in form
that.__updateResult(cdata, layout, opts)
# hide suggest-menu
suggest_Menu.hide()
# close popover
if that.popover
that.popover.hide()
)
items: menu_items
# if no hits set "empty" message to menu
if itemList.items.length == 0
itemList =
items: [
text: "<NAME>"
value: undefined
]
suggest_Menu.setItemList(itemList)
suggest_Menu.show()
)
), delayMillisseconds
#######################################################################
# create form
__getEditorFields: (cdata) ->
# read searchtypes from datamodell-options
dropDownSearchOptions = []
# offer DifferentiatedPerson
if @getCustomSchemaSettings().add_aat?.value
option = (
value: 'aat'
text: 'Art & Architecture Thesaurus'
)
dropDownSearchOptions.push option
# offer CorporateBody?
if @getCustomSchemaSettings().add_tgn?.value
option = (
value: 'tgn'
text: 'Getty Thesaurus of Geographic Names'
)
dropDownSearchOptions.push option
# offer PlaceOrGeographicName?
if @getCustomSchemaSettings().add_ulan?.value
option = (
value: 'ulan'
text: 'Union List of Artist Names'
)
dropDownSearchOptions.push option
# add "Alle"-Option? If count of options > 1!
#if dropDownSearchOptions.length > 1
# option = (
# value: 'all_supported_types'
# text: 'Alle'
# )
# dropDownSearchOptions.unshift option
# if empty options -> offer all
if dropDownSearchOptions.length == 0
dropDownSearchOptions = [
(
value: 'aat'
text: 'Art & Architecture Thesaurus'
)
(
value: 'tgn'
text: 'Getty Thesaurus of Geographic Names'
)
(
value: 'ulan'
text: 'Union List of Artist Names'
)
]
[{
type: CUI.Select
undo_and_changed_support: false
form:
label: $$('custom.data.type.getty.modal.form.text.type')
options: dropDownSearchOptions
name: 'gettySelectType'
class: 'commonPlugin_Select'
}
{
type: CUI.Select
undo_and_changed_support: false
class: 'commonPlugin_Select'
form:
label: $$('custom.data.type.getty.modal.form.text.count')
options: [
(
value: 10
text: '10 Vorschläge'
)
(
value: 20
text: '20 Vorschläge'
)
(
value: 50
text: '50 Vorschläge'
)
(
value: 100
text: '100 Vorschläge'
)
]
name: 'countOfSuggestions'
}
{
type: CUI.Input
undo_and_changed_support: false
form:
label: $$("custom.data.type.getty.modal.form.text.searchbar")
placeholder: $$("custom.data.type.getty.modal.form.text.searchbar.placeholder")
name: "searchbarInput"
class: 'commonPlugin_Input'
}
]
#######################################################################
# renders the "result" in original form (outside popover)
__renderButtonByData: (cdata) ->
# when status is empty or invalid --> message
switch @getDataStatus(cdata)
when "empty"
return new CUI.EmptyLabel(text: $$("custom.data.type.getty.edit.no_getty")).DOM
when "invalid"
return new CUI.EmptyLabel(text: $$("custom.data.type.getty.edit.no_valid_getty")).DOM
# if status is ok
conceptURI = CUI.parseLocation(cdata.conceptURI).url
tt_text = $$("custom.data.type.getty.url.tooltip", name: cdata.conceptName)
# replace conceptUri with better human-readable website
# http://vocab.getty.edu/aat/300386183 turns http://vocab.getty.edu/page/aat/300386183
displayUri = cdata.conceptURI.replace('http://vocab.getty.edu', 'http://vocab.getty.edu/page')
# output Button with Name of picked Entry and URI
encodedURI = encodeURIComponent(displayUri)
new CUI.HorizontalLayout
maximize: true
left:
content:
new CUI.Label
centered: false
text: cdata.conceptName
center:
content:
# output Button with Name of picked Entry and Url to the Source
new CUI.ButtonHref
appearance: "link"
href: displayUri
target: "_blank"
tooltip:
markdown: true
text: tt_text
right: null
.DOM
#######################################################################
# zeige die gewählten Optionen im Datenmodell unter dem Button an
getCustomDataOptionsInDatamodelInfo: (custom_settings) ->
tags = []
if custom_settings.add_aat?.value
tags.push "✓ AAT"
else
tags.push "✘ AAT"
if custom_settings.add_tgn?.value
tags.push "✓ TGN"
else
tags.push "✘ TGN"
if custom_settings.add_ulan?.value
tags.push "✓ ULAN"
else
tags.push "✘ ULAN"
tags
CustomDataType.register(CustomDataTypeGetty)
| true | class CustomDataTypeGetty extends CustomDataTypeWithCommons
#######################################################################
# return name of plugin
getCustomDataTypeName: ->
"custom:base.custom-data-type-getty.getty"
#######################################################################
# return name (l10n) of plugin
getCustomDataTypeNameLocalized: ->
$$("custom.data.type.getty.name")
#######################################################################
# NOT IMPLEMENTED YET!
__getAdditionalTooltipInfo: (uri, tooltip, extendedInfo_xhr) ->
# download infos
if extendedInfo_xhr.xhr != undefined
# abort eventually running request
extendedInfo_xhr.abort()
uriParts = uri.split('/')
gettyID = uriParts.pop()
gettyType = uriParts.pop()
uri = 'http://vocab.getty.edu/' + gettyType + '/' + gettyID + '.json'
# start new request
xurl = location.protocol + '//jsontojsonp.gbv.de/?url=' + uri
extendedInfo_xhr = new (CUI.XHR)(url: xurl)
extendedInfo_xhr.start()
.done((data, status, statusText) ->
if data.results
htmlContent = '<span style="padding: 10px 10px 0px 10px; font-weight: bold">' + $$('custom.data.type.getty.config.parameter.mask.infopop.info.label') + '</span>'
htmlContent += '<table style="border-spacing: 10px; border-collapse: separate;">'
# list all labels
htmlContent += "<tr><td>" + $$('custom.data.type.getty.config.parameter.mask.infopop.labels.label') + ":</td>"
bindings = data.results.bindings
labels = []
for binding, key in bindings
if binding.Predicate.type == 'uri' && binding.Predicate.value == 'http://www.w3.org/2000/01/rdf-schema#label'
labels.push('- ' + binding.Object.value)
htmlContent += "<td>" + labels.join('<br />') + "</td></tr>"
htmlContent += "</table>"
tooltip.DOM.innerHTML = htmlContent
tooltip.autoSize()
else
tooltip.hide()
tooltip.destroy()
return false
)
.fail((data, status, statusText) ->
tooltip.hide()
tooltip.destroy()
return false
)
return
#######################################################################
# handle suggestions-menu
__updateSuggestionsMenu: (cdata, cdata_form, searchstring, input, suggest_Menu, searchsuggest_xhr, layout, opts) ->
that = @
delayMillisseconds = 200
setTimeout ( ->
getty_searchterm = searchstring
getty_countSuggestions = 20
if (cdata_form)
getty_searchterm = cdata_form.getFieldsByName("searchbarInput")[0].getValue()
getty_searchtype = cdata_form.getFieldsByName("gettySelectType")[0].getValue()
getty_countSuggestions = cdata_form.getFieldsByName("countOfSuggestions")[0].getValue()
# if "search-all-types", search all allowed types
if getty_searchtype == 'all_supported_types' || !getty_searchtype
getty_searchtype = []
if that.getCustomSchemaSettings().add_aat?.value
getty_searchtype.push 'aat'
if that.getCustomSchemaSettings().add_tgn?.value
getty_searchtype.push 'tgn'
if that.getCustomSchemaSettings().add_ulan?.value
getty_searchtype.push 'ulan'
getty_searchtype = getty_searchtype.join(',')
if getty_searchterm.length == 0
return
# run autocomplete-search via xhr
if searchsuggest_xhr.xhr != undefined
# abort eventually running request
searchsuggest_xhr.xhr.abort()
# start new request
searchsuggest_xhr.xhr = new (CUI.XHR)(url: location.protocol + '//ws.gbv.de/suggest/getty/?searchstring=' + getty_searchterm + '&voc=' + getty_searchtype + '&count=' + getty_countSuggestions)
searchsuggest_xhr.xhr.start().done((data, status, statusText) ->
# init xhr for tooltipcontent
extendedInfo_xhr = { "xhr" : undefined }
# create new menu with suggestions
menu_items = []
for suggestion, key in data[1]
do(key) ->
# the actual Featureclass...
aktType = data[2][key]
lastType = ''
if key > 0
lastType = data[2][key-1]
if aktType != lastType
item =
divider: true
menu_items.push item
item =
label: aktType
menu_items.push item
item =
divider: true
menu_items.push item
item =
text: suggestion
value: data[3][key]
tooltip:
markdown: true
placement: "e"
content: (tooltip) ->
that.__getAdditionalTooltipInfo(data[3][key], tooltip, extendedInfo_xhr)
new CUI.Label(icon: "spinner", text: "lade Informationen")
menu_items.push item
# set new items to menu
itemList =
onClick: (ev2, btn) ->
# lock in save data
cdata.conceptURI = btn.getOpt("value")
cdata.conceptName = btn.getText()
cdata.conceptFulltext = cdata.conceptName
# try to get better fulltext
encodedURL = encodeURIComponent(cdata.conceptURI + '.json')
dataEntry_xhr = new (CUI.XHR)(url: location.protocol + '//jsontojsonp.gbv.de/?url=' + encodedURL)
dataEntry_xhr.start().done((data, status, statusText) ->
# generate fulltext from data
if data.results
bindings = data.results.bindings
# add labels to fulltext
labels = []
for binding, key in bindings
if binding.Predicate.type == 'uri' && binding.Predicate.value == 'http://www.w3.org/2000/01/rdf-schema#label'
labels.push(binding.Object.value)
cdata.conceptFulltext = labels.join(' ')
# update the layout in form
that.__updateResult(cdata, layout, opts)
# hide suggest-menu
suggest_Menu.hide()
# close popover
if that.popover
that.popover.hide()
)
.fail((data, status, statusText) ->
# update the layout in form
that.__updateResult(cdata, layout, opts)
# hide suggest-menu
suggest_Menu.hide()
# close popover
if that.popover
that.popover.hide()
)
items: menu_items
# if no hits set "empty" message to menu
if itemList.items.length == 0
itemList =
items: [
text: "PI:NAME:<NAME>END_PI"
value: undefined
]
suggest_Menu.setItemList(itemList)
suggest_Menu.show()
)
), delayMillisseconds
#######################################################################
# create form
__getEditorFields: (cdata) ->
# read searchtypes from datamodell-options
dropDownSearchOptions = []
# offer DifferentiatedPerson
if @getCustomSchemaSettings().add_aat?.value
option = (
value: 'aat'
text: 'Art & Architecture Thesaurus'
)
dropDownSearchOptions.push option
# offer CorporateBody?
if @getCustomSchemaSettings().add_tgn?.value
option = (
value: 'tgn'
text: 'Getty Thesaurus of Geographic Names'
)
dropDownSearchOptions.push option
# offer PlaceOrGeographicName?
if @getCustomSchemaSettings().add_ulan?.value
option = (
value: 'ulan'
text: 'Union List of Artist Names'
)
dropDownSearchOptions.push option
# add "Alle"-Option? If count of options > 1!
#if dropDownSearchOptions.length > 1
# option = (
# value: 'all_supported_types'
# text: 'Alle'
# )
# dropDownSearchOptions.unshift option
# if empty options -> offer all
if dropDownSearchOptions.length == 0
dropDownSearchOptions = [
(
value: 'aat'
text: 'Art & Architecture Thesaurus'
)
(
value: 'tgn'
text: 'Getty Thesaurus of Geographic Names'
)
(
value: 'ulan'
text: 'Union List of Artist Names'
)
]
[{
type: CUI.Select
undo_and_changed_support: false
form:
label: $$('custom.data.type.getty.modal.form.text.type')
options: dropDownSearchOptions
name: 'gettySelectType'
class: 'commonPlugin_Select'
}
{
type: CUI.Select
undo_and_changed_support: false
class: 'commonPlugin_Select'
form:
label: $$('custom.data.type.getty.modal.form.text.count')
options: [
(
value: 10
text: '10 Vorschläge'
)
(
value: 20
text: '20 Vorschläge'
)
(
value: 50
text: '50 Vorschläge'
)
(
value: 100
text: '100 Vorschläge'
)
]
name: 'countOfSuggestions'
}
{
type: CUI.Input
undo_and_changed_support: false
form:
label: $$("custom.data.type.getty.modal.form.text.searchbar")
placeholder: $$("custom.data.type.getty.modal.form.text.searchbar.placeholder")
name: "searchbarInput"
class: 'commonPlugin_Input'
}
]
#######################################################################
# renders the "result" in original form (outside popover)
__renderButtonByData: (cdata) ->
# when status is empty or invalid --> message
switch @getDataStatus(cdata)
when "empty"
return new CUI.EmptyLabel(text: $$("custom.data.type.getty.edit.no_getty")).DOM
when "invalid"
return new CUI.EmptyLabel(text: $$("custom.data.type.getty.edit.no_valid_getty")).DOM
# if status is ok
conceptURI = CUI.parseLocation(cdata.conceptURI).url
tt_text = $$("custom.data.type.getty.url.tooltip", name: cdata.conceptName)
# replace conceptUri with better human-readable website
# http://vocab.getty.edu/aat/300386183 turns http://vocab.getty.edu/page/aat/300386183
displayUri = cdata.conceptURI.replace('http://vocab.getty.edu', 'http://vocab.getty.edu/page')
# output Button with Name of picked Entry and URI
encodedURI = encodeURIComponent(displayUri)
new CUI.HorizontalLayout
maximize: true
left:
content:
new CUI.Label
centered: false
text: cdata.conceptName
center:
content:
# output Button with Name of picked Entry and Url to the Source
new CUI.ButtonHref
appearance: "link"
href: displayUri
target: "_blank"
tooltip:
markdown: true
text: tt_text
right: null
.DOM
#######################################################################
# zeige die gewählten Optionen im Datenmodell unter dem Button an
getCustomDataOptionsInDatamodelInfo: (custom_settings) ->
tags = []
if custom_settings.add_aat?.value
tags.push "✓ AAT"
else
tags.push "✘ AAT"
if custom_settings.add_tgn?.value
tags.push "✓ TGN"
else
tags.push "✘ TGN"
if custom_settings.add_ulan?.value
tags.push "✓ ULAN"
else
tags.push "✘ ULAN"
tags
CustomDataType.register(CustomDataTypeGetty)
|
[
{
"context": " map lines\n\n map_done: () ->\n msg = {name: \"MAPPER_DONE\", job_id: @job_id, id: @_id}\n @send_to_server ",
"end": 3646,
"score": 0.9084214568138123,
"start": 3635,
"tag": "USERNAME",
"value": "MAPPER_DONE"
},
{
"context": "() ->\n msg = {name: \"MAPPER_D... | src/public/javascripts/lib/models/worker.coffee | dwetterau/countdera | 2 | firebase = require '../firebase_client.coffee'
config = require '../../../../config.coffee'
constants = require '../../../../constants.coffee'
q = require 'q'
class Worker
constructor: (statecallback) ->
@_last_update = new Date().getTime()
@_connections = {}
@_status = {
state: 'IDLE'
}
@statecallback = statecallback
init: () ->
@get_id()
@listen()
setInterval () =>
before = @_last_update
@heartbeat () ->
#console.log "Heartbeated... diff=", (new Date().getTime() - before)
, constants.HEARTBEAT_INTERVAL
@statecallback @_status.state
heartbeat: (callback) ->
@_update_time()
@save_to_firebase(callback)
get_id: () ->
id_ref = firebase.WORKER_ID_REF.push "new_worker"
@_id = id_ref.name()
_update_time: () ->
@_last_update = new Date().getTime()
to_json: () ->
object =
id: @_id
last_update: @_last_update
status: @_status
return object
id: () ->
return @_id
save_to_firebase: (callback) ->
update_object = {}
update_object[@_id] = @to_json()
firebase.WORKER_STATUS_REF.update update_object, callback
process_message: (message) ->
message_type = message.name
if message_type == "MAP_START"
@start_map(message)
else if message_type == "REDUCE_NODES"
@send_map_data(message)
else if message_type == "JOB_DONE"
@finish_job(message)
else if message_type == "START_REDUCE"
@start_reduce(message)
else if message_type == "START_MAP_OUTPUT"
@add_data_src(message)
else if message_type == "MAP_OUTPUT"
@add_map_output(message)
else if message_type == "END_MAP_OUTPUT"
@close_data_src(message)
else if message_type == "REDUCE_DONE"
@finish_reduce(message)
else
throw new Error("Unknown message!")
listen: () ->
message_ref = firebase.WORKER_MESSAGE_REF.child(@_id)
message_ref.on 'child_added', (new_child) =>
@process_message(new_child.val())
message_ref.child(new_child.name()).remove()
send_to_server: (message, callback) ->
other = firebase.SERVER_MESSAGE_REF
other.push message, callback
send_to_friend: (client, message, callback) ->
other = firebase.WORKER_MESSAGE_REF.child(client)
other.push message, callback
finish_job: () ->
@data = null
@mappings = null
@map_code = null
@clean_reduce()
start_map: (map_start_message) ->
@_status.state = 'MAPPER'
@statecallback(@_status.state)
@job_id = map_start_message.job_id
@index = map_start_message.index
@get_data(map_start_message.url).then(() =>
return @get_mapping_code()
).then () =>
@run_map_job()
@map_done()
get_data: (url) ->
@_status.state = "DOWNLOADING_MAPPING_DATA"
@statecallback(@_status.state)
deferred = q.defer()
@data = ''
$.get url, (data) =>
@data = data
deferred.resolve()
return deferred.promise
get_mapping_code: () ->
@_status.state = "DOWNLOADING_MAPPING_CODE"
@statecallback(@_status.state)
deferred = q.defer()
firebase.JOB_STATUS_REF.child(@job_id).child('map_code').once 'value', (snapshot) =>
@map_code = snapshot.val()
deferred.resolve()
return deferred.promise
run_map_job: () ->
@_status.state = "MAPPING"
@statecallback(@_status.state)
@mappings = []
emit = (key, object) =>
@mappings.push [key, object]
lines = @data.split('\n')
lines = (line for line in lines when line.length > 0)
map = (lines) =>
eval(@map_code)
map lines
map_done: () ->
msg = {name: "MAPPER_DONE", job_id: @job_id, id: @_id}
@send_to_server msg, () =>
@_status.state = 'MAPPER_DONE'
@statecallback(@_status.state)
send_map_data: (reduce_node_list) ->
@_status.state = "SENDING_MAPPED_RESULTS"
@statecallback(@_status.state)
num_nodes = reduce_node_list.nodes.length
# Group all of the messages together
reducer_queues = []
for client in reduce_node_list.nodes
reducer_queues.push []
for tuple in @mappings
hash = @hashval(tuple[0])
reducer_index = hash % num_nodes
reducer_queues[reducer_index].push tuple
for queue, queue_index in reducer_queues
batched_queue = []
# Batch the individual tuples
current_batch = []
for tuple, index in queue
if index > 0 and index % constants.BATCH_SIZE == 0
batched_queue.push {tuples: current_batch}
current_batch = []
current_batch.push tuple
if current_batch.length
batched_queue.push {tuples: current_batch}
reducer_queues[queue_index] = batched_queue
for client in reduce_node_list.nodes
@send_to_friend client,
name: 'START_MAP_OUTPUT'
index: @index
total_sent = 0
total_to_send = 0
for queue in reducer_queues
for batched_tuples in queue
total_to_send += batched_tuples.tuples.length
for queue, queue_index in reducer_queues
for batched_tuples, index in queue
to_send_client = reduce_node_list.nodes[queue_index]
@send_to_friend to_send_client,
name: 'MAP_OUTPUT'
index: @index
key: batched_tuples
total_sent += batched_tuples.tuples.length
@statecallback(@_status.state, "Sent " + total_sent + " / " + total_to_send)
for client in reduce_node_list.nodes
@send_to_friend client,
name: 'END_MAP_OUTPUT'
index: @index
@_status.state = 'MAPPER_DONE'
@statecallback(@_status.state)
start_reduce: (start_reduce_message) ->
@_status.state = 'REDUCER'
@statecallback(@_status.state)
@job_id = start_reduce_message.job_id
@index = start_reduce_message.index
@number_of_mappers = start_reduce_message.number_of_mappers
@reduce_data = {}
@num_done = 0
@mapper_done = (false for _ in @number_of_mappers)
get_reduce_code: () ->
@_status.state = "DOWNLOADING_REDUCE_CODE"
@statecallback(@_status.state)
deferred = q.defer()
firebase.JOB_STATUS_REF.child(@job_id).child('reduce_code').once 'value', (snapshot) =>
@reduce_code = snapshot.val()
deferred.resolve()
return deferred.promise
add_data_src: (map_data_msg) ->
@_status.state = "RECEIVING_REDUCE_DATA"
@statecallback(@_status.state)
if @mapper_done[map_data_msg.index]
return
@reduce_data[map_data_msg.index] = []
close_data_src: (map_data_msg) ->
if not @mapper_done[map_data_msg.index]
@num_done++
@mapper_done[map_data_msg.index] = true
if @num_done == @number_of_mappers
@get_reduce_code().then () =>
@do_reduce()
add_map_output: (map_data_msg) ->
if @mapper_done[map_data_msg.index]
return
# Unpack the batched message
for tuple in map_data_msg.key.tuples
@reduce_data[map_data_msg.index].push(tuple)
do_reduce: () ->
@_status.state = "REDUCING"
@statecallback(@_status.state)
collected_data = {}
for index, list of @reduce_data
for item in list
if item[0] not of collected_data
collected_data[item[0]] = []
collected_data[item[0]].push(item[1])
data_for_jimmy = {}
reduce = (key, map_output_list) =>
emit = (line) ->
if key not of data_for_jimmy
data_for_jimmy[key] = []
data_for_jimmy[key].push(line)
eval(@reduce_code)
num_reduced = 0
for key, list of collected_data
reduce(key, list)
num_reduced++
@finish_reduce(data_for_jimmy)
finish_reduce: (data_for_jimmy) ->
@_status.state = "SENDING_TO_IO_SERVER"
@statecallback(@_status.state)
# We want to collect the key -> [output_lines] and send a certain number of lines at a time
messages = []
current_batch = []
current_batch_length = 0
for key, list of data_for_jimmy
if list.length + current_batch_length > constants.BATCH_SIZE
messages.push current_batch
current_batch = []
current_batch_length = 0
current_batch.push [key, if list.length == 1 then list[0] else list]
current_batch_length += list.length
if current_batch.length
messages.push current_batch
# Start message to Jimmy
firebase.IO_SERVER_MESSAGE_REF.push
name: "START_REDUCER_OUTPUT",
reducer: @index,
job: @job_id
for message in messages
firebase.IO_SERVER_MESSAGE_REF.push {
name: "REDUCER_OUTPUT"
reducer: @index
message
job: @job_id
}
firebase.IO_SERVER_MESSAGE_REF.push
name: "STOP_REDUCER_OUTPUT",
reducer: @index,
job: @job_id
@send_to_server
name: "REDUCE_DONE"
index: @index
job_id: @job_id
@clean_reduce()
clean_reduce: () ->
@reduce_code = null
@reduce_data = null
@job_id = null
@number_of_mappers = null
@reduce_data = {}
@num_done = 0
@mapper_done = null
@_status.state = 'IDLE'
@statecallback(@_status.state)
hashval: (s) ->
hash = 0
chr = null
if s.length == 0
return hash;
for i in s.length
chr = this.charCodeAt(i)
hash = ((hash << 5) - hash) + chr
hash |= 0
return hash;
getState: () ->
return @_status.state
module.exports = {Worker} | 89568 | firebase = require '../firebase_client.coffee'
config = require '../../../../config.coffee'
constants = require '../../../../constants.coffee'
q = require 'q'
class Worker
constructor: (statecallback) ->
@_last_update = new Date().getTime()
@_connections = {}
@_status = {
state: 'IDLE'
}
@statecallback = statecallback
init: () ->
@get_id()
@listen()
setInterval () =>
before = @_last_update
@heartbeat () ->
#console.log "Heartbeated... diff=", (new Date().getTime() - before)
, constants.HEARTBEAT_INTERVAL
@statecallback @_status.state
heartbeat: (callback) ->
@_update_time()
@save_to_firebase(callback)
get_id: () ->
id_ref = firebase.WORKER_ID_REF.push "new_worker"
@_id = id_ref.name()
_update_time: () ->
@_last_update = new Date().getTime()
to_json: () ->
object =
id: @_id
last_update: @_last_update
status: @_status
return object
id: () ->
return @_id
save_to_firebase: (callback) ->
update_object = {}
update_object[@_id] = @to_json()
firebase.WORKER_STATUS_REF.update update_object, callback
process_message: (message) ->
message_type = message.name
if message_type == "MAP_START"
@start_map(message)
else if message_type == "REDUCE_NODES"
@send_map_data(message)
else if message_type == "JOB_DONE"
@finish_job(message)
else if message_type == "START_REDUCE"
@start_reduce(message)
else if message_type == "START_MAP_OUTPUT"
@add_data_src(message)
else if message_type == "MAP_OUTPUT"
@add_map_output(message)
else if message_type == "END_MAP_OUTPUT"
@close_data_src(message)
else if message_type == "REDUCE_DONE"
@finish_reduce(message)
else
throw new Error("Unknown message!")
listen: () ->
message_ref = firebase.WORKER_MESSAGE_REF.child(@_id)
message_ref.on 'child_added', (new_child) =>
@process_message(new_child.val())
message_ref.child(new_child.name()).remove()
send_to_server: (message, callback) ->
other = firebase.SERVER_MESSAGE_REF
other.push message, callback
send_to_friend: (client, message, callback) ->
other = firebase.WORKER_MESSAGE_REF.child(client)
other.push message, callback
finish_job: () ->
@data = null
@mappings = null
@map_code = null
@clean_reduce()
start_map: (map_start_message) ->
@_status.state = 'MAPPER'
@statecallback(@_status.state)
@job_id = map_start_message.job_id
@index = map_start_message.index
@get_data(map_start_message.url).then(() =>
return @get_mapping_code()
).then () =>
@run_map_job()
@map_done()
get_data: (url) ->
@_status.state = "DOWNLOADING_MAPPING_DATA"
@statecallback(@_status.state)
deferred = q.defer()
@data = ''
$.get url, (data) =>
@data = data
deferred.resolve()
return deferred.promise
get_mapping_code: () ->
@_status.state = "DOWNLOADING_MAPPING_CODE"
@statecallback(@_status.state)
deferred = q.defer()
firebase.JOB_STATUS_REF.child(@job_id).child('map_code').once 'value', (snapshot) =>
@map_code = snapshot.val()
deferred.resolve()
return deferred.promise
run_map_job: () ->
@_status.state = "MAPPING"
@statecallback(@_status.state)
@mappings = []
emit = (key, object) =>
@mappings.push [key, object]
lines = @data.split('\n')
lines = (line for line in lines when line.length > 0)
map = (lines) =>
eval(@map_code)
map lines
map_done: () ->
msg = {name: "MAPPER_DONE", job_id: @job_id, id: @_id}
@send_to_server msg, () =>
@_status.state = 'MAPPER_DONE'
@statecallback(@_status.state)
send_map_data: (reduce_node_list) ->
@_status.state = "SENDING_MAPPED_RESULTS"
@statecallback(@_status.state)
num_nodes = reduce_node_list.nodes.length
# Group all of the messages together
reducer_queues = []
for client in reduce_node_list.nodes
reducer_queues.push []
for tuple in @mappings
hash = @hashval(tuple[0])
reducer_index = hash % num_nodes
reducer_queues[reducer_index].push tuple
for queue, queue_index in reducer_queues
batched_queue = []
# Batch the individual tuples
current_batch = []
for tuple, index in queue
if index > 0 and index % constants.BATCH_SIZE == 0
batched_queue.push {tuples: current_batch}
current_batch = []
current_batch.push tuple
if current_batch.length
batched_queue.push {tuples: current_batch}
reducer_queues[queue_index] = batched_queue
for client in reduce_node_list.nodes
@send_to_friend client,
name: 'START_MAP_OUTPUT'
index: @index
total_sent = 0
total_to_send = 0
for queue in reducer_queues
for batched_tuples in queue
total_to_send += batched_tuples.tuples.length
for queue, queue_index in reducer_queues
for batched_tuples, index in queue
to_send_client = reduce_node_list.nodes[queue_index]
@send_to_friend to_send_client,
name: 'MAP_OUTPUT'
index: @index
key: batched_tuples
total_sent += batched_tuples.tuples.length
@statecallback(@_status.state, "Sent " + total_sent + " / " + total_to_send)
for client in reduce_node_list.nodes
@send_to_friend client,
name: 'END_MAP_OUTPUT'
index: @index
@_status.state = 'MAPPER_DONE'
@statecallback(@_status.state)
start_reduce: (start_reduce_message) ->
@_status.state = 'REDUCER'
@statecallback(@_status.state)
@job_id = start_reduce_message.job_id
@index = start_reduce_message.index
@number_of_mappers = start_reduce_message.number_of_mappers
@reduce_data = {}
@num_done = 0
@mapper_done = (false for _ in @number_of_mappers)
get_reduce_code: () ->
@_status.state = "DOWNLOADING_REDUCE_CODE"
@statecallback(@_status.state)
deferred = q.defer()
firebase.JOB_STATUS_REF.child(@job_id).child('reduce_code').once 'value', (snapshot) =>
@reduce_code = snapshot.val()
deferred.resolve()
return deferred.promise
add_data_src: (map_data_msg) ->
@_status.state = "RECEIVING_REDUCE_DATA"
@statecallback(@_status.state)
if @mapper_done[map_data_msg.index]
return
@reduce_data[map_data_msg.index] = []
close_data_src: (map_data_msg) ->
if not @mapper_done[map_data_msg.index]
@num_done++
@mapper_done[map_data_msg.index] = true
if @num_done == @number_of_mappers
@get_reduce_code().then () =>
@do_reduce()
add_map_output: (map_data_msg) ->
if @mapper_done[map_data_msg.index]
return
# Unpack the batched message
for tuple in map_data_msg.key.tuples
@reduce_data[map_data_msg.index].push(tuple)
do_reduce: () ->
@_status.state = "REDUCING"
@statecallback(@_status.state)
collected_data = {}
for index, list of @reduce_data
for item in list
if item[0] not of collected_data
collected_data[item[0]] = []
collected_data[item[0]].push(item[1])
data_for_jimmy = {}
reduce = (key, map_output_list) =>
emit = (line) ->
if key not of data_for_jimmy
data_for_jimmy[key] = []
data_for_jimmy[key].push(line)
eval(@reduce_code)
num_reduced = 0
for key, list of collected_data
reduce(key, list)
num_reduced++
@finish_reduce(data_for_jimmy)
finish_reduce: (data_for_jimmy) ->
@_status.state = "SENDING_TO_IO_SERVER"
@statecallback(@_status.state)
# We want to collect the key -> [output_lines] and send a certain number of lines at a time
messages = []
current_batch = []
current_batch_length = 0
for key, list of data_for_jimmy
if list.length + current_batch_length > constants.BATCH_SIZE
messages.push current_batch
current_batch = []
current_batch_length = 0
current_batch.push [key, if list.length == 1 then list[0] else list]
current_batch_length += list.length
if current_batch.length
messages.push current_batch
# Start message to <NAME>
firebase.IO_SERVER_MESSAGE_REF.push
name: "START_REDUCER_OUTPUT",
reducer: @index,
job: @job_id
for message in messages
firebase.IO_SERVER_MESSAGE_REF.push {
name: "REDUCER_OUTPUT"
reducer: @index
message
job: @job_id
}
firebase.IO_SERVER_MESSAGE_REF.push
name: "STOP_REDUCER_OUTPUT",
reducer: @index,
job: @job_id
@send_to_server
name: "REDUCE_DONE"
index: @index
job_id: @job_id
@clean_reduce()
clean_reduce: () ->
@reduce_code = null
@reduce_data = null
@job_id = null
@number_of_mappers = null
@reduce_data = {}
@num_done = 0
@mapper_done = null
@_status.state = 'IDLE'
@statecallback(@_status.state)
hashval: (s) ->
hash = 0
chr = null
if s.length == 0
return hash;
for i in s.length
chr = this.charCodeAt(i)
hash = ((hash << 5) - hash) + chr
hash |= 0
return hash;
getState: () ->
return @_status.state
module.exports = {Worker} | true | firebase = require '../firebase_client.coffee'
config = require '../../../../config.coffee'
constants = require '../../../../constants.coffee'
q = require 'q'
class Worker
constructor: (statecallback) ->
@_last_update = new Date().getTime()
@_connections = {}
@_status = {
state: 'IDLE'
}
@statecallback = statecallback
init: () ->
@get_id()
@listen()
setInterval () =>
before = @_last_update
@heartbeat () ->
#console.log "Heartbeated... diff=", (new Date().getTime() - before)
, constants.HEARTBEAT_INTERVAL
@statecallback @_status.state
heartbeat: (callback) ->
@_update_time()
@save_to_firebase(callback)
get_id: () ->
id_ref = firebase.WORKER_ID_REF.push "new_worker"
@_id = id_ref.name()
_update_time: () ->
@_last_update = new Date().getTime()
to_json: () ->
object =
id: @_id
last_update: @_last_update
status: @_status
return object
id: () ->
return @_id
save_to_firebase: (callback) ->
update_object = {}
update_object[@_id] = @to_json()
firebase.WORKER_STATUS_REF.update update_object, callback
process_message: (message) ->
message_type = message.name
if message_type == "MAP_START"
@start_map(message)
else if message_type == "REDUCE_NODES"
@send_map_data(message)
else if message_type == "JOB_DONE"
@finish_job(message)
else if message_type == "START_REDUCE"
@start_reduce(message)
else if message_type == "START_MAP_OUTPUT"
@add_data_src(message)
else if message_type == "MAP_OUTPUT"
@add_map_output(message)
else if message_type == "END_MAP_OUTPUT"
@close_data_src(message)
else if message_type == "REDUCE_DONE"
@finish_reduce(message)
else
throw new Error("Unknown message!")
listen: () ->
message_ref = firebase.WORKER_MESSAGE_REF.child(@_id)
message_ref.on 'child_added', (new_child) =>
@process_message(new_child.val())
message_ref.child(new_child.name()).remove()
send_to_server: (message, callback) ->
other = firebase.SERVER_MESSAGE_REF
other.push message, callback
send_to_friend: (client, message, callback) ->
other = firebase.WORKER_MESSAGE_REF.child(client)
other.push message, callback
finish_job: () ->
@data = null
@mappings = null
@map_code = null
@clean_reduce()
start_map: (map_start_message) ->
@_status.state = 'MAPPER'
@statecallback(@_status.state)
@job_id = map_start_message.job_id
@index = map_start_message.index
@get_data(map_start_message.url).then(() =>
return @get_mapping_code()
).then () =>
@run_map_job()
@map_done()
get_data: (url) ->
@_status.state = "DOWNLOADING_MAPPING_DATA"
@statecallback(@_status.state)
deferred = q.defer()
@data = ''
$.get url, (data) =>
@data = data
deferred.resolve()
return deferred.promise
get_mapping_code: () ->
@_status.state = "DOWNLOADING_MAPPING_CODE"
@statecallback(@_status.state)
deferred = q.defer()
firebase.JOB_STATUS_REF.child(@job_id).child('map_code').once 'value', (snapshot) =>
@map_code = snapshot.val()
deferred.resolve()
return deferred.promise
run_map_job: () ->
@_status.state = "MAPPING"
@statecallback(@_status.state)
@mappings = []
emit = (key, object) =>
@mappings.push [key, object]
lines = @data.split('\n')
lines = (line for line in lines when line.length > 0)
map = (lines) =>
eval(@map_code)
map lines
map_done: () ->
msg = {name: "MAPPER_DONE", job_id: @job_id, id: @_id}
@send_to_server msg, () =>
@_status.state = 'MAPPER_DONE'
@statecallback(@_status.state)
send_map_data: (reduce_node_list) ->
@_status.state = "SENDING_MAPPED_RESULTS"
@statecallback(@_status.state)
num_nodes = reduce_node_list.nodes.length
# Group all of the messages together
reducer_queues = []
for client in reduce_node_list.nodes
reducer_queues.push []
for tuple in @mappings
hash = @hashval(tuple[0])
reducer_index = hash % num_nodes
reducer_queues[reducer_index].push tuple
for queue, queue_index in reducer_queues
batched_queue = []
# Batch the individual tuples
current_batch = []
for tuple, index in queue
if index > 0 and index % constants.BATCH_SIZE == 0
batched_queue.push {tuples: current_batch}
current_batch = []
current_batch.push tuple
if current_batch.length
batched_queue.push {tuples: current_batch}
reducer_queues[queue_index] = batched_queue
for client in reduce_node_list.nodes
@send_to_friend client,
name: 'START_MAP_OUTPUT'
index: @index
total_sent = 0
total_to_send = 0
for queue in reducer_queues
for batched_tuples in queue
total_to_send += batched_tuples.tuples.length
for queue, queue_index in reducer_queues
for batched_tuples, index in queue
to_send_client = reduce_node_list.nodes[queue_index]
@send_to_friend to_send_client,
name: 'MAP_OUTPUT'
index: @index
key: batched_tuples
total_sent += batched_tuples.tuples.length
@statecallback(@_status.state, "Sent " + total_sent + " / " + total_to_send)
for client in reduce_node_list.nodes
@send_to_friend client,
name: 'END_MAP_OUTPUT'
index: @index
@_status.state = 'MAPPER_DONE'
@statecallback(@_status.state)
start_reduce: (start_reduce_message) ->
@_status.state = 'REDUCER'
@statecallback(@_status.state)
@job_id = start_reduce_message.job_id
@index = start_reduce_message.index
@number_of_mappers = start_reduce_message.number_of_mappers
@reduce_data = {}
@num_done = 0
@mapper_done = (false for _ in @number_of_mappers)
get_reduce_code: () ->
@_status.state = "DOWNLOADING_REDUCE_CODE"
@statecallback(@_status.state)
deferred = q.defer()
firebase.JOB_STATUS_REF.child(@job_id).child('reduce_code').once 'value', (snapshot) =>
@reduce_code = snapshot.val()
deferred.resolve()
return deferred.promise
add_data_src: (map_data_msg) ->
@_status.state = "RECEIVING_REDUCE_DATA"
@statecallback(@_status.state)
if @mapper_done[map_data_msg.index]
return
@reduce_data[map_data_msg.index] = []
close_data_src: (map_data_msg) ->
if not @mapper_done[map_data_msg.index]
@num_done++
@mapper_done[map_data_msg.index] = true
if @num_done == @number_of_mappers
@get_reduce_code().then () =>
@do_reduce()
add_map_output: (map_data_msg) ->
if @mapper_done[map_data_msg.index]
return
# Unpack the batched message
for tuple in map_data_msg.key.tuples
@reduce_data[map_data_msg.index].push(tuple)
do_reduce: () ->
@_status.state = "REDUCING"
@statecallback(@_status.state)
collected_data = {}
for index, list of @reduce_data
for item in list
if item[0] not of collected_data
collected_data[item[0]] = []
collected_data[item[0]].push(item[1])
data_for_jimmy = {}
reduce = (key, map_output_list) =>
emit = (line) ->
if key not of data_for_jimmy
data_for_jimmy[key] = []
data_for_jimmy[key].push(line)
eval(@reduce_code)
num_reduced = 0
for key, list of collected_data
reduce(key, list)
num_reduced++
@finish_reduce(data_for_jimmy)
finish_reduce: (data_for_jimmy) ->
@_status.state = "SENDING_TO_IO_SERVER"
@statecallback(@_status.state)
# We want to collect the key -> [output_lines] and send a certain number of lines at a time
messages = []
current_batch = []
current_batch_length = 0
for key, list of data_for_jimmy
if list.length + current_batch_length > constants.BATCH_SIZE
messages.push current_batch
current_batch = []
current_batch_length = 0
current_batch.push [key, if list.length == 1 then list[0] else list]
current_batch_length += list.length
if current_batch.length
messages.push current_batch
# Start message to PI:NAME:<NAME>END_PI
firebase.IO_SERVER_MESSAGE_REF.push
name: "START_REDUCER_OUTPUT",
reducer: @index,
job: @job_id
for message in messages
firebase.IO_SERVER_MESSAGE_REF.push {
name: "REDUCER_OUTPUT"
reducer: @index
message
job: @job_id
}
firebase.IO_SERVER_MESSAGE_REF.push
name: "STOP_REDUCER_OUTPUT",
reducer: @index,
job: @job_id
@send_to_server
name: "REDUCE_DONE"
index: @index
job_id: @job_id
@clean_reduce()
clean_reduce: () ->
@reduce_code = null
@reduce_data = null
@job_id = null
@number_of_mappers = null
@reduce_data = {}
@num_done = 0
@mapper_done = null
@_status.state = 'IDLE'
@statecallback(@_status.state)
hashval: (s) ->
hash = 0
chr = null
if s.length == 0
return hash;
for i in s.length
chr = this.charCodeAt(i)
hash = ((hash << 5) - hash) + chr
hash |= 0
return hash;
getState: () ->
return @_status.state
module.exports = {Worker} |
[
{
"context": "# Copyright (C) 2013 John Judnich\n# Released under The MIT License - see \"LICENSE\" ",
"end": 33,
"score": 0.9998670816421509,
"start": 21,
"tag": "NAME",
"value": "John Judnich"
}
] | source/PlanetMath.coffee | anandprabhakar0507/Kosmos | 46 | # Copyright (C) 2013 John Judnich
# Released under The MIT License - see "LICENSE" file for details.
root = exports ? this
root.cubeFaceQuaternion = []
root.cubeFaceMatrix = []
# Maps plane coordinates (where top left = [0,0] and bottom right = [1,1])
# to a coordinates on a unit cube (corners at [-1,-1,-1] and [+1,+1,+1]), based on
# which face of the cube the coordinates belong to.
root.mapPlaneToCube = (u, v, faceIndex) ->
pos = vec3.fromValues(u * 2 - 1, v * 2 - 1, 1)
vec3.transformQuat(pos, pos, cubeFaceQuaternion[faceIndex])
return pos
initialize = ->
cubeFaceQuaternion[i] = quat.create() for i in [0..5]
unitX = vec3.fromValues(1, 0, 0)
unitY = vec3.fromValues(0, 1, 0)
quat.setAxisAngle(cubeFaceQuaternion[1], unitY, xgl.degToRad(180))
quat.setAxisAngle(cubeFaceQuaternion[2], unitY, xgl.degToRad(-90))
quat.setAxisAngle(cubeFaceQuaternion[3], unitY, xgl.degToRad(90))
quat.setAxisAngle(cubeFaceQuaternion[4], unitX, xgl.degToRad(90))
quat.setAxisAngle(cubeFaceQuaternion[5], unitX, xgl.degToRad(-90))
for i in [0..5]
cubeFaceMatrix[i] = mat3.create()
mat3.fromQuat(cubeFaceMatrix[i], cubeFaceQuaternion[i])
initialize()
| 82879 | # Copyright (C) 2013 <NAME>
# Released under The MIT License - see "LICENSE" file for details.
root = exports ? this
root.cubeFaceQuaternion = []
root.cubeFaceMatrix = []
# Maps plane coordinates (where top left = [0,0] and bottom right = [1,1])
# to a coordinates on a unit cube (corners at [-1,-1,-1] and [+1,+1,+1]), based on
# which face of the cube the coordinates belong to.
root.mapPlaneToCube = (u, v, faceIndex) ->
pos = vec3.fromValues(u * 2 - 1, v * 2 - 1, 1)
vec3.transformQuat(pos, pos, cubeFaceQuaternion[faceIndex])
return pos
initialize = ->
cubeFaceQuaternion[i] = quat.create() for i in [0..5]
unitX = vec3.fromValues(1, 0, 0)
unitY = vec3.fromValues(0, 1, 0)
quat.setAxisAngle(cubeFaceQuaternion[1], unitY, xgl.degToRad(180))
quat.setAxisAngle(cubeFaceQuaternion[2], unitY, xgl.degToRad(-90))
quat.setAxisAngle(cubeFaceQuaternion[3], unitY, xgl.degToRad(90))
quat.setAxisAngle(cubeFaceQuaternion[4], unitX, xgl.degToRad(90))
quat.setAxisAngle(cubeFaceQuaternion[5], unitX, xgl.degToRad(-90))
for i in [0..5]
cubeFaceMatrix[i] = mat3.create()
mat3.fromQuat(cubeFaceMatrix[i], cubeFaceQuaternion[i])
initialize()
| true | # Copyright (C) 2013 PI:NAME:<NAME>END_PI
# Released under The MIT License - see "LICENSE" file for details.
root = exports ? this
root.cubeFaceQuaternion = []
root.cubeFaceMatrix = []
# Maps plane coordinates (where top left = [0,0] and bottom right = [1,1])
# to a coordinates on a unit cube (corners at [-1,-1,-1] and [+1,+1,+1]), based on
# which face of the cube the coordinates belong to.
root.mapPlaneToCube = (u, v, faceIndex) ->
pos = vec3.fromValues(u * 2 - 1, v * 2 - 1, 1)
vec3.transformQuat(pos, pos, cubeFaceQuaternion[faceIndex])
return pos
initialize = ->
cubeFaceQuaternion[i] = quat.create() for i in [0..5]
unitX = vec3.fromValues(1, 0, 0)
unitY = vec3.fromValues(0, 1, 0)
quat.setAxisAngle(cubeFaceQuaternion[1], unitY, xgl.degToRad(180))
quat.setAxisAngle(cubeFaceQuaternion[2], unitY, xgl.degToRad(-90))
quat.setAxisAngle(cubeFaceQuaternion[3], unitY, xgl.degToRad(90))
quat.setAxisAngle(cubeFaceQuaternion[4], unitX, xgl.degToRad(90))
quat.setAxisAngle(cubeFaceQuaternion[5], unitX, xgl.degToRad(-90))
for i in [0..5]
cubeFaceMatrix[i] = mat3.create()
mat3.fromQuat(cubeFaceMatrix[i], cubeFaceQuaternion[i])
initialize()
|
[
{
"context": "opyright 2013 Canopy Canopy Canopy, Inc.\n# Authors Adam Florin & Anthony Tran\n#\nclass Alongslide::Scrolling\n\n #",
"end": 117,
"score": 0.9997655749320984,
"start": 106,
"tag": "NAME",
"value": "Adam Florin"
},
{
"context": "Canopy Canopy Canopy, Inc.\n# Authors Ad... | app/assets/javascripts/alongslide/scrolling.coffee | triplecanopy/alongslide | 33 | #
# alongslide/scrolling.coffee: Skrollr wrapper.
#
# Copyright 2013 Canopy Canopy Canopy, Inc.
# Authors Adam Florin & Anthony Tran
#
class Alongslide::Scrolling
# For applyTransition.
#
TRANSITIONS:
in : [-1..0]
out: [0..1]
FLIP_THRESHOLD : 0.04
WAIT_BEFORE_RESET_MS : 250
SLIDE_DURATION_MS : 250
FORCE_SLIDE_DURATION_MS : 100
NUM_WHEEL_HISTORY_EVENTS: 10
MAGNITUDE_THRESHOLD : 2.2
currentPosition : 0
indexedTransitions : {}
# For desktop scroll throttling.
#
wheelHistory : []
lastAverageMagnitude : 0
ignoreScroll : false
lastRequestedPosition: 0
mouseDown : false
# browser history
stateData: {}
constructor: (options= {}) ->
{@frames} = options
@skrollr = skrollr.init
emitEvents: true
horizontal: true
edgeStrategy: 'set'
render: @snap
easing:
easeInOutQuad: (p) ->
if p < 0.5
Math.pow(p*2, 1.5) / 2
else
1 - Math.pow((p * -2 + 2), 1.5) / 2;
easeOutQuad: (p) ->
1 - Math.pow(1 - p, 2)
@arrowKeys()
@events()
unless @skrollr.isMobile()
@throttleScrollEvents()
@monitorScroll()
@monitorMouse()
# Init skrollr once content data attributes are populated.
#
# @param - frameAspect - percentage horizontal offset (0.-1.)
# to factor in when applying scroll transitions
#
render: (@frameAspect, lastFramePosition) ->
@applyTransitions(lastFramePosition)
@skrollr.refresh()
# TODO: write API that injects functions
# i.e. functionName(event, frame number, function) `('before', 3, animateTable)`
events: =>
@frames.on 'skrollrBefore', (e) -> e.target
@frames.on 'skrollrBetween', (e) -> e.target
@frames.on 'skrollrAfter', (e) -> e.target
# Apply skrollr-style attrs based on Alongslide attrs.
#
#
applyTransitions: (lastFramePosition) ->
@indexedTransitions = {}
@frames.find('.frame').each (index, frameEl) =>
frame = $(frameEl)
keyframes =
in: parseInt(frame.data alongslide.layout.IN_POINT_KEY)
out: parseInt(frame.data alongslide.layout.OUT_POINT_KEY)
if (keyframes.in is lastFramePosition) or (keyframes.out is -1)
keyframes.out = null
else
keyframes.out ||= keyframes.in
@indexedTransitions[keyframes.in] ?= {in: [], out: []}
@indexedTransitions[keyframes.in].in.push frame
if keyframes.out?
@indexedTransitions[keyframes.out] ?= {in: [], out: []}
@indexedTransitions[keyframes.out].out.push frame
@applyTransition frame, _(keyframes).extend lastFramePosition: lastFramePosition
if @skrollr.isMobile()
# For mobile, stage positions 0 and 1
_.each [0, 1], (position) =>
_.each @indexedTransitions[position].in, (frame) ->
frame.removeClass('unstaged')
else
# For desktop, stage all
@frames.find('.frame').each (index, frameEl) =>
$(frameEl).removeClass('unstaged')
# Write skrollr-style scroll transitions into jQuery DOM element.
#
# Note that, since a frame may enter and exit with different transitions,
# the CSS snippets for each transition should zero out effects of other
# transitions. (That's why the "slide" transition sets opacity.)
#
# Also, frames may scroll over a shorter distance ('scale') if they
# are with horizontally pinned panels. The code below must be context-aware
# enough to know when to do a normal-length scroll and when to shorten it.
#
# @param frame: jQuery object wrapping new DOM frame
# @param options: hash containing:
# - in: percentage of total page width when frame should enter
# - out (optional): percentage of total page width when frame should exit
# - lastFramePosition: last position of any frame in DOM.
#
# @return frame
#
applyTransition: (frame, options = {}) ->
# fuzzy logic coefficient. see below.
A_LITTLE_MORE = 2
options = @transitionOptions frame, options
# Flow frames have a left offset; panels and backgrounds do not.
offset = if frame.parent().hasClass('flow') then @frameAspect.left else 0
# if frame is partial width, scale the scroll down
frameScale = alongslide.layout.framePartialWidth(frame)
# transition is either 'in' or 'out'
for transition, directions of @TRANSITIONS
if options[transition]?
# direction is either -1, 0, or 1.
for direction in directions
# Set framescale for horizontal panels if there's another horizontal
# panel at the opposite edge before AND after the transition.
#
if Math.abs(direction) > 0
if frame.parent().hasClass('panels')
panelAlignment = alongslide.layout.panelAlignment(frame)
if _(alongslide.layout.HORIZONTAL_EDGES).contains panelAlignment
oppositeEdge =
if frame.hasClass('left') then 'right'
else if frame.hasClass('right') then 'left'
if (alongslide.layout.horizontalPanelAt(options[transition], oppositeEdge) and
alongslide.layout.horizontalPanelAt(options[transition] + direction, oppositeEdge))
frameScale = 0.495
# In certain cases, we need more than one keypoint per direction.
#
keypoints =
if frameScale?
# if frameScale is set, use it--but add an additional keypoint
# at 1.0 to make sure these closely-packed frames are out of
# the visible frame when they need to be be.
_.map [frameScale, 1.0], (scale, index) ->
magnitude = direction * (parseInt(index)+1)
position = options[transition] + magnitude
# if there isn't a horizontally pinned panel here, then scroll normally.
scale = 1.0 unless alongslide.layout.horizontalPanelAt(position)
# Double keypoints in order to keep the frame out of the visible
# window until absolutely necessary so that it doesn't sit atop
# the visible frame (and consume link clicks).
#
[ {magnitude: magnitude, scale: scale * A_LITTLE_MORE},
{magnitude: magnitude * 0.99, scale: scale}]
else if options.transition[transition] is "fade" and direction isnt 0
# fade transitions need a secret keypoint so that they fade
# in place but also don't hang out with opacity: 0 on top of
# other content when they're not supposed to be there.
[ {magnitude: direction * 0.99, scale: 0.0},
{magnitude: direction, scale: 1.0}]
else
# default: one keypoint
[{magnitude: direction, scale: 1.0}]
# apply Skrollr transitions for each keypoint.
#
for keypoint in _.flatten(keypoints)
{magnitude, scale} = keypoint
position = options[transition] + magnitude
# Don't write extra transitions beyond the end of the piece
unless position > options.lastFramePosition
styles = {}
# x translate
translateBy = (offset - direction) * scale
windowWidth = $(window).width() + alongslide.layout.scrollbarOffset
translateByPx = Math.round(translateBy * Math.max(windowWidth, alongslide.layout.FRAME_WIDTH))
styles["#{prefix.css}transform"] =
"translate(#{translateByPx}px, 0) translateZ(0)"
# opacity
styles.opacity = if options.transition[transition] is "fade"
1.0 - Math.abs(direction)
else
1.0
# apply the data for Skrollr.
frame.attr "data-#{Math.round(position * 100)}p",
(_.map styles, (value, key) -> "#{key}: #{value}").join("; ")
# Check frame's CSS classes for transition cues in the format
# `*-in` or `*-out`.
#
# Currently defaults to "slide", and does no validation.
#
transitionOptions: (frame, options = {}) ->
frameClass = frame.get(0).className
options.transition =
_.object _.map @TRANSITIONS, (directions, transition) ->
effectMatch = frameClass.match(new RegExp("(\\S+)-#{transition}"))
effect = if effectMatch then effectMatch[1] else "slide"
[transition, effect]
return options
# If we're in the refractory period, extinguish all scroll events immediately.
#
# Desktop only.
#
throttleScrollEvents: ->
$(window).on 'wheel mousewheel DOMMouseScroll MozMousePixelScroll', (e) =>
deltaX = e.originalEvent.deltaX || e.originalEvent.wheelDeltaX || 0
deltaY = e.originalEvent.deltaY || e.originalEvent.wheelDeltaY || 0
averageMagnitude = @updateWheelHistory(deltaX)
if @ignoreScroll
if averageMagnitude > @lastAverageMagnitude * @MAGNITUDE_THRESHOLD
@ignoreScroll = false
else if Math.abs(deltaX) > Math.abs(deltaY)
e.preventDefault()
@lastAverageMagnitude = averageMagnitude
# To gauge scroll inertia on desktop, need to constantly populate our
# wheelHistory array with zeroes to mark time.
#
# Desktop only.
#
monitorScroll: ->
# zero handler
zeroHistory = => @lastAverageMagnitude = @updateWheelHistory(0)
# init wheel history
_(@NUM_WHEEL_HISTORY_EVENTS).times -> zeroHistory()
# repeat forever.
setInterval zeroHistory, 5
# Add the latest delta to the running history, enforce max length.
#
# Returns average after updating.
#
updateWheelHistory: (delta) ->
# add delta to history
@wheelHistory.unshift(delta)
# trim history
@wheelHistory.pop() while @wheelHistory.length > @NUM_WHEEL_HISTORY_EVENTS
# return average
sum = _.reduce(@wheelHistory, ((memo, num) -> memo + num), 0)
average = sum / @wheelHistory.length
return Math.abs(average)
# Monitor mousedown state on desktop to separate scrollbar from mousewheel
#
monitorMouse: ->
$(document).mousedown =>
@mouseDown = true
$(document).mouseup =>
@mouseDown = false
requestedPosition = $(window).scrollLeft() / $(window).width()
window.alongslide?.scrolling.scrollToPosition(requestedPosition)
# Scroll to requested frame.
#
# Don't scroll below zero, and don't do redundant scrolls.
#
# @param position - ALS position (= frame number). May be floating point!
#
# @option skrollr - caller may pass in skrollr if our variable hasn't been
# set yet
# @option force - if true, force a corrective scroll, even if we think we're
# at the position we think we're supposed to be at.
# @option scrollMethod - is this a "scroll", a "touch", or "keys"?
#
scrollToPosition: (requestedPosition, options = {}) =>
# use our stored copy of skrollr instance if available
skrollr = @skrollr || options.skrollr
clearTimeout @resetTimeout
# round floating point position up or down based on thresholds
deltaRequestedPosition = requestedPosition - @lastRequestedPosition
deltaPosition = requestedPosition - @currentPosition
position =
if deltaRequestedPosition > 0
if deltaPosition > @FLIP_THRESHOLD
Math.ceil requestedPosition
else if deltaRequestedPosition < 0
if deltaPosition < -@FLIP_THRESHOLD
Math.floor requestedPosition
position ?= @currentPosition
# contain within bounds
position = Math.max(0, position)
position = Math.min(position, alongslide?.layout.lastFramePosition()) if alongslide?
if position isnt @currentPosition
# scroll to new (integer) position
scrollTo = position
duration = @SLIDE_DURATION_MS
if alongslide.layout.horizontalPanelAt(position) and alongslide.layout.horizontalPanelAt(@currentPosition)
duration /= 2
else if requestedPosition isnt @currentPosition
# didn't quite land on a new frame. revert back to current position after timeout.
@resetTimeout = setTimeout((=>
@scrollToPosition(@currentPosition, force: true)
), @WAIT_BEFORE_RESET_MS)
else if options.force
if (position * $(window).width()) isnt skrollr.getScrollPosition()
scrollTo = @currentPosition
duration = @FORCE_SLIDE_DURATION_MS
@doScroll(scrollTo, skrollr, duration, options) if scrollTo?
@lastRequestedPosition = requestedPosition
#
#
doScroll: (scrollTo, skrollr, duration, options) ->
scrollDelta = scrollTo - @currentPosition
@currentPosition = scrollTo
# Block all future scrolls until new scroll has begun.
# See throttleScrollEvents().
unless skrollr.isMobile() or options.scrollMethod is "keys"
@ignoreScroll = true
# Do scroll
skrollr.animateTo scrollTo * $(window).width(),
duration: duration
easing: 'easeOutQuad'
done: (skrollr) =>
stateData =
index: @currentPosition
alongslide.state.updateLocation(stateData)
# For mobile, stage/unstage frames after transition
if @skrollr.isMobile()
setTimeout((=>
if Math.abs(scrollDelta) > 0
stagePosition = scrollTo + scrollDelta
stageTransition = if scrollDelta > 0 then 'in' else 'out'
_.each @indexedTransitions[stagePosition]?[stageTransition], (frame) ->
frame.removeClass('unstaged').hide()
setTimeout((-> frame.show()), 0)
unstagePosition = @currentPosition - 2 * scrollDelta
unstageTransition = if scrollDelta > 0 then 'out' else 'in'
_.each @indexedTransitions[unstagePosition]?[unstageTransition], (frame) ->
frame.addClass('unstaged')
), duration)
# Snap-to-content scrolling, implemented as a skrollr callback, called after
# each frame in the animation loop.
#
# Bias the scroll so that it moves in the same direction as the user's input
# (i.e., use floor()/ceil() rather than round(), so that scroll never
# snaps BACK, which can feel disheartening as a user experience).
#
snap: (info) ->
# don't do anything if skrollr is animating
return if @isAnimatingTo()
# don't scroll past the document end
return if info.curTop > info.maxTop
# don't animate if user is clicking scrollbar
return if window.alongslide?.scrolling.mouseDown
# see how far the user has scrolled, scroll to the next frame.
requestedPosition = info.curTop / $(window).width()
window.alongslide?.scrolling.scrollToPosition(requestedPosition, skrollr: @)
# Listen to left/right arrow (unless modifier keys are pressed),
# and scroll accordingly.
#
arrowKeys: ->
$(document).keydown (event) =>
if event.altKey or event.shiftKey or event.ctrlKey or event.metaKey
return true
else
switch event.keyCode
when 37 then @scrollToPosition(@currentPosition - 1, scrollMethod: "keys")
when 39 then @scrollToPosition(@currentPosition + 1, scrollMethod: "keys")
else propagate_event = true
return propagate_event?
| 179634 | #
# alongslide/scrolling.coffee: Skrollr wrapper.
#
# Copyright 2013 Canopy Canopy Canopy, Inc.
# Authors <NAME> & <NAME>
#
class Alongslide::Scrolling
# For applyTransition.
#
TRANSITIONS:
in : [-1..0]
out: [0..1]
FLIP_THRESHOLD : 0.04
WAIT_BEFORE_RESET_MS : 250
SLIDE_DURATION_MS : 250
FORCE_SLIDE_DURATION_MS : 100
NUM_WHEEL_HISTORY_EVENTS: 10
MAGNITUDE_THRESHOLD : 2.2
currentPosition : 0
indexedTransitions : {}
# For desktop scroll throttling.
#
wheelHistory : []
lastAverageMagnitude : 0
ignoreScroll : false
lastRequestedPosition: 0
mouseDown : false
# browser history
stateData: {}
constructor: (options= {}) ->
{@frames} = options
@skrollr = skrollr.init
emitEvents: true
horizontal: true
edgeStrategy: 'set'
render: @snap
easing:
easeInOutQuad: (p) ->
if p < 0.5
Math.pow(p*2, 1.5) / 2
else
1 - Math.pow((p * -2 + 2), 1.5) / 2;
easeOutQuad: (p) ->
1 - Math.pow(1 - p, 2)
@arrowKeys()
@events()
unless @skrollr.isMobile()
@throttleScrollEvents()
@monitorScroll()
@monitorMouse()
# Init skrollr once content data attributes are populated.
#
# @param - frameAspect - percentage horizontal offset (0.-1.)
# to factor in when applying scroll transitions
#
render: (@frameAspect, lastFramePosition) ->
@applyTransitions(lastFramePosition)
@skrollr.refresh()
# TODO: write API that injects functions
# i.e. functionName(event, frame number, function) `('before', 3, animateTable)`
events: =>
@frames.on 'skrollrBefore', (e) -> e.target
@frames.on 'skrollrBetween', (e) -> e.target
@frames.on 'skrollrAfter', (e) -> e.target
# Apply skrollr-style attrs based on Alongslide attrs.
#
#
applyTransitions: (lastFramePosition) ->
@indexedTransitions = {}
@frames.find('.frame').each (index, frameEl) =>
frame = $(frameEl)
keyframes =
in: parseInt(frame.data alongslide.layout.IN_POINT_KEY)
out: parseInt(frame.data alongslide.layout.OUT_POINT_KEY)
if (keyframes.in is lastFramePosition) or (keyframes.out is -1)
keyframes.out = null
else
keyframes.out ||= keyframes.in
@indexedTransitions[keyframes.in] ?= {in: [], out: []}
@indexedTransitions[keyframes.in].in.push frame
if keyframes.out?
@indexedTransitions[keyframes.out] ?= {in: [], out: []}
@indexedTransitions[keyframes.out].out.push frame
@applyTransition frame, _(keyframes).extend lastFramePosition: lastFramePosition
if @skrollr.isMobile()
# For mobile, stage positions 0 and 1
_.each [0, 1], (position) =>
_.each @indexedTransitions[position].in, (frame) ->
frame.removeClass('unstaged')
else
# For desktop, stage all
@frames.find('.frame').each (index, frameEl) =>
$(frameEl).removeClass('unstaged')
# Write skrollr-style scroll transitions into jQuery DOM element.
#
# Note that, since a frame may enter and exit with different transitions,
# the CSS snippets for each transition should zero out effects of other
# transitions. (That's why the "slide" transition sets opacity.)
#
# Also, frames may scroll over a shorter distance ('scale') if they
# are with horizontally pinned panels. The code below must be context-aware
# enough to know when to do a normal-length scroll and when to shorten it.
#
# @param frame: jQuery object wrapping new DOM frame
# @param options: hash containing:
# - in: percentage of total page width when frame should enter
# - out (optional): percentage of total page width when frame should exit
# - lastFramePosition: last position of any frame in DOM.
#
# @return frame
#
applyTransition: (frame, options = {}) ->
# fuzzy logic coefficient. see below.
A_LITTLE_MORE = 2
options = @transitionOptions frame, options
# Flow frames have a left offset; panels and backgrounds do not.
offset = if frame.parent().hasClass('flow') then @frameAspect.left else 0
# if frame is partial width, scale the scroll down
frameScale = alongslide.layout.framePartialWidth(frame)
# transition is either 'in' or 'out'
for transition, directions of @TRANSITIONS
if options[transition]?
# direction is either -1, 0, or 1.
for direction in directions
# Set framescale for horizontal panels if there's another horizontal
# panel at the opposite edge before AND after the transition.
#
if Math.abs(direction) > 0
if frame.parent().hasClass('panels')
panelAlignment = alongslide.layout.panelAlignment(frame)
if _(alongslide.layout.HORIZONTAL_EDGES).contains panelAlignment
oppositeEdge =
if frame.hasClass('left') then 'right'
else if frame.hasClass('right') then 'left'
if (alongslide.layout.horizontalPanelAt(options[transition], oppositeEdge) and
alongslide.layout.horizontalPanelAt(options[transition] + direction, oppositeEdge))
frameScale = 0.495
# In certain cases, we need more than one keypoint per direction.
#
keypoints =
if frameScale?
# if frameScale is set, use it--but add an additional keypoint
# at 1.0 to make sure these closely-packed frames are out of
# the visible frame when they need to be be.
_.map [frameScale, 1.0], (scale, index) ->
magnitude = direction * (parseInt(index)+1)
position = options[transition] + magnitude
# if there isn't a horizontally pinned panel here, then scroll normally.
scale = 1.0 unless alongslide.layout.horizontalPanelAt(position)
# Double keypoints in order to keep the frame out of the visible
# window until absolutely necessary so that it doesn't sit atop
# the visible frame (and consume link clicks).
#
[ {magnitude: magnitude, scale: scale * A_LITTLE_MORE},
{magnitude: magnitude * 0.99, scale: scale}]
else if options.transition[transition] is "fade" and direction isnt 0
# fade transitions need a secret keypoint so that they fade
# in place but also don't hang out with opacity: 0 on top of
# other content when they're not supposed to be there.
[ {magnitude: direction * 0.99, scale: 0.0},
{magnitude: direction, scale: 1.0}]
else
# default: one keypoint
[{magnitude: direction, scale: 1.0}]
# apply Skrollr transitions for each keypoint.
#
for keypoint in _.flatten(keypoints)
{magnitude, scale} = keypoint
position = options[transition] + magnitude
# Don't write extra transitions beyond the end of the piece
unless position > options.lastFramePosition
styles = {}
# x translate
translateBy = (offset - direction) * scale
windowWidth = $(window).width() + alongslide.layout.scrollbarOffset
translateByPx = Math.round(translateBy * Math.max(windowWidth, alongslide.layout.FRAME_WIDTH))
styles["#{prefix.css}transform"] =
"translate(#{translateByPx}px, 0) translateZ(0)"
# opacity
styles.opacity = if options.transition[transition] is "fade"
1.0 - Math.abs(direction)
else
1.0
# apply the data for Skrollr.
frame.attr "data-#{Math.round(position * 100)}p",
(_.map styles, (value, key) -> "#{key}: #{value}").join("; ")
# Check frame's CSS classes for transition cues in the format
# `*-in` or `*-out`.
#
# Currently defaults to "slide", and does no validation.
#
transitionOptions: (frame, options = {}) ->
frameClass = frame.get(0).className
options.transition =
_.object _.map @TRANSITIONS, (directions, transition) ->
effectMatch = frameClass.match(new RegExp("(\\S+)-#{transition}"))
effect = if effectMatch then effectMatch[1] else "slide"
[transition, effect]
return options
# If we're in the refractory period, extinguish all scroll events immediately.
#
# Desktop only.
#
throttleScrollEvents: ->
$(window).on 'wheel mousewheel DOMMouseScroll MozMousePixelScroll', (e) =>
deltaX = e.originalEvent.deltaX || e.originalEvent.wheelDeltaX || 0
deltaY = e.originalEvent.deltaY || e.originalEvent.wheelDeltaY || 0
averageMagnitude = @updateWheelHistory(deltaX)
if @ignoreScroll
if averageMagnitude > @lastAverageMagnitude * @MAGNITUDE_THRESHOLD
@ignoreScroll = false
else if Math.abs(deltaX) > Math.abs(deltaY)
e.preventDefault()
@lastAverageMagnitude = averageMagnitude
# To gauge scroll inertia on desktop, need to constantly populate our
# wheelHistory array with zeroes to mark time.
#
# Desktop only.
#
monitorScroll: ->
# zero handler
zeroHistory = => @lastAverageMagnitude = @updateWheelHistory(0)
# init wheel history
_(@NUM_WHEEL_HISTORY_EVENTS).times -> zeroHistory()
# repeat forever.
setInterval zeroHistory, 5
# Add the latest delta to the running history, enforce max length.
#
# Returns average after updating.
#
updateWheelHistory: (delta) ->
# add delta to history
@wheelHistory.unshift(delta)
# trim history
@wheelHistory.pop() while @wheelHistory.length > @NUM_WHEEL_HISTORY_EVENTS
# return average
sum = _.reduce(@wheelHistory, ((memo, num) -> memo + num), 0)
average = sum / @wheelHistory.length
return Math.abs(average)
# Monitor mousedown state on desktop to separate scrollbar from mousewheel
#
monitorMouse: ->
$(document).mousedown =>
@mouseDown = true
$(document).mouseup =>
@mouseDown = false
requestedPosition = $(window).scrollLeft() / $(window).width()
window.alongslide?.scrolling.scrollToPosition(requestedPosition)
# Scroll to requested frame.
#
# Don't scroll below zero, and don't do redundant scrolls.
#
# @param position - ALS position (= frame number). May be floating point!
#
# @option skrollr - caller may pass in skrollr if our variable hasn't been
# set yet
# @option force - if true, force a corrective scroll, even if we think we're
# at the position we think we're supposed to be at.
# @option scrollMethod - is this a "scroll", a "touch", or "keys"?
#
scrollToPosition: (requestedPosition, options = {}) =>
# use our stored copy of skrollr instance if available
skrollr = @skrollr || options.skrollr
clearTimeout @resetTimeout
# round floating point position up or down based on thresholds
deltaRequestedPosition = requestedPosition - @lastRequestedPosition
deltaPosition = requestedPosition - @currentPosition
position =
if deltaRequestedPosition > 0
if deltaPosition > @FLIP_THRESHOLD
Math.ceil requestedPosition
else if deltaRequestedPosition < 0
if deltaPosition < -@FLIP_THRESHOLD
Math.floor requestedPosition
position ?= @currentPosition
# contain within bounds
position = Math.max(0, position)
position = Math.min(position, alongslide?.layout.lastFramePosition()) if alongslide?
if position isnt @currentPosition
# scroll to new (integer) position
scrollTo = position
duration = @SLIDE_DURATION_MS
if alongslide.layout.horizontalPanelAt(position) and alongslide.layout.horizontalPanelAt(@currentPosition)
duration /= 2
else if requestedPosition isnt @currentPosition
# didn't quite land on a new frame. revert back to current position after timeout.
@resetTimeout = setTimeout((=>
@scrollToPosition(@currentPosition, force: true)
), @WAIT_BEFORE_RESET_MS)
else if options.force
if (position * $(window).width()) isnt skrollr.getScrollPosition()
scrollTo = @currentPosition
duration = @FORCE_SLIDE_DURATION_MS
@doScroll(scrollTo, skrollr, duration, options) if scrollTo?
@lastRequestedPosition = requestedPosition
#
#
doScroll: (scrollTo, skrollr, duration, options) ->
scrollDelta = scrollTo - @currentPosition
@currentPosition = scrollTo
# Block all future scrolls until new scroll has begun.
# See throttleScrollEvents().
unless skrollr.isMobile() or options.scrollMethod is "keys"
@ignoreScroll = true
# Do scroll
skrollr.animateTo scrollTo * $(window).width(),
duration: duration
easing: 'easeOutQuad'
done: (skrollr) =>
stateData =
index: @currentPosition
alongslide.state.updateLocation(stateData)
# For mobile, stage/unstage frames after transition
if @skrollr.isMobile()
setTimeout((=>
if Math.abs(scrollDelta) > 0
stagePosition = scrollTo + scrollDelta
stageTransition = if scrollDelta > 0 then 'in' else 'out'
_.each @indexedTransitions[stagePosition]?[stageTransition], (frame) ->
frame.removeClass('unstaged').hide()
setTimeout((-> frame.show()), 0)
unstagePosition = @currentPosition - 2 * scrollDelta
unstageTransition = if scrollDelta > 0 then 'out' else 'in'
_.each @indexedTransitions[unstagePosition]?[unstageTransition], (frame) ->
frame.addClass('unstaged')
), duration)
# Snap-to-content scrolling, implemented as a skrollr callback, called after
# each frame in the animation loop.
#
# Bias the scroll so that it moves in the same direction as the user's input
# (i.e., use floor()/ceil() rather than round(), so that scroll never
# snaps BACK, which can feel disheartening as a user experience).
#
snap: (info) ->
# don't do anything if skrollr is animating
return if @isAnimatingTo()
# don't scroll past the document end
return if info.curTop > info.maxTop
# don't animate if user is clicking scrollbar
return if window.alongslide?.scrolling.mouseDown
# see how far the user has scrolled, scroll to the next frame.
requestedPosition = info.curTop / $(window).width()
window.alongslide?.scrolling.scrollToPosition(requestedPosition, skrollr: @)
# Listen to left/right arrow (unless modifier keys are pressed),
# and scroll accordingly.
#
arrowKeys: ->
$(document).keydown (event) =>
if event.altKey or event.shiftKey or event.ctrlKey or event.metaKey
return true
else
switch event.keyCode
when 37 then @scrollToPosition(@currentPosition - 1, scrollMethod: "keys")
when 39 then @scrollToPosition(@currentPosition + 1, scrollMethod: "keys")
else propagate_event = true
return propagate_event?
| true | #
# alongslide/scrolling.coffee: Skrollr wrapper.
#
# Copyright 2013 Canopy Canopy Canopy, Inc.
# Authors PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI
#
class Alongslide::Scrolling
# For applyTransition.
#
TRANSITIONS:
in : [-1..0]
out: [0..1]
FLIP_THRESHOLD : 0.04
WAIT_BEFORE_RESET_MS : 250
SLIDE_DURATION_MS : 250
FORCE_SLIDE_DURATION_MS : 100
NUM_WHEEL_HISTORY_EVENTS: 10
MAGNITUDE_THRESHOLD : 2.2
currentPosition : 0
indexedTransitions : {}
# For desktop scroll throttling.
#
wheelHistory : []
lastAverageMagnitude : 0
ignoreScroll : false
lastRequestedPosition: 0
mouseDown : false
# browser history
stateData: {}
constructor: (options= {}) ->
{@frames} = options
@skrollr = skrollr.init
emitEvents: true
horizontal: true
edgeStrategy: 'set'
render: @snap
easing:
easeInOutQuad: (p) ->
if p < 0.5
Math.pow(p*2, 1.5) / 2
else
1 - Math.pow((p * -2 + 2), 1.5) / 2;
easeOutQuad: (p) ->
1 - Math.pow(1 - p, 2)
@arrowKeys()
@events()
unless @skrollr.isMobile()
@throttleScrollEvents()
@monitorScroll()
@monitorMouse()
# Init skrollr once content data attributes are populated.
#
# @param - frameAspect - percentage horizontal offset (0.-1.)
# to factor in when applying scroll transitions
#
render: (@frameAspect, lastFramePosition) ->
@applyTransitions(lastFramePosition)
@skrollr.refresh()
# TODO: write API that injects functions
# i.e. functionName(event, frame number, function) `('before', 3, animateTable)`
events: =>
@frames.on 'skrollrBefore', (e) -> e.target
@frames.on 'skrollrBetween', (e) -> e.target
@frames.on 'skrollrAfter', (e) -> e.target
# Apply skrollr-style attrs based on Alongslide attrs.
#
#
applyTransitions: (lastFramePosition) ->
@indexedTransitions = {}
@frames.find('.frame').each (index, frameEl) =>
frame = $(frameEl)
keyframes =
in: parseInt(frame.data alongslide.layout.IN_POINT_KEY)
out: parseInt(frame.data alongslide.layout.OUT_POINT_KEY)
if (keyframes.in is lastFramePosition) or (keyframes.out is -1)
keyframes.out = null
else
keyframes.out ||= keyframes.in
@indexedTransitions[keyframes.in] ?= {in: [], out: []}
@indexedTransitions[keyframes.in].in.push frame
if keyframes.out?
@indexedTransitions[keyframes.out] ?= {in: [], out: []}
@indexedTransitions[keyframes.out].out.push frame
@applyTransition frame, _(keyframes).extend lastFramePosition: lastFramePosition
if @skrollr.isMobile()
# For mobile, stage positions 0 and 1
_.each [0, 1], (position) =>
_.each @indexedTransitions[position].in, (frame) ->
frame.removeClass('unstaged')
else
# For desktop, stage all
@frames.find('.frame').each (index, frameEl) =>
$(frameEl).removeClass('unstaged')
# Write skrollr-style scroll transitions into jQuery DOM element.
#
# Note that, since a frame may enter and exit with different transitions,
# the CSS snippets for each transition should zero out effects of other
# transitions. (That's why the "slide" transition sets opacity.)
#
# Also, frames may scroll over a shorter distance ('scale') if they
# are with horizontally pinned panels. The code below must be context-aware
# enough to know when to do a normal-length scroll and when to shorten it.
#
# @param frame: jQuery object wrapping new DOM frame
# @param options: hash containing:
# - in: percentage of total page width when frame should enter
# - out (optional): percentage of total page width when frame should exit
# - lastFramePosition: last position of any frame in DOM.
#
# @return frame
#
applyTransition: (frame, options = {}) ->
# fuzzy logic coefficient. see below.
A_LITTLE_MORE = 2
options = @transitionOptions frame, options
# Flow frames have a left offset; panels and backgrounds do not.
offset = if frame.parent().hasClass('flow') then @frameAspect.left else 0
# if frame is partial width, scale the scroll down
frameScale = alongslide.layout.framePartialWidth(frame)
# transition is either 'in' or 'out'
for transition, directions of @TRANSITIONS
if options[transition]?
# direction is either -1, 0, or 1.
for direction in directions
# Set framescale for horizontal panels if there's another horizontal
# panel at the opposite edge before AND after the transition.
#
if Math.abs(direction) > 0
if frame.parent().hasClass('panels')
panelAlignment = alongslide.layout.panelAlignment(frame)
if _(alongslide.layout.HORIZONTAL_EDGES).contains panelAlignment
oppositeEdge =
if frame.hasClass('left') then 'right'
else if frame.hasClass('right') then 'left'
if (alongslide.layout.horizontalPanelAt(options[transition], oppositeEdge) and
alongslide.layout.horizontalPanelAt(options[transition] + direction, oppositeEdge))
frameScale = 0.495
# In certain cases, we need more than one keypoint per direction.
#
keypoints =
if frameScale?
# if frameScale is set, use it--but add an additional keypoint
# at 1.0 to make sure these closely-packed frames are out of
# the visible frame when they need to be be.
_.map [frameScale, 1.0], (scale, index) ->
magnitude = direction * (parseInt(index)+1)
position = options[transition] + magnitude
# if there isn't a horizontally pinned panel here, then scroll normally.
scale = 1.0 unless alongslide.layout.horizontalPanelAt(position)
# Double keypoints in order to keep the frame out of the visible
# window until absolutely necessary so that it doesn't sit atop
# the visible frame (and consume link clicks).
#
[ {magnitude: magnitude, scale: scale * A_LITTLE_MORE},
{magnitude: magnitude * 0.99, scale: scale}]
else if options.transition[transition] is "fade" and direction isnt 0
# fade transitions need a secret keypoint so that they fade
# in place but also don't hang out with opacity: 0 on top of
# other content when they're not supposed to be there.
[ {magnitude: direction * 0.99, scale: 0.0},
{magnitude: direction, scale: 1.0}]
else
# default: one keypoint
[{magnitude: direction, scale: 1.0}]
# apply Skrollr transitions for each keypoint.
#
for keypoint in _.flatten(keypoints)
{magnitude, scale} = keypoint
position = options[transition] + magnitude
# Don't write extra transitions beyond the end of the piece
unless position > options.lastFramePosition
styles = {}
# x translate
translateBy = (offset - direction) * scale
windowWidth = $(window).width() + alongslide.layout.scrollbarOffset
translateByPx = Math.round(translateBy * Math.max(windowWidth, alongslide.layout.FRAME_WIDTH))
styles["#{prefix.css}transform"] =
"translate(#{translateByPx}px, 0) translateZ(0)"
# opacity
styles.opacity = if options.transition[transition] is "fade"
1.0 - Math.abs(direction)
else
1.0
# apply the data for Skrollr.
frame.attr "data-#{Math.round(position * 100)}p",
(_.map styles, (value, key) -> "#{key}: #{value}").join("; ")
# Check frame's CSS classes for transition cues in the format
# `*-in` or `*-out`.
#
# Currently defaults to "slide", and does no validation.
#
transitionOptions: (frame, options = {}) ->
frameClass = frame.get(0).className
options.transition =
_.object _.map @TRANSITIONS, (directions, transition) ->
effectMatch = frameClass.match(new RegExp("(\\S+)-#{transition}"))
effect = if effectMatch then effectMatch[1] else "slide"
[transition, effect]
return options
# If we're in the refractory period, extinguish all scroll events immediately.
#
# Desktop only.
#
throttleScrollEvents: ->
$(window).on 'wheel mousewheel DOMMouseScroll MozMousePixelScroll', (e) =>
deltaX = e.originalEvent.deltaX || e.originalEvent.wheelDeltaX || 0
deltaY = e.originalEvent.deltaY || e.originalEvent.wheelDeltaY || 0
averageMagnitude = @updateWheelHistory(deltaX)
if @ignoreScroll
if averageMagnitude > @lastAverageMagnitude * @MAGNITUDE_THRESHOLD
@ignoreScroll = false
else if Math.abs(deltaX) > Math.abs(deltaY)
e.preventDefault()
@lastAverageMagnitude = averageMagnitude
# To gauge scroll inertia on desktop, need to constantly populate our
# wheelHistory array with zeroes to mark time.
#
# Desktop only.
#
monitorScroll: ->
# zero handler
zeroHistory = => @lastAverageMagnitude = @updateWheelHistory(0)
# init wheel history
_(@NUM_WHEEL_HISTORY_EVENTS).times -> zeroHistory()
# repeat forever.
setInterval zeroHistory, 5
# Add the latest delta to the running history, enforce max length.
#
# Returns average after updating.
#
updateWheelHistory: (delta) ->
# add delta to history
@wheelHistory.unshift(delta)
# trim history
@wheelHistory.pop() while @wheelHistory.length > @NUM_WHEEL_HISTORY_EVENTS
# return average
sum = _.reduce(@wheelHistory, ((memo, num) -> memo + num), 0)
average = sum / @wheelHistory.length
return Math.abs(average)
# Monitor mousedown state on desktop to separate scrollbar from mousewheel
#
monitorMouse: ->
$(document).mousedown =>
@mouseDown = true
$(document).mouseup =>
@mouseDown = false
requestedPosition = $(window).scrollLeft() / $(window).width()
window.alongslide?.scrolling.scrollToPosition(requestedPosition)
# Scroll to requested frame.
#
# Don't scroll below zero, and don't do redundant scrolls.
#
# @param position - ALS position (= frame number). May be floating point!
#
# @option skrollr - caller may pass in skrollr if our variable hasn't been
# set yet
# @option force - if true, force a corrective scroll, even if we think we're
# at the position we think we're supposed to be at.
# @option scrollMethod - is this a "scroll", a "touch", or "keys"?
#
scrollToPosition: (requestedPosition, options = {}) =>
# use our stored copy of skrollr instance if available
skrollr = @skrollr || options.skrollr
clearTimeout @resetTimeout
# round floating point position up or down based on thresholds
deltaRequestedPosition = requestedPosition - @lastRequestedPosition
deltaPosition = requestedPosition - @currentPosition
position =
if deltaRequestedPosition > 0
if deltaPosition > @FLIP_THRESHOLD
Math.ceil requestedPosition
else if deltaRequestedPosition < 0
if deltaPosition < -@FLIP_THRESHOLD
Math.floor requestedPosition
position ?= @currentPosition
# contain within bounds
position = Math.max(0, position)
position = Math.min(position, alongslide?.layout.lastFramePosition()) if alongslide?
if position isnt @currentPosition
# scroll to new (integer) position
scrollTo = position
duration = @SLIDE_DURATION_MS
if alongslide.layout.horizontalPanelAt(position) and alongslide.layout.horizontalPanelAt(@currentPosition)
duration /= 2
else if requestedPosition isnt @currentPosition
# didn't quite land on a new frame. revert back to current position after timeout.
@resetTimeout = setTimeout((=>
@scrollToPosition(@currentPosition, force: true)
), @WAIT_BEFORE_RESET_MS)
else if options.force
if (position * $(window).width()) isnt skrollr.getScrollPosition()
scrollTo = @currentPosition
duration = @FORCE_SLIDE_DURATION_MS
@doScroll(scrollTo, skrollr, duration, options) if scrollTo?
@lastRequestedPosition = requestedPosition
#
#
doScroll: (scrollTo, skrollr, duration, options) ->
scrollDelta = scrollTo - @currentPosition
@currentPosition = scrollTo
# Block all future scrolls until new scroll has begun.
# See throttleScrollEvents().
unless skrollr.isMobile() or options.scrollMethod is "keys"
@ignoreScroll = true
# Do scroll
skrollr.animateTo scrollTo * $(window).width(),
duration: duration
easing: 'easeOutQuad'
done: (skrollr) =>
stateData =
index: @currentPosition
alongslide.state.updateLocation(stateData)
# For mobile, stage/unstage frames after transition
if @skrollr.isMobile()
setTimeout((=>
if Math.abs(scrollDelta) > 0
stagePosition = scrollTo + scrollDelta
stageTransition = if scrollDelta > 0 then 'in' else 'out'
_.each @indexedTransitions[stagePosition]?[stageTransition], (frame) ->
frame.removeClass('unstaged').hide()
setTimeout((-> frame.show()), 0)
unstagePosition = @currentPosition - 2 * scrollDelta
unstageTransition = if scrollDelta > 0 then 'out' else 'in'
_.each @indexedTransitions[unstagePosition]?[unstageTransition], (frame) ->
frame.addClass('unstaged')
), duration)
# Snap-to-content scrolling, implemented as a skrollr callback, called after
# each frame in the animation loop.
#
# Bias the scroll so that it moves in the same direction as the user's input
# (i.e., use floor()/ceil() rather than round(), so that scroll never
# snaps BACK, which can feel disheartening as a user experience).
#
snap: (info) ->
# don't do anything if skrollr is animating
return if @isAnimatingTo()
# don't scroll past the document end
return if info.curTop > info.maxTop
# don't animate if user is clicking scrollbar
return if window.alongslide?.scrolling.mouseDown
# see how far the user has scrolled, scroll to the next frame.
requestedPosition = info.curTop / $(window).width()
window.alongslide?.scrolling.scrollToPosition(requestedPosition, skrollr: @)
# Listen to left/right arrow (unless modifier keys are pressed),
# and scroll accordingly.
#
arrowKeys: ->
$(document).keydown (event) =>
if event.altKey or event.shiftKey or event.ctrlKey or event.metaKey
return true
else
switch event.keyCode
when 37 then @scrollToPosition(@currentPosition - 1, scrollMethod: "keys")
when 39 then @scrollToPosition(@currentPosition + 1, scrollMethod: "keys")
else propagate_event = true
return propagate_event?
|
[
{
"context": "ce': 'path',\n 'keys': [\n 'b'\n ]\n }\n }, JSON.parse(",
"end": 929,
"score": 0.8698724508285522,
"start": 928,
"tag": "KEY",
"value": "b"
}
] | labs/api/meetings/test/routetests.coffee | thong-hoczita/bigbluebutton | 0 | hapi = require('hapi')
assert = require('assert')
chai = require('chai')
assert = chai.assert
routes = require('../lib/routes')
# integration tests for API endpoint
# setup server with firing up - use inject instead
server = new hapi.Server()
server.route(routes.routes)
# parseurls endpoint test
describe 'add endpoint', ->
it 'add - should add two numbers together', ->
server.inject({method: 'PUT', url: '/sum/add/5/5'}, (res) ->
assert.deepEqual({'equals': 10}, JSON.parse(res.payload))
done()
)
it 'add - should error if a string is passed', (done) ->
server.inject({method: 'PUT', url: '/sum/add/100/x'}, (res) ->
assert.deepEqual({
'statusCode': 400,
'error': 'Bad Request',
'message': 'the value of b must be a number',
'validation': {
'source': 'path',
'keys': [
'b'
]
}
}, JSON.parse(res.payload))
done()
) | 106997 | hapi = require('hapi')
assert = require('assert')
chai = require('chai')
assert = chai.assert
routes = require('../lib/routes')
# integration tests for API endpoint
# setup server with firing up - use inject instead
server = new hapi.Server()
server.route(routes.routes)
# parseurls endpoint test
describe 'add endpoint', ->
it 'add - should add two numbers together', ->
server.inject({method: 'PUT', url: '/sum/add/5/5'}, (res) ->
assert.deepEqual({'equals': 10}, JSON.parse(res.payload))
done()
)
it 'add - should error if a string is passed', (done) ->
server.inject({method: 'PUT', url: '/sum/add/100/x'}, (res) ->
assert.deepEqual({
'statusCode': 400,
'error': 'Bad Request',
'message': 'the value of b must be a number',
'validation': {
'source': 'path',
'keys': [
'<KEY>'
]
}
}, JSON.parse(res.payload))
done()
) | true | hapi = require('hapi')
assert = require('assert')
chai = require('chai')
assert = chai.assert
routes = require('../lib/routes')
# integration tests for API endpoint
# setup server with firing up - use inject instead
server = new hapi.Server()
server.route(routes.routes)
# parseurls endpoint test
describe 'add endpoint', ->
it 'add - should add two numbers together', ->
server.inject({method: 'PUT', url: '/sum/add/5/5'}, (res) ->
assert.deepEqual({'equals': 10}, JSON.parse(res.payload))
done()
)
it 'add - should error if a string is passed', (done) ->
server.inject({method: 'PUT', url: '/sum/add/100/x'}, (res) ->
assert.deepEqual({
'statusCode': 400,
'error': 'Bad Request',
'message': 'the value of b must be a number',
'validation': {
'source': 'path',
'keys': [
'PI:KEY:<KEY>END_PI'
]
}
}, JSON.parse(res.payload))
done()
) |
[
{
"context": "e <[owner/]repo> from package.json\n#\n# Author:\n# Tatshro Mitsuno <tmitsuno@yahoo-corp.jp>\n\nPublishRelease = requir",
"end": 422,
"score": 0.9998603463172913,
"start": 407,
"tag": "NAME",
"value": "Tatshro Mitsuno"
},
{
"context": "rom package.json\n#\n# Author:\n... | src/index.coffee | yahoojapan/hubot-package-version-release | 1 | # Description:
# create github release from package.json
#
# Dependencies:
# githubot
#
# Configuration:
# HUBOT_GITHUB_TOKEN (required)
# HUBOT_GITHUB_BASE_BRANCH (optional)
# HUBOT_GITHUB_OWNER (optional)
# HUBOT_GITHUB_RAW (optional)
# HUBOT_GITHUB_API (optional)
#
# Commands:
# hubot publish release <[owner/]repo> from package.json
#
# Author:
# Tatshro Mitsuno <tmitsuno@yahoo-corp.jp>
PublishRelease = require './publish'
module.exports = (robot) ->
robot.respond /publish release ([\w\-\.\/]+) from package.json/i, (msg) ->
if msg.match[1].indexOf('/') is -1
if process.env.HUBOT_GITHUB_OWNER?
fullName = process.env.HUBOT_GITHUB_OWNER + '/' + msg.match[1]
else
msg.send 'owner not specified'
return
else
fullName = msg.match[1]
publishRelease = new PublishRelease {
fullName: fullName
branch: process.env.HUBOT_GITHUB_BASE_BRANCH || 'release'
rawUrl: process.env.HUBOT_GITHUB_RAW || 'https://raw.github.com'
}, robot
publishRelease.publish (err, res) ->
if err?
msg.send err
else
msg.send res
# [TODO] webhooks entry point
| 152413 | # Description:
# create github release from package.json
#
# Dependencies:
# githubot
#
# Configuration:
# HUBOT_GITHUB_TOKEN (required)
# HUBOT_GITHUB_BASE_BRANCH (optional)
# HUBOT_GITHUB_OWNER (optional)
# HUBOT_GITHUB_RAW (optional)
# HUBOT_GITHUB_API (optional)
#
# Commands:
# hubot publish release <[owner/]repo> from package.json
#
# Author:
# <NAME> <<EMAIL>>
PublishRelease = require './publish'
module.exports = (robot) ->
robot.respond /publish release ([\w\-\.\/]+) from package.json/i, (msg) ->
if msg.match[1].indexOf('/') is -1
if process.env.HUBOT_GITHUB_OWNER?
fullName = process.env.HUBOT_GITHUB_OWNER + '/' + msg.match[1]
else
msg.send 'owner not specified'
return
else
fullName = msg.match[1]
publishRelease = new PublishRelease {
fullName: fullName
branch: process.env.HUBOT_GITHUB_BASE_BRANCH || 'release'
rawUrl: process.env.HUBOT_GITHUB_RAW || 'https://raw.github.com'
}, robot
publishRelease.publish (err, res) ->
if err?
msg.send err
else
msg.send res
# [TODO] webhooks entry point
| true | # Description:
# create github release from package.json
#
# Dependencies:
# githubot
#
# Configuration:
# HUBOT_GITHUB_TOKEN (required)
# HUBOT_GITHUB_BASE_BRANCH (optional)
# HUBOT_GITHUB_OWNER (optional)
# HUBOT_GITHUB_RAW (optional)
# HUBOT_GITHUB_API (optional)
#
# Commands:
# hubot publish release <[owner/]repo> from package.json
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
PublishRelease = require './publish'
module.exports = (robot) ->
robot.respond /publish release ([\w\-\.\/]+) from package.json/i, (msg) ->
if msg.match[1].indexOf('/') is -1
if process.env.HUBOT_GITHUB_OWNER?
fullName = process.env.HUBOT_GITHUB_OWNER + '/' + msg.match[1]
else
msg.send 'owner not specified'
return
else
fullName = msg.match[1]
publishRelease = new PublishRelease {
fullName: fullName
branch: process.env.HUBOT_GITHUB_BASE_BRANCH || 'release'
rawUrl: process.env.HUBOT_GITHUB_RAW || 'https://raw.github.com'
}, robot
publishRelease.publish (err, res) ->
if err?
msg.send err
else
msg.send res
# [TODO] webhooks entry point
|
[
{
"context": "email':\n prefix: 'eml-text'\n body: '''\nTo: \"John Doe\" <to@example.com>\nFrom: \"Mario Z.\" <from@example.",
"end": 85,
"score": 0.9998030662536621,
"start": 77,
"tag": "NAME",
"value": "John Doe"
},
{
"context": " prefix: 'eml-text'\n body: '''\nTo: \"John... | snippets/language-eml.cson | pchaigno/language-eml | 6 | '.text.eml':
'Plain-Text email':
prefix: 'eml-text'
body: '''
To: "John Doe" <to@example.com>
From: "Mario Z." <from@example.com>
Subject: This is a PlainText email
$2
'''
'HTML email':
prefix: 'eml-html'
body: '''
To: "John Doe" <to@example.com>
From: "Mario Z." <from@example.com>
Subject: This is a HTML email
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit
<html>
<head>
<title>This is a HTML email</title>
</head>
<body>
<p>$2</p>
</body>
</html>
'''
'MIME email':
prefix: 'eml-mime'
body: '''
To: "John Doe" <to@example.com>
From: "Mario Z." <from@example.com>
Subject: This is a MultiPart email
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="random_multipart_separator";
charset=UTF-8
--random_multipart_separator
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit
Hi,
$2
--random_multipart_separator
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit
<html>
<head></head>
<body>
<strong>Hi,</strong>
<p>$2</p>
</body>
</html>
--random_multipart_separator--
'''
| 27805 | '.text.eml':
'Plain-Text email':
prefix: 'eml-text'
body: '''
To: "<NAME>" <<EMAIL>>
From: "<NAME>." <<EMAIL>>
Subject: This is a PlainText email
$2
'''
'HTML email':
prefix: 'eml-html'
body: '''
To: "<NAME>" <<EMAIL>>
From: "<NAME>." <<EMAIL>>
Subject: This is a HTML email
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit
<html>
<head>
<title>This is a HTML email</title>
</head>
<body>
<p>$2</p>
</body>
</html>
'''
'MIME email':
prefix: 'eml-mime'
body: '''
To: "<NAME>" <<EMAIL>>
From: "<NAME>." <<EMAIL>>
Subject: This is a MultiPart email
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="random_multipart_separator";
charset=UTF-8
--random_multipart_separator
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit
Hi,
$2
--random_multipart_separator
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit
<html>
<head></head>
<body>
<strong>Hi,</strong>
<p>$2</p>
</body>
</html>
--random_multipart_separator--
'''
| true | '.text.eml':
'Plain-Text email':
prefix: 'eml-text'
body: '''
To: "PI:NAME:<NAME>END_PI" <PI:EMAIL:<EMAIL>END_PI>
From: "PI:NAME:<NAME>END_PI." <PI:EMAIL:<EMAIL>END_PI>
Subject: This is a PlainText email
$2
'''
'HTML email':
prefix: 'eml-html'
body: '''
To: "PI:NAME:<NAME>END_PI" <PI:EMAIL:<EMAIL>END_PI>
From: "PI:NAME:<NAME>END_PI." <PI:EMAIL:<EMAIL>END_PI>
Subject: This is a HTML email
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit
<html>
<head>
<title>This is a HTML email</title>
</head>
<body>
<p>$2</p>
</body>
</html>
'''
'MIME email':
prefix: 'eml-mime'
body: '''
To: "PI:NAME:<NAME>END_PI" <PI:EMAIL:<EMAIL>END_PI>
From: "PI:NAME:<NAME>END_PI." <PI:EMAIL:<EMAIL>END_PI>
Subject: This is a MultiPart email
Mime-Version: 1.0
Content-Type: multipart/alternative;
boundary="random_multipart_separator";
charset=UTF-8
--random_multipart_separator
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit
Hi,
$2
--random_multipart_separator
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 7bit
<html>
<head></head>
<body>
<strong>Hi,</strong>
<p>$2</p>
</body>
</html>
--random_multipart_separator--
'''
|
[
{
"context": " username : @.req.body.username,\n password : @.req.",
"end": 1942,
"score": 0.750636637210846,
"start": 1934,
"tag": "USERNAME",
"value": "username"
},
{
"context": "sername,\n password ... | src/controllers/User-Sign-Up-Controller.coffee | TeamMentor/TM_Site | 0 | signUp_fail = 'guest/sign-up-Fail.jade'
signUpPage_Unavailable = 'guest/sign-up-cant-connect.jade'
signUp_Ok = 'guest/sign-up-OK.html'
login_page = '/browser-detect-login'
errorMessage = "TEAM Mentor is unavailable, please contact us at "
request = null
Config = null
Analytics_Service = null
Hubspot_Service = null
Jade_Service = null
Login_Controller = null
request = null
request = null
class User_Sign_Up_Controller
dependencies: ->
request = require('request')
Login_Controller = require('../controllers/Login-Controller')
Analytics_Service = require('../services/Analytics-Service')
Hubspot_Service = require('../services/Hubspot-Service')
Jade_Service = require('../services/Jade-Service')
constructor: (req, res, options)->
@.dependencies()
@.config = require '../config'
@.options = options || {}
@.req = req || {}
@.res = res || {}
@.webServices = @.options.webServices ||"#{global.config?.tm_design?.tm_35_Server}#{global.config?.tm_design?.webServices}"
@.login = new Login_Controller(req,res)
@.analyticsService = new Analytics_Service(@.req, @.res)
@.hubspotService = new Hubspot_Service(@.req,@.res)
@.jade_Service = new Jade_Service()
@.redirectToLoginPage = @.config?.options?.tm_design?.redirectToLoginPage
json_Mode: ()=>
@.render_Page = (page, data)=>
data.page = page
@.res.json data
@.res.redirect = (page)=>
data =
page : page
viewModel: {}
result : 'OK'
@.res.json data
@
userSignUp: ()=>
userViewModel =
{
username : @.req.body.username,
password : @.req.body.password,
confirmpassword : @.req.body['confirm-password']
email : @.req.body.email
firstname : @.req.body.firstname,
lastname : @.req.body.lastname,
company : @.req.body.company,
title : @.req.body.title,
country : @.req.body.country,
state : @.req.body.state
errorMessage :''
}
newUser =
{
username : @.req.body.username,
password : @.req.body.password,
email : @.req.body.email,
firstname : @.req.body.firstname,
lastname : @.req.body.lastname,
company : @.req.body.company,
title : @.req.body.title,
country : @.req.body.country,
state : @.req.body.state
}
if(@.req.body.username is undefined or @.req.body.username =='')
userViewModel.errorMessage = 'Username is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.password is undefined or @.req.body.password =='')
userViewModel.errorMessage = 'Password is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body['confirm-password'] is undefined or @.req.body['confirm-password'] =='')
userViewModel.errorMessage = 'Confirm password is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if (@.req.body.password != @.req.body['confirm-password'])
userViewModel.errorMessage = 'Passwords don\'t match'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.email is undefined or @.req.body.email =='')
userViewModel.errorMessage = 'Email is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.firstname is undefined or @.req.body.firstname =='')
userViewModel.errorMessage = 'First Name is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.lastname is undefined or @.req.body.lastname =='')
userViewModel.errorMessage = 'Last Name is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.country is undefined or @.req.body.country =='')
userViewModel.errorMessage = 'Country is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
options = {
method: 'post',
body: {newUser: newUser},
json: true,
url: @.webServices + '/CreateUser_Response'
};
request options, (error, response, body)=>
if (error and error.code is "ENOTFOUND")
#[QA] ADD ISSUE: Refactor this to show TM 500 error message
logger?.info ('Could not connect with TM 3.5 server')
userViewModel.errorMessage =errorMessage
return @.render_Page signUpPage_Unavailable, {viewModel:userViewModel}
if (error or response.body is null or response.statusCode isnt 200)
logger?.info ('Bad response received from TM 3.5 server')
userViewModel.errorMessage =errorMessage
return @.render_Page signUpPage_Unavailable, {viewModel:userViewModel}
signUpResponse = response.body?.d
if (not signUpResponse) or (not signUpResponse.Validation_Results)
logger?.info ('Bad data received from TM 3.5 server')
return @.render_Page signUpPage_Unavailable, {viewModel: errorMessage : 'An error occurred' }
message = ''
if (signUpResponse.Signup_Status is 0)
@.analyticsService.track('Signup','User Account',"Signup Success #{@.req.body.username}")
@.hubspotService.submitHubspotForm()
# If redirectToLoginPage config setting is set to true, then redirecting to login upon successful signup
# otherwise redirect to index
if (@.redirectToLoginPage)
return @.res.redirect login_page
else
return @.login.loginUser()
if (signUpResponse.Validation_Results.empty())
message = signUpResponse.Simple_Error_Message || 'An error occurred'
else
message = signUpResponse.Validation_Results.first().Message
userViewModel.errorMessage = message
@.analyticsService.track('Signup','User Account',"Signup Failed #{@.req.body.username}")
@.render_Page signUp_fail, {viewModel:userViewModel}
render_Page: (jade_Page,params)=>
@.res.send @.jade_Service.render_Jade_File jade_Page, params
module.exports = User_Sign_Up_Controller | 114940 | signUp_fail = 'guest/sign-up-Fail.jade'
signUpPage_Unavailable = 'guest/sign-up-cant-connect.jade'
signUp_Ok = 'guest/sign-up-OK.html'
login_page = '/browser-detect-login'
errorMessage = "TEAM Mentor is unavailable, please contact us at "
request = null
Config = null
Analytics_Service = null
Hubspot_Service = null
Jade_Service = null
Login_Controller = null
request = null
request = null
class User_Sign_Up_Controller
dependencies: ->
request = require('request')
Login_Controller = require('../controllers/Login-Controller')
Analytics_Service = require('../services/Analytics-Service')
Hubspot_Service = require('../services/Hubspot-Service')
Jade_Service = require('../services/Jade-Service')
constructor: (req, res, options)->
@.dependencies()
@.config = require '../config'
@.options = options || {}
@.req = req || {}
@.res = res || {}
@.webServices = @.options.webServices ||"#{global.config?.tm_design?.tm_35_Server}#{global.config?.tm_design?.webServices}"
@.login = new Login_Controller(req,res)
@.analyticsService = new Analytics_Service(@.req, @.res)
@.hubspotService = new Hubspot_Service(@.req,@.res)
@.jade_Service = new Jade_Service()
@.redirectToLoginPage = @.config?.options?.tm_design?.redirectToLoginPage
json_Mode: ()=>
@.render_Page = (page, data)=>
data.page = page
@.res.json data
@.res.redirect = (page)=>
data =
page : page
viewModel: {}
result : 'OK'
@.res.json data
@
userSignUp: ()=>
userViewModel =
{
username : @.req.body.username,
password : <PASSWORD>,
confirmpassword : @.req.body['confirm-password']
email : @.req.body.email
firstname : @.req.body.firstname,
lastname : @.req.body.lastname,
company : @.req.body.company,
title : @.req.body.title,
country : @.req.body.country,
state : @.req.body.state
errorMessage :''
}
newUser =
{
username : @.req.body.username,
password : <PASSWORD>,
email : @.req.body.email,
firstname : @.req.body.firstname,
lastname : @.req.body.lastname,
company : @.req.body.company,
title : @.req.body.title,
country : @.req.body.country,
state : @.req.body.state
}
if(@.req.body.username is undefined or @.req.body.username =='')
userViewModel.errorMessage = 'Username is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.password is undefined or @.req.body.password =='')
userViewModel.errorMessage = 'Password is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body['confirm-password'] is undefined or @.req.body['confirm-password'] =='')
userViewModel.errorMessage = 'Confirm password is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if (@.req.body.password != @.req.body['confirm-password'])
userViewModel.errorMessage = 'Passwords don\'t match'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.email is undefined or @.req.body.email =='')
userViewModel.errorMessage = 'Email is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.firstname is undefined or @.req.body.firstname =='')
userViewModel.errorMessage = 'First Name is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.lastname is undefined or @.req.body.lastname =='')
userViewModel.errorMessage = 'Last Name is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.country is undefined or @.req.body.country =='')
userViewModel.errorMessage = 'Country is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
options = {
method: 'post',
body: {newUser: newUser},
json: true,
url: @.webServices + '/CreateUser_Response'
};
request options, (error, response, body)=>
if (error and error.code is "ENOTFOUND")
#[QA] ADD ISSUE: Refactor this to show TM 500 error message
logger?.info ('Could not connect with TM 3.5 server')
userViewModel.errorMessage =errorMessage
return @.render_Page signUpPage_Unavailable, {viewModel:userViewModel}
if (error or response.body is null or response.statusCode isnt 200)
logger?.info ('Bad response received from TM 3.5 server')
userViewModel.errorMessage =errorMessage
return @.render_Page signUpPage_Unavailable, {viewModel:userViewModel}
signUpResponse = response.body?.d
if (not signUpResponse) or (not signUpResponse.Validation_Results)
logger?.info ('Bad data received from TM 3.5 server')
return @.render_Page signUpPage_Unavailable, {viewModel: errorMessage : 'An error occurred' }
message = ''
if (signUpResponse.Signup_Status is 0)
@.analyticsService.track('Signup','User Account',"Signup Success #{@.req.body.username}")
@.hubspotService.submitHubspotForm()
# If redirectToLoginPage config setting is set to true, then redirecting to login upon successful signup
# otherwise redirect to index
if (@.redirectToLoginPage)
return @.res.redirect login_page
else
return @.login.loginUser()
if (signUpResponse.Validation_Results.empty())
message = signUpResponse.Simple_Error_Message || 'An error occurred'
else
message = signUpResponse.Validation_Results.first().Message
userViewModel.errorMessage = message
@.analyticsService.track('Signup','User Account',"Signup Failed #{@.req.body.username}")
@.render_Page signUp_fail, {viewModel:userViewModel}
render_Page: (jade_Page,params)=>
@.res.send @.jade_Service.render_Jade_File jade_Page, params
module.exports = User_Sign_Up_Controller | true | signUp_fail = 'guest/sign-up-Fail.jade'
signUpPage_Unavailable = 'guest/sign-up-cant-connect.jade'
signUp_Ok = 'guest/sign-up-OK.html'
login_page = '/browser-detect-login'
errorMessage = "TEAM Mentor is unavailable, please contact us at "
request = null
Config = null
Analytics_Service = null
Hubspot_Service = null
Jade_Service = null
Login_Controller = null
request = null
request = null
class User_Sign_Up_Controller
dependencies: ->
request = require('request')
Login_Controller = require('../controllers/Login-Controller')
Analytics_Service = require('../services/Analytics-Service')
Hubspot_Service = require('../services/Hubspot-Service')
Jade_Service = require('../services/Jade-Service')
constructor: (req, res, options)->
@.dependencies()
@.config = require '../config'
@.options = options || {}
@.req = req || {}
@.res = res || {}
@.webServices = @.options.webServices ||"#{global.config?.tm_design?.tm_35_Server}#{global.config?.tm_design?.webServices}"
@.login = new Login_Controller(req,res)
@.analyticsService = new Analytics_Service(@.req, @.res)
@.hubspotService = new Hubspot_Service(@.req,@.res)
@.jade_Service = new Jade_Service()
@.redirectToLoginPage = @.config?.options?.tm_design?.redirectToLoginPage
json_Mode: ()=>
@.render_Page = (page, data)=>
data.page = page
@.res.json data
@.res.redirect = (page)=>
data =
page : page
viewModel: {}
result : 'OK'
@.res.json data
@
userSignUp: ()=>
userViewModel =
{
username : @.req.body.username,
password : PI:PASSWORD:<PASSWORD>END_PI,
confirmpassword : @.req.body['confirm-password']
email : @.req.body.email
firstname : @.req.body.firstname,
lastname : @.req.body.lastname,
company : @.req.body.company,
title : @.req.body.title,
country : @.req.body.country,
state : @.req.body.state
errorMessage :''
}
newUser =
{
username : @.req.body.username,
password : PI:PASSWORD:<PASSWORD>END_PI,
email : @.req.body.email,
firstname : @.req.body.firstname,
lastname : @.req.body.lastname,
company : @.req.body.company,
title : @.req.body.title,
country : @.req.body.country,
state : @.req.body.state
}
if(@.req.body.username is undefined or @.req.body.username =='')
userViewModel.errorMessage = 'Username is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.password is undefined or @.req.body.password =='')
userViewModel.errorMessage = 'Password is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body['confirm-password'] is undefined or @.req.body['confirm-password'] =='')
userViewModel.errorMessage = 'Confirm password is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if (@.req.body.password != @.req.body['confirm-password'])
userViewModel.errorMessage = 'Passwords don\'t match'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.email is undefined or @.req.body.email =='')
userViewModel.errorMessage = 'Email is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.firstname is undefined or @.req.body.firstname =='')
userViewModel.errorMessage = 'First Name is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.lastname is undefined or @.req.body.lastname =='')
userViewModel.errorMessage = 'Last Name is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
if(@.req.body.country is undefined or @.req.body.country =='')
userViewModel.errorMessage = 'Country is a required field.'
return @.render_Page signUp_fail,viewModel: userViewModel
options = {
method: 'post',
body: {newUser: newUser},
json: true,
url: @.webServices + '/CreateUser_Response'
};
request options, (error, response, body)=>
if (error and error.code is "ENOTFOUND")
#[QA] ADD ISSUE: Refactor this to show TM 500 error message
logger?.info ('Could not connect with TM 3.5 server')
userViewModel.errorMessage =errorMessage
return @.render_Page signUpPage_Unavailable, {viewModel:userViewModel}
if (error or response.body is null or response.statusCode isnt 200)
logger?.info ('Bad response received from TM 3.5 server')
userViewModel.errorMessage =errorMessage
return @.render_Page signUpPage_Unavailable, {viewModel:userViewModel}
signUpResponse = response.body?.d
if (not signUpResponse) or (not signUpResponse.Validation_Results)
logger?.info ('Bad data received from TM 3.5 server')
return @.render_Page signUpPage_Unavailable, {viewModel: errorMessage : 'An error occurred' }
message = ''
if (signUpResponse.Signup_Status is 0)
@.analyticsService.track('Signup','User Account',"Signup Success #{@.req.body.username}")
@.hubspotService.submitHubspotForm()
# If redirectToLoginPage config setting is set to true, then redirecting to login upon successful signup
# otherwise redirect to index
if (@.redirectToLoginPage)
return @.res.redirect login_page
else
return @.login.loginUser()
if (signUpResponse.Validation_Results.empty())
message = signUpResponse.Simple_Error_Message || 'An error occurred'
else
message = signUpResponse.Validation_Results.first().Message
userViewModel.errorMessage = message
@.analyticsService.track('Signup','User Account',"Signup Failed #{@.req.body.username}")
@.render_Page signUp_fail, {viewModel:userViewModel}
render_Page: (jade_Page,params)=>
@.res.send @.jade_Service.render_Jade_File jade_Page, params
module.exports = User_Sign_Up_Controller |
[
{
"context": "n 5+ Confirm Dialog Modal\n# version 0.3\n# (c) 2014 joe johnston [joe@simple10.com]\n# released under the MIT licen",
"end": 119,
"score": 0.9998485445976257,
"start": 107,
"tag": "NAME",
"value": "joe johnston"
},
{
"context": "alog Modal\n# version 0.3\n# (c) 2014 jo... | vendor/assets/javascripts/rails_confirm_dialog.js.coffee | gablarsen/playinpeel | 3 | #
# Rails 3+ with Twitter Bootstrap 2+ or Zurb Foundation 5+ Confirm Dialog Modal
# version 0.3
# (c) 2014 joe johnston [joe@simple10.com]
# released under the MIT license
#
# Dependencies:
# jQuery
#
# Overview:
# Override $.rails.allowAction to intercept clicked elements with data-confirm. If message is an object, use
# jQuery.tmpl to populate and open a jQuery UI dialog. If message is a string, open a genric jQuery UI dialog.
#
# Example with Haml + Bootstrap 3:
# = link_to 'Delete Account', destroy_user_path(current_user), data: { confirm: 'Are you sure?', confirm_modal: '#delete-user-modal' }, method: :delete
# #delete-user-modal.modal.fade{tabindex: -1, role: 'dialog', 'aria-labelledby' => 'delete-user-modal-title', 'aria-hidden' => true}
# .modal-dialog
# .modal-content
# .modal-header
# %button.close{data: {dismiss: 'modal'}, 'aria-hidden' => true} ×
# %h4#delete-user-modal-title Are you sure?
# .modal-body
# %span.label.label-danger Warning
# This cannot be undone.
# .modal-footer
# %button.btn.btn-danger{data: {confirm: 'true', dismiss: 'modal'} Yes, delete my account
# %button.btn.btn-default{data: {dismiss: 'modal'}} Cancel
Confirm =
initRailsHook: ->
$.rails.allowAction = (elem) =>
@allowAction(elem)
allowAction: (elem) ->
modal = elem.data('confirm-modal')
return true unless modal
$modal = $(modal)
if $modal && $.rails.fire(elem, 'confirm')
@showModal($modal, elem)
return false
confirmed: (elem) ->
if $.rails.fire(elem, 'confirm:complete', [true])
$.rails.allowAction = -> true
elem.trigger('click')
$.rails.allowAction = @allowAction
showModal: ($modal, elem) ->
if $modal.hasClass 'reveal-modal'
# Foundation
$modal.foundation 'reveal', 'open'
$modal.find('[data-dismiss]').on('click', => $modal.foundation 'reveal', 'close')
else
# Bootstrap
$modal.modal()
$modal.find('[data-confirm]').on('click', => @confirmed(elem))
$ -> Confirm.initRailsHook()
| 146984 | #
# Rails 3+ with Twitter Bootstrap 2+ or Zurb Foundation 5+ Confirm Dialog Modal
# version 0.3
# (c) 2014 <NAME> [<EMAIL>]
# released under the MIT license
#
# Dependencies:
# jQuery
#
# Overview:
# Override $.rails.allowAction to intercept clicked elements with data-confirm. If message is an object, use
# jQuery.tmpl to populate and open a jQuery UI dialog. If message is a string, open a genric jQuery UI dialog.
#
# Example with Haml + Bootstrap 3:
# = link_to 'Delete Account', destroy_user_path(current_user), data: { confirm: 'Are you sure?', confirm_modal: '#delete-user-modal' }, method: :delete
# #delete-user-modal.modal.fade{tabindex: -1, role: 'dialog', 'aria-labelledby' => 'delete-user-modal-title', 'aria-hidden' => true}
# .modal-dialog
# .modal-content
# .modal-header
# %button.close{data: {dismiss: 'modal'}, 'aria-hidden' => true} ×
# %h4#delete-user-modal-title Are you sure?
# .modal-body
# %span.label.label-danger Warning
# This cannot be undone.
# .modal-footer
# %button.btn.btn-danger{data: {confirm: 'true', dismiss: 'modal'} Yes, delete my account
# %button.btn.btn-default{data: {dismiss: 'modal'}} Cancel
Confirm =
initRailsHook: ->
$.rails.allowAction = (elem) =>
@allowAction(elem)
allowAction: (elem) ->
modal = elem.data('confirm-modal')
return true unless modal
$modal = $(modal)
if $modal && $.rails.fire(elem, 'confirm')
@showModal($modal, elem)
return false
confirmed: (elem) ->
if $.rails.fire(elem, 'confirm:complete', [true])
$.rails.allowAction = -> true
elem.trigger('click')
$.rails.allowAction = @allowAction
showModal: ($modal, elem) ->
if $modal.hasClass 'reveal-modal'
# Foundation
$modal.foundation 'reveal', 'open'
$modal.find('[data-dismiss]').on('click', => $modal.foundation 'reveal', 'close')
else
# Bootstrap
$modal.modal()
$modal.find('[data-confirm]').on('click', => @confirmed(elem))
$ -> Confirm.initRailsHook()
| true | #
# Rails 3+ with Twitter Bootstrap 2+ or Zurb Foundation 5+ Confirm Dialog Modal
# version 0.3
# (c) 2014 PI:NAME:<NAME>END_PI [PI:EMAIL:<EMAIL>END_PI]
# released under the MIT license
#
# Dependencies:
# jQuery
#
# Overview:
# Override $.rails.allowAction to intercept clicked elements with data-confirm. If message is an object, use
# jQuery.tmpl to populate and open a jQuery UI dialog. If message is a string, open a genric jQuery UI dialog.
#
# Example with Haml + Bootstrap 3:
# = link_to 'Delete Account', destroy_user_path(current_user), data: { confirm: 'Are you sure?', confirm_modal: '#delete-user-modal' }, method: :delete
# #delete-user-modal.modal.fade{tabindex: -1, role: 'dialog', 'aria-labelledby' => 'delete-user-modal-title', 'aria-hidden' => true}
# .modal-dialog
# .modal-content
# .modal-header
# %button.close{data: {dismiss: 'modal'}, 'aria-hidden' => true} ×
# %h4#delete-user-modal-title Are you sure?
# .modal-body
# %span.label.label-danger Warning
# This cannot be undone.
# .modal-footer
# %button.btn.btn-danger{data: {confirm: 'true', dismiss: 'modal'} Yes, delete my account
# %button.btn.btn-default{data: {dismiss: 'modal'}} Cancel
Confirm =
initRailsHook: ->
$.rails.allowAction = (elem) =>
@allowAction(elem)
allowAction: (elem) ->
modal = elem.data('confirm-modal')
return true unless modal
$modal = $(modal)
if $modal && $.rails.fire(elem, 'confirm')
@showModal($modal, elem)
return false
confirmed: (elem) ->
if $.rails.fire(elem, 'confirm:complete', [true])
$.rails.allowAction = -> true
elem.trigger('click')
$.rails.allowAction = @allowAction
showModal: ($modal, elem) ->
if $modal.hasClass 'reveal-modal'
# Foundation
$modal.foundation 'reveal', 'open'
$modal.find('[data-dismiss]').on('click', => $modal.foundation 'reveal', 'close')
else
# Bootstrap
$modal.modal()
$modal.find('[data-confirm]').on('click', => @confirmed(elem))
$ -> Confirm.initRailsHook()
|
[
{
"context": ": 0xd00d\n uuid: 'gateblu-uuid'\n token: 'gateblu-token'\n\n @deviceList =\n getList: sinon.stub()\n\n",
"end": 293,
"score": 0.7049446105957031,
"start": 280,
"tag": "PASSWORD",
"value": "gateblu-token"
},
{
"context": "deviceList.getList.yields null,... | test/gateblu-service-spec.coffee | octoblu/node-gateblu-service | 0 | _ = require 'lodash'
shmock = require '@octoblu/shmock'
GatebluService = require '../src/gateblu-service'
describe 'GatebluService', ->
beforeEach ->
meshbluConfig =
server: 'localhost'
port: 0xd00d
uuid: 'gateblu-uuid'
token: 'gateblu-token'
@deviceList =
getList: sinon.stub()
@deviceWatcher =
onConfig: sinon.stub()
@deviceManager =
start: sinon.stub()
shutdown: sinon.stub()
@meshblu = shmock 0xd00d
@gatebluAuth = new Buffer('gateblu-uuid:gateblu-token').toString('base64')
@sut = new GatebluService {meshbluConfig}, {@deviceList, @deviceWatcher, @deviceManager}
afterEach (done) ->
@meshblu.close => done()
describe 'when it has devices and is started', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: true
}
@deviceList.getList.yields null, [
{uuid: 'superman', type: 'superhero', connector: 'clark-kent', token: 'some-token', gateblu: running: true}
{uuid: 'spiderman', type: 'superhero', connector: 'peter-parker', token: 'some-token', gateblu: running: true}
{uuid: 'ironman', type: 'superhero', connector: 'tony-stark', token: 'some-token', gateblu: running: false}
]
@deviceManager.start.yields null
@sut.start()
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
it 'should listen for changes', ->
expect(@deviceWatcher.onConfig).to.have.been.called
it 'should start superman', ->
superman =
uuid: 'superman'
type: 'superhero'
connector: 'clark-kent'
token: 'some-token'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith superman
it 'should start spiderman', ->
spiderman =
uuid: 'spiderman'
type: 'superhero'
connector: 'peter-parker'
token: 'some-token'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith spiderman
it 'should start ironman', ->
ironman =
uuid: 'ironman'
type: 'superhero'
connector: 'tony-stark'
token: 'some-token'
gateblu:
running: false
expect(@deviceManager.start).to.have.been.calledWith ironman
describe 'when it gets a config event', ->
describe 'when it is already running and is still running', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: true
}
@sut._onConfig null, uuid: 'gateblu-uuid'
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
it 'should start superman', ->
superman =
uuid: 'superman'
type: 'superhero'
connector: 'clark-kent'
token: 'some-token'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith superman
it 'should start spiderman', ->
spiderman =
uuid: 'spiderman'
type: 'superhero'
connector: 'peter-parker'
token: 'some-token'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith spiderman
it 'should start ironman', ->
ironman =
uuid: 'ironman'
type: 'superhero'
connector: 'tony-stark'
token: 'some-token'
gateblu:
running: false
expect(@deviceManager.start).to.have.been.calledWith ironman
describe 'when it has no devices and is started', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: true
}
@deviceList.getList.yields null, []
@sut.start()
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
describe 'when it stops running', ->
beforeEach (done) ->
@secondGetGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: false
}
@sut._onConfig null, uuid: 'gateblu-uuid'
_.delay done, 100
it 'should get the gateblu device', ->
@secondGetGatebluDevice.done()
it 'should call deviceManager.shutdown', ->
expect(@deviceManager.shutdown).to.have.been.called
describe 'when it has no devices and is not running', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: false
}
@deviceList.getList.yields null, []
@sut.start()
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
it 'should call deviceManager.shutdown', ->
expect(@deviceManager.shutdown).to.have.been.called
| 47179 | _ = require 'lodash'
shmock = require '@octoblu/shmock'
GatebluService = require '../src/gateblu-service'
describe 'GatebluService', ->
beforeEach ->
meshbluConfig =
server: 'localhost'
port: 0xd00d
uuid: 'gateblu-uuid'
token: '<PASSWORD>'
@deviceList =
getList: sinon.stub()
@deviceWatcher =
onConfig: sinon.stub()
@deviceManager =
start: sinon.stub()
shutdown: sinon.stub()
@meshblu = shmock 0xd00d
@gatebluAuth = new Buffer('gateblu-uuid:gateblu-token').toString('base64')
@sut = new GatebluService {meshbluConfig}, {@deviceList, @deviceWatcher, @deviceManager}
afterEach (done) ->
@meshblu.close => done()
describe 'when it has devices and is started', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: true
}
@deviceList.getList.yields null, [
{uuid: 'superman', type: 'superhero', connector: 'clark-kent', token: 'some-token', gateblu: running: true}
{uuid: 'spiderman', type: 'superhero', connector: 'peter-parker', token: '<KEY>', gateblu: running: true}
{uuid: 'ironman', type: 'superhero', connector: 'tony-stark', token: 'some-<KEY>', gateblu: running: false}
]
@deviceManager.start.yields null
@sut.start()
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
it 'should listen for changes', ->
expect(@deviceWatcher.onConfig).to.have.been.called
it 'should start superman', ->
superman =
uuid: '<NAME>'
type: 'superhero'
connector: 'clark-kent'
token: '<KEY>'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith superman
it 'should start spiderman', ->
spiderman =
uuid: '<NAME> <NAME>'
type: 'superhero'
connector: 'peter-parker'
token: '<KEY>'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith spiderman
it 'should start ironman', ->
ironman =
uuid: '<NAME>'
type: 'superhero'
connector: 'tony-stark'
token: '<KEY>'
gateblu:
running: false
expect(@deviceManager.start).to.have.been.calledWith ironman
describe 'when it gets a config event', ->
describe 'when it is already running and is still running', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: true
}
@sut._onConfig null, uuid: 'gateblu-uuid'
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
it 'should start superman', ->
superman =
uuid: '<NAME>'
type: 'superhero'
connector: 'clark-kent'
token: '<KEY>'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith superman
it 'should start spiderman', ->
spiderman =
uuid: '<NAME> <NAME>'
type: 'superhero'
connector: 'peter-parker'
token: '<KEY>'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith spiderman
it 'should start ironman', ->
ironman =
uuid: 'ironman'
type: 'superhero'
connector: 'tony-stark'
token: '<KEY>'
gateblu:
running: false
expect(@deviceManager.start).to.have.been.calledWith ironman
describe 'when it has no devices and is started', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: true
}
@deviceList.getList.yields null, []
@sut.start()
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
describe 'when it stops running', ->
beforeEach (done) ->
@secondGetGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: false
}
@sut._onConfig null, uuid: 'gateblu-uuid'
_.delay done, 100
it 'should get the gateblu device', ->
@secondGetGatebluDevice.done()
it 'should call deviceManager.shutdown', ->
expect(@deviceManager.shutdown).to.have.been.called
describe 'when it has no devices and is not running', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: false
}
@deviceList.getList.yields null, []
@sut.start()
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
it 'should call deviceManager.shutdown', ->
expect(@deviceManager.shutdown).to.have.been.called
| true | _ = require 'lodash'
shmock = require '@octoblu/shmock'
GatebluService = require '../src/gateblu-service'
describe 'GatebluService', ->
beforeEach ->
meshbluConfig =
server: 'localhost'
port: 0xd00d
uuid: 'gateblu-uuid'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
@deviceList =
getList: sinon.stub()
@deviceWatcher =
onConfig: sinon.stub()
@deviceManager =
start: sinon.stub()
shutdown: sinon.stub()
@meshblu = shmock 0xd00d
@gatebluAuth = new Buffer('gateblu-uuid:gateblu-token').toString('base64')
@sut = new GatebluService {meshbluConfig}, {@deviceList, @deviceWatcher, @deviceManager}
afterEach (done) ->
@meshblu.close => done()
describe 'when it has devices and is started', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: true
}
@deviceList.getList.yields null, [
{uuid: 'superman', type: 'superhero', connector: 'clark-kent', token: 'some-token', gateblu: running: true}
{uuid: 'spiderman', type: 'superhero', connector: 'peter-parker', token: 'PI:KEY:<KEY>END_PI', gateblu: running: true}
{uuid: 'ironman', type: 'superhero', connector: 'tony-stark', token: 'some-PI:KEY:<KEY>END_PI', gateblu: running: false}
]
@deviceManager.start.yields null
@sut.start()
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
it 'should listen for changes', ->
expect(@deviceWatcher.onConfig).to.have.been.called
it 'should start superman', ->
superman =
uuid: 'PI:NAME:<NAME>END_PI'
type: 'superhero'
connector: 'clark-kent'
token: 'PI:KEY:<KEY>END_PI'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith superman
it 'should start spiderman', ->
spiderman =
uuid: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
type: 'superhero'
connector: 'peter-parker'
token: 'PI:KEY:<KEY>END_PI'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith spiderman
it 'should start ironman', ->
ironman =
uuid: 'PI:NAME:<NAME>END_PI'
type: 'superhero'
connector: 'tony-stark'
token: 'PI:KEY:<KEY>END_PI'
gateblu:
running: false
expect(@deviceManager.start).to.have.been.calledWith ironman
describe 'when it gets a config event', ->
describe 'when it is already running and is still running', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: true
}
@sut._onConfig null, uuid: 'gateblu-uuid'
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
it 'should start superman', ->
superman =
uuid: 'PI:NAME:<NAME>END_PI'
type: 'superhero'
connector: 'clark-kent'
token: 'PI:KEY:<KEY>END_PI'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith superman
it 'should start spiderman', ->
spiderman =
uuid: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
type: 'superhero'
connector: 'peter-parker'
token: 'PI:KEY:<KEY>END_PI'
gateblu:
running: true
expect(@deviceManager.start).to.have.been.calledWith spiderman
it 'should start ironman', ->
ironman =
uuid: 'ironman'
type: 'superhero'
connector: 'tony-stark'
token: 'PI:PASSWORD:<KEY>END_PI'
gateblu:
running: false
expect(@deviceManager.start).to.have.been.calledWith ironman
describe 'when it has no devices and is started', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: true
}
@deviceList.getList.yields null, []
@sut.start()
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
describe 'when it stops running', ->
beforeEach (done) ->
@secondGetGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: false
}
@sut._onConfig null, uuid: 'gateblu-uuid'
_.delay done, 100
it 'should get the gateblu device', ->
@secondGetGatebluDevice.done()
it 'should call deviceManager.shutdown', ->
expect(@deviceManager.shutdown).to.have.been.called
describe 'when it has no devices and is not running', ->
beforeEach (done) ->
@getGatebluDevice = @meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{@gatebluAuth}"
.reply 200, {
uuid: 'gateblu-uuid'
gateblu:
running: false
}
@deviceList.getList.yields null, []
@sut.start()
_.delay done, 100
it 'should get the gateblu device', ->
@getGatebluDevice.done()
it 'should call deviceManager.shutdown', ->
expect(@deviceManager.shutdown).to.have.been.called
|
[
{
"context": "er, MarkerManager, uiGmapPromise) ->\n keys = ['coords', 'icon', 'options', 'fit']\n class MarkerChildModel extends ModelKey\n ",
"end": 448,
"score": 0.927708089351654,
"start": 414,
"tag": "KEY",
"value": "coords', 'icon', 'options', 'fit']"
},
{
"context": ... | public/bower_components/angular-google-maps/src/coffee/directives/api/models/child/marker-child-model.coffee | arslannaseem/notasoft | 0 | angular.module('uiGmapgoogle-maps.directives.api.models.child')
.factory 'uiGmapMarkerChildModel', [
'uiGmapModelKey', 'uiGmapGmapUtil',
'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction',
'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise',
(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) ->
keys = ['coords', 'icon', 'options', 'fit']
class MarkerChildModel extends ModelKey
@include GmapUtil
@include EventsHelper
@include MarkerOptions
destroy = (child) ->
if child?.gMarker?
child.removeEvents child.externalListeners
child.removeEvents child.internalListeners
if child?.gMarker
child.gMarkerManager.remove child.gMarker if child.removeFromManager
child.gMarker.setMap null
child.gMarker = null
constructor: (scope, @model, @keys, @gMap, @defaults, @doClick, @gMarkerManager, @doDrawSelf = true,
@trackModel = true, @needRedraw = false) ->
#where @model is a reference to model in the controller scope
#clonedModel is a copy for comparison
@clonedModel = _.clone @model,true
@deferred = uiGmapPromise.defer()
_.each @keys, (v, k) =>
@[k + 'Key'] = if _.isFunction @keys[k] then @keys[k]() else @keys[k]
@idKey = @idKeyKey or 'id'
@id = @model[@idKey] if @model[@idKey]?
super(scope)
@scope.getGMarker = =>
@gMarker
@firstTime = true
if @trackModel
@scope.model = @model
@scope.$watch 'model', (newValue, oldValue) =>
if (newValue != oldValue)
@handleModelChanges newValue, oldValue
, true
else
action = new PropertyAction (calledKey, newVal) =>
#being in a closure works , direct to setMyScope is not working (but should?)
if not @firstTime
@setMyScope calledKey, scope
, false
_.each @keys, (v, k) ->
scope.$watch k, action.sic, true
#hiding destroy functionality as it should only be called via scope.$destroy()
@scope.$on '$destroy', =>
destroy @
# avoid double creation, but this might be needed for <marker>
# @setMyScope 'all', @model, undefined, true
@createMarker @model
$log.info @
destroy: (removeFromManager = true)=>
@removeFromManager = removeFromManager
@scope.$destroy()
handleModelChanges: (newValue, oldValue) =>
changes = @getChanges newValue, oldValue, IMarker.keys
if not @firstTime
ctr = 0
len = _.keys(changes).length
_.each changes, (v, k) =>
ctr += 1
doDraw = len == ctr
@setMyScope k, newValue, oldValue, false, true, doDraw
@needRedraw = true
updateModel: (model) =>
@cloneModel = _.clone(model,true)
@setMyScope 'all', model, @model
renderGMarker: (doDraw = true, validCb) ->
#doDraw is to only update the marker on the map when it is really ready
coords = @getProp(@coordsKey, @model)
if coords?
if !@validateCoords coords
$log.debug 'MarkerChild does not have coords yet. They may be defined later.'
return
validCb() if validCb?
@gMarkerManager.add @gMarker if doDraw and @gMarker
else
@gMarkerManager.remove @gMarker if doDraw and @gMarker
setMyScope: (thingThatChanged, model, oldModel = undefined, isInit = false, doDraw = true) =>
if not model?
model = @model
else
@model = model
if !@gMarker
@setOptions @scope, doDraw
justCreated = true
switch thingThatChanged
when 'all'
_.each @keys, (v, k) =>
@setMyScope k, model, oldModel, isInit, doDraw
when 'icon'
@maybeSetScopeValue 'icon', model, oldModel, @iconKey, @evalModelHandle, isInit, @setIcon, doDraw
when 'coords'
@maybeSetScopeValue 'coords', model, oldModel, @coordsKey, @evalModelHandle, isInit, @setCoords, doDraw
when 'options'
@createMarker(model, oldModel, isInit, doDraw) if !justCreated
createMarker: (model, oldModel = undefined, isInit = false, doDraw = true)=>
@maybeSetScopeValue 'options', model, oldModel, @optionsKey, @evalModelHandle, isInit, @setOptions, doDraw
@firstTime = false
maybeSetScopeValue: (scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter = undefined,
doDraw = true) =>
gSetter(@scope, doDraw) if gSetter?
@gMarkerManager.draw() if @doDrawSelf and doDraw
isNotValid: (scope, doCheckGmarker = true) =>
hasNoGmarker = unless doCheckGmarker then false else @gMarker == undefined
hasIdenticalScopes = unless @trackModel then scope.$id != @scope.$id else false
hasIdenticalScopes or hasNoGmarker
setCoords: (scope, doDraw = true) =>
return if @isNotValid(scope) or !@gMarker?
@renderGMarker doDraw, =>
newModelVal = @getProp @coordsKey, @model
newGValue = @getCoords newModelVal
oldGValue = @gMarker.getPosition()
if oldGValue? and newGValue?
return if newGValue.lng() == oldGValue.lng() and newGValue.lat() == oldGValue.lat()
@gMarker.setPosition newGValue
@gMarker.setVisible @validateCoords newModelVal
setIcon: (scope, doDraw = true) =>
return if @isNotValid(scope) or !@gMarker?
@renderGMarker doDraw, =>
oldValue = @gMarker.getIcon()
newValue = @getProp 'icon', @model
return if oldValue == newValue
@gMarker.setIcon newValue
coords = @getProp 'coords', @model
@gMarker.setPosition @getCoords coords
@gMarker.setVisible @validateCoords coords
setOptions: (scope, doDraw = true) =>
return if @isNotValid scope, false
@renderGMarker doDraw, =>
coords = @getProp @coordsKey, @model
icon = @getProp @iconKey, @model
_options = @getProp @optionsKey, @model
@opts = @createOptions coords, icon, _options
#update existing options if it is the same type
if @gMarker?
@gMarker.setOptions @opts
unless @gMarker
if @isLabel @opts
@gMarker = new MarkerWithLabel @setLabelOptions @opts
else
@gMarker = new google.maps.Marker @opts
_.extend @gMarker, model: @model
#hook external event handlers for events
@removeEvents @externalListeners if @externalListeners
@removeEvents @internalListeners if @internalListeners
@externalListeners = @setEvents @gMarker, @scope, @model, ['dragend']
#must pass fake $evalAsync see events-helper
@internalListeners = @setEvents @gMarker, {events: @internalEvents(), $evalAsync: () ->}, @model
@gMarker.key = @id if @id?
if @gMarker and (@gMarker.getMap() or @gMarkerManager.type != MarkerManager.type)
@deferred.resolve @gMarker
else
return @deferred.reject 'gMarker is null' unless @gMarker
unless @gMarker?.getMap() and @gMarkerManager.type == MarkerManager.type
$log.debug 'gMarker has no map yet'
@deferred.resolve @gMarker
if @model[@fitKey]
@gMarkerManager.fit()
setLabelOptions: (opts) =>
opts.labelAnchor = @getLabelPositionPoint opts.labelAnchor
opts
internalEvents: =>
dragend: (marker, eventName, model, mousearg) =>
modelToSet = if @trackModel then @scope.model else @model
newCoords = @setCoordsFromEvent @modelOrKey(modelToSet, @coordsKey), @gMarker.getPosition()
modelToSet = @setVal model, @coordsKey, newCoords
#since we ignored dragend for scope above, if @scope.events has it then we should fire it
events = @scope.events
events.dragend(marker, eventName, modelToSet, mousearg) if events?.dragend?
@scope.$apply()
click: (marker, eventName, model, mousearg) =>
click = if _.isFunction(@clickKey) then @clickKey else @getProp @clickKey, @model
if @doClick and click?
@scope.$evalAsync click marker, eventName, @model, mousearg
MarkerChildModel
]
| 165122 | angular.module('uiGmapgoogle-maps.directives.api.models.child')
.factory 'uiGmapMarkerChildModel', [
'uiGmapModelKey', 'uiGmapGmapUtil',
'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction',
'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise',
(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) ->
keys = ['<KEY>
class MarkerChildModel extends ModelKey
@include GmapUtil
@include EventsHelper
@include MarkerOptions
destroy = (child) ->
if child?.gMarker?
child.removeEvents child.externalListeners
child.removeEvents child.internalListeners
if child?.gMarker
child.gMarkerManager.remove child.gMarker if child.removeFromManager
child.gMarker.setMap null
child.gMarker = null
constructor: (scope, @model, @keys, @gMap, @defaults, @doClick, @gMarkerManager, @doDrawSelf = true,
@trackModel = true, @needRedraw = false) ->
#where @model is a reference to model in the controller scope
#clonedModel is a copy for comparison
@clonedModel = _.clone @model,true
@deferred = uiGmapPromise.defer()
_.each @keys, (v, k) =>
@[k + 'Key'] = if _.isFunction @keys[k] then @keys[k]() else @keys[k]
@idKey = @idKeyKey or 'id'
@id = @model[@idKey] if @model[@idKey]?
super(scope)
@scope.getGMarker = =>
@gMarker
@firstTime = true
if @trackModel
@scope.model = @model
@scope.$watch 'model', (newValue, oldValue) =>
if (newValue != oldValue)
@handleModelChanges newValue, oldValue
, true
else
action = new PropertyAction (calledKey, newVal) =>
#being in a closure works , direct to setMyScope is not working (but should?)
if not @firstTime
@setMyScope calledKey, scope
, false
_.each @keys, (v, k) ->
scope.$watch k, action.sic, true
#hiding destroy functionality as it should only be called via scope.$destroy()
@scope.$on '$destroy', =>
destroy @
# avoid double creation, but this might be needed for <marker>
# @setMyScope 'all', @model, undefined, true
@createMarker @model
$log.info @
destroy: (removeFromManager = true)=>
@removeFromManager = removeFromManager
@scope.$destroy()
handleModelChanges: (newValue, oldValue) =>
changes = @getChanges newValue, oldValue, IMarker.keys
if not @firstTime
ctr = 0
len = _.keys(changes).length
_.each changes, (v, k) =>
ctr += 1
doDraw = len == ctr
@setMyScope k, newValue, oldValue, false, true, doDraw
@needRedraw = true
updateModel: (model) =>
@cloneModel = _.clone(model,true)
@setMyScope 'all', model, @model
renderGMarker: (doDraw = true, validCb) ->
#doDraw is to only update the marker on the map when it is really ready
coords = @getProp(@coordsKey, @model)
if coords?
if !@validateCoords coords
$log.debug 'MarkerChild does not have coords yet. They may be defined later.'
return
validCb() if validCb?
@gMarkerManager.add @gMarker if doDraw and @gMarker
else
@gMarkerManager.remove @gMarker if doDraw and @gMarker
setMyScope: (thingThatChanged, model, oldModel = undefined, isInit = false, doDraw = true) =>
if not model?
model = @model
else
@model = model
if !@gMarker
@setOptions @scope, doDraw
justCreated = true
switch thingThatChanged
when 'all'
_.each @keys, (v, k) =>
@setMyScope k, model, oldModel, isInit, doDraw
when 'icon'
@maybeSetScopeValue 'icon', model, oldModel, @iconKey, @evalModelHandle, isInit, @setIcon, doDraw
when 'coords'
@maybeSetScopeValue 'coords', model, oldModel, @coordsKey, @evalModelHandle, isInit, @setCoords, doDraw
when 'options'
@createMarker(model, oldModel, isInit, doDraw) if !justCreated
createMarker: (model, oldModel = undefined, isInit = false, doDraw = true)=>
@maybeSetScopeValue 'options', model, oldModel, @optionsKey, @evalModelHandle, isInit, @setOptions, doDraw
@firstTime = false
maybeSetScopeValue: (scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter = undefined,
doDraw = true) =>
gSetter(@scope, doDraw) if gSetter?
@gMarkerManager.draw() if @doDrawSelf and doDraw
isNotValid: (scope, doCheckGmarker = true) =>
hasNoGmarker = unless doCheckGmarker then false else @gMarker == undefined
hasIdenticalScopes = unless @trackModel then scope.$id != @scope.$id else false
hasIdenticalScopes or hasNoGmarker
setCoords: (scope, doDraw = true) =>
return if @isNotValid(scope) or !@gMarker?
@renderGMarker doDraw, =>
newModelVal = @getProp @coordsKey, @model
newGValue = @getCoords newModelVal
oldGValue = @gMarker.getPosition()
if oldGValue? and newGValue?
return if newGValue.lng() == oldGValue.lng() and newGValue.lat() == oldGValue.lat()
@gMarker.setPosition newGValue
@gMarker.setVisible @validateCoords newModelVal
setIcon: (scope, doDraw = true) =>
return if @isNotValid(scope) or !@gMarker?
@renderGMarker doDraw, =>
oldValue = @gMarker.getIcon()
newValue = @getProp 'icon', @model
return if oldValue == newValue
@gMarker.setIcon newValue
coords = @getProp 'coords', @model
@gMarker.setPosition @getCoords coords
@gMarker.setVisible @validateCoords coords
setOptions: (scope, doDraw = true) =>
return if @isNotValid scope, false
@renderGMarker doDraw, =>
coords = @getProp @coordsKey, @model
icon = @getProp @iconKey, @model
_options = @getProp @optionsKey, @model
@opts = @createOptions coords, icon, _options
#update existing options if it is the same type
if @gMarker?
@gMarker.setOptions @opts
unless @gMarker
if @isLabel @opts
@gMarker = new MarkerWithLabel @setLabelOptions @opts
else
@gMarker = new google.maps.Marker @opts
_.extend @gMarker, model: @model
#hook external event handlers for events
@removeEvents @externalListeners if @externalListeners
@removeEvents @internalListeners if @internalListeners
@externalListeners = @setEvents @gMarker, @scope, @model, ['dragend']
#must pass fake $evalAsync see events-helper
@internalListeners = @setEvents @gMarker, {events: @internalEvents(), $evalAsync: () ->}, @model
@gMarker.key = @<KEY> if @id?
if @gMarker and (@gMarker.getMap() or @gMarkerManager.type != MarkerManager.type)
@deferred.resolve @gMarker
else
return @deferred.reject 'gMarker is null' unless @gMarker
unless @gMarker?.getMap() and @gMarkerManager.type == MarkerManager.type
$log.debug 'gMarker has no map yet'
@deferred.resolve @gMarker
if @model[@fitKey]
@gMarkerManager.fit()
setLabelOptions: (opts) =>
opts.labelAnchor = @getLabelPositionPoint opts.labelAnchor
opts
internalEvents: =>
dragend: (marker, eventName, model, mousearg) =>
modelToSet = if @trackModel then @scope.model else @model
newCoords = @setCoordsFromEvent @modelOrKey(modelToSet, @coordsKey), @gMarker.getPosition()
modelToSet = @setVal model, @coordsKey, newCoords
#since we ignored dragend for scope above, if @scope.events has it then we should fire it
events = @scope.events
events.dragend(marker, eventName, modelToSet, mousearg) if events?.dragend?
@scope.$apply()
click: (marker, eventName, model, mousearg) =>
click = if _.isFunction(@clickKey) then @clickKey else @getProp @clickKey, @model
if @doClick and click?
@scope.$evalAsync click marker, eventName, @model, mousearg
MarkerChildModel
]
| true | angular.module('uiGmapgoogle-maps.directives.api.models.child')
.factory 'uiGmapMarkerChildModel', [
'uiGmapModelKey', 'uiGmapGmapUtil',
'uiGmapLogger', 'uiGmapEventsHelper', 'uiGmapPropertyAction',
'uiGmapMarkerOptions', 'uiGmapIMarker', 'uiGmapMarkerManager', 'uiGmapPromise',
(ModelKey, GmapUtil, $log, EventsHelper, PropertyAction, MarkerOptions, IMarker, MarkerManager, uiGmapPromise) ->
keys = ['PI:KEY:<KEY>END_PI
class MarkerChildModel extends ModelKey
@include GmapUtil
@include EventsHelper
@include MarkerOptions
destroy = (child) ->
if child?.gMarker?
child.removeEvents child.externalListeners
child.removeEvents child.internalListeners
if child?.gMarker
child.gMarkerManager.remove child.gMarker if child.removeFromManager
child.gMarker.setMap null
child.gMarker = null
constructor: (scope, @model, @keys, @gMap, @defaults, @doClick, @gMarkerManager, @doDrawSelf = true,
@trackModel = true, @needRedraw = false) ->
#where @model is a reference to model in the controller scope
#clonedModel is a copy for comparison
@clonedModel = _.clone @model,true
@deferred = uiGmapPromise.defer()
_.each @keys, (v, k) =>
@[k + 'Key'] = if _.isFunction @keys[k] then @keys[k]() else @keys[k]
@idKey = @idKeyKey or 'id'
@id = @model[@idKey] if @model[@idKey]?
super(scope)
@scope.getGMarker = =>
@gMarker
@firstTime = true
if @trackModel
@scope.model = @model
@scope.$watch 'model', (newValue, oldValue) =>
if (newValue != oldValue)
@handleModelChanges newValue, oldValue
, true
else
action = new PropertyAction (calledKey, newVal) =>
#being in a closure works , direct to setMyScope is not working (but should?)
if not @firstTime
@setMyScope calledKey, scope
, false
_.each @keys, (v, k) ->
scope.$watch k, action.sic, true
#hiding destroy functionality as it should only be called via scope.$destroy()
@scope.$on '$destroy', =>
destroy @
# avoid double creation, but this might be needed for <marker>
# @setMyScope 'all', @model, undefined, true
@createMarker @model
$log.info @
destroy: (removeFromManager = true)=>
@removeFromManager = removeFromManager
@scope.$destroy()
handleModelChanges: (newValue, oldValue) =>
changes = @getChanges newValue, oldValue, IMarker.keys
if not @firstTime
ctr = 0
len = _.keys(changes).length
_.each changes, (v, k) =>
ctr += 1
doDraw = len == ctr
@setMyScope k, newValue, oldValue, false, true, doDraw
@needRedraw = true
updateModel: (model) =>
@cloneModel = _.clone(model,true)
@setMyScope 'all', model, @model
renderGMarker: (doDraw = true, validCb) ->
#doDraw is to only update the marker on the map when it is really ready
coords = @getProp(@coordsKey, @model)
if coords?
if !@validateCoords coords
$log.debug 'MarkerChild does not have coords yet. They may be defined later.'
return
validCb() if validCb?
@gMarkerManager.add @gMarker if doDraw and @gMarker
else
@gMarkerManager.remove @gMarker if doDraw and @gMarker
setMyScope: (thingThatChanged, model, oldModel = undefined, isInit = false, doDraw = true) =>
if not model?
model = @model
else
@model = model
if !@gMarker
@setOptions @scope, doDraw
justCreated = true
switch thingThatChanged
when 'all'
_.each @keys, (v, k) =>
@setMyScope k, model, oldModel, isInit, doDraw
when 'icon'
@maybeSetScopeValue 'icon', model, oldModel, @iconKey, @evalModelHandle, isInit, @setIcon, doDraw
when 'coords'
@maybeSetScopeValue 'coords', model, oldModel, @coordsKey, @evalModelHandle, isInit, @setCoords, doDraw
when 'options'
@createMarker(model, oldModel, isInit, doDraw) if !justCreated
createMarker: (model, oldModel = undefined, isInit = false, doDraw = true)=>
@maybeSetScopeValue 'options', model, oldModel, @optionsKey, @evalModelHandle, isInit, @setOptions, doDraw
@firstTime = false
maybeSetScopeValue: (scopePropName, model, oldModel, modelKey, evaluate, isInit, gSetter = undefined,
doDraw = true) =>
gSetter(@scope, doDraw) if gSetter?
@gMarkerManager.draw() if @doDrawSelf and doDraw
isNotValid: (scope, doCheckGmarker = true) =>
hasNoGmarker = unless doCheckGmarker then false else @gMarker == undefined
hasIdenticalScopes = unless @trackModel then scope.$id != @scope.$id else false
hasIdenticalScopes or hasNoGmarker
setCoords: (scope, doDraw = true) =>
return if @isNotValid(scope) or !@gMarker?
@renderGMarker doDraw, =>
newModelVal = @getProp @coordsKey, @model
newGValue = @getCoords newModelVal
oldGValue = @gMarker.getPosition()
if oldGValue? and newGValue?
return if newGValue.lng() == oldGValue.lng() and newGValue.lat() == oldGValue.lat()
@gMarker.setPosition newGValue
@gMarker.setVisible @validateCoords newModelVal
setIcon: (scope, doDraw = true) =>
return if @isNotValid(scope) or !@gMarker?
@renderGMarker doDraw, =>
oldValue = @gMarker.getIcon()
newValue = @getProp 'icon', @model
return if oldValue == newValue
@gMarker.setIcon newValue
coords = @getProp 'coords', @model
@gMarker.setPosition @getCoords coords
@gMarker.setVisible @validateCoords coords
setOptions: (scope, doDraw = true) =>
return if @isNotValid scope, false
@renderGMarker doDraw, =>
coords = @getProp @coordsKey, @model
icon = @getProp @iconKey, @model
_options = @getProp @optionsKey, @model
@opts = @createOptions coords, icon, _options
#update existing options if it is the same type
if @gMarker?
@gMarker.setOptions @opts
unless @gMarker
if @isLabel @opts
@gMarker = new MarkerWithLabel @setLabelOptions @opts
else
@gMarker = new google.maps.Marker @opts
_.extend @gMarker, model: @model
#hook external event handlers for events
@removeEvents @externalListeners if @externalListeners
@removeEvents @internalListeners if @internalListeners
@externalListeners = @setEvents @gMarker, @scope, @model, ['dragend']
#must pass fake $evalAsync see events-helper
@internalListeners = @setEvents @gMarker, {events: @internalEvents(), $evalAsync: () ->}, @model
@gMarker.key = @PI:KEY:<KEY>END_PI if @id?
if @gMarker and (@gMarker.getMap() or @gMarkerManager.type != MarkerManager.type)
@deferred.resolve @gMarker
else
return @deferred.reject 'gMarker is null' unless @gMarker
unless @gMarker?.getMap() and @gMarkerManager.type == MarkerManager.type
$log.debug 'gMarker has no map yet'
@deferred.resolve @gMarker
if @model[@fitKey]
@gMarkerManager.fit()
setLabelOptions: (opts) =>
opts.labelAnchor = @getLabelPositionPoint opts.labelAnchor
opts
internalEvents: =>
dragend: (marker, eventName, model, mousearg) =>
modelToSet = if @trackModel then @scope.model else @model
newCoords = @setCoordsFromEvent @modelOrKey(modelToSet, @coordsKey), @gMarker.getPosition()
modelToSet = @setVal model, @coordsKey, newCoords
#since we ignored dragend for scope above, if @scope.events has it then we should fire it
events = @scope.events
events.dragend(marker, eventName, modelToSet, mousearg) if events?.dragend?
@scope.$apply()
click: (marker, eventName, model, mousearg) =>
click = if _.isFunction(@clickKey) then @clickKey else @getProp @clickKey, @model
if @doClick and click?
@scope.$evalAsync click marker, eventName, @model, mousearg
MarkerChildModel
]
|
[
{
"context": "plate({title: title, base_url: base_url, username: username, message: message})\n\t\topts = {\n\t\t\tfrom: 'support@",
"end": 2144,
"score": 0.5373497009277344,
"start": 2136,
"tag": "USERNAME",
"value": "username"
},
{
"context": "username, message: message})\n\t\topts... | server/mailer.coffee | willroberts/duelyst | 5 | fs = require 'fs'
os = require 'os'
path = require 'path'
nodemailer = require 'nodemailer'
hbs = require 'hbs'
handlebars = hbs.handlebars
config = require '../config/config.js'
# Pretty error printing, helps with stack traces
PrettyError = require 'pretty-error'
prettyError = new PrettyError()
prettyError.skipNodeFiles()
prettyError.withoutColors()
prettyError.skipPackage('bluebird')
env = config.get('env')
if env is 'development'
base_url = "http://localhost:#{config.get('port')}"
else if env is 'staging'
base_url = ""
else if env is 'production'
base_url = ""
class Email
constructor: () ->
@loadTemplates()
@transporter = nodemailer.createTransport
host: 'smtp.mandrillapp.com'
port: 587
auth:
user: ''
pass: ''
loadTemplates: () ->
try
@default_template = fs.readFileSync(__dirname + '/templates/email-default.hbs').toString()
@signup_template = fs.readFileSync(__dirname + '/templates/email-signup.hbs').toString()
@resend_template = fs.readFileSync(__dirname + '/templates/email-resend.hbs').toString()
@taken_template = fs.readFileSync(__dirname + '/templates/email-taken.hbs').toString()
@forgot_template = fs.readFileSync(__dirname + '/templates/email-forgot.hbs').toString()
@verify_template = fs.readFileSync(__dirname + '/templates/email-verify.hbs').toString()
@confirm_template = fs.readFileSync(__dirname + '/templates/email-confirm.hbs').toString()
@alert_template = fs.readFileSync(__dirname + '/templates/email-alert.hbs').toString()
@steam_alert_template = fs.readFileSync(__dirname + '/templates/email-steam-alert.hbs').toString()
@notify_template = fs.readFileSync(__dirname + '/templates/email-notify.hbs').toString()
@receipt_template = fs.readFileSync(__dirname + '/templates/email-receipt.hbs').toString()
@giftcrate_template = fs.readFileSync(__dirname + '/templates/email-giftcrate.hbs').toString()
catch e
throw new Error("Failed to load email templates.")
sendMail: (username, email, title, message, cb) ->
template = handlebars.compile(@default_template)
html = template({title: title, base_url: base_url, username: username, message: message})
opts = {
from: 'support@duelyst.com'
to: email
subject: "DUELYST - #{title}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendEmailVerificationLink: (username, email, token, cb) ->
template = handlebars.compile(@verify_template)
html = template({title: 'Verify Email', base_url: base_url, username: username, token: token})
opts = {
from: 'support@duelyst.com'
to: email
subject: "Verify your DUELYST account email"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendSignup: (username, email, token, cb) ->
template = handlebars.compile(@signup_template)
html = template({title: 'Welcome', base_url: base_url, username: username, token: token})
opts = {
from: 'support@duelyst.com'
to: email
subject: "Welcome to DUELYST"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendReceipt: (username, email, receiptNumber, boosterCount, cb) ->
template = handlebars.compile(@receipt_template)
html = template({title: 'Welcome', base_url: base_url, username: username, receipt_number: receiptNumber, booster_count:boosterCount})
opts = {
from: 'support@duelyst.com'
to: email
subject: "DUELYST Purchase Receipt"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
resendSignup: (username, email, token, cb) ->
template = handlebars.compile(@resend_template)
html = template({title: 'Confirm', base_url: base_url, username: username, token: token})
opts = {
from: 'support@duelyst.com'
to: email
subject: "Duelyst - Complete your registration"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendTakenEmail: (username, email, token, cb) ->
template = handlebars.compile(@taken_template)
html = template({title: 'Taken', username: username, token: token})
opts = {
from: 'support@duelyst.com'
to: email
subject: "Duelyst - Email already registered"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendForgotPassword: (username, email, token, cb) ->
template = handlebars.compile(@forgot_template)
html = template({title: 'Reset', base_url: base_url, username: username, token: token})
opts = {
from: 'support@duelyst.com'
to: email
subject: "Duelyst - Reset your password"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendPasswordConfirmation: (username, email, cb) ->
template = handlebars.compile(@confirm_template)
html = template({title: 'Reset', base_url: base_url, username: username})
opts = {
from: 'support@duelyst.com'
to: email
subject: "Duelyst - Password has been updated"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendNotification: (title, message, cb) ->
template = handlebars.compile(@notify_template)
html = template({title: title, message: message})
opts = {
from: "admin@duelyst.com"
to: "servers+#{env}@counterplay.co"
subject: "[#{env}] Duelyst - NOTIFICATION - #{title}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendTeamPurchaseNotification: (username, userId, email, chargeId, price, cb) ->
opts = {
from: "admin@counterplay.co"
to: "purchase-notifications@counterplay.co"
subject: "[#{env}] Duelyst - PURCHASE - #{username} spent #{price} - #{chargeId}"
html: "#{username} (email:#{email}) (id:#{userId}) spent #{price}. Charge ID #{chargeId}"
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendTeamPurchaseErrorNotification: (subject, message, cb) ->
opts = {
from: "admin@counterplay.co"
to: "purchase-error-notifications@counterplay.co"
subject: "[#{env}] Duelyst - NOTIFICATION - #{subject}"
html: message
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendErrorAlert: (server, error, cb) ->
template = handlebars.compile(@alert_template)
html = template({title: 'Server Error', base_url: base_url, server: JSON.stringify(server), error: error})
opts = {
from: "admin@duelyst.com"
to: "server-errors+#{env}@counterplay.co"
subject: "[#{env}] Duelyst - SERVER ALERT! #{server.hostname}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendCrashAlert: (server, error, cb) ->
prettyErrorInfo = prettyError.render(error)
template = handlebars.compile(@alert_template)
html = template({title: 'Server Crash', base_url: base_url, server: JSON.stringify(server), error: error, prettyErrorInfo: prettyErrorInfo})
opts = {
from: "admin@duelyst.com"
to: "server-alerts+#{env}@counterplay.co"
subject: "[#{env}] Duelyst - SERVER CRASH! #{server.hostname}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendSteamAlert: (txn, server, error, cb) ->
template = handlebars.compile(@steam_alert_template)
html = template({
title: 'Steam Transaction Error',
base_url: base_url,
txn: JSON.stringify(txn),
server: JSON.stringify(server),
error: error
})
opts = {
from: "admin@duelyst.com"
to: "server-errors+#{env}@counterplay.co"
subject: "[#{env}] Duelyst - Steam Transaction Error! #{server.hostname}"
html: html
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendPlayerReport: (playerUsername, playerId, message, fromUserId, fromEmail = null, cb) ->
opts = {
from: fromEmail || "admin@duelyst.com"
to: "player-abuse-reports@counterplay.co"
subject: "[#{env}] REPORT: #{playerUsername} (#{playerId}) reported"
text: "#{message}\n\n =============== \n\n by #{fromUserId}"
}
@transporter.sendMail opts, (error, info) ->
if cb?
if error
return cb(error)
else
return cb(null, info.response)
sendCRMActivityReport: (subject, htmlMessage, cb)->
opts = {
from: "admin@duelyst.com"
to: "servers+#{env}@counterplay.co"
subject: "[#{env}] Duelyst - CRM ACTIVITY - #{subject}"
html: htmlMessage
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendGiftCrate: (username, email, cb) ->
template = handlebars.compile(@giftcrate_template)
html = template({title: 'Come unlock your FREE gift crate', base_url: base_url, username: username})
opts = {
from: 'DUELYST <support@duelyst.com>'
to: email
subject: "FREE Duelyst Gift Crate"
html: html
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
module.exports = new Email
| 194889 | fs = require 'fs'
os = require 'os'
path = require 'path'
nodemailer = require 'nodemailer'
hbs = require 'hbs'
handlebars = hbs.handlebars
config = require '../config/config.js'
# Pretty error printing, helps with stack traces
PrettyError = require 'pretty-error'
prettyError = new PrettyError()
prettyError.skipNodeFiles()
prettyError.withoutColors()
prettyError.skipPackage('bluebird')
env = config.get('env')
if env is 'development'
base_url = "http://localhost:#{config.get('port')}"
else if env is 'staging'
base_url = ""
else if env is 'production'
base_url = ""
class Email
constructor: () ->
@loadTemplates()
@transporter = nodemailer.createTransport
host: 'smtp.mandrillapp.com'
port: 587
auth:
user: ''
pass: ''
loadTemplates: () ->
try
@default_template = fs.readFileSync(__dirname + '/templates/email-default.hbs').toString()
@signup_template = fs.readFileSync(__dirname + '/templates/email-signup.hbs').toString()
@resend_template = fs.readFileSync(__dirname + '/templates/email-resend.hbs').toString()
@taken_template = fs.readFileSync(__dirname + '/templates/email-taken.hbs').toString()
@forgot_template = fs.readFileSync(__dirname + '/templates/email-forgot.hbs').toString()
@verify_template = fs.readFileSync(__dirname + '/templates/email-verify.hbs').toString()
@confirm_template = fs.readFileSync(__dirname + '/templates/email-confirm.hbs').toString()
@alert_template = fs.readFileSync(__dirname + '/templates/email-alert.hbs').toString()
@steam_alert_template = fs.readFileSync(__dirname + '/templates/email-steam-alert.hbs').toString()
@notify_template = fs.readFileSync(__dirname + '/templates/email-notify.hbs').toString()
@receipt_template = fs.readFileSync(__dirname + '/templates/email-receipt.hbs').toString()
@giftcrate_template = fs.readFileSync(__dirname + '/templates/email-giftcrate.hbs').toString()
catch e
throw new Error("Failed to load email templates.")
sendMail: (username, email, title, message, cb) ->
template = handlebars.compile(@default_template)
html = template({title: title, base_url: base_url, username: username, message: message})
opts = {
from: '<EMAIL>'
to: email
subject: "DUELYST - #{title}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendEmailVerificationLink: (username, email, token, cb) ->
template = handlebars.compile(@verify_template)
html = template({title: 'Verify Email', base_url: base_url, username: username, token: token})
opts = {
from: '<EMAIL>'
to: email
subject: "Verify your DUELYST account email"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendSignup: (username, email, token, cb) ->
template = handlebars.compile(@signup_template)
html = template({title: 'Welcome', base_url: base_url, username: username, token: token})
opts = {
from: '<EMAIL>'
to: email
subject: "Welcome to DUELYST"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendReceipt: (username, email, receiptNumber, boosterCount, cb) ->
template = handlebars.compile(@receipt_template)
html = template({title: 'Welcome', base_url: base_url, username: username, receipt_number: receiptNumber, booster_count:boosterCount})
opts = {
from: '<EMAIL>'
to: email
subject: "DUELYST Purchase Receipt"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
resendSignup: (username, email, token, cb) ->
template = handlebars.compile(@resend_template)
html = template({title: 'Confirm', base_url: base_url, username: username, token: token})
opts = {
from: '<EMAIL>'
to: email
subject: "Duelyst - Complete your registration"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendTakenEmail: (username, email, token, cb) ->
template = handlebars.compile(@taken_template)
html = template({title: 'Taken', username: username, token: token})
opts = {
from: '<EMAIL>'
to: email
subject: "Duelyst - Email already registered"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendForgotPassword: (username, email, token, cb) ->
template = handlebars.compile(@forgot_template)
html = template({title: 'Reset', base_url: base_url, username: username, token: token})
opts = {
from: '<EMAIL>'
to: email
subject: "Duelyst - Reset your password"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendPasswordConfirmation: (username, email, cb) ->
template = handlebars.compile(@confirm_template)
html = template({title: 'Reset', base_url: base_url, username: username})
opts = {
from: '<EMAIL>'
to: email
subject: "Duelyst - Password has been updated"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendNotification: (title, message, cb) ->
template = handlebars.compile(@notify_template)
html = template({title: title, message: message})
opts = {
from: "<EMAIL>"
to: "<EMAIL>"
subject: "[#{env}] Duelyst - NOTIFICATION - #{title}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendTeamPurchaseNotification: (username, userId, email, chargeId, price, cb) ->
opts = {
from: "<EMAIL>"
to: "<EMAIL>"
subject: "[#{env}] Duelyst - PURCHASE - #{username} spent #{price} - #{chargeId}"
html: "#{username} (email:#{email}) (id:#{userId}) spent #{price}. Charge ID #{chargeId}"
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendTeamPurchaseErrorNotification: (subject, message, cb) ->
opts = {
from: "<EMAIL>"
to: "<EMAIL>"
subject: "[#{env}] Duelyst - NOTIFICATION - #{subject}"
html: message
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendErrorAlert: (server, error, cb) ->
template = handlebars.compile(@alert_template)
html = template({title: 'Server Error', base_url: base_url, server: JSON.stringify(server), error: error})
opts = {
from: "<EMAIL>"
to: "<EMAIL>"
subject: "[#{env}] Duelyst - SERVER ALERT! #{server.hostname}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendCrashAlert: (server, error, cb) ->
prettyErrorInfo = prettyError.render(error)
template = handlebars.compile(@alert_template)
html = template({title: 'Server Crash', base_url: base_url, server: JSON.stringify(server), error: error, prettyErrorInfo: prettyErrorInfo})
opts = {
from: "<EMAIL>"
to: "<EMAIL>"
subject: "[#{env}] Duelyst - SERVER CRASH! #{server.hostname}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendSteamAlert: (txn, server, error, cb) ->
template = handlebars.compile(@steam_alert_template)
html = template({
title: 'Steam Transaction Error',
base_url: base_url,
txn: JSON.stringify(txn),
server: JSON.stringify(server),
error: error
})
opts = {
from: "<EMAIL>"
to: "<EMAIL>"
subject: "[#{env}] Duelyst - Steam Transaction Error! #{server.hostname}"
html: html
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendPlayerReport: (playerUsername, playerId, message, fromUserId, fromEmail = null, cb) ->
opts = {
from: fromEmail || "<EMAIL>"
to: "<EMAIL>"
subject: "[#{env}] REPORT: #{playerUsername} (#{playerId}) reported"
text: "#{message}\n\n =============== \n\n by #{fromUserId}"
}
@transporter.sendMail opts, (error, info) ->
if cb?
if error
return cb(error)
else
return cb(null, info.response)
sendCRMActivityReport: (subject, htmlMessage, cb)->
opts = {
from: "<EMAIL>"
to: "<EMAIL>"
subject: "[#{env}] Duelyst - CRM ACTIVITY - #{subject}"
html: htmlMessage
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendGiftCrate: (username, email, cb) ->
template = handlebars.compile(@giftcrate_template)
html = template({title: 'Come unlock your FREE gift crate', base_url: base_url, username: username})
opts = {
from: 'DUELYST <<EMAIL>>'
to: email
subject: "FREE Duelyst Gift Crate"
html: html
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
module.exports = new Email
| true | fs = require 'fs'
os = require 'os'
path = require 'path'
nodemailer = require 'nodemailer'
hbs = require 'hbs'
handlebars = hbs.handlebars
config = require '../config/config.js'
# Pretty error printing, helps with stack traces
PrettyError = require 'pretty-error'
prettyError = new PrettyError()
prettyError.skipNodeFiles()
prettyError.withoutColors()
prettyError.skipPackage('bluebird')
env = config.get('env')
if env is 'development'
base_url = "http://localhost:#{config.get('port')}"
else if env is 'staging'
base_url = ""
else if env is 'production'
base_url = ""
class Email
constructor: () ->
@loadTemplates()
@transporter = nodemailer.createTransport
host: 'smtp.mandrillapp.com'
port: 587
auth:
user: ''
pass: ''
loadTemplates: () ->
try
@default_template = fs.readFileSync(__dirname + '/templates/email-default.hbs').toString()
@signup_template = fs.readFileSync(__dirname + '/templates/email-signup.hbs').toString()
@resend_template = fs.readFileSync(__dirname + '/templates/email-resend.hbs').toString()
@taken_template = fs.readFileSync(__dirname + '/templates/email-taken.hbs').toString()
@forgot_template = fs.readFileSync(__dirname + '/templates/email-forgot.hbs').toString()
@verify_template = fs.readFileSync(__dirname + '/templates/email-verify.hbs').toString()
@confirm_template = fs.readFileSync(__dirname + '/templates/email-confirm.hbs').toString()
@alert_template = fs.readFileSync(__dirname + '/templates/email-alert.hbs').toString()
@steam_alert_template = fs.readFileSync(__dirname + '/templates/email-steam-alert.hbs').toString()
@notify_template = fs.readFileSync(__dirname + '/templates/email-notify.hbs').toString()
@receipt_template = fs.readFileSync(__dirname + '/templates/email-receipt.hbs').toString()
@giftcrate_template = fs.readFileSync(__dirname + '/templates/email-giftcrate.hbs').toString()
catch e
throw new Error("Failed to load email templates.")
sendMail: (username, email, title, message, cb) ->
template = handlebars.compile(@default_template)
html = template({title: title, base_url: base_url, username: username, message: message})
opts = {
from: 'PI:EMAIL:<EMAIL>END_PI'
to: email
subject: "DUELYST - #{title}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendEmailVerificationLink: (username, email, token, cb) ->
template = handlebars.compile(@verify_template)
html = template({title: 'Verify Email', base_url: base_url, username: username, token: token})
opts = {
from: 'PI:EMAIL:<EMAIL>END_PI'
to: email
subject: "Verify your DUELYST account email"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendSignup: (username, email, token, cb) ->
template = handlebars.compile(@signup_template)
html = template({title: 'Welcome', base_url: base_url, username: username, token: token})
opts = {
from: 'PI:EMAIL:<EMAIL>END_PI'
to: email
subject: "Welcome to DUELYST"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendReceipt: (username, email, receiptNumber, boosterCount, cb) ->
template = handlebars.compile(@receipt_template)
html = template({title: 'Welcome', base_url: base_url, username: username, receipt_number: receiptNumber, booster_count:boosterCount})
opts = {
from: 'PI:EMAIL:<EMAIL>END_PI'
to: email
subject: "DUELYST Purchase Receipt"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
resendSignup: (username, email, token, cb) ->
template = handlebars.compile(@resend_template)
html = template({title: 'Confirm', base_url: base_url, username: username, token: token})
opts = {
from: 'PI:EMAIL:<EMAIL>END_PI'
to: email
subject: "Duelyst - Complete your registration"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendTakenEmail: (username, email, token, cb) ->
template = handlebars.compile(@taken_template)
html = template({title: 'Taken', username: username, token: token})
opts = {
from: 'PI:EMAIL:<EMAIL>END_PI'
to: email
subject: "Duelyst - Email already registered"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendForgotPassword: (username, email, token, cb) ->
template = handlebars.compile(@forgot_template)
html = template({title: 'Reset', base_url: base_url, username: username, token: token})
opts = {
from: 'PI:EMAIL:<EMAIL>END_PI'
to: email
subject: "Duelyst - Reset your password"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendPasswordConfirmation: (username, email, cb) ->
template = handlebars.compile(@confirm_template)
html = template({title: 'Reset', base_url: base_url, username: username})
opts = {
from: 'PI:EMAIL:<EMAIL>END_PI'
to: email
subject: "Duelyst - Password has been updated"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendNotification: (title, message, cb) ->
template = handlebars.compile(@notify_template)
html = template({title: title, message: message})
opts = {
from: "PI:EMAIL:<EMAIL>END_PI"
to: "PI:EMAIL:<EMAIL>END_PI"
subject: "[#{env}] Duelyst - NOTIFICATION - #{title}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendTeamPurchaseNotification: (username, userId, email, chargeId, price, cb) ->
opts = {
from: "PI:EMAIL:<EMAIL>END_PI"
to: "PI:EMAIL:<EMAIL>END_PI"
subject: "[#{env}] Duelyst - PURCHASE - #{username} spent #{price} - #{chargeId}"
html: "#{username} (email:#{email}) (id:#{userId}) spent #{price}. Charge ID #{chargeId}"
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendTeamPurchaseErrorNotification: (subject, message, cb) ->
opts = {
from: "PI:EMAIL:<EMAIL>END_PI"
to: "PI:EMAIL:<EMAIL>END_PI"
subject: "[#{env}] Duelyst - NOTIFICATION - #{subject}"
html: message
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendErrorAlert: (server, error, cb) ->
template = handlebars.compile(@alert_template)
html = template({title: 'Server Error', base_url: base_url, server: JSON.stringify(server), error: error})
opts = {
from: "PI:EMAIL:<EMAIL>END_PI"
to: "PI:EMAIL:<EMAIL>END_PI"
subject: "[#{env}] Duelyst - SERVER ALERT! #{server.hostname}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendCrashAlert: (server, error, cb) ->
prettyErrorInfo = prettyError.render(error)
template = handlebars.compile(@alert_template)
html = template({title: 'Server Crash', base_url: base_url, server: JSON.stringify(server), error: error, prettyErrorInfo: prettyErrorInfo})
opts = {
from: "PI:EMAIL:<EMAIL>END_PI"
to: "PI:EMAIL:<EMAIL>END_PI"
subject: "[#{env}] Duelyst - SERVER CRASH! #{server.hostname}"
html: html
# plaintext fallback
# text: ''
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendSteamAlert: (txn, server, error, cb) ->
template = handlebars.compile(@steam_alert_template)
html = template({
title: 'Steam Transaction Error',
base_url: base_url,
txn: JSON.stringify(txn),
server: JSON.stringify(server),
error: error
})
opts = {
from: "PI:EMAIL:<EMAIL>END_PI"
to: "PI:EMAIL:<EMAIL>END_PI"
subject: "[#{env}] Duelyst - Steam Transaction Error! #{server.hostname}"
html: html
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendPlayerReport: (playerUsername, playerId, message, fromUserId, fromEmail = null, cb) ->
opts = {
from: fromEmail || "PI:EMAIL:<EMAIL>END_PI"
to: "PI:EMAIL:<EMAIL>END_PI"
subject: "[#{env}] REPORT: #{playerUsername} (#{playerId}) reported"
text: "#{message}\n\n =============== \n\n by #{fromUserId}"
}
@transporter.sendMail opts, (error, info) ->
if cb?
if error
return cb(error)
else
return cb(null, info.response)
sendCRMActivityReport: (subject, htmlMessage, cb)->
opts = {
from: "PI:EMAIL:<EMAIL>END_PI"
to: "PI:EMAIL:<EMAIL>END_PI"
subject: "[#{env}] Duelyst - CRM ACTIVITY - #{subject}"
html: htmlMessage
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
sendGiftCrate: (username, email, cb) ->
template = handlebars.compile(@giftcrate_template)
html = template({title: 'Come unlock your FREE gift crate', base_url: base_url, username: username})
opts = {
from: 'DUELYST <PI:EMAIL:<EMAIL>END_PI>'
to: email
subject: "FREE Duelyst Gift Crate"
html: html
}
@transporter.sendMail opts, (error, info) ->
if error
return cb(error)
else
return cb(null, info.response)
module.exports = new Email
|
[
{
"context": "# (c) 2013-2018 Flowhub UG\n# (c) 2011-2012 Henri Bergius, Nemein\n# NoFlo may be freely distributed und",
"end": 116,
"score": 0.9998559951782227,
"start": 103,
"tag": "NAME",
"value": "Henri Bergius"
},
{
"context": "2018 Flowhub UG\n# (c) 2011-2012 He... | src/lib/Network.coffee | rrothenb/noflo | 0 | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2018 Flowhub UG
# (c) 2011-2012 Henri Bergius, Nemein
# NoFlo may be freely distributed under the MIT license
BaseNetwork = require './BaseNetwork'
# ## The NoFlo network coordinator
#
# NoFlo networks consist of processes connected to each other
# via sockets attached from outports to inports.
#
# The role of the network coordinator is to take a graph and
# instantiate all the necessary processes from the designated
# components, attach sockets between them, and handle the sending
# of Initial Information Packets.
class Network extends BaseNetwork
# All NoFlo networks are instantiated with a graph. Upon instantiation
# they will load all the needed components, instantiate them, and
# set up the defined connections and IIPs.
constructor: (graph, options = {}) ->
super graph, options
# Add a process to the network. The node will also be registered
# with the current graph.
addNode: (node, options, callback) ->
if typeof options is 'function'
callback = options
options = {}
super node, options, (err, process) =>
return callback err if err
unless options.initial
@graph.addNode node.id, node.component, node.metadata
callback null, process
# Remove a process from the network. The node will also be removed
# from the current graph.
removeNode: (node, callback) ->
super node, (err) =>
return callback err if err
@graph.removeNode node.id
callback()
# Rename a process in the network. Renaming a process also modifies
# the current graph.
renameNode: (oldId, newId, callback) ->
super oldId, newId, (err) =>
return callback err if err
@graph.renameNode oldId, newId
callback()
# Add a connection to the network. The edge will also be registered
# with the current graph.
addEdge: (edge, options, callback) ->
if typeof options is 'function'
callback = options
options = {}
super edge, options, (err) =>
return callback err if err
unless options.initial
@graph.addEdgeIndex edge.from.node, edge.from.port, edge.from.index, edge.to.node, edge.to.port, edge.to.index, edge.metadata
callback()
# Remove a connection from the network. The edge will also be removed
# from the current graph.
removeEdge: (edge, callback) ->
super edge, (err) =>
return callback err if err
@graph.removeEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port
callback()
# Add an IIP to the network. The IIP will also be registered with the
# current graph. If the network is running, the IIP will be sent immediately.
addInitial: (iip, options, callback) ->
if typeof options is 'function'
callback = options
options = {}
super iip, options, (err) =>
return callback err if err
unless options.initial
@graph.addInitialIndex iip.from.data, iip.to.node, iip.to.port, iip.to.index, iip.metadata
callback()
# Remove an IIP from the network. The IIP will also be removed from the
# current graph.
removeInitial: (iip, callback) ->
super iip, (err) =>
return callback err if err
@graph.removeInitial iip.to.node, iip.to.port
callback()
exports.Network = Network
| 167109 | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2018 Flowhub UG
# (c) 2011-2012 <NAME>, <NAME>
# NoFlo may be freely distributed under the MIT license
BaseNetwork = require './BaseNetwork'
# ## The NoFlo network coordinator
#
# NoFlo networks consist of processes connected to each other
# via sockets attached from outports to inports.
#
# The role of the network coordinator is to take a graph and
# instantiate all the necessary processes from the designated
# components, attach sockets between them, and handle the sending
# of Initial Information Packets.
class Network extends BaseNetwork
# All NoFlo networks are instantiated with a graph. Upon instantiation
# they will load all the needed components, instantiate them, and
# set up the defined connections and IIPs.
constructor: (graph, options = {}) ->
super graph, options
# Add a process to the network. The node will also be registered
# with the current graph.
addNode: (node, options, callback) ->
if typeof options is 'function'
callback = options
options = {}
super node, options, (err, process) =>
return callback err if err
unless options.initial
@graph.addNode node.id, node.component, node.metadata
callback null, process
# Remove a process from the network. The node will also be removed
# from the current graph.
removeNode: (node, callback) ->
super node, (err) =>
return callback err if err
@graph.removeNode node.id
callback()
# Rename a process in the network. Renaming a process also modifies
# the current graph.
renameNode: (oldId, newId, callback) ->
super oldId, newId, (err) =>
return callback err if err
@graph.renameNode oldId, newId
callback()
# Add a connection to the network. The edge will also be registered
# with the current graph.
addEdge: (edge, options, callback) ->
if typeof options is 'function'
callback = options
options = {}
super edge, options, (err) =>
return callback err if err
unless options.initial
@graph.addEdgeIndex edge.from.node, edge.from.port, edge.from.index, edge.to.node, edge.to.port, edge.to.index, edge.metadata
callback()
# Remove a connection from the network. The edge will also be removed
# from the current graph.
removeEdge: (edge, callback) ->
super edge, (err) =>
return callback err if err
@graph.removeEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port
callback()
# Add an IIP to the network. The IIP will also be registered with the
# current graph. If the network is running, the IIP will be sent immediately.
addInitial: (iip, options, callback) ->
if typeof options is 'function'
callback = options
options = {}
super iip, options, (err) =>
return callback err if err
unless options.initial
@graph.addInitialIndex iip.from.data, iip.to.node, iip.to.port, iip.to.index, iip.metadata
callback()
# Remove an IIP from the network. The IIP will also be removed from the
# current graph.
removeInitial: (iip, callback) ->
super iip, (err) =>
return callback err if err
@graph.removeInitial iip.to.node, iip.to.port
callback()
exports.Network = Network
| true | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2018 Flowhub UG
# (c) 2011-2012 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
# NoFlo may be freely distributed under the MIT license
BaseNetwork = require './BaseNetwork'
# ## The NoFlo network coordinator
#
# NoFlo networks consist of processes connected to each other
# via sockets attached from outports to inports.
#
# The role of the network coordinator is to take a graph and
# instantiate all the necessary processes from the designated
# components, attach sockets between them, and handle the sending
# of Initial Information Packets.
class Network extends BaseNetwork
# All NoFlo networks are instantiated with a graph. Upon instantiation
# they will load all the needed components, instantiate them, and
# set up the defined connections and IIPs.
constructor: (graph, options = {}) ->
super graph, options
# Add a process to the network. The node will also be registered
# with the current graph.
addNode: (node, options, callback) ->
if typeof options is 'function'
callback = options
options = {}
super node, options, (err, process) =>
return callback err if err
unless options.initial
@graph.addNode node.id, node.component, node.metadata
callback null, process
# Remove a process from the network. The node will also be removed
# from the current graph.
removeNode: (node, callback) ->
super node, (err) =>
return callback err if err
@graph.removeNode node.id
callback()
# Rename a process in the network. Renaming a process also modifies
# the current graph.
renameNode: (oldId, newId, callback) ->
super oldId, newId, (err) =>
return callback err if err
@graph.renameNode oldId, newId
callback()
# Add a connection to the network. The edge will also be registered
# with the current graph.
addEdge: (edge, options, callback) ->
if typeof options is 'function'
callback = options
options = {}
super edge, options, (err) =>
return callback err if err
unless options.initial
@graph.addEdgeIndex edge.from.node, edge.from.port, edge.from.index, edge.to.node, edge.to.port, edge.to.index, edge.metadata
callback()
# Remove a connection from the network. The edge will also be removed
# from the current graph.
removeEdge: (edge, callback) ->
super edge, (err) =>
return callback err if err
@graph.removeEdge edge.from.node, edge.from.port, edge.to.node, edge.to.port
callback()
# Add an IIP to the network. The IIP will also be registered with the
# current graph. If the network is running, the IIP will be sent immediately.
addInitial: (iip, options, callback) ->
if typeof options is 'function'
callback = options
options = {}
super iip, options, (err) =>
return callback err if err
unless options.initial
@graph.addInitialIndex iip.from.data, iip.to.node, iip.to.port, iip.to.index, iip.metadata
callback()
# Remove an IIP from the network. The IIP will also be removed from the
# current graph.
removeInitial: (iip, callback) ->
super iip, (err) =>
return callback err if err
@graph.removeInitial iip.to.node, iip.to.port
callback()
exports.Network = Network
|
[
{
"context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nFoldingTextService = requi",
"end": 35,
"score": 0.9997143745422363,
"start": 21,
"tag": "NAME",
"value": "Jesse Grosjean"
}
] | atom/packages/foldingtext-for-atom/lib/extensions/tags/index.coffee | prookie/dotfiles-1 | 0 | # Copyright (c) 2015 Jesse Grosjean. All rights reserved.
FoldingTextService = require '../../foldingtext-service'
TokenInputElement = require '../ui/token-input-element'
ListInputElement = require '../ui/list-input-element'
{CompositeDisposable} = require 'atom'
FoldingTextService.observeOutlineEditors (editor) ->
editor.addItemBadgeRenderer (item, addBadgeElement) ->
if tags = item.getAttribute 'data-tags', true
for each in tags
each = each.trim()
a = document.createElement 'A'
a.className = 'ft-tag'
a.setAttribute 'data-tag', each
a.textContent = each
addBadgeElement a
FoldingTextService.eventRegistery.listen '.ft-tag',
click: (e) ->
tag = e.target.textContent
outlineEditor = FoldingTextService.OutlineEditor.findOutlineEditor e.target
outlineEditor.setSearch "##{tag}"
e.stopPropagation()
e.preventDefault()
editTags = (editor) ->
savedSelection = editor.selection
selectedItems = savedSelection.items
item = savedSelection.focusItem
return unless selectedItems.length > 0
outlineTagsMap = {}
for eachItem in editor.outline.evaluateItemPath('#')
for eachTag in eachItem.getAttribute('data-tags', true) or []
outlineTagsMap[eachTag] = true
selectedTagsMap = {}
for eachItem in selectedItems
for eachTag in eachItem.getAttribute('data-tags', true) or []
selectedTagsMap[eachTag] = true
addedTokens = {}
deletedTokens = {}
tokenInput = document.createElement 'ft-token-input'
tokenInput.setPlaceholderText 'Tag…'
tokenInput.tokenizeText(Object.keys(selectedTagsMap).join(','))
tokenInput.setDelegate
didAddToken: (token) ->
outlineTagsMap[token] = true
addedTokens[token] = true
delete deletedTokens[token]
didDeleteToken: (token) ->
delete addedTokens[token]
deletedTokens[token] = true
cancelled: ->
tokenInputPanel.destroy()
restoreFocus: ->
editor.focus()
editor.moveSelectionRange savedSelection
confirm: ->
text = tokenInput.getText()
if text
tokenInput.tokenizeText()
else
if selectedItems.length is 1
tokens = tokenInput.getTokens()
tokens = null unless tokens.length > 0
selectedItems[0].setAttribute('data-tags', tokens)
else if selectedItems.length > 1
editor.outline.beginUpdates()
for each in selectedItems
eachTags = each.getAttribute('data-tags', true) or []
changed = false
for eachDeleted of deletedTokens
if eachDeleted in eachTags
eachTags.splice(eachTags.indexOf(eachDeleted), 1)
changed = true
for eachAdded of addedTokens
unless eachAdded in eachTags
eachTags.push eachAdded
changed = true
if changed
eachTags = null unless eachTags.length > 0
each.setAttribute('data-tags', eachTags)
editor.outline.endUpdates()
tokenInputPanel.destroy()
@restoreFocus()
tokenInputPanel = atom.workspace.addPopoverPanel
item: tokenInput
className: 'ft-text-input-panel'
target: -> editor.getClientRectForItemOffset(item, item.bodyText.length)
viewport: -> editor.outlineEditorElement.getBoundingClientRect()
placement: 'bottom'
tokenInput.focusTextEditor()
clearTags = (editor) ->
outline = editor.outline
undoManager = outline.undoManager
selectedItems = editor.selection.items
if selectedItems.length
outline.beginUpdates()
undoManager.beginUndoGrouping()
for each in selectedItems
each.removeAttribute 'data-tags'
outline.endUpdates()
undoManager.endUndoGrouping()
atom.commands.add 'ft-outline-editor',
'outline-editor:edit-tags': -> editTags @editor
'outline-editor:clear-tags': -> clearTags @editor
atom.commands.add 'ft-outline-editor .ft-tag',
'outline-editor:delete-tag': (e) ->
tag = @textContent
editor = FoldingTextService.OutlineEditor.findOutlineEditor this
item = editor.selection.focusItem
tags = item.getAttribute 'data-tags', true
if tag in tags
tags.splice(tags.indexOf(tag), 1)
tags = null unless tags.length > 0
item.setAttribute 'data-tags', tags
e.stopPropagation()
e.preventDefault()
atom.keymaps.add 'tags-bindings',
'ft-outline-editor':
'cmd-shift-t': 'outline-editor:edit-tags'
'ft-outline-editor.outline-mode':
't': 'outline-editor:edit-tags'
#atom.contextMenu.add
# 'ft-outline-editor .ft-tag': [
# {label: 'Delete Tag', command: 'outline-editor:delete-tag'}
# ] | 75447 | # Copyright (c) 2015 <NAME>. All rights reserved.
FoldingTextService = require '../../foldingtext-service'
TokenInputElement = require '../ui/token-input-element'
ListInputElement = require '../ui/list-input-element'
{CompositeDisposable} = require 'atom'
FoldingTextService.observeOutlineEditors (editor) ->
editor.addItemBadgeRenderer (item, addBadgeElement) ->
if tags = item.getAttribute 'data-tags', true
for each in tags
each = each.trim()
a = document.createElement 'A'
a.className = 'ft-tag'
a.setAttribute 'data-tag', each
a.textContent = each
addBadgeElement a
FoldingTextService.eventRegistery.listen '.ft-tag',
click: (e) ->
tag = e.target.textContent
outlineEditor = FoldingTextService.OutlineEditor.findOutlineEditor e.target
outlineEditor.setSearch "##{tag}"
e.stopPropagation()
e.preventDefault()
editTags = (editor) ->
savedSelection = editor.selection
selectedItems = savedSelection.items
item = savedSelection.focusItem
return unless selectedItems.length > 0
outlineTagsMap = {}
for eachItem in editor.outline.evaluateItemPath('#')
for eachTag in eachItem.getAttribute('data-tags', true) or []
outlineTagsMap[eachTag] = true
selectedTagsMap = {}
for eachItem in selectedItems
for eachTag in eachItem.getAttribute('data-tags', true) or []
selectedTagsMap[eachTag] = true
addedTokens = {}
deletedTokens = {}
tokenInput = document.createElement 'ft-token-input'
tokenInput.setPlaceholderText 'Tag…'
tokenInput.tokenizeText(Object.keys(selectedTagsMap).join(','))
tokenInput.setDelegate
didAddToken: (token) ->
outlineTagsMap[token] = true
addedTokens[token] = true
delete deletedTokens[token]
didDeleteToken: (token) ->
delete addedTokens[token]
deletedTokens[token] = true
cancelled: ->
tokenInputPanel.destroy()
restoreFocus: ->
editor.focus()
editor.moveSelectionRange savedSelection
confirm: ->
text = tokenInput.getText()
if text
tokenInput.tokenizeText()
else
if selectedItems.length is 1
tokens = tokenInput.getTokens()
tokens = null unless tokens.length > 0
selectedItems[0].setAttribute('data-tags', tokens)
else if selectedItems.length > 1
editor.outline.beginUpdates()
for each in selectedItems
eachTags = each.getAttribute('data-tags', true) or []
changed = false
for eachDeleted of deletedTokens
if eachDeleted in eachTags
eachTags.splice(eachTags.indexOf(eachDeleted), 1)
changed = true
for eachAdded of addedTokens
unless eachAdded in eachTags
eachTags.push eachAdded
changed = true
if changed
eachTags = null unless eachTags.length > 0
each.setAttribute('data-tags', eachTags)
editor.outline.endUpdates()
tokenInputPanel.destroy()
@restoreFocus()
tokenInputPanel = atom.workspace.addPopoverPanel
item: tokenInput
className: 'ft-text-input-panel'
target: -> editor.getClientRectForItemOffset(item, item.bodyText.length)
viewport: -> editor.outlineEditorElement.getBoundingClientRect()
placement: 'bottom'
tokenInput.focusTextEditor()
clearTags = (editor) ->
outline = editor.outline
undoManager = outline.undoManager
selectedItems = editor.selection.items
if selectedItems.length
outline.beginUpdates()
undoManager.beginUndoGrouping()
for each in selectedItems
each.removeAttribute 'data-tags'
outline.endUpdates()
undoManager.endUndoGrouping()
atom.commands.add 'ft-outline-editor',
'outline-editor:edit-tags': -> editTags @editor
'outline-editor:clear-tags': -> clearTags @editor
atom.commands.add 'ft-outline-editor .ft-tag',
'outline-editor:delete-tag': (e) ->
tag = @textContent
editor = FoldingTextService.OutlineEditor.findOutlineEditor this
item = editor.selection.focusItem
tags = item.getAttribute 'data-tags', true
if tag in tags
tags.splice(tags.indexOf(tag), 1)
tags = null unless tags.length > 0
item.setAttribute 'data-tags', tags
e.stopPropagation()
e.preventDefault()
atom.keymaps.add 'tags-bindings',
'ft-outline-editor':
'cmd-shift-t': 'outline-editor:edit-tags'
'ft-outline-editor.outline-mode':
't': 'outline-editor:edit-tags'
#atom.contextMenu.add
# 'ft-outline-editor .ft-tag': [
# {label: 'Delete Tag', command: 'outline-editor:delete-tag'}
# ] | true | # Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved.
FoldingTextService = require '../../foldingtext-service'
TokenInputElement = require '../ui/token-input-element'
ListInputElement = require '../ui/list-input-element'
{CompositeDisposable} = require 'atom'
FoldingTextService.observeOutlineEditors (editor) ->
editor.addItemBadgeRenderer (item, addBadgeElement) ->
if tags = item.getAttribute 'data-tags', true
for each in tags
each = each.trim()
a = document.createElement 'A'
a.className = 'ft-tag'
a.setAttribute 'data-tag', each
a.textContent = each
addBadgeElement a
FoldingTextService.eventRegistery.listen '.ft-tag',
click: (e) ->
tag = e.target.textContent
outlineEditor = FoldingTextService.OutlineEditor.findOutlineEditor e.target
outlineEditor.setSearch "##{tag}"
e.stopPropagation()
e.preventDefault()
editTags = (editor) ->
savedSelection = editor.selection
selectedItems = savedSelection.items
item = savedSelection.focusItem
return unless selectedItems.length > 0
outlineTagsMap = {}
for eachItem in editor.outline.evaluateItemPath('#')
for eachTag in eachItem.getAttribute('data-tags', true) or []
outlineTagsMap[eachTag] = true
selectedTagsMap = {}
for eachItem in selectedItems
for eachTag in eachItem.getAttribute('data-tags', true) or []
selectedTagsMap[eachTag] = true
addedTokens = {}
deletedTokens = {}
tokenInput = document.createElement 'ft-token-input'
tokenInput.setPlaceholderText 'Tag…'
tokenInput.tokenizeText(Object.keys(selectedTagsMap).join(','))
tokenInput.setDelegate
didAddToken: (token) ->
outlineTagsMap[token] = true
addedTokens[token] = true
delete deletedTokens[token]
didDeleteToken: (token) ->
delete addedTokens[token]
deletedTokens[token] = true
cancelled: ->
tokenInputPanel.destroy()
restoreFocus: ->
editor.focus()
editor.moveSelectionRange savedSelection
confirm: ->
text = tokenInput.getText()
if text
tokenInput.tokenizeText()
else
if selectedItems.length is 1
tokens = tokenInput.getTokens()
tokens = null unless tokens.length > 0
selectedItems[0].setAttribute('data-tags', tokens)
else if selectedItems.length > 1
editor.outline.beginUpdates()
for each in selectedItems
eachTags = each.getAttribute('data-tags', true) or []
changed = false
for eachDeleted of deletedTokens
if eachDeleted in eachTags
eachTags.splice(eachTags.indexOf(eachDeleted), 1)
changed = true
for eachAdded of addedTokens
unless eachAdded in eachTags
eachTags.push eachAdded
changed = true
if changed
eachTags = null unless eachTags.length > 0
each.setAttribute('data-tags', eachTags)
editor.outline.endUpdates()
tokenInputPanel.destroy()
@restoreFocus()
tokenInputPanel = atom.workspace.addPopoverPanel
item: tokenInput
className: 'ft-text-input-panel'
target: -> editor.getClientRectForItemOffset(item, item.bodyText.length)
viewport: -> editor.outlineEditorElement.getBoundingClientRect()
placement: 'bottom'
tokenInput.focusTextEditor()
clearTags = (editor) ->
outline = editor.outline
undoManager = outline.undoManager
selectedItems = editor.selection.items
if selectedItems.length
outline.beginUpdates()
undoManager.beginUndoGrouping()
for each in selectedItems
each.removeAttribute 'data-tags'
outline.endUpdates()
undoManager.endUndoGrouping()
atom.commands.add 'ft-outline-editor',
'outline-editor:edit-tags': -> editTags @editor
'outline-editor:clear-tags': -> clearTags @editor
atom.commands.add 'ft-outline-editor .ft-tag',
'outline-editor:delete-tag': (e) ->
tag = @textContent
editor = FoldingTextService.OutlineEditor.findOutlineEditor this
item = editor.selection.focusItem
tags = item.getAttribute 'data-tags', true
if tag in tags
tags.splice(tags.indexOf(tag), 1)
tags = null unless tags.length > 0
item.setAttribute 'data-tags', tags
e.stopPropagation()
e.preventDefault()
atom.keymaps.add 'tags-bindings',
'ft-outline-editor':
'cmd-shift-t': 'outline-editor:edit-tags'
'ft-outline-editor.outline-mode':
't': 'outline-editor:edit-tags'
#atom.contextMenu.add
# 'ft-outline-editor .ft-tag': [
# {label: 'Delete Tag', command: 'outline-editor:delete-tag'}
# ] |
[
{
"context": "nversion routine.\n@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.\n@module utils/html-to-wpml\n###\n\n\n_ ",
"end": 117,
"score": 0.9997646808624268,
"start": 105,
"tag": "NAME",
"value": "James Devlin"
}
] | src/utils/html-to-wpml.coffee | focusaurus/HackMyResume | 2 | ###*
Definition of the Markdown to WordProcessingML conversion routine.
@license MIT. Copyright (c) 2015 James Devlin / FluentDesk.
@module utils/html-to-wpml
###
_ = require 'underscore'
HTML5Tokenizer = require 'simple-html-tokenizer'
module.exports = ( html ) ->
# Tokenize the HTML stream.
tokens = HTML5Tokenizer.tokenize( html )
final = is_bold = is_italic = is_link = link_url = ''
# Process <em>, <strong>, and <a> elements in the HTML stream, producing
# equivalent WordProcessingML that can be dumped into a <w:p> or other
# text container element.
_.each tokens, ( tok ) ->
switch tok.type
when 'StartTag'
switch tok.tagName
when 'p' then final += '<w:p>'
when 'strong' then is_bold = true
when 'em' then is_italic = true
when 'a'
is_link = true;
link_url = tok.attributes.filter((attr) -> attr[0] == 'href' )[0][1];
when 'EndTag'
switch tok.tagName
when 'p' then final += '</w:p>'
when 'strong' then is_bold = false
when 'em' then is_italic = false
when 'a' then is_link = false
when 'Chars'
if( tok.chars.trim().length )
style = if is_bold then '<w:b/>' else ''
style += if is_italic then '<w:i/>' else ''
style += if is_link then '<w:rStyle w:val="Hyperlink"/>' else ''
final +=
(if is_link then ('<w:hlink w:dest="' + link_url + '">') else '') +
'<w:r><w:rPr>' + style + '</w:rPr><w:t>' + tok.chars +
'</w:t></w:r>' + (if is_link then '</w:hlink>' else '')
final
| 40942 | ###*
Definition of the Markdown to WordProcessingML conversion routine.
@license MIT. Copyright (c) 2015 <NAME> / FluentDesk.
@module utils/html-to-wpml
###
_ = require 'underscore'
HTML5Tokenizer = require 'simple-html-tokenizer'
module.exports = ( html ) ->
# Tokenize the HTML stream.
tokens = HTML5Tokenizer.tokenize( html )
final = is_bold = is_italic = is_link = link_url = ''
# Process <em>, <strong>, and <a> elements in the HTML stream, producing
# equivalent WordProcessingML that can be dumped into a <w:p> or other
# text container element.
_.each tokens, ( tok ) ->
switch tok.type
when 'StartTag'
switch tok.tagName
when 'p' then final += '<w:p>'
when 'strong' then is_bold = true
when 'em' then is_italic = true
when 'a'
is_link = true;
link_url = tok.attributes.filter((attr) -> attr[0] == 'href' )[0][1];
when 'EndTag'
switch tok.tagName
when 'p' then final += '</w:p>'
when 'strong' then is_bold = false
when 'em' then is_italic = false
when 'a' then is_link = false
when 'Chars'
if( tok.chars.trim().length )
style = if is_bold then '<w:b/>' else ''
style += if is_italic then '<w:i/>' else ''
style += if is_link then '<w:rStyle w:val="Hyperlink"/>' else ''
final +=
(if is_link then ('<w:hlink w:dest="' + link_url + '">') else '') +
'<w:r><w:rPr>' + style + '</w:rPr><w:t>' + tok.chars +
'</w:t></w:r>' + (if is_link then '</w:hlink>' else '')
final
| true | ###*
Definition of the Markdown to WordProcessingML conversion routine.
@license MIT. Copyright (c) 2015 PI:NAME:<NAME>END_PI / FluentDesk.
@module utils/html-to-wpml
###
_ = require 'underscore'
HTML5Tokenizer = require 'simple-html-tokenizer'
module.exports = ( html ) ->
# Tokenize the HTML stream.
tokens = HTML5Tokenizer.tokenize( html )
final = is_bold = is_italic = is_link = link_url = ''
# Process <em>, <strong>, and <a> elements in the HTML stream, producing
# equivalent WordProcessingML that can be dumped into a <w:p> or other
# text container element.
_.each tokens, ( tok ) ->
switch tok.type
when 'StartTag'
switch tok.tagName
when 'p' then final += '<w:p>'
when 'strong' then is_bold = true
when 'em' then is_italic = true
when 'a'
is_link = true;
link_url = tok.attributes.filter((attr) -> attr[0] == 'href' )[0][1];
when 'EndTag'
switch tok.tagName
when 'p' then final += '</w:p>'
when 'strong' then is_bold = false
when 'em' then is_italic = false
when 'a' then is_link = false
when 'Chars'
if( tok.chars.trim().length )
style = if is_bold then '<w:b/>' else ''
style += if is_italic then '<w:i/>' else ''
style += if is_link then '<w:rStyle w:val="Hyperlink"/>' else ''
final +=
(if is_link then ('<w:hlink w:dest="' + link_url + '">') else '') +
'<w:r><w:rPr>' + style + '</w:rPr><w:t>' + tok.chars +
'</w:t></w:r>' + (if is_link then '</w:hlink>' else '')
final
|
[
{
"context": "###\n resource-embedder\n https://github.com/callumlocke/resource-embedder\n\n Copyright 2013 Callum Locke\n",
"end": 56,
"score": 0.9995028972625732,
"start": 45,
"tag": "USERNAME",
"value": "callumlocke"
},
{
"context": "om/callumlocke/resource-embedder\n\n Copyri... | src/resource-embedder.coffee | callumlocke/resource-embedder | 1 | ###
resource-embedder
https://github.com/callumlocke/resource-embedder
Copyright 2013 Callum Locke
Licensed under the MIT license.
###
fs = require 'graceful-fs'
path = require 'path'
htmlparser = require 'htmlparser2'
assign = require('lodash').assign
Resource = require './resource'
getLineIndent = require './get-line-indent'
parseFileSize = require './parse-file-size'
defaults =
threshold: '5KB'
stylesheets: true
scripts: true
deleteEmbeddedFiles: false
indentEachLine = (str, indent) ->
lines = str.split '\n'
indent + lines.join "\n#{indent}"
module.exports = class ResourceEmbedder
constructor: (_options) ->
# Normalise arguments
if typeof _options is 'string'
htmlFile = arguments[0]
_options = arguments[1] || {}
_options.htmlFile = htmlFile
# Build options
@options = assign {}, defaults, _options
@options.htmlFile = path.resolve @options.htmlFile
if not @options.assetRoot
@options.assetRoot = path.dirname(@options.htmlFile) unless @options.assetRoot?
@options.assetRoot = path.resolve @options.assetRoot
if typeof @options.threshold isnt 'number'
@options.threshold = parseFileSize @options.threshold
get: (callback) ->
fs.readFile @options.htmlFile, (err, inputMarkup) =>
throw err if err
inputMarkup = inputMarkup.toString()
embeddableResources = {}
tagCounter = 1
finished = false
warnings = []
doEmbedding = =>
for own k, er of embeddableResources
return if !er.body? || !er.elementEndIndex?
outputMarkup = ''
index = 0
for own k, er of embeddableResources
er.body = er.body.toString()
multiline = (er.body.indexOf('\n') isnt -1)
if multiline
indent = getLineIndent er.elementStartIndex, inputMarkup
else indent = ''
body = (if indent.length then indentEachLine(er.body, indent) else er.body)
outputMarkup += (
inputMarkup.substring(index, er.elementStartIndex) +
"<#{er.type}>" +
(if multiline then '\n' else '') +
body +
(if multiline then '\n' else '') +
indent + "</#{er.type}>"
)
index = er.elementEndIndex + 1
if @options.deleteEmbeddedFiles && fs.existsSync er.path
fs.unlinkSync er.path
outputMarkup += inputMarkup.substring index
callback outputMarkup, (if warnings.length then warnings else null)
parser = new htmlparser.Parser
onopentag: (tagName, attributes) =>
tagCounter++
thisTagId = tagCounter
startIndexOfThisTag = parser.startIndex
resource = new Resource tagName, attributes, @options
resource.isEmbeddable (embed) =>
if embed
if !embeddableResources[thisTagId]?
embeddableResources[thisTagId] = {}
er = embeddableResources[thisTagId]
er.body = resource.contents
er.type = (if tagName is 'script' then 'script' else 'style')
er.path = path.resolve path.join(@options.assetRoot, resource.target)
er.elementStartIndex = startIndexOfThisTag
else
warnings.push resource.warning if resource.warning?
process.nextTick -> delete embeddableResources[thisTagId]
if finished
process.nextTick doEmbedding
onclosetag: (tagName) ->
switch tagName
when 'script', 'link'
if !embeddableResources[tagCounter]?
embeddableResources[tagCounter] = {}
er = embeddableResources[tagCounter]
er.elementEndIndex = parser.endIndex
if finished
throw new Error 'Should never happen!'
onend: ->
finished = true
parser.write(inputMarkup)
parser.end()
| 17900 | ###
resource-embedder
https://github.com/callumlocke/resource-embedder
Copyright 2013 <NAME>
Licensed under the MIT license.
###
fs = require 'graceful-fs'
path = require 'path'
htmlparser = require 'htmlparser2'
assign = require('lodash').assign
Resource = require './resource'
getLineIndent = require './get-line-indent'
parseFileSize = require './parse-file-size'
defaults =
threshold: '5KB'
stylesheets: true
scripts: true
deleteEmbeddedFiles: false
indentEachLine = (str, indent) ->
lines = str.split '\n'
indent + lines.join "\n#{indent}"
module.exports = class ResourceEmbedder
constructor: (_options) ->
# Normalise arguments
if typeof _options is 'string'
htmlFile = arguments[0]
_options = arguments[1] || {}
_options.htmlFile = htmlFile
# Build options
@options = assign {}, defaults, _options
@options.htmlFile = path.resolve @options.htmlFile
if not @options.assetRoot
@options.assetRoot = path.dirname(@options.htmlFile) unless @options.assetRoot?
@options.assetRoot = path.resolve @options.assetRoot
if typeof @options.threshold isnt 'number'
@options.threshold = parseFileSize @options.threshold
get: (callback) ->
fs.readFile @options.htmlFile, (err, inputMarkup) =>
throw err if err
inputMarkup = inputMarkup.toString()
embeddableResources = {}
tagCounter = 1
finished = false
warnings = []
doEmbedding = =>
for own k, er of embeddableResources
return if !er.body? || !er.elementEndIndex?
outputMarkup = ''
index = 0
for own k, er of embeddableResources
er.body = er.body.toString()
multiline = (er.body.indexOf('\n') isnt -1)
if multiline
indent = getLineIndent er.elementStartIndex, inputMarkup
else indent = ''
body = (if indent.length then indentEachLine(er.body, indent) else er.body)
outputMarkup += (
inputMarkup.substring(index, er.elementStartIndex) +
"<#{er.type}>" +
(if multiline then '\n' else '') +
body +
(if multiline then '\n' else '') +
indent + "</#{er.type}>"
)
index = er.elementEndIndex + 1
if @options.deleteEmbeddedFiles && fs.existsSync er.path
fs.unlinkSync er.path
outputMarkup += inputMarkup.substring index
callback outputMarkup, (if warnings.length then warnings else null)
parser = new htmlparser.Parser
onopentag: (tagName, attributes) =>
tagCounter++
thisTagId = tagCounter
startIndexOfThisTag = parser.startIndex
resource = new Resource tagName, attributes, @options
resource.isEmbeddable (embed) =>
if embed
if !embeddableResources[thisTagId]?
embeddableResources[thisTagId] = {}
er = embeddableResources[thisTagId]
er.body = resource.contents
er.type = (if tagName is 'script' then 'script' else 'style')
er.path = path.resolve path.join(@options.assetRoot, resource.target)
er.elementStartIndex = startIndexOfThisTag
else
warnings.push resource.warning if resource.warning?
process.nextTick -> delete embeddableResources[thisTagId]
if finished
process.nextTick doEmbedding
onclosetag: (tagName) ->
switch tagName
when 'script', 'link'
if !embeddableResources[tagCounter]?
embeddableResources[tagCounter] = {}
er = embeddableResources[tagCounter]
er.elementEndIndex = parser.endIndex
if finished
throw new Error 'Should never happen!'
onend: ->
finished = true
parser.write(inputMarkup)
parser.end()
| true | ###
resource-embedder
https://github.com/callumlocke/resource-embedder
Copyright 2013 PI:NAME:<NAME>END_PI
Licensed under the MIT license.
###
fs = require 'graceful-fs'
path = require 'path'
htmlparser = require 'htmlparser2'
assign = require('lodash').assign
Resource = require './resource'
getLineIndent = require './get-line-indent'
parseFileSize = require './parse-file-size'
defaults =
threshold: '5KB'
stylesheets: true
scripts: true
deleteEmbeddedFiles: false
indentEachLine = (str, indent) ->
lines = str.split '\n'
indent + lines.join "\n#{indent}"
module.exports = class ResourceEmbedder
constructor: (_options) ->
# Normalise arguments
if typeof _options is 'string'
htmlFile = arguments[0]
_options = arguments[1] || {}
_options.htmlFile = htmlFile
# Build options
@options = assign {}, defaults, _options
@options.htmlFile = path.resolve @options.htmlFile
if not @options.assetRoot
@options.assetRoot = path.dirname(@options.htmlFile) unless @options.assetRoot?
@options.assetRoot = path.resolve @options.assetRoot
if typeof @options.threshold isnt 'number'
@options.threshold = parseFileSize @options.threshold
get: (callback) ->
fs.readFile @options.htmlFile, (err, inputMarkup) =>
throw err if err
inputMarkup = inputMarkup.toString()
embeddableResources = {}
tagCounter = 1
finished = false
warnings = []
doEmbedding = =>
for own k, er of embeddableResources
return if !er.body? || !er.elementEndIndex?
outputMarkup = ''
index = 0
for own k, er of embeddableResources
er.body = er.body.toString()
multiline = (er.body.indexOf('\n') isnt -1)
if multiline
indent = getLineIndent er.elementStartIndex, inputMarkup
else indent = ''
body = (if indent.length then indentEachLine(er.body, indent) else er.body)
outputMarkup += (
inputMarkup.substring(index, er.elementStartIndex) +
"<#{er.type}>" +
(if multiline then '\n' else '') +
body +
(if multiline then '\n' else '') +
indent + "</#{er.type}>"
)
index = er.elementEndIndex + 1
if @options.deleteEmbeddedFiles && fs.existsSync er.path
fs.unlinkSync er.path
outputMarkup += inputMarkup.substring index
callback outputMarkup, (if warnings.length then warnings else null)
parser = new htmlparser.Parser
onopentag: (tagName, attributes) =>
tagCounter++
thisTagId = tagCounter
startIndexOfThisTag = parser.startIndex
resource = new Resource tagName, attributes, @options
resource.isEmbeddable (embed) =>
if embed
if !embeddableResources[thisTagId]?
embeddableResources[thisTagId] = {}
er = embeddableResources[thisTagId]
er.body = resource.contents
er.type = (if tagName is 'script' then 'script' else 'style')
er.path = path.resolve path.join(@options.assetRoot, resource.target)
er.elementStartIndex = startIndexOfThisTag
else
warnings.push resource.warning if resource.warning?
process.nextTick -> delete embeddableResources[thisTagId]
if finished
process.nextTick doEmbedding
onclosetag: (tagName) ->
switch tagName
when 'script', 'link'
if !embeddableResources[tagCounter]?
embeddableResources[tagCounter] = {}
er = embeddableResources[tagCounter]
er.elementEndIndex = parser.endIndex
if finished
throw new Error 'Should never happen!'
onend: ->
finished = true
parser.write(inputMarkup)
parser.end()
|
[
{
"context": " 'fetchEtcdTokenURL'\n 'username:fetch': 'fetchUsername'\n 'password:validate': 'validatePassword'\n ",
"end": 611,
"score": 0.834611177444458,
"start": 598,
"tag": "USERNAME",
"value": "fetchUsername"
},
{
"context": " 'fetchUsername'\n 'password:... | src/app/ipc/config.coffee | s1090709/vessel | 101 | # Provide an interface for creating and reading environment config files
_ = require 'underscore'
exec = require('child_process').exec
spawn = require('child_process').spawn
fs = require 'fs-plus'
restler = require 'restler'
sudofy = require 'sudofy'
tempWrite = require 'temp-write'
Listener = require './base'
Logger = require '../utils/logger'
class Config extends Listener
events:
'cloudconfig:generate': 'generateCloudConfig'
'directory:ensure': 'ensureDirectory'
'etcd:url:fetch': 'fetchEtcdTokenURL'
'username:fetch': 'fetchUsername'
'password:validate': 'validatePassword'
'vagrantfile:generate': 'generateVagrantfile'
ensureDirectory: (event, path, callback) ->
if fs.existsSync path
stats = fs.statSync path
event.sender.send callback, stats.isDirectory()
else
fs.mkdir path, '0755'
event.sender.send callback, true
fetchEtcdTokenURL: (event, callback) ->
request = restler.get 'https://discovery.etcd.io/new'
, rejectUnauthorized=false
request.on 'complete', (data, response) ->
Logger.debug "[config] Got etcd discovery URL of #{data}"
if response.statusCode == 200
event.sender.send callback, data
else
event.sender.send callback, null
fetchUsername: (event, callback) ->
event.sender.send callback, process.env.USER
generateCloudConfig: (event, path, url, preview, callback) ->
templatePath = fs.realpathSync "#{__dirname}/../templates/cloud-config.yml"
template = fs.readFileSync templatePath, 'utf8'
renderer = _.template template
try
value = renderer url: url
catch err
value = "Render error: #{err}"
if preview is true
event.sender.send callback, value
else
fs.writeFile "#{path}/cloud-config.yml", value, 'utf8', (err) ->
event.sender.send callback, (if err? then false else true)
generateVagrantfile: (event, values, path, preview, callback) ->
templatePath = fs.realpathSync "#{__dirname}/../templates/Vagrantfile"
template = fs.readFileSync templatePath, 'utf8'
renderer = _.template(template)
if preview is true
try
value = renderer(values)
catch err
value = "Render error: #{err}"
event.sender.send callback, value
else
fs.writeFile "#{path}/Vagrantfile", renderer(values), 'utf8', (err) ->
event.sender.send callback, if err? then false else true
validatePassword: (event, value, callback) ->
command = sudofy.command 'true', {
password: value
}
exec command, (err, stdout, stderr) ->
Logger.info "[config validatePassword]: stderr #{stderr}"
event.sender.send callback, if err? then false else true
if not instance?
instance = new Config
module.exports = instance
| 58413 | # Provide an interface for creating and reading environment config files
_ = require 'underscore'
exec = require('child_process').exec
spawn = require('child_process').spawn
fs = require 'fs-plus'
restler = require 'restler'
sudofy = require 'sudofy'
tempWrite = require 'temp-write'
Listener = require './base'
Logger = require '../utils/logger'
class Config extends Listener
events:
'cloudconfig:generate': 'generateCloudConfig'
'directory:ensure': 'ensureDirectory'
'etcd:url:fetch': 'fetchEtcdTokenURL'
'username:fetch': 'fetchUsername'
'password:validate': '<PASSWORD>'
'vagrantfile:generate': 'generateVagrantfile'
ensureDirectory: (event, path, callback) ->
if fs.existsSync path
stats = fs.statSync path
event.sender.send callback, stats.isDirectory()
else
fs.mkdir path, '0755'
event.sender.send callback, true
fetchEtcdTokenURL: (event, callback) ->
request = restler.get 'https://discovery.etcd.io/new'
, rejectUnauthorized=false
request.on 'complete', (data, response) ->
Logger.debug "[config] Got etcd discovery URL of #{data}"
if response.statusCode == 200
event.sender.send callback, data
else
event.sender.send callback, null
fetchUsername: (event, callback) ->
event.sender.send callback, process.env.USER
generateCloudConfig: (event, path, url, preview, callback) ->
templatePath = fs.realpathSync "#{__dirname}/../templates/cloud-config.yml"
template = fs.readFileSync templatePath, 'utf8'
renderer = _.template template
try
value = renderer url: url
catch err
value = "Render error: #{err}"
if preview is true
event.sender.send callback, value
else
fs.writeFile "#{path}/cloud-config.yml", value, 'utf8', (err) ->
event.sender.send callback, (if err? then false else true)
generateVagrantfile: (event, values, path, preview, callback) ->
templatePath = fs.realpathSync "#{__dirname}/../templates/Vagrantfile"
template = fs.readFileSync templatePath, 'utf8'
renderer = _.template(template)
if preview is true
try
value = renderer(values)
catch err
value = "Render error: #{err}"
event.sender.send callback, value
else
fs.writeFile "#{path}/Vagrantfile", renderer(values), 'utf8', (err) ->
event.sender.send callback, if err? then false else true
validatePassword: (event, value, callback) ->
command = sudofy.command 'true', {
password: <PASSWORD>
}
exec command, (err, stdout, stderr) ->
Logger.info "[config validatePassword]: stderr #{stderr}"
event.sender.send callback, if err? then false else true
if not instance?
instance = new Config
module.exports = instance
| true | # Provide an interface for creating and reading environment config files
_ = require 'underscore'
exec = require('child_process').exec
spawn = require('child_process').spawn
fs = require 'fs-plus'
restler = require 'restler'
sudofy = require 'sudofy'
tempWrite = require 'temp-write'
Listener = require './base'
Logger = require '../utils/logger'
class Config extends Listener
events:
'cloudconfig:generate': 'generateCloudConfig'
'directory:ensure': 'ensureDirectory'
'etcd:url:fetch': 'fetchEtcdTokenURL'
'username:fetch': 'fetchUsername'
'password:validate': 'PI:PASSWORD:<PASSWORD>END_PI'
'vagrantfile:generate': 'generateVagrantfile'
ensureDirectory: (event, path, callback) ->
if fs.existsSync path
stats = fs.statSync path
event.sender.send callback, stats.isDirectory()
else
fs.mkdir path, '0755'
event.sender.send callback, true
fetchEtcdTokenURL: (event, callback) ->
request = restler.get 'https://discovery.etcd.io/new'
, rejectUnauthorized=false
request.on 'complete', (data, response) ->
Logger.debug "[config] Got etcd discovery URL of #{data}"
if response.statusCode == 200
event.sender.send callback, data
else
event.sender.send callback, null
fetchUsername: (event, callback) ->
event.sender.send callback, process.env.USER
generateCloudConfig: (event, path, url, preview, callback) ->
templatePath = fs.realpathSync "#{__dirname}/../templates/cloud-config.yml"
template = fs.readFileSync templatePath, 'utf8'
renderer = _.template template
try
value = renderer url: url
catch err
value = "Render error: #{err}"
if preview is true
event.sender.send callback, value
else
fs.writeFile "#{path}/cloud-config.yml", value, 'utf8', (err) ->
event.sender.send callback, (if err? then false else true)
generateVagrantfile: (event, values, path, preview, callback) ->
templatePath = fs.realpathSync "#{__dirname}/../templates/Vagrantfile"
template = fs.readFileSync templatePath, 'utf8'
renderer = _.template(template)
if preview is true
try
value = renderer(values)
catch err
value = "Render error: #{err}"
event.sender.send callback, value
else
fs.writeFile "#{path}/Vagrantfile", renderer(values), 'utf8', (err) ->
event.sender.send callback, if err? then false else true
validatePassword: (event, value, callback) ->
command = sudofy.command 'true', {
password: PI:PASSWORD:<PASSWORD>END_PI
}
exec command, (err, stdout, stderr) ->
Logger.info "[config validatePassword]: stderr #{stderr}"
event.sender.send callback, if err? then false else true
if not instance?
instance = new Config
module.exports = instance
|
[
{
"context": "HR) ->\n jqXHR.setRequestHeader('X-Spree-Token', 'ad76617dfee35d1b793d8d67187e85c7075ccea6bed232c9')\n",
"end": 625,
"score": 0.974035382270813,
"start": 577,
"tag": "PASSWORD",
"value": "ad76617dfee35d1b793d8d67187e85c7075ccea6bed232c9"
}
] | app/assets/javascripts/spree/ember/frontend/application.js.coffee | venkatesh3007/spree_ember | 1 | //= require jquery
//= require handlebars
//= require ember
//= require spree
//= require_self
//= require ./frontend
Spree.Resolver = Ember.DefaultResolver.extend
resolveTemplate: (parsedName) ->
Ember.TEMPLATES['spree/ember/frontend/' + parsedName.name] ||
Ember.TEMPLATES.NOT_FOUND
Spree.App = Ember.Application.create
LOG_VIEW_LOOKUPS: true,
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true,
LOG_ACTIVE_GENERATION: true,
Resolver: Spree.Resolver,
$.ajaxPrefilter (options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-Spree-Token', 'ad76617dfee35d1b793d8d67187e85c7075ccea6bed232c9')
| 111628 | //= require jquery
//= require handlebars
//= require ember
//= require spree
//= require_self
//= require ./frontend
Spree.Resolver = Ember.DefaultResolver.extend
resolveTemplate: (parsedName) ->
Ember.TEMPLATES['spree/ember/frontend/' + parsedName.name] ||
Ember.TEMPLATES.NOT_FOUND
Spree.App = Ember.Application.create
LOG_VIEW_LOOKUPS: true,
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true,
LOG_ACTIVE_GENERATION: true,
Resolver: Spree.Resolver,
$.ajaxPrefilter (options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-Spree-Token', '<PASSWORD>')
| true | //= require jquery
//= require handlebars
//= require ember
//= require spree
//= require_self
//= require ./frontend
Spree.Resolver = Ember.DefaultResolver.extend
resolveTemplate: (parsedName) ->
Ember.TEMPLATES['spree/ember/frontend/' + parsedName.name] ||
Ember.TEMPLATES.NOT_FOUND
Spree.App = Ember.Application.create
LOG_VIEW_LOOKUPS: true,
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true,
LOG_ACTIVE_GENERATION: true,
Resolver: Spree.Resolver,
$.ajaxPrefilter (options, originalOptions, jqXHR) ->
jqXHR.setRequestHeader('X-Spree-Token', 'PI:PASSWORD:<PASSWORD>END_PI')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.